diff options
Diffstat (limited to 'src/sandbox/agent.rs')
| -rw-r--r-- | src/sandbox/agent.rs | 279 |
1 files changed, 279 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; |
