Builders — Specification #
Status: DRAFT for refinement. See Resolved Decisions for what is settled and Open Questions for what is not.
Overview #
A builder is sower's isolated execution layer: a garden that runs work in cloud-hypervisor microVMs on behalf of the server. Pipelines are the first client, not the point — the builder contract is a general "execute this, isolated" primitive, and everything sower executes server-side goes through it from day one. Evaluating a repository is code execution; it never happens on the server, only inside a builder VM.
Known clients:
- Pipeline steps —
eval,build,check,effectas guest executions;pushas a builder-side engine operation (spec-pipeline.md, Execution Image). - Image materialization — the builtin chain applied to images (spec-pipeline.md, Image seeds).
- Seed trust — the sandboxed eval/build half of the ephemeral signing model (spec-seed-trust.md, D5c and phases 4–5).
- Remote
sower-build— a possible later client submitting work instead of running it locally.
This spec owns the builder role, the execution contract, the host–guest contract, the guest Nix store strategy, dispatch, and the security boundaries. The pipeline definition contract that generates executions is spec-pipeline.md's; the trust model executions must uphold is spec-seed-trust.md's.
Design Principles #
- A builder is a garden role, not a second fleet. Builders
register, authenticate (
private_key_jwt), connect outbound, report versions, and self-update via seeds and subscriptions exactly as gardens do. There is no separate builder registration, protocol stack, or upgrade mechanism. - Executions are generic; semantics live in the guest. The host knows images, resources, network policy, commands, and streams. It does not know what a pipeline, step, or seed is. Builtin step behavior ships as programs in the stock image, versioned by the guest contract.
- Isolation is the product. The VM boundary, process sandbox, and host-enforced network policy protect the host and other executions. There is no non-VM server-side execution path and no unrestricted network mode.
- Privilege is setup, not execution. The existing root activator provisions narrowly scoped resources under operator policy. The garden host agent and VMM stay unprivileged; neither guest traffic nor guest commands run through the activator.
- Authority never rides with untrusted code. Every sower credential — substitution, push, registration, signing — is held host-side, minted short-TTL and scoped, and exercised on the execution's behalf. Guests receive only the user secrets a step declares, injected as files.
- Everything the builder runs is Nix. Images are closures: the stock image rides in the builder's own deployed closure, and user images arrive as seeds through the same registry, cache, and subscription machinery as everything else.
- Local mode stays.
sower-buildkeeps its in-process eval/build for development and bootstrap. It shares the step vocabulary, not the builder path; only server-side execution requires builders.
Model #
| Term | Meaning |
|---|---|
| Builder | A garden with the builder capability: a host agent executing microVMs for the server. |
| Execution | One unit of dispatched work: image + command + payload + resources → event stream + result. |
| Run | A client-scoped group of executions: pins to one builder and scopes its work-store gcroots. |
| Image | A complete guest system closure — the stock image, or a mkImage output as a seed. |
| Host agent | The unprivileged builder role of the garden application: VM lifecycle, vsock services, secrets, work store. |
| Activator | The existing root boundary: operator-authorized setup and release of execution network resources. |
| Network endpoint | An operator-approved destination address/protocol/port resource; a reference requests access, never grants it. |
| Guest runtime | The sower-owned service inside every image that receives the command and mediates I/O. |
| Work store | The host agent's separate Nix store for all execution I/O; the host system store stays clean. |
| Dispatch | Server-side assignment of a queued execution to a builder: free once per run, then pinned. |
Builder Role #
A builder is a registered garden whose connection advertises the builder capability:
| Field | Description |
|---|---|
| systems | Systems it can execute (x86_64-linux, aarch64-linux, …). |
| slots | Maximum concurrent executions. |
| memory | Total memory budget for guest VMs, in MiB. |
| features | Host capabilities (e.g. kvm; nested virtualisation later). |
| contract | Guest-contract range it accepts; nothing outside it is dispatched. |
The server gates dispatch on the builder's reported version, following
the existing contract discipline. Builder software is deployed like any
garden's: as seeds under the builder's own subscriptions and policy.
The stock image ships inside that closure — every builder holds it from
the moment it is deployed, with no fetch, no registry lookup, and no
bootstrap ordering problem. It sits at a well-known path the builder's
own configuration provides at eval and build time, so nobody has to
carry its store path around: dispatch names it stock and the host
agent resolves the rest. Custom images arrive the other way: a
builder subscribes to image seeds with a stage-only policy
(spec-pipeline.md, Image seeds), so those images are pinned
locally before a run asks.
The host agent is part of the garden application, not a service beside it: the same supervision tree, channel, and deployment path that already make a garden a garden. It prefers native Elixir throughout and falls to Rust as needed, through a NIF or port. That is a choice inside the agent, not a component boundary, and it changes no contract.
The existing activator is the only privileged setup boundary, not a new builder daemon or a general root-command service. It creates and releases execution-specific TAPs, routes, isolation namespaces, and nftables rules. The host agent owns orchestration, starts the VMM unprivileged, and serves the scoped vsock endpoints. The activator does not launch repository commands, handle packets in userspace, or hold guest-facing application services. Builder installation must provision this scoped activator capability and operator policy before networked work can run.
Execution Contract #
The dispatch message. Schemas live in sower_client and are covered by
the contract baseline.
| Field | Type | Required | Description |
|---|---|---|---|
| sid | string | yes | Execution id; idempotency key for redispatch. |
| run_sid | string | yes | The run this execution belongs to: gcroot scope, pin key, lifecycle owner. |
| system | string | yes | Target system; what dispatch matched the builder on. |
| image | string | yes | stock for the builder's own image, or an image seed's store path. |
| command | object | yes | { path, args, env } — a store-path executable inside the image's closure. |
| payload | object | yes | JSON delivered to the command on stdin (a pipeline item, for step executions). |
| vm | object | yes | { cpus, memory }, resolved by the server from definition defaults. |
| network | string | yes | none (default; no NIC) or full (routed NIC with mandatory host filtering). |
| network_endpoints | string[] | no | Approved endpoint resource sids, server-resolved; default [], valid only with full. |
| caches | object[] | no | Upstream caches the read proxy fronts for this execution; server-resolved. |
| secrets | object | no | Named user-secret material injected as files (see Security). Never logged/persisted. |
| paths | string[] | no | Work-store roots the read proxy serves this execution (closure allowlist). |
| timeout | string | yes | Execution deadline. |
The host never templates or interprets command and payload — it
execs one and delivers the other, exactly once, per the item context
convention (spec-pipeline.md). The pipeline engine, not the builder,
resolves step kinds to commands: eval becomes the stock runtime's
eval program; a check becomes the built app's executable. Arbitrary
commands are excluded at pipeline validation, not here — a definition
may only name executables built from the pinned source, while the
builder contract stays generic rather than interpreting client semantics.
Resource access is still constrained by operator policy, independently
of command validation. Commands are customized through three channels:
static args, static env, and the structured payload on stdin;
anything richer is Nix — wrap the program and bake the configuration
into the derivation.
Events stream back over the garden channel as the execution proceeds:
| Event | Payload |
|---|---|
| started | Builder accepted; VM booted. |
| log | Stdout/stderr chunks, interleaved, sequence-numbered. |
| item | A structured JSON document emitted by the command (see Host–Guest). |
| paths | Store paths produced and exported (see Store Strategy). |
| exited | Terminal: exit code, or failed / cancelled / timeout + reason. |
item events are how streaming entry-point steps work: one eval
execution emits an item per derivation as its attribute walk proceeds,
and the pipeline engine fans them into consuming phases without waiting
for the walk to finish.
Engine operations carry a different message over the same queue and
channel. push, the only one today, takes sid, run_sid, the
work-store paths to upload, the cache resource to upload them to,
and timeout; image, vm, network, and network_endpoints have
no meaning because nothing boots. It reports the same events minus
item, and occupies one slot against a fixed minimal memory budget, so
capacity accounting stays uniform and concurrent uploads are bounded by
the same arithmetic as everything else.
Host–Guest Contract #
Every image embeds the sower guest runtime via the mandatory base
module of sower.lib.mkImage (spec-pipeline.md, Execution
Image), and stamps /etc/sower/image.json with a versioned
guest-contract marker. The host agent refuses images whose marker is
missing or out of its supported range — the runtime surface is a
cross-component contract like any other. One marker versions that whole
surface, vsock protocol included; there is no second negotiation, and
builders advertise the range they accept so the server never dispatches
an image it would refuse.
The builder design uses vsock for three services: the control channel
(command delivery, events, exit), the read proxy, and the write endpoint
(see Nix Store Strategy). The guest runtime forwards localhost HTTP to
the latter two, so unmodified nix sees an ordinary substituter and upload
target. The current local image implementation provides command execution
only; the cache services and server-side builder dispatch remain separate.
The command's own I/O convention is unchanged from the pipeline spec:
payload as JSON on stdin, stdout and stderr captured as the step log.
Programs that emit items (eval; later, checks enriching items) write
JSON lines to a runtime-provided descriptor, which the runtime forwards
as item events — application stdout stays log, never protocol.
The guest runtime receives commands over vsock after boot, injects
nothing into their environment beyond command.env, and reports exit
status. Disposable execution remains the default composition: boot, await
readiness, execute one command, await its result, then stop the VM and await
certified cleanup. A persistent VM instead remains available after command
completion, retaining its scratch disk and guest state until explicitly
stopped or its VM owner is lost. Commands are serial within a VM; independent
VMs may execute concurrently. Commands are never automatically replayed.
Keeping a VM alive does not introduce interactive access. Brokered SSH or console access remains a separate service and authorization decision.
Local command protocol #
The implemented Rust executor listens on guest vsock port 5000. Garden
opens Cloud Hypervisor's owned Unix socket, sends CONNECT 5000\n, consumes
OK <host-port>\n, then exchanges binary stream frames.
Each frame has a one-byte kind, a four-byte unsigned big-endian payload length, and at most 65,536 payload bytes. Kind 1 is JSON metadata; kinds 2 and 3 carry raw stdout and stderr. Ordering is preserved within each output stream, without a cross-stream ordering guarantee.
The guest sends {"type":"ready","version":1,"contract":2}. The version-1
ready envelope preserves legacy protocol compatibility; the contract marker
advertises the persistent command surface. One execute request carries
type, version, path, args, env, and stdin; args excludes argv[0].
Contract-2 commands use execute version 2 and terminal metadata version 2.
The executor launches the absolute path directly with only the supplied
environment, writes JSON stdin, closes it, and drains both output pipes.
An exited event contains either an integer code or an integer signal,
with the other field null. Request/spawn failures return an error event,
never a fabricated exit status.
Each command uses a separate connection. While it runs, the host may send
{"type":"cancel","version":2}; the guest kills and reaps the command tree
before reporting its actual exit code or signal. Disconnect also cancels and
reaps the command tree. The guest accepts the next connection only after
cleanup, so readiness on that connection certifies the previous command is
gone. A stalled output consumer cannot block host-side cancellation.
VMManager owns VM lifetime independently from Garden and command execution.
Its OTP application starts alongside Garden in the release; restarting Garden
does not stop its VMs. An independent guard reclaims ephemeral scratch and known
files only after confirmed VM teardown. Uncertain cleanup or unexpected files
retain resources and capacity reservations. Contract-2 guests support repeated
commands; contract-1 guests support one command followed by teardown through the
same manager boundary.
VM admission #
Garden resolves images and translates their complete boot artifacts into
VMManager.Config. The manager does not load images or read Garden configuration.
The configuration specifies a kernel, optional initrd, ordered native or
manager-created ephemeral disks, and optional devices. A native disk remains
caller-owned; an ephemeral disk is allocated and formatted by the manager.
Optional serial and console devices use native CloudHypervisor.Config.Output
structs; relative single-filename outputs belong to the manager's attempt
directory and are cleaned after certified teardown, while absolute paths remain
caller-owned.
Garden's image helper supplies the root and scratch layout and Sower guest
devices; generic callers need neither scratch storage nor the Sower agent.
define/1 durably records a configuration under its caller-supplied ID.
start/1 persists desired running state, and await_running/1 waits for the
hypervisor's Running state. await_ready/1 waits for the Sower guest handshake
and returns {:error, :guest_agent_disabled} when there is no guest agent.
Definitions, desired state, resource reservations, and bounded restart accounting
survive manager and application restarts. Reconciliation reconnects to a matching
live runtime or restores a desired VM after its runtime is gone.
execute/2 returns a command handle. command_status/1, await_command/1,
and cancel_command/1 address that command, not VM lifetime. Command caller
loss cancels only its command. VM lifetime is not owned by the defining caller.
Only one command may be active per VM; a busy VM rejects another execution.
Command completion or cancellation leaves the VM running.
status/1 and list/0 observe definitions and runtimes. stop/1 persists stopped
intent and waits for certified ephemeral cleanup, including any active command.
remove/1 removes a stopped definition without deleting persistent disks;
delete_storage/1 is the separate explicit persistent-storage operation.
The local CLI composes define/start/readiness/execute/await-command/stop/remove
through the same manager boundary. Standalone mix sower.vm.run uses a private
per-invocation manager and state directory, without opening Garden's store or
changing its budgets. In-process Garden.VM.CLI.run/3 uses the supplied or
already-running default manager. Disposable VM IDs are random across BEAM
restarts. Output callbacks retain the (stream, bytes) interface; callers
capture their job/step identity in the callback.
Generic VM configurations can omit networking or explicitly attach an
externally managed host network; the manager does not destroy external
attachments. Garden image callers opt into IPv4 public egress with
network: :full; the default network: :none still supplies no NIC. The operator must enable
services.sower.activator.network.enable and configure its public DNS resolver
and protected destination addresses. Garden uses short-lived requests on the
existing /run/sower-activator/activator.sock Accept=true socket, with
type="network" and network_action of provision, revoke, release, or
cleanup; execution_id and lease identify the relevant operation.
Responses use the normal id/type/data/exit_code envelope. Provision emits
one output whose data is JSON containing lease, tap, mac, address,
gateway, and dns; complete with exit code zero certifies success.
Errors emit error and a nonzero completion. Activation behavior is unchanged.
The privileged activator authenticates the peer's system service cgroup
against network.gardenUnits (default ["sower-garden.service"]), derives the
instance, and records its owner identity. Garden and Cloud Hypervisor remain
unprivileged. Local socket overrides use the socket_path option to
Garden.VM.Network.request/1.
Static address, gateway, DNS, and MAC kernel parameters configure the image
before its vsock executor reports readiness. The guest retains the standard
cache.nixos.org substituter and signing key with signature verification.
This direct public substitution is the local network baseline, not the future
credentialed work-store proxy.
Images advertise "network_config": "static" in additive boot metadata, loaded
as network_config: :static in Elixir. This declares support for Garden-supplied
static addressing, gateway, and DNS; it does not enable networking. Images
without this declaration remain usable with none; full rejects them before
admission. Older Gardens ignore the additive metadata field.
The guard revokes network connectivity before stopping the VMM and releases
the lease after certified teardown. Network cleanup failures retain admission
accounting; full never falls back to none. Independent executions operate
concurrently. A short host-wide flock protects allocation records; execution
operations use bounded, stable hashed lock files (colliding hashes serialize).
No host commands run under the allocation lock. Execution-owned nftables
tables avoid shared policy rebuilds. Root-only runtime JSON lives beneath
network.stateDirectory (default /run/sower-network). There is no separate
network daemon, lifetime socket, reaper, or durable lease journal.
The Garden service uses KillMode=control-group: no VMM survives its stop.
Root-privileged ExecStartPre reconciliation runs before admission, and
ExecStopPost cleanup runs after cgroup termination, using the same generated
policy and explicit service instance. Other configured Garden units must
install equivalent hooks. Request-scoped activator services are not bound to
Garden's lifetime because activation itself may restart Garden.
Networking-enabled Garden units default to no cgroup memory ceiling, rather
than the BEAM-only 200 MiB limit: guest memory is charged to the same cgroup.
Operators may set an explicit aggregate MemoryMax; networking-disabled
deployments retain the 200 MiB default.
Garden configuration sets vm_capacity with positive integer vms,
cpus, memory (bytes), and scratch_bytes. Defaults admit one VM,
one CPU, 512 MiB memory, and 4 GiB scratch. Reservations cover the entire VM
lifetime, including startup, idle time between commands, execution, and
stopping; these are admission budgets, not hard host isolation.
Oversized requests return request_exceeds_capacity; requests
that exceed currently available resources return capacity_exhausted,
both with the exhausted dimension. Neither case queues or allocates a VM.
Certified native teardown and successful owned-file cleanup normally release a reservation. Cleanup failures retain their VM ID, directory, and reservation; a terminal command result is not evidence that VM resources were released. Definitions remain durable until explicitly removed, rather than being evicted as a bounded cache of disposable execution results.
For a same-host-boot reservation whose controller was lost,
VMManager.abandon_reservation(id, server \\ VMManager.Manager) is an explicit
operator escape hatch, never automatic recovery. It rejects a live registered
controller and returns {:ok, snapshot} only after durably archiving the old
definition in abandoned_attempts and clearing its active reservation and network
custody. The snapshot retains configuration, paths, lease, attempt and boot/BEAM
identities. Abandonment does not certify cleanup, signal processes, revoke or
release networking, or delete storage. The operator owns manual cleanup of
abandoned resources. A later start or update can create a fresh attempt under the
same VM ID while retaining the archive; remove/1 deletes that metadata without
cleaning archived resources. delete_storage/1 returns
{:error, :cleanup_uncertain} while any abandoned attempt remains archived,
even after a later attempt cleans up successfully, because persistent paths
may overlap abandoned custody.
Orderly manager-application shutdown stops native runtimes while preserving desired state for restoration on the next boot. A host reboot invalidates previous-boot native identities and reconciles desired VMs. A same-boot abrupt BEAM loss without a matching live external runtime cannot certify old cleanup; its reservations remain retained. Host-enforced containment and production systemd isolation remain separate from this extraction. Commands are never replayed during recovery.
Nix Store Strategy #
The execution layer never touches the builder host's own store. All execution I/O flows through the work store — a separate Nix store at its own root, owned by the host agent — so the host system's closure contains exactly what the operator deployed and never a guest-produced path. Wiping the work store must never break the builder host.
- Ingress: substitution through the read proxy. Guests have no network device by default. The guest runtime forwards localhost HTTP to host-side vsock services, so unmodified nix inside the guest sees an ordinary substituter: the read proxy serves the execution's declared work-store roots first and its resolved upstream caches on miss, caching fetches in the work store (LRU, size-limited — the ncps shape). Upstream credentials live in the proxy, never in the guest. The guest builds in its own scratch store; inputs are copied in once per miss and are warm for every later guest on that builder.
- Egress:
nix copyto the write endpoint. A producing program copies the closures it wants to persist to the host agent's write endpoint — plain binary-cache protocol over the same vsock. The agent imports into the work store under gcroots scoped to the execution'srun_sidand emits thepathsevent. What a program does not copy out does not exist after the VM dies, so egress naming needs no separate mechanism. - Boot images are read from where they legitimately live, in the host store: the stock image at the well-known path in the builder's own deployed closure, custom images as registered seeds staged through its subscription. Both are operator-governed and pinned. Ephemeral merge-run images are work products and live in the work store like any other.
- Sharing between builders happens at the cache layer, never as a shared filesystem — nix local stores are single-writer. Within a run the question does not arise, because the run is pinned to one builder (see Dispatch). Between runs, and for the later cross-system case, the shared layer is the cache the run pushes to, or a caching proxy several builders front.
- Fixed-output derivations under the default no-network policy must
substitute from the proxy or fail, consistent with sources-are-inputs
(spec-pipeline.md, Repository Input).
fullnetwork exists for the checks and effects that genuinely reach out.
Run outputs and cached substitutions are separate budgets. Substitutions are evictable at any time under the LRU; paths under a live run's gcroot are not, because a later execution of that run is entitled to read them. The server releases a run's gcroots when the run closes, after which its outputs fall to the LRU like anything else and the cache remains the durable artifact layer. A builder whose work store is full stops accepting new runs — executions of runs already pinned to it still schedule, since finishing a run is what releases its gcroots. The pressure surfaces as scheduling backpressure, never as a failure mid-run. Storage is not endorsement — whether a work-store path may be activated anywhere is the signing layer's question (spec-seed-trust.md).
Dispatch #
The server owns a queue of executions and assigns each to a connected
builder matching system with a free slot, sufficient memory, and work
store headroom, over the garden channel — the same discipline as
deployment dispatch. Not everything dispatched boots a VM: builder-side
engine operations — push, uploading from the work store with the
scheme-dispatched backend client (niks3://, attic://, otherwise
nix copy) and host-held credentials — ride the same queue and channel
without a guest.
- Runs pin to a builder. Placement is decided once, for a run's
first execution; every later execution carrying that
run_sidgoes to the same builder. Executions consume each other's products — a build reads the eval's derivations, a check reads the build's outputs, a push uploads them — and only the pinned builder's work store holds them. Push has no other option in any design: it uploads paths, so it runs where the paths are. - Pinning is the simple half of a two-step answer. The general mechanism is a cache round-trip between executions, reusing the machinery push already needs and unlocking runs that span systems. It also pays a copy on every hand-off, so pinning ships first and the cache path arrives where cross-system runs or builder loss make that copy worth paying. Neither changes the contract fields.
- Run close is a server→builder message carrying the
run_sid. It releases the run's gcroots and frees its pin; nothing else does. - Failure: a builder disconnecting or dying mid-execution fails the execution; the server does not transparently re-run it. Losing a builder loses the unpushed work-store products of every run pinned to it, so those runs re-place from scratch on rerun and rebuild whatever was not pushed. Retry is the client layer's move (a pipeline rerun memoizes past completed work), keeping builder semantics at-most-once and dumb.
- Cancellation and timeout: revoke network connectivity and kill the
VM; the execution reports
cancelledortimeoutrespectively. Already-exported paths and emitted items stand. All terminal paths release execution resources through the lifecycle below. - Placement policy beyond system, capacity, and the run pin — labels, tenant pools — is a future consideration; the contract fields do not change for it.
Security #
- Networking is externally enforced.
nonesupplies no NIC;fulluses routed per-execution TAPs and mandatory host nftables filtering. Neither guest configuration nor a pipeline definition can remove the protections specified in Network Policy. - The VMM is unprivileged and execution-scoped. It receives only its image, scratch storage, sockets, and required device handles (including KVM and its own TAP). It has no garden credentials, access to other executions, or broad host filesystem access. The host agent retains the credentials needed for its own services; it does not pass them through VMM arguments, environment, or inherited descriptors. Seccomp, process/filesystem sandboxing, and resource limits remain required independent protections, not substitutes for network policy.
- Secrets are injected by the host agent at VM start as files under
/run/sower/secrets/<name>on a tmpfs, and die with the VM. They arrive in the dispatch message over the channel's TLS, are never written to the builder's disk or logs, and never enter the image or any Nix store. Access decisions happened server-side (spec-pipeline.md, Secrets); the host mounts only what dispatch delivered. - Sower's own credentials never enter guests. Upstream-cache auth lives in the read proxy; push and registration credentials are minted short-TTL and scoped to the host agent and server, which authenticate on the execution's behalf. The quarantine-cache redirection for untrusted runs happens at minting; the builder is indifferent.
- Host-side push is bounded by minting and by the trust model. A push operation uploads exactly the server-named paths from the work store, with a credential minted for that operation — short-TTL, bound to the one cache resource the run's capability set selected. A compromised guest holds nothing; a compromised builder host can pollute the caches it was directed at, during the window, and nothing more — cache content is transport, never trust. Activation requires the signing layer's verification regardless of what any cache serves.
- Backend clients are part of the builder closure. The upload
clients scheme dispatch selects among ship pinned in the builder
host's own seed — operator-governed like the rest of the host
closure, overridable in the builder's NixOS configuration, and never
influenced by a run definition: repository-derived code executes
only in guests. The builtin push serves registered cache resources;
uploading anywhere else — a public cachix, mirrors, unsupported
backends — is an
effectin a guest with the user's own secret, which is its correct owner. - Signing separation (D5c): no execution that evaluates or runs repository-derived code receives signing credentials. The ephemeral signing of spec-seed-trust.md is performed by the host agent (or a dedicated non-guest step) over a completed, exported result — the compromise of a guest never yields signing authority.
Network Policy #
These are required implementation contracts. The Garden-local public IPv4 path described above does not implement private endpoint authorization or server dispatch. Cloud-hypervisor remains the single execution backend; its choice does not depend on all setup being rootless.
Modes and topology #
noneis the default. No network device, route to the outside, or general-purpose network proxy is supplied. Guest loopback works for services inside the same VM. Control, the Nix read proxy, and the write endpoint remain execution-scoped vsock services, not arbitrary tunnels; enabling networking changes neither their scope nor store and credential ownership.fullmeans networked, not unrestricted. Public internet egress is permitted only within operator policy. It never authorizes access to the builder, other execution guests, metadata, or control-plane services. Private and other special-use destinations are denied by default; narrowly approved endpoint exceptions are described below.- One routed TAP per execution. Provision per-execution network isolation, using network namespaces where needed to isolate routes and devices. Do not bridge guests directly onto the physical LAN; a bridge is not a security boundary. Host nftables rules enforce the boundary outside the guest and VMM. There is no parallel or fallback passt implementation. Routing and any necessary NAT provide connectivity, not authorization.
Endpoint references and authorization #
network_endpoints is the minimal exception mechanism, not another
network mode. A pipeline requests registered resources by name or sid
via vm.network_endpoints; other clients use the same generic resource
references. The server resolves names to stable sids, authorizes them
against the run's capability set, and dispatches only those sids. Unknown
or unauthorized references fail validation. An empty list requests no
exceptions; a non-empty list with network = none is invalid.
An endpoint resource denotes a finite set of exact destination IP
addresses, a transport protocol (tcp or udp), and destination ports.
It is not an arbitrary URL, subnet, wildcard, proxy, or firewall rule.
The server registry is the reference and per-run authorization layer;
the activator independently looks up each sid in its operator-governed
local policy. That local entry bounds the addresses, protocol, ports,
and availability to this builder. The server and garden BEAM cannot
create or widen it. Missing local approval fails the execution before
connectivity; it does not silently drop a requested exception or select
a weaker mode. A compromised orchestrator remains bounded by those
operator-approved endpoints, not by an allowlist it supplies itself.
This supports a check of a private garden application without treating the garden's deployment channel as reachable or authorized. The check still owns its target configuration; an endpoint reference grants only the specified network reachability, not credentials, service discovery, or permission to activate a seed. Definitions cannot self-authorize private access by naming an IP or changing a repository file.
Effective access is the intersection of server-granted references and operator approval, subject to mandatory denials. No endpoint can override denial of builder-host addresses/services, other execution guests, metadata endpoints, or control-plane services. Operator policy can further restrict public egress and endpoint access; an explicit operator deny wins over an endpoint grant. Only the private/special-use destination default may be lifted for the exact approved tuple.
Endpoint address sets are pinned when an execution is provisioned. Hostnames used by apps are not firewall identities: every resulting packet is checked against its actual destination. DNS re-resolution cannot expand a grant, and address changes require operator-approved reprovisioning rather than automatic firewall widening. Policy tightening or revocation must remove affected access, including existing flows, or terminate the affected executions before taking effect; failures remain closed.
Packet enforcement #
- Apply default-deny host INPUT and forwarding rules for each execution.
Public egress allowed by policy and approved endpoint tuples are the
only forwarded openings. Cover all builder addresses, including its
non-loopback LAN/public addresses, not just
127.0.0.1or::1. Protect metadata and control-plane destinations regardless of whether their addresses are private, link-local, or public; their address sets are operator-maintained, never inferred solely from private ranges. - Deny guest-to-guest traffic, including between executions in the same run. Deny unsolicited inbound connections. Admit only replies to permitted outbound flows, scoped to the originating execution; a generic established-flow rule must not bypass mandatory denials, revocation, or isolation when addresses are reused.
- Bind source addresses and link-layer identity to the provisioned TAP. Reject source spoofing, guest routing advertisements, and attempts to use another execution's route or interface. Apply equivalent destination and anti-spoofing protections to IPv4 and IPv6; if IPv6 is not provisioned, deny it rather than leaving an alternate path.
- Any required DNS, DHCP, ARP, or NDP bootstrap traffic is confined to operator-selected peers and the minimal protocol/port/link scope. Such exceptions do not grant general host access or override the service denials above. Do not expose a general host resolver/proxy interface as an escape from the egress filter.
- Check the effective destination across routing/NAT so translation or hairpin routing cannot bypass a denial. Deny special-use destinations (including loopback, link-local, private, multicast, and reserved ranges) except the narrowly scoped bootstrap traffic and approved endpoint tuples. No alternate device or address family may evade the same policy.
This is address-based isolation, not an application-layer provenance or data-loss guarantee. An allowed public service or approved endpoint can relay traffic or data; host filtering cannot promise otherwise. Operator approval must account for that authority, and user secrets remain available to the guest programs to which they were granted.
Provisioning and teardown #
The activator accepts only constrained provision/release operations from the local authorized host agent, bound to an execution identity and its resource ownership. It validates modes and endpoint references against operator policy itself. No raw commands, arbitrary nftables snippets, unchecked paths, caller-chosen namespace handles, or caller-chosen resource names cross this interface. Names and handles are derived and tracked by the activator; a reused sid cannot take over another execution's resources.
Provision isolation and install the complete deny-first firewall before
enabling the TAP or making a route usable by a guest. Only then hand the
execution-scoped device access to the unprivileged VMM. Partial setup,
policy rejection, firewall failure, or missing prerequisites roll back
with no reachable guest; no unfiltered fallback is allowed. none
creates no TAP or network exception resources.
Normal exit, cancellation, timeout, failed boot, host-agent/VMM crash, and builder restart all require cleanup. Revoke connectivity first, stop any remaining VMM, and then release the execution's TAP, routes, namespace, firewall and connection-tracking state. Keep deny protection until its interfaces are gone. Release is idempotent and ownership-checked; duplicate, late, or concurrent cleanup cannot remove a different execution's resources. Do not reuse addresses or identifiers while stale flows or resources could authorize traffic.
Crash recovery must not depend on the unprivileged agent successfully sending a final request. The privileged lifecycle must detect abandoned owners, keep surviving resources filtered, and reclaim them. On restart, reconcile leftover resources before accepting work; if safe cleanup or policy enforcement cannot be established, quarantine the affected resources and refuse new networked execution rather than flush shared rules or continue unfiltered. This does not change at-most-once execution, run pinning, or the separate run-close gcroot lifecycle.
Local Mode and Development #
sower-build keeps its in-process eval/build path: development and
bootstrap must work on a laptop with no builder fleet, no KVM, no
server. The CLI and the stock image's guest programs share the step
vocabulary (Nix.Eval.Jobs and friends) as libraries; isolation is a
property of the server-side path, not of the vocabulary.
Server-side, there is exactly one execution path — through builders.
The development server therefore needs a local builder: sower_dev
runs one unprivileged host agent beside the server. KVM, the existing
activator's privileged network setup capability, and operator-governed
network policy are explicit prerequisites. E2e runs real
cloud-hypervisor builders inside its incus VMs under nested KVM — an
accepted infrastructure assumption — with the same activator, routed
TAPs, and firewall enforcement. Test endpoint approvals belong to the
operator-controlled fixture configuration, not repository code. There
is no degraded, container-backed, root-run VMM, or unfiltered networking
mode for development or tests.
The local image/network scenario runs with
nix build --option sandbox false .#checks.x86_64-linux.image.
It needs nested KVM and real public DNS/HTTPS access: the guest downloads the
GitHub installer asset without executing it and runs cowsay through ordinary
signed substitution. The permanent scenario pins its nixpkgs revision.
The driver’s image-network-scenario command accepts SOWER_COWSAY_REF for the
manual floating-ref baseline; its default remains the pinned revision.
Implementation acceptance #
The following scenarios are required before the corresponding execution path ships; they are not evidence of current implementation or live verification:
- A
noneexecution has no NIC, cannot reach external addresses, and still runs loopback services, substitutes through the scoped vsock read proxy, and exports through the write endpoint. - A
fullexecution reaches an allowed public destination, while attempts to reach builder loopback and non-loopback services, another execution (including one in the same run), metadata, control-plane, and unapproved private/special-use destinations fail. - A server-authorized, locally operator-approved private endpoint permits exactly its address/protocol/port tuple. Wrong ports, unapproved references, a server-supplied forged grant, and a grant targeting a non-overridable destination fail. DNS changes do not widen it; revocation closes existing as well as new flows.
- IPv4/IPv6, source spoofing, routing/NAT, unsolicited inbound, and bootstrap-protocol attempts cannot bypass isolation. Replies to a permitted flow work only for its owning execution.
- Inject failures before and after each provisioning stage, cancel and time out running guests, kill the VMM/agent/activator, and restart the builder. No stage exposes an unfiltered interface; recovery reclaims leftovers. Concurrent executions and duplicate/late teardown retain each other's resources and cannot inherit old flow authorization.
- Exercise these scenarios between real nested-KVM guests in e2e, observing denied traffic at protected services as well as guest failures. Verify the agent and VMM run unprivileged and that the VMM cannot read garden credentials or another execution's files/devices. Missing privileged setup or firewall support must fail closed, never select a weaker test path.
Phasing #
- Builder role + generic executions. Capability advertisement, dispatch with run pinning and run close, event stream, stock image with eval and build guest programs, the work store, and the vsock read/write services. Includes no-NIC isolation, unprivileged VMM sandboxing, and failure cleanup from the first execution. Unblocks sow-221.
- Builder-side push, credential minting. Backend upload clients on the host agent; scoped short-TTL credentials; quarantine redirection.
- Custom images.
sower.lib.mkImage, image seeds, materialization, pre-warm subscriptions, pinning. - Filtered networking, secrets, and user code. Scoped activator
setup, routed TAPs, nftables, endpoint authorization, crash-safe
teardown, and the network acceptance scenarios must land before any
server-dispatched
fullexecution is admitted. Local image VMs have the public-web/DNS-only path described above; dispatch and private endpoint authorization remain separate. Secret injection andcheck/effectstep kinds land in the pipeline engine; private checks require the approved endpoint path, not a temporary unrestricted mode. - Seed-trust integration. Ephemeral signing on builders (spec-seed-trust.md phases 4–5), signing separation enforced.
Resolved Decisions #
- Builders are a garden role. Registration, auth, channel, versioning, and self-update are the garden's; no parallel mechanism.
- The host agent is part of the garden application. Native Elixir by preference, in the garden's own supervision tree and deployment path, falling to Rust through a NIF or port as needed — never a second builder service or a second execution contract. The existing root activator remains the narrowly scoped privileged setup boundary; it does not run guest commands or carry guest traffic.
- The execution contract is generic. Image + command + payload + resources + network + secrets → events. Step semantics live in guest programs; the host never interprets work.
- Runs are identified by an sid.
run_sidscopes work-store gcroots, keys the builder pin, and is what the server's run-close message releases. - Runs pin to a builder. A run's first execution picks the builder
and every later one follows,
pushincluded, because only that builder's work store holds what they consume. A cache round-trip between executions is the general mechanism and arrives when cross-system runs or builder loss justify the copy. - Commands are store-path executables with plain args. The host
execs what dispatch names and templates nothing. Excluding arbitrary
commands is pipeline validation's job; static
args/envand the stdin payload are the customization channels. - Structured output is a runtime channel, not stdout. Items flow as JSONL over a runtime descriptor; application stdout stays log.
- One guest-contract marker versions the whole host–guest surface, vsock protocol included, and builders advertise the range they accept so the server never dispatches an image they would refuse.
- The work store is the only store executions touch. The builder host's system store never holds a guest-produced path; wiping the work store never breaks the host. Sharing between builders happens at the cache layer, never as a shared filesystem.
- Run outputs sit outside the LRU. Eviction governs cached substitutions only; a full work store stops scheduling new runs rather than dropping a live run's products.
- The stock image ships in the builder closure, at a well-known
path its own configuration provides at eval and build time. Dispatch
names it
stockand the host resolves it; only custom images come through registry, cache, and subscriptions. - Ingress and egress are the binary-cache protocol over vsock.
Guests substitute through the read proxy and
nix copyresults to the write endpoint; no NIC is involved, no bespoke NAR protocol exists, and what a program does not copy out does not persist. - Network modes stay
noneandfull, never unrestricted.nonehas no NIC;fullpermits operator-governed public egress through routed TAPs and host nftables. No physical-LAN bridge or passt fallback. Scoped vsock services work in both modes. - Private access is an approved endpoint reference. The server authorizes resource sids per run; the activator independently bounds them by operator-owned exact address/protocol/port grants. Builder, metadata, control-plane, and other-guest protections are mandatory and cannot be overridden.
- Privilege ends at setup. The garden host agent and VMM run unprivileged. Firewall installation precedes connectivity; all lifecycle failures and cleanup remain fail-closed, including dev/e2e.
- push is a builder-side engine operation. No VM: the host agent
uploads from the work store with the backend-specific client and
host-held credentials. The builtin serves registered cache resources
only; external publication is an
effectwith user credentials. - push carries its own message shape. Same queue and channel, but paths and a target cache in place of image, vm, and network. It boots nothing, and still takes one slot and a fixed minimal budget so capacity is counted one way.
- Backend clients are a pinned, operator-governed set. They ship in the builder host closure; a run definition can never name a binary the host executes.
- Storage is not endorsement. Serving a guest-produced path says nothing about activation; that remains the signing layer's decision.
- Executions are at-most-once. Builder failure fails the execution; retry is memoized rerun at the client layer.
- No sower authority in guests at all. Proxies and host-side operations hold every sower credential — substitution, push, registration, signing; guests receive only declared user secrets.
- Local mode stays.
sower-buildruns in-process for dev and bootstrap; only the server-side path requires builders. - Cloud-hypervisor is the only execution backend. No degraded or container-backed builder modes anywhere, tests included: e2e runs real cloud-hypervisor builders under nested KVM. Incus remains e2e scaffolding for gardens, never an execution backend.
Open Questions #
- Secret transport. User secrets ride the dispatch message today; is a pull-at-start flow (builder fetches sealed material when the VM boots) worth the extra round trip to shrink the window material exists outside the host's memory?
- Capacity model. Slots + memory budget vs. real bin-packing on cpus/memory; whether eval's memory ceilings need reflecting in advertisement. Spindle's per-image budgets with work-conserving fair allocation are prior art. Pinning sharpens this: a pinned run's later executions queue behind their own builder rather than spilling to a free one, so a mis-sized builder stalls a run instead of a slot.
- Event-stream bounds. An untrusted guest can emit
loganditemevents without limit, and the spec states no size cap, truncation, or backpressure — a host-protection gap, not hygiene. Relatedly, a builder disconnecting fails the execution, which makes a transient channel blip kill a two-hour build; logs are sequence-numbered, which gestures at resume, but no reconnect window is specified. - Image on miss. Pre-warm subscriptions cover the happy path, and the stock image is always local. When dispatch would name an image a builder has not staged, is that a placement constraint (only builders holding it are candidates) or a fetch the execution waits on? Phase 3.
- Read proxy implementation. Adopt ncps or build the equivalent against the work store.
- Who performs ephemeral signing. The host agent or a dedicated non-guest step (see Security); phase 5 picks one.