diff options
| author | aur-build <aur-build@localhost> | 2026-11-19 11:36:36 +0000 |
|---|---|---|
| committer | aur-build <aur-build@localhost> | 2026-11-19 11:36:36 +0000 |
| commit | 3374ffd34921e1de414e8b07f69753113f5ba5f9 (patch) | |
| tree | ea60c89b4e80d9c690761eb6399f2ddcfad56daa /src/sandbox | |
| parent | bc8f069d18c5de3dee04ae303227a255248efc1e (diff) | |
| download | aur-build-3374ffd34921e1de414e8b07f69753113f5ba5f9.tar.gz aur-build-3374ffd34921e1de414e8b07f69753113f5ba5f9.zip | |
sandbox: ephemeral agent, wire protocol, and the hub's remote backend
The seam from the previous commits only had one body. This adds the
other one: a sandbox-agent binary that dials the hub (outbound
rendezvous — the hub never needs a route into an untrusted box), serves
Run/Put/Get frames over length-prefixed JSON, streams the child's
stdout/stderr as they fill, and dies — taking its child with it — when
the connection drops or its TTL expires. The TTL watchdog is the
backstop under every leak: hub crash, partition, a forgotten destroy.
Hub side, RemoteBackend implements the same SandboxBackend: acquire
waits for a dial-in and verifies the shared token and profile before a
lease exists; a vanished sandbox fails the step, which is already the
shape of an expired lease (I5), so the remote path adds no new failure
vocabulary. Run frames carry the hub's child environment, so the §16a
shim protocol reaches remote children exactly as local ones — which is
what makes the end-to-end test honest: a real build, real frames, real
log streaming into the SSE-tailed file, no root and no container.
Workspace sync over the wire is deliberately not here: Run carries a
hub-side cwd, honest for loopback-shaped deployments and this test
tier, and the module says so rather than pretending.
Diffstat (limited to 'src/sandbox')
| -rw-r--r-- | src/sandbox/agent.rs | 279 | ||||
| -rw-r--r-- | src/sandbox/mod.rs | 3 | ||||
| -rw-r--r-- | src/sandbox/remote.rs | 240 | ||||
| -rw-r--r-- | src/sandbox/wire.rs | 141 |
4 files changed, 663 insertions, 0 deletions
diff --git a/src/sandbox/agent.rs b/src/sandbox/agent.rs new file mode 100644 index 0000000..3964d2c --- /dev/null +++ b/src/sandbox/agent.rs @@ -0,0 +1,279 @@ +//! 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}; +use std::process::Stdio; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use crossbeam_channel::unbounded; + +use crate::error::{Error, Result}; +use crate::sandbox::wire::{self, Frame}; + +/// CLI-shaped arguments for the `sandbox-agent` binary. +#[derive(Debug, Clone)] +pub struct AgentOptions { + pub hub: String, + pub token: String, + pub profile: String, + pub ttl: Duration, +} + +pub fn serve(opts: &AgentOptions) -> Result<()> { + let stream = connect_with_retry(&opts.hub, Duration::from_secs(15))?; + let agent_id = format!("sandbox-{}", std::process::id()); + wire::write_frame( + &mut stream.try_clone()?, + &Frame::Hello { + token: opts.token.clone(), + agent_id: agent_id.clone(), + profiles: vec![opts.profile.clone()], + }, + )?; + + let mut reader = BufReader::new(stream.try_clone()?); + let writer = Arc::new(Mutex::new(stream)); + let ttl = match wire::read_frame(&mut reader)? { + Some(Frame::HelloAck { ttl_secs }) => Duration::from_secs(ttl_secs.max(1)), + Some(other) => return Err(Error::invalid(format!("agent: expected hello_ack, got {other:?}"))), + None => return Err(Error::other("agent: hub closed the connection at rendezvous")), + }; + + let blobs = blob_dir(&agent_id); + std::fs::create_dir_all(&blobs)?; + + // Shared watchdog state: the reader thread stamps every inbound frame; + // the watchdog exits (killing the child) when the hub goes silent. + let last_inbound = Arc::new(Mutex::new(Instant::now())); + let child = Arc::new(Mutex::new(None::<u32>)); + let alive = Arc::new(AtomicBool::new(true)); + { + let (last, child, alive, ttl) = + (last_inbound.clone(), child.clone(), alive.clone(), ttl); + std::thread::spawn(move || loop { + std::thread::sleep(Duration::from_millis(1000)); + let quiet = last.lock().unwrap().elapsed(); + if quiet > ttl { + eprintln!("agent: hub silent for {quiet:?} past the TTL; dying"); + if let Some(pid) = *child.lock().unwrap() { + unsafe { + libc::kill(pid as i32, libc::SIGKILL); + } + } + std::process::exit(1); + } + if !alive.load(Ordering::Relaxed) { + return; + } + }); + } + + let mut outcome = Ok(()); + loop { + let frame = match wire::read_frame(&mut reader) { + Ok(Some(f)) => f, + Ok(None) => break, // hub hung up: the lease is over + Err(e) => { + outcome = Err(e.into()); + break; + } + }; + *last_inbound.lock().unwrap() = Instant::now(); + let stop = match handle(frame, &writer, &blobs, &child) { + Ok(stop) => stop, + Err(e) => { + outcome = Err(e); + break; + } + }; + if stop { + break; + } + } + alive.store(false, Ordering::Relaxed); + // Whatever we were running dies with us, always. + if let Some(pid) = *child.lock().unwrap() { + unsafe { + libc::kill(pid as i32, libc::SIGKILL); + } + } + let _ = std::fs::remove_dir_all(&blobs); + outcome +} + +/// Returns true when the agent should stop (Destroy / fatal child loss). +fn handle( + frame: Frame, + writer: &Arc<Mutex<TcpStream>>, + blobs: &Path, + child: &Arc<Mutex<Option<u32>>>, +) -> Result<bool> { + match frame { + Frame::Destroy {} => Ok(true), + Frame::Ping {} => Ok(false), + Frame::Put { req, digest, data } => { + let bytes = wire::unhex(&data).map_err(io_err)?; + // The agent verifies content-addressing on its side too: a blob + // that does not hash to its name is refused, not staged. + if crate::hash::hex(&bytes) != digest { + reply(writer, req, Err("put: data does not hash to the claimed digest"))?; + return Ok(false); + } + std::fs::write(safe_blob_path(blobs, &digest)?, &bytes)?; + reply(writer, req, Ok(()))?; + Ok(false) + } + Frame::Get { req, digest } => match std::fs::read(safe_blob_path(blobs, &digest)?) { + Ok(bytes) => { + wire::write_frame(writer.lock().unwrap().deref_mut(), &Frame::Blob { req, data: wire::hex_bytes(&bytes) })?; + Ok(false) + } + Err(_) => { + reply(writer, req, Err("get: no such blob"))?; + Ok(false) + } + }, + Frame::Run { req, argv, cwd, env } => { + run_child(req, argv, cwd, env, writer, blobs, child)?; + Ok(false) + } + other => Err(Error::invalid(format!("agent: unexpected frame {other:?}"))), + } +} + +fn run_child( + req: u64, + argv: Vec<String>, + cwd: Option<String>, + env: Vec<(String, String)>, + writer: &Arc<Mutex<TcpStream>>, + blobs: &Path, + child: &Arc<Mutex<Option<u32>>>, +) -> Result<()> { + let mut argv = argv; + // Expand `blob:<digest>` argv elements, like the loopback backend does. + for a in argv.iter_mut() { + if let Some(digest) = a.strip_prefix("blob:") { + *a = safe_blob_path(blobs, digest)?.display().to_string(); + } + } + let program = argv.first().ok_or_else(|| Error::invalid("run: empty argv"))?; + let mut c = std::process::Command::new(program); + c.args(&argv[1..]) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + if let Some(dir) = cwd { + c.current_dir(dir); + } + for (k, v) in env { + c.env(k, v); + } + let mut proc = c.spawn()?; + *child.lock().unwrap() = Some(proc.id()); + + // Stream both pipes as they fill: readers hand chunks to the frame writer + // over a channel, so a chatty build never blocks on the socket and vice + // versa. + let (tx, rx) = unbounded::<(&'static str, Vec<u8>)>(); + let mut pipes = Vec::new(); + let pipes_spec: [(&'static str, Option<Box<dyn std::io::Read + Send>>); 2] = [ + ("stdout", proc.stdout.take().map(|r| Box::new(r) as Box<dyn std::io::Read + Send>)), + ("stderr", proc.stderr.take().map(|r| Box::new(r) as Box<dyn std::io::Read + Send>)), + ]; + for (name, pipe) in pipes_spec { + if let Some(mut pipe) = pipe { + let tx = tx.clone(); + pipes.push(std::thread::spawn(move || { + use std::io::Read; + let mut buf = [0u8; 8192]; + loop { + match pipe.read(&mut buf) { + Ok(0) | Err(_) => break, + Ok(n) => { + if tx.send((name, buf[..n].to_vec())).is_err() { + break; + } + } + } + } + })); + } + } + drop(tx); + while let Ok((stream, bytes)) = rx.recv() { + wire::write_frame( + writer.lock().unwrap().deref_mut(), + &Frame::Log { req, stream: stream.to_string(), data: wire::hex_bytes(&bytes) }, + )?; + } + for p in pipes { + let _ = p.join(); + } + let status = proc.wait()?; + *child.lock().unwrap() = None; + wire::write_frame( + writer.lock().unwrap().deref_mut(), + &Frame::Exit { req, code: status.code() }, + )?; + Ok(()) +} + +fn reply(writer: &Arc<Mutex<TcpStream>>, req: u64, result: std::result::Result<(), &str>) -> Result<()> { + let frame = match result { + Ok(()) => Frame::Ok { req }, + Err(msg) => Frame::Err { req, msg: msg.to_string() }, + }; + wire::write_frame(writer.lock().unwrap().deref_mut(), &frame)?; + Ok(()) +} + +fn connect_with_retry(hub: &str, for_long: Duration) -> std::result::Result<TcpStream, Error> { + let deadline = Instant::now() + for_long; + loop { + match TcpStream::connect(hub) { + Ok(s) => return Ok(s), + Err(_) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(100)), + Err(e) => return Err(Error::other(format!("agent: cannot reach hub {hub}: {e}"))), + } + } +} + +/// Blob scratch, removed when the lease ends. +fn blob_dir(agent_id: &str) -> PathBuf { + std::env::temp_dir().join(format!("aur-{agent_id}-blobs")) +} + +/// Digests are the only blob names, and they must stay path-safe — the same +/// rule the loopback backend enforces, so a hostile frame cannot escape the +/// blob directory. +fn safe_blob_path(blobs: &Path, digest: &str) -> Result<PathBuf> { + if digest.is_empty() + || digest.len() > 128 + || !digest.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') + { + return Err(Error::fail_closed(format!("blob digest {digest:?} is not usable"))); + } + Ok(blobs.join(digest)) +} + +fn io_err(e: std::io::Error) -> Error { + Error::other(e.to_string()) +} + +use std::ops::DerefMut; diff --git a/src/sandbox/mod.rs b/src/sandbox/mod.rs index 5be5f4f..89bef23 100644 --- a/src/sandbox/mod.rs +++ b/src/sandbox/mod.rs @@ -31,7 +31,10 @@ use std::time::Duration; use crate::error::Result; +pub mod agent; 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 diff --git a/src/sandbox/remote.rs b/src/sandbox/remote.rs new file mode 100644 index 0000000..c1ad998 --- /dev/null +++ b/src/sandbox/remote.rs @@ -0,0 +1,240 @@ +//! 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::net::TcpListener; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; + +use crossbeam_channel::Receiver; + +use crate::config::Config; +use crate::error::{Error, Result}; +use crate::sandbox::wire::{self, Frame}; +use crate::sandbox::{Exit, Sandbox, SandboxBackend, SandboxInfo, SandboxSpec}; + +pub struct RemoteBackend { + cfg: Config, + token: String, + addr: String, + /// Connections the accept thread has taken off the listener but not yet + /// rendezvoused. `acquire` waits on this up to the spec's TTL. + queue: Receiver<std::net::TcpStream>, +} + +impl RemoteBackend { + /// Bind the agent listener. `addr` may name port 0; [`Self::local_addr`] + /// reports what actually got bound, which is how a test (or a supervisor) + /// hands the address to the agent without a port negotiation dance. + pub fn bind(cfg: &Config, addr: &str, token: &str) -> Result<Self> { + let listener = TcpListener::bind(addr)?; + let local = listener.local_addr()?.to_string(); + let (tx, rx) = crossbeam_channel::unbounded(); + std::thread::spawn(move || { + for stream in listener.incoming() { + match stream { + Ok(s) => { + let _ = tx.send(s); + } + Err(_) => break, + } + } + }); + Ok(Self { cfg: cfg.clone(), token: token.to_string(), addr: local, queue: rx }) + } + + pub fn local_addr(&self) -> &str { + &self.addr + } +} + +impl SandboxBackend for RemoteBackend { + fn acquire(&self, spec: &SandboxSpec) -> Result<Arc<dyn Sandbox>> { + let stream = self.queue.recv_timeout(spec.ttl).map_err(|_| { + Error::other(format!( + "no sandbox connected to {} within the lease window", + self.addr + )) + })?; + // The rendezvous itself is bounded; the run loop is not (pings keep + // the agent's watchdog fed, and a dead agent fails the step anyway). + let _ = stream.set_read_timeout(Some(spec.ttl)); + let mut reader = BufReader::new(stream.try_clone()?); + let agent_id = match wire::read_frame(&mut reader)? { + Some(Frame::Hello { token, agent_id, profiles }) => { + if token != self.token { + return Err(Error::fail_closed(format!( + "sandbox {agent_id} presented the wrong token" + ))); + } + if !profiles.is_empty() && !profiles.contains(&spec.profile) { + return Err(Error::fail_closed(format!( + "sandbox {agent_id} serves {profiles:?}, not profile {}", + spec.profile + ))); + } + agent_id + } + Some(other) => return Err(Error::invalid(format!("expected hello, got {other:?}"))), + None => return Err(Error::other("sandbox disconnected at rendezvous")), + }; + wire::write_frame(&mut stream.try_clone()?, &Frame::HelloAck { ttl_secs: spec.ttl.as_secs().max(1) })?; + let _ = stream.set_read_timeout(None); + Ok(Arc::new(RemoteSandbox { + cfg: self.cfg.clone(), + id: agent_id, + ttl: spec.ttl, + reader: Mutex::new(reader), + writer: Mutex::new(stream), + req: AtomicU64::new(1), + })) + } + + fn status(&self) -> Result<Vec<SandboxInfo>> { + Ok(vec![SandboxInfo { + id: format!("remote@{}", self.addr), + profile: self.cfg.build_profile.clone(), + warm: !self.queue.is_empty(), + }]) + } +} + +pub struct RemoteSandbox { + cfg: Config, + id: String, + ttl: std::time::Duration, + reader: Mutex<BufReader<std::net::TcpStream>>, + writer: Mutex<std::net::TcpStream>, + req: AtomicU64, +} + +impl RemoteSandbox { + fn send(&self, frame: &Frame) -> Result<()> { + wire::write_frame(&mut *self.writer.lock().unwrap(), frame).map_err(Into::into) + } + + /// Read frames until a reply for `req` arrives. `Log` frames for that + /// request are handed to `sink` (stream name + bytes) as they arrive, so + /// the caller gets live streaming *and* can accumulate what it needs. + fn pump(&self, req: u64, sink: &mut dyn FnMut(&str, &[u8])) -> Result<Frame> { + loop { + let frame = match wire::read_frame(&mut *self.reader.lock().unwrap())? { + Some(f) => f, + None => return Err(Error::other(format!("sandbox {} vanished", self.id))), + }; + match frame { + Frame::Log { req: r, ref stream, ref data } if r == req => { + sink(stream, &wire::unhex(data)?); + } + Frame::Exit { req: r, .. } + | Frame::Blob { req: r, .. } + | Frame::Ok { req: r } + | Frame::Err { req: r, .. } + if r == req => + { + return Ok(frame) + } + _ => {} // Ping echoes and foreign requests are not ours + } + } + } +} + +impl Sandbox for RemoteSandbox { + fn id(&self) -> &str { + &self.id + } + + fn run(&self, cmd: &crate::sandbox::Cmd, on_log: &mut dyn FnMut(&[u8])) -> Result<Exit> { + let req = self.req.fetch_add(1, Ordering::SeqCst); + self.send(&Frame::Run { + req, + argv: cmd.argv.clone(), + cwd: cmd.cwd.as_ref().map(|p| p.display().to_string()), + env: self.cfg.child_env_pairs(), + })?; + // Keepalive: the agent's watchdog expects a frame at least every TTL; + // a long build produces none of its own on the control connection. + let stop = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let mut writer = self.writer.lock().unwrap().try_clone()?; + { + let (stop, interval) = (stop.clone(), self.ttl / 3); + std::thread::spawn(move || { + while !stop.load(Ordering::SeqCst) { + std::thread::sleep(interval.max(std::time::Duration::from_millis(50))); + if stop.load(Ordering::SeqCst) { + break; + } + if wire::write_frame(&mut writer, &Frame::Ping {}).is_err() { + break; + } + } + }); + } + let mut stdout = Vec::new(); + let mut stderr = Vec::new(); + let result = self.pump(req, &mut |stream, bytes| { + // The build log gets bytes in arrival order; the captured halves + // keep stdout and stderr apart so error tails name the right one, + // exactly like the loopback sandbox's Exit. + on_log(bytes); + if stream == "stderr" { + stderr.extend_from_slice(bytes); + } else { + stdout.extend_from_slice(bytes); + } + }); + stop.store(true, Ordering::SeqCst); + match result? { + Frame::Exit { code, .. } => Ok(Exit { code, stdout, stderr }), + Frame::Err { msg, .. } => Err(Error::other(format!("sandbox {}: {msg}", self.id))), + other => Err(Error::invalid(format!("sandbox {}: unexpected {other:?}", self.id))), + } + } + + fn put(&self, digest: &str, r: &mut dyn std::io::Read) -> Result<()> { + let req = self.req.fetch_add(1, Ordering::SeqCst); + let mut buf = Vec::new(); + r.read_to_end(&mut buf)?; + self.send(&Frame::Put { req, digest: digest.to_string(), data: wire::hex_bytes(&buf) })?; + match self.pump(req, &mut |_, _| {})? { + Frame::Ok { .. } => Ok(()), + Frame::Err { msg, .. } => Err(Error::fail_closed(format!("sandbox {}: {msg}", self.id))), + other => Err(Error::invalid(format!("sandbox {}: unexpected {other:?}", self.id))), + } + } + + fn get(&self, digest: &str) -> Result<Box<dyn std::io::Read>> { + let req = self.req.fetch_add(1, Ordering::SeqCst); + self.send(&Frame::Get { req, digest: digest.to_string() })?; + match self.pump(req, &mut |_, _| {})? { + Frame::Blob { data, .. } => Ok(Box::new(std::io::Cursor::new(wire::unhex(&data)?))), + Frame::Err { msg, .. } => Err(Error::other(format!("sandbox {}: {msg}", self.id))), + other => Err(Error::invalid(format!("sandbox {}: unexpected {other:?}", self.id))), + } + } + + fn destroy(&self) -> Result<()> { + // Best effort: a sandbox that is already gone has nothing to destroy. + let _ = self.send(&Frame::Destroy {}); + Ok(()) + } +} diff --git a/src/sandbox/wire.rs b/src/sandbox/wire.rs new file mode 100644 index 0000000..4ea1c74 --- /dev/null +++ b/src/sandbox/wire.rs @@ -0,0 +1,141 @@ +//! 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}; + +/// Refuse absurd frames before allocating for them. Blobs ride as hex inside +/// the frame, so this bounds a real package at ~2 GiB of hex — far above +/// anything legitimate, far below "accept whatever the sandbox sends". +pub const MAX_FRAME_BYTES: u32 = 2 * 1024 * 1024 * 1024; + +/// One protocol frame. `req` correlates a reply with a request; unsolicited +/// frames (`Ping`, `Hello`, `HelloAck`) carry none. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(tag = "t", rename_all = "snake_case")] +pub enum Frame { + /// agent → hub, first frame on every connection: the outbound rendezvous. + Hello { token: String, agent_id: String, profiles: Vec<String> }, + /// 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). + 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. + Put { req: u64, digest: String, data: String }, + /// hub → agent: pull this blob back out (artifacts come home by digest). + Get { req: u64, digest: String }, + /// agent → hub: reply to `Get`. + Blob { req: u64, data: String }, + /// agent → hub: generic success for `Put`/`Get`. + Ok { req: u64 }, + /// agent → hub: generic failure. + 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. + Destroy {}, +} + +pub fn write_frame(w: &mut impl Write, f: &Frame) -> io::Result<()> { + let body = serde_json::to_vec(f) + .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?; + if body.len() as u64 > MAX_FRAME_BYTES as u64 { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "frame too large")); + } + w.write_all(&(body.len() as u32).to_be_bytes())?; + w.write_all(&body)?; + 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. +pub fn read_frame(r: &mut impl BufRead) -> io::Result<Option<Frame>> { + let mut len = [0u8; 4]; + match r.read_exact(&mut len) { + Ok(()) => {} + Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => return Ok(None), + Err(e) => return Err(e), + } + let n = u32::from_be_bytes(len) as usize; + if n as u32 > MAX_FRAME_BYTES { + return Err(io::Error::new(io::ErrorKind::InvalidData, "frame too large")); + } + let mut body = vec![0u8; n]; + r.read_exact(&mut body)?; + let f: Frame = serde_json::from_slice(&body) + .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?; + Ok(Some(f)) +} + +pub fn hex_bytes(b: &[u8]) -> String { + hex::encode(b) +} + +pub fn unhex(s: &str) -> io::Result<Vec<u8>> { + hex::decode(s).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn frames_round_trip_through_a_byte_stream() { + let mut buf = Vec::new(); + write_frame(&mut buf, &Frame::Hello { token: "t".into(), agent_id: "a".into(), profiles: vec!["p".into()] }).unwrap(); + write_frame(&mut buf, &Frame::Log { req: 7, stream: "stdout".into(), data: hex_bytes(b"hello") }).unwrap(); + write_frame(&mut buf, &Frame::Exit { req: 7, code: Some(0) }).unwrap(); + let mut cur = std::io::BufReader::new(std::io::Cursor::new(buf)); + match read_frame(&mut cur).unwrap().unwrap() { + Frame::Hello { token, .. } => assert_eq!(token, "t"), + other => panic!("{other:?}"), + } + match read_frame(&mut cur).unwrap().unwrap() { + Frame::Log { req, data, .. } => { + assert_eq!(req, 7); + assert_eq!(unhex(&data).unwrap(), b"hello"); + } + other => panic!("{other:?}"), + } + match read_frame(&mut cur).unwrap().unwrap() { + Frame::Exit { req, code } => assert_eq!((req, code), (7, Some(0))), + other => panic!("{other:?}"), + } + assert!(read_frame(&mut cur).unwrap().is_none(), "clean close reads as None"); + } + + #[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); + let mut cur = std::io::BufReader::new(std::io::Cursor::new(buf)); + assert!(read_frame(&mut cur).is_err() || read_frame(&mut cur).unwrap().is_none()); + } +} |
