//! 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 }, /// hub → agent: rendezvous accepted; `ttl_secs` arms the agent's watchdog. HelloAck { ttl_secs: u64 }, /// hub → agent: run argv. `blob:` 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, cwd: Option, 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 }, /// 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> { 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> { 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()); } }