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 already have via `Put`; `env` is the hub's child environment. 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 blob. The agent verifies `data` hashes to /// `digest` before writing. Put { req: u64, digest: String, data: String }, /// hub → agent: pull this blob back out. 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. TTL is the guarantee, this is courtesy. 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 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> { 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() { 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()); } }