diff options
Diffstat (limited to 'src/sandbox')
| -rw-r--r-- | src/sandbox/agent.rs | 15 | ||||
| -rw-r--r-- | src/sandbox/kata.rs | 34 | ||||
| -rw-r--r-- | src/sandbox/loopback.rs | 13 | ||||
| -rw-r--r-- | src/sandbox/mod.rs | 99 | ||||
| -rw-r--r-- | src/sandbox/remote.rs | 21 | ||||
| -rw-r--r-- | src/sandbox/wire.rs | 36 |
6 files changed, 38 insertions, 180 deletions
diff --git a/src/sandbox/agent.rs b/src/sandbox/agent.rs index 09a6f93..d7b841c 100644 --- a/src/sandbox/agent.rs +++ b/src/sandbox/agent.rs @@ -1,18 +1,3 @@ -//! The ephemeral sandbox agent: what runs *inside* the sandbox. -//! -//! One connection, one lease, one life: the agent dials the hub (outbound -//! rendezvous — the hub never needs a route into an untrusted box), accepts -//! `Run`/`Put`/`Get` frames for as long as the hub keeps the connection alive, -//! and dies — taking its child processes with it — when the connection drops -//! or its TTL expires. There is no state between leases by design: the sandbox -//! is disposable, the TTL is the guarantee, and a leaked sandbox is a bug in -//! the TTL watchdog, not a lifecycle question. -//! -//! The TTL watchdog is the backstop under every failure mode: hub crashes, -//! network partition, a hub bug that forgets `Destroy`. The hub keeps it fed -//! with `Ping` frames while a run is in flight; silence longer than the TTL -//! means nobody is coming, so the agent kills its child and exits. - use std::io::BufReader; use std::net::TcpStream; use std::path::{Path, PathBuf}; diff --git a/src/sandbox/kata.rs b/src/sandbox/kata.rs index c7d717f..9169f9f 100644 --- a/src/sandbox/kata.rs +++ b/src/sandbox/kata.rs @@ -1,25 +1,3 @@ -//! The kata backend: ad-hoc, TTL-bounded sandboxes provisioned by an -//! orchestrator, leased over the same agent protocol as everything else. -//! -//! This is composition, not a new protocol: a kata sandbox is a small VM that -//! boots the `sandbox-agent` image pointed at this hub, and `acquire` is -//! "ask the provisioner for a box, then wait for *that specific box* to dial -//! in". The nonce each lease generates is handed to the provisioner and comes -//! back as the agent's `agent_id`, so a stray sandbox can never be leased to -//! the wrong build, and a sandbox that never dials in is a TTL expiry — the -//! same vocabulary every other failure in this system speaks (I5). -//! -//! The payload is an agent-sandbox-style Kubernetes CR (`runtimeClass: kata`, -//! `activeDeadlineSeconds` as the TTL the orchestrator enforces). It is a pure -//! function, unit-tested; the network call that sends it is exercised only by -//! the gated live tier, which skips — with a printed note, never a silent -//! pass — wherever a cluster is absent. -//! -//! The `LocalAgentProvisioner` is the shape this tier is tested with: a real -//! `sandbox-agent` process, real rendezvous, no VM. It is to kata what the -//! loopback backend is to a clean machine — the honest stand-in that keeps -//! the interface itself under test. - use std::collections::HashMap; use std::io::BufReader; use std::net::{TcpListener, TcpStream}; @@ -218,16 +196,12 @@ impl KataBackend { /// /// A Kata backend cannot share only its listener the way the plain remote /// backend does: it routes every dial-in by the nonce in its `Hello` into a - /// map that belongs to it, so two backends on one address would each see - /// half the dial-ins and neither could complete a rendezvous. So the whole - /// backend is shared, not just the socket — which is also what makes - /// "one listener per process" true here, since binding happens exactly once - /// per distinct configuration. + /// map that belongs to it, so two backends on one address would each see half + /// the dial-ins. The whole backend is therefore shared, and binding happens + /// exactly once per distinct configuration. /// /// The key is a digest of everything that distinguishes one backend from - /// another, so the rendezvous token and the cluster bearer are not sitting - /// around in a second place, and two configurations that differ only in - /// unrelated hub settings still get their own backend. + /// another, so the tokens are not sitting around in a second place. pub fn shared_for(cfg: &Config) -> Result<Arc<KataBackend>> { let crate::config::Sandbox::AgentSandbox { api, namespace, bearer, image, listen, token, .. } = &cfg.sandbox diff --git a/src/sandbox/loopback.rs b/src/sandbox/loopback.rs index 8e9f52d..8a3c229 100644 --- a/src/sandbox/loopback.rs +++ b/src/sandbox/loopback.rs @@ -1,16 +1,3 @@ -//! The loopback backend: run sandbox commands as local subprocesses. -//! -//! This is today's behavior wearing the new interface — same `Config::child_env` -//! shim protocol (§16a), same captured output, same process as the hub. It is -//! what `cargo test` exercises and what a single machine with devtools runs; -//! the shim suite passing unchanged through this file is what makes the seam a -//! pure refactor rather than a re-architecture. -//! -//! Isolation here is *none*: the "sandbox" is the hub's own user. That is -//! honest — the loopback backend is for development, tests, and the local -//! chroot deployment where §14's sudo rules are the boundary — and the Kata -//! backend is where the machine boundary lives. - use std::fs; use std::io::Read; use std::path::PathBuf; diff --git a/src/sandbox/mod.rs b/src/sandbox/mod.rs index 13cf282..ea3e126 100644 --- a/src/sandbox/mod.rs +++ b/src/sandbox/mod.rs @@ -1,29 +1,3 @@ -//! The sandbox seam: where build code actually runs (§8, remote-builder design). -//! -//! The pipeline executes untrusted recipe code, and the security boundary around -//! it has so far been "a chroot on this machine, with sudo rules" (§14). That -//! boundary is a *deployment* fact, not a pipeline fact: the step machine should -//! not know whether it is talking to a local process, a Kata container on a -//! cluster, or a loopback harness. So every subprocess the pipeline runs goes -//! through this interface instead of spawning one itself. -//! -//! Two implementations exist: -//! -//! * [`loopback::LoopbackBackend`] — today's behavior: commands run as local -//! subprocesses of the hub process, with the §16a shim protocol applied -//! through [`Config::child_env`]. This is what `cargo test` and a single -//! machine with devtools use. -//! * (planned) a Kata/agent-sandbox backend that leases disposable, TTL-bounded -//! sandboxes and speaks the wire protocol; the pipeline cannot tell the -//! difference, which is the entire point of the seam. -//! -//! The unit of isolation is a *sandbox lease*: [`SandboxBackend::acquire`] -//! hands out a handle, steps run commands on it, and the handle is destroyable -//! at any time. Nothing may assume a sandbox outlives its TTL, and nothing may -//! assume two tasks share one. Blob transfer is content-addressed by design: -//! there is no "path on the sandbox" concept in the interface at all, which -//! removes a class of hostile-write bugs that a path-based API would invite. - use std::collections::HashMap; use std::io::Read; use std::net::{TcpListener, TcpStream}; @@ -42,15 +16,14 @@ pub mod loopback; pub mod remote; pub mod wire; -/// A command to run inside a sandbox. Deliberately argv-shaped, not -/// `Command`-shaped: a remote sandbox must never be handed a shell string, and -/// the environment is the backend's business (see `Config::child_env`), not the -/// caller's. +/// A command to run inside a sandbox. Deliberately argv-shaped, never +/// shell-shaped: a remote sandbox must not be handed a shell string. The +/// environment is the backend's business (see `Config::child_env`). /// -/// An argv element of the form `blob:<digest>` names a content-addressed blob -/// staged with [`Sandbox::put`]: the backend expands it to wherever that blob -/// materializes inside the sandbox. Callers never name sandbox-local paths — -/// that is what keeps a loopback step byte-identical to a remote one. +/// An argv element of the form `blob:<digest>` names a blob staged with +/// [`Sandbox::put`]; the backend expands it to wherever the blob materializes +/// inside the sandbox. Callers never name sandbox-local paths, which is what +/// keeps a loopback step byte-identical to a remote one. #[derive(Debug, Clone)] pub struct Cmd { pub argv: Vec<String>, @@ -69,15 +42,12 @@ impl Cmd { self.cwd = Some(dir.into()); self } - /// The program name, for error messages. pub fn name(&self) -> &str { self.argv.first().map(String::as_str).unwrap_or("") } } -/// A finished command: exit status plus captured output. `code` is `None` when -/// the child died by signal — `success()` is false either way, matching what -/// `ExitStatus::success` would have said before the seam existed. +/// A finished command. `code` is `None` when the child died by signal. #[derive(Debug)] pub struct Exit { pub code: Option<i32>, @@ -92,11 +62,9 @@ impl Exit { } /// What a caller asks the pool for. `profile` is the only affinity key warm -/// pools need today (one warm root per build profile, §8.3); `task` is for -/// attribution and rendezvous, `ttl` is the guarantee that the sandbox is dead -/// no matter what this process then does, and `disk_mb` is the admission hint -/// that replaces the hub's local disk-headroom check (§8.2) once builds leave -/// the hub's filesystem. +/// pools need today (§8.3); `ttl` is the guarantee that the sandbox is dead no +/// matter what this process then does; `disk_mb` replaces the hub's local +/// disk-headroom check (§8.2) once builds leave the hub's filesystem. #[derive(Debug, Clone)] pub struct SandboxSpec { pub profile: String, @@ -111,7 +79,7 @@ impl SandboxSpec { } } -/// Pool state for the UI and notices: who is warm, who is busy, what profile. +/// Pool state for the UI and notices. #[derive(Debug, Clone)] pub struct SandboxInfo { pub id: String, @@ -121,37 +89,30 @@ pub struct SandboxInfo { /// A leased sandbox. `run` streams output through `on_log` as it arrives and /// also returns it captured, so a step can parse stdout while the build log -/// stays complete. `put`/`get` move content-addressed blobs in and out — the -/// hub pulls artifacts by digest and never accepts a destination path from a -/// sandbox, which is the same I9 posture the local staging-containment checks -/// already enforce. +/// stays complete. `put`/`get` move content-addressed blobs and never accept a +/// destination path from a sandbox — the same I9 posture the local staging +/// containment checks enforce. pub trait Sandbox: Send + Sync { fn id(&self) -> &str; fn run(&self, cmd: &Cmd, on_log: &mut dyn FnMut(&[u8])) -> Result<Exit>; fn put(&self, digest: &str, r: &mut dyn Read) -> Result<()>; fn get(&self, digest: &str) -> Result<Box<dyn Read>>; - /// Idempotent, and also happens by itself when the TTL bites. Destroying a - /// sandbox must never be the only thing standing between untrusted code and - /// the world. + /// Idempotent, and also happens by itself when the TTL bites. fn destroy(&self) -> Result<()>; } /// The pool. `acquire` may return a pre-warmed sandbox, cold-start one, or fail -/// when at quota; callers treat a failed acquire like a blocked build, not a -/// broken one. +/// when at quota; a failed acquire is a blocked build, not a broken one. pub trait SandboxBackend: Send + Sync { fn acquire(&self, spec: &SandboxSpec) -> Result<Arc<dyn Sandbox>>; fn status(&self) -> Result<Vec<SandboxInfo>>; } -/// Turn a configuration into the backend it names — the only place that does, -/// so "which backend" has exactly one answer. +/// Turn a configuration into the backend it names — the only place that does. /// /// `Config::validate` runs here as well as at startup: a guard that only exists -/// in the CLI is a guard a test, a tool, or a future daemon can walk past. -/// And an unknown or unwired kind is an error, never a fallthrough — a build -/// configured for a Kata VM that quietly ran as the hub's own user is the -/// failure this function used to have. +/// in the CLI is a guard a test or a future daemon can walk past. An unknown or +/// unwired kind is an error, never a fallthrough. pub fn backend_for(cfg: &Config) -> Result<Arc<dyn SandboxBackend>> { cfg.validate()?; match &cfg.sandbox { @@ -175,23 +136,17 @@ pub(crate) struct Bound { /// One bound listener per `(address, token)` per process. /// -/// The listener is a property of the *process*, not of a build. Binding it per -/// build — which is what happened while `Ctx::new` constructed a backend for -/// every build — meant a second concurrent build hit `EADDRINUSE` on a fixed -/// `listen` and failed for a reason that had nothing to do with its package. -/// Sharing the queue is also exactly the semantics the agent protocol has: an -/// agent dials in when it is booted, and whichever build is waiting takes it. -/// -/// The token is part of the key on purpose. Two different tokens cannot share a -/// listener, and reusing the first one's listener for a second, different token -/// would be a fail-open surprise; forcing a real bind makes the mistake loud. +/// The listener belongs to the process, not to a build: binding it per build +/// meant a second concurrent build hit `EADDRINUSE` for a reason unrelated to +/// its package. The token is part of the key because two different tokens +/// cannot share a listener, and silently reusing the first one's listener would +/// be a fail-open surprise. pub(crate) fn bound_listener(addr: &str, token: &str) -> Result<Bound> { static REGISTRY: OnceLock<Mutex<HashMap<(String, String), Bound>>> = OnceLock::new(); let registry = REGISTRY.get_or_init(|| Mutex::new(HashMap::new())); let key = (addr.to_string(), token.to_string()); - // A poisoned registry means a panic in some other thread's bind; the map - // itself is still sound, so recover rather than wedge every later build — - // the same posture as the publish lock. + // A poisoned registry means a panic in another thread's bind; the map is + // still sound, so recover rather than wedge every later build. let mut reg = registry.lock().unwrap_or_else(|p| p.into_inner()); if let Some(b) = reg.get(&key) { return Ok(b.clone()); diff --git a/src/sandbox/remote.rs b/src/sandbox/remote.rs index d02335c..1f9514f 100644 --- a/src/sandbox/remote.rs +++ b/src/sandbox/remote.rs @@ -1,24 +1,3 @@ -//! The hub side of the agent protocol: a [`SandboxBackend`] that leases -//! sandboxes which dial in from outside. -//! -//! The rendezvous is outbound-only: `acquire` waits for an agent to connect -//! and present the shared token, and every command since then is a frame on -//! the connection *the agent initiated*. A sandbox that vanishes mid-run is -//! not an error this code invents — a closed connection reads as a failed -//! step, which reads as an expired lease, which the reaper already turns into -//! a requeue (I5). The remote backend adds no new failure vocabulary. -//! -//! One connection is one lease: after `destroy` (or a drop of the hub side), -//! the agent dies and the next `acquire` waits for a fresh one. That matches -//! the disposable-sandbox model — warm pooling across steps of one build is -//! a backend optimization, not an interface requirement. -//! -//! Workspace note: `Run` frames carry a hub-side `cwd`, which is honest for -//! loopback-shaped deployments and the test tier where hub and sandbox share -//! a filesystem. A remote-over-the-network deployment needs the workspace -//! manifest/tar sync from the design sketch; that is deliberately not here -//! yet, and nothing should pretend otherwise. - use std::io::BufReader; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; diff --git a/src/sandbox/wire.rs b/src/sandbox/wire.rs index 4ea1c74..8f03063 100644 --- a/src/sandbox/wire.rs +++ b/src/sandbox/wire.rs @@ -1,19 +1,3 @@ -//! The hub↔sandbox wire protocol: length-prefixed JSON frames over a plain -//! socket, payloads hex-encoded. -//! -//! Deliberately boring, and deliberately dependency-free: one frame is a 4-byte -//! big-endian length followed by one JSON object. Binary payloads ride inside -//! the JSON as hex — twice the bytes of base64, but `hex` is already a -//! dependency and blobs (recipes, pinned packages) are small. A frame is -//! self-delimiting, so a reader that times out mid-frame cannot silently -//! desynchronize: the connection is dead, and a dead sandbox is a lease -//! expiry, which the reaper already knows how to handle (I5). -//! -//! The direction of connection matters: the *agent dials the hub*, never the -//! reverse. A sandbox is untrusted the moment it boots; the hub must never need -//! a route into it. Everything the hub wants — runs, blobs, teardown — is a -//! frame on the connection the agent initiated (outbound rendezvous). - use std::io::{self, BufRead, Write}; use serde::{Deserialize, Serialize}; @@ -33,18 +17,16 @@ pub enum Frame { /// hub → agent: rendezvous accepted; `ttl_secs` arms the agent's watchdog. HelloAck { ttl_secs: u64 }, /// hub → agent: run argv. `blob:<digest>` argv elements name blobs the - /// agent must have received via `Put`. `env` is the hub's child - /// environment (the §16a shim protocol rides on it in tests). + /// agent must already have via `Put`; `env` is the hub's child environment. Run { req: u64, argv: Vec<String>, cwd: Option<String>, env: Vec<(String, String)> }, /// agent → hub: a chunk of the running child's output, hex-encoded. Log { req: u64, stream: String, data: String }, /// agent → hub: the child finished. `code` is None when it died by signal. Exit { req: u64, code: Option<i32> }, - /// hub → agent: stage this content-addressed blob. The agent verifies - /// `data` hashes to `digest` before writing — the same posture the local - /// pacman fake enforces. + /// hub → agent: stage this blob. The agent verifies `data` hashes to + /// `digest` before writing. Put { req: u64, digest: String, data: String }, - /// hub → agent: pull this blob back out (artifacts come home by digest). + /// hub → agent: pull this blob back out. Get { req: u64, digest: String }, /// agent → hub: reply to `Get`. Blob { req: u64, data: String }, @@ -54,8 +36,7 @@ pub enum Frame { Err { req: u64, msg: String }, /// hub → agent: keepalive; resets the agent's TTL watchdog. Ping {}, - /// hub → agent: tear down now. The agent would also die on its own when - /// the connection drops — destroy is courtesy, TTL is the guarantee. + /// hub → agent: tear down now. TTL is the guarantee, this is courtesy. Destroy {}, } @@ -70,9 +51,8 @@ pub fn write_frame(w: &mut impl Write, f: &Frame) -> io::Result<()> { w.flush() } -/// Read one frame. `Ok(None)` means the peer closed the connection cleanly — -/// which, for a sandbox, is indistinguishable from "the sandbox is gone" and -/// therefore means the same thing to the hub: lease expired, requeue. +/// Read one frame. `Ok(None)` means a clean close, which for a sandbox means +/// the lease expired and the build should requeue. pub fn read_frame(r: &mut impl BufRead) -> io::Result<Option<Frame>> { let mut len = [0u8; 4]; match r.read_exact(&mut len) { @@ -130,8 +110,6 @@ mod tests { #[test] fn a_truncated_frame_is_an_error_not_a_silent_none() { - // Half a frame on the wire must read as a dead connection through an - // error path, never as a parsed frame. let mut buf = Vec::new(); write_frame(&mut buf, &Frame::Ping {}).unwrap(); buf.truncate(3); |
