diff --git a/src/api_client.rs b/src/api_client.rs index 8c67494..1cf6b74 100644 --- a/src/api_client.rs +++ b/src/api_client.rs @@ -25,6 +25,9 @@ fn timezone_header() -> reqwest::header::HeaderMap { headers } +/// The longest `floo sandboxes create` waits: an image's first build, under the API's own limit. +const SANDBOX_CREATE_WAIT: Duration = Duration::from_secs(26 * 60); + impl FlooClient { pub fn new(config: Option) -> Result { let config = config.unwrap_or_else(load_config); @@ -1436,6 +1439,69 @@ impl FlooClient { self.handle_response_value(resp) } + /// Create a sandbox. Its image builds the first time it is asked for, which + /// can take minutes, so this waits as long as the API does. + pub fn create_sandbox(&self, body: &Value) -> Result { + let req = self.client.post(self.url("/v1/orgs/sandboxes")).json(body); + let resp = self.send_waiting(req, SANDBOX_CREATE_WAIT)?; + self.handle_response_value(resp) + } + + /// Run a command in a sandbox and wait for it to end, up to its own timeout. + pub fn exec_in_sandbox( + &self, + sandbox_id: &str, + body: &Value, + timeout_secs: u64, + ) -> Result { + let path = format!("/v1/orgs/sandboxes/{sandbox_id}/exec"); + let req = self.client.post(self.url(&path)).json(body); + let resp = self.send_waiting(req, Duration::from_secs(timeout_secs + 60))?; + self.handle_response_value(resp) + } + + pub fn list_sandbox_files(&self, sandbox_id: &str, path: &str) -> Result { + let url = format!("/v1/orgs/sandboxes/{sandbox_id}/files"); + let resp = self.get_with_query(&url, &[("path", path)])?; + self.handle_response_value(resp) + } + + pub fn read_sandbox_file(&self, sandbox_id: &str, path: &str) -> Result { + let url = format!("/v1/orgs/sandboxes/{sandbox_id}/files/content"); + let resp = self.get_with_query(&url, &[("path", path)])?; + self.handle_response_value(resp) + } + + pub fn write_sandbox_file( + &self, + sandbox_id: &str, + path: &str, + body: &Value, + ) -> Result<(), FlooApiError> { + let url = format!("/v1/orgs/sandboxes/{sandbox_id}/files/content"); + let req = self + .client + .put(self.url(&url)) + .query(&[("path", path)]) + .json(body); + let resp = self.send_waiting(req, Duration::from_secs(120))?; + if !resp.status().is_success() { + self.handle_response_value(resp)?; + } + Ok(()) + } + + /// Send a request that may take longer than the client's usual 30 s. + fn send_waiting( + &self, + req: reqwest::blocking::RequestBuilder, + wait: Duration, + ) -> Result { + self.apply_headers(req.timeout(wait)) + .send() + .map_err(|e| FlooApiError::new(0, "CONNECTION_ERROR", e.to_string())) + } + pub fn terminate_sandbox(&self, sandbox_id: &str) -> Result<(), FlooApiError> { let path = format!("/v1/orgs/sandboxes/{sandbox_id}/terminate"); let resp = self.post_json(&path, &serde_json::json!({}))?; diff --git a/src/cli.rs b/src/cli.rs index 020e7a1..166ba05 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -573,18 +573,22 @@ read-only + manual trigger; new jobs are added by editing config and deploying." #[command(subcommand)] Events(EventsCommands), - /// Find your running sandboxes, read what one printed, tag it, or end it. + /// Create sandboxes, run commands and copy files in them, find them, and end them. #[command( subcommand, after_help = "\ Examples: - floo sandboxes list Every running sandbox in the org + floo sandboxes create --app agents Prints the new sandbox's id + floo sandboxes exec sb-abc123 -- python -c 'print(1 + 1)' + floo sandboxes cp ./app.py sb-abc123:/work/app.py + floo sandboxes cp sb-abc123:/work/out.json ./out.json + floo sandboxes ls sb-abc123 /work floo sandboxes list --app agents --tag task=build floo sandboxes logs sb-abc123 What its own command printed last floo sandboxes tag sb-abc123 task=build user=ada floo sandboxes terminate sb-abc123 End it (asks you to type its id) -Programs create sandboxes with the floo-sandbox SDK (pip or npm); the CLI never does." +Programs do the same with the floo-sandbox SDK (pip or npm)." )] Sandboxes(SandboxesCommands), @@ -1836,6 +1840,88 @@ Examples: #[derive(Subcommand)] pub enum SandboxesCommands { + /// Create a sandbox and print its ID. + /// + /// It is only files until a command runs: a machine attaches for each + /// command and lets go soon after, so an idle sandbox bills no compute. + Create { + /// The app it belongs to, by name. Made if the org has none by that name. + #[arg(short, long)] + app: String, + + /// A Dockerfile to build its image from. Default: Debian with Python + /// 3.13, pip, uv and a compiler. + #[arg(long, value_name = "FILE")] + image_file: Option, + + /// small (1 vCPU, 512 MiB), medium (2 vCPUs, 2 GiB) or large (4 vCPUs, 4 GiB). + #[arg(long, default_value = "small", value_parser = ["small", "medium", "large"])] + size: String, + + /// Seconds it lives before it ends, up to 86400. + #[arg(long, default_value_t = 600)] + timeout: u64, + + /// A variable every command in it runs with, as NAME=VALUE. Repeatable. + #[arg(long = "env", value_name = "NAME=VALUE")] + env: Vec, + + /// A name unique among the app's running sandboxes. + #[arg(long)] + name: Option, + + /// A tag to list it by, as name=value. Repeatable. + #[arg(long = "tag", value_name = "NAME=VALUE")] + tags: Vec, + }, + + /// Run a command in a sandbox, print its output, and exit with its exit code. + /// + /// Put the command after `--`. It runs as given, with no shell: use + /// `sh -c '...'` for pipes and `&&`. + Exec { + /// The sandbox's ID, from `floo sandboxes create` or `list`. + sandbox_id: String, + + /// The directory it runs in. + #[arg(short, long)] + workdir: Option, + + /// A variable it runs with, as NAME=VALUE. Repeatable. + #[arg(long = "env", value_name = "NAME=VALUE")] + env: Vec, + + /// Seconds it may run before it is ended, up to 1500. + #[arg(long, default_value_t = 300)] + timeout: u64, + + /// The program and its arguments. + #[arg(last = true, required = true, value_name = "COMMAND")] + command: Vec, + }, + + /// Copy a file into or out of a sandbox. + /// + /// Write the sandbox side as ID:/path. The local side may be `-` for + /// stdin or stdout. Missing directories in the sandbox are made. + Cp { + /// Where to copy from: a local path, `-`, or ID:/path. + source: String, + + /// Where to copy to: a local path, `-`, or ID:/path. + destination: String, + }, + + /// List what a directory in a sandbox holds. + Ls { + /// The sandbox's ID, from `floo sandboxes create` or `list`. + sandbox_id: String, + + /// The directory, as an absolute path. + #[arg(default_value = "/")] + path: String, + }, + /// List the org's sandboxes that have not finished, newest first. List { /// Only this app's sandboxes (name or ID). @@ -2811,6 +2897,39 @@ pub fn run() { }, Commands::Sandboxes(sub) => match sub { + SandboxesCommands::Create { + app, + image_file, + size, + timeout, + env, + name, + tags, + } => commands::sandboxes::create(&commands::sandboxes::CreateArgs { + app: &app, + image_file: image_file.as_deref(), + size: &size, + timeout, + env: &env, + name: name.as_deref(), + tags: &tags, + }), + SandboxesCommands::Exec { + sandbox_id, + workdir, + env, + timeout, + command, + } => { + commands::sandboxes::exec(&sandbox_id, &command, workdir.as_deref(), &env, timeout) + } + SandboxesCommands::Cp { + source, + destination, + } => commands::sandboxes::cp(&source, &destination), + SandboxesCommands::Ls { sandbox_id, path } => { + commands::sandboxes::ls(&sandbox_id, &path) + } SandboxesCommands::List { app, tags } => { commands::sandboxes::list(app.as_deref(), &tags) } diff --git a/src/commands/sandboxes.rs b/src/commands/sandboxes.rs index 4313ae3..9aca6c2 100644 --- a/src/commands/sandboxes.rs +++ b/src/commands/sandboxes.rs @@ -1,9 +1,12 @@ -//! `floo sandboxes`: find an org's running sandboxes, read what one printed, tag -//! it, and end it. Sandboxes are made by programs with the `floo-sandbox` SDK; -//! the CLI never creates one. +//! `floo sandboxes`: create a sandbox, run commands in it, copy files in and +//! out, find the org's running sandboxes, read what one printed, tag it, and end +//! it. Programs can do the same with the `floo-sandbox` SDK. +use std::io::{Read, Write}; use std::process; +use base64::Engine; + use serde_json::Value; use crate::api_client::FlooClient; @@ -11,6 +14,236 @@ use crate::confirm::{confirm_tier3, ConfirmOutcome, RiskMetadata, Tier}; use crate::errors::{ErrorCode, FlooApiError}; use crate::output; +/// What `floo sandboxes create` asks for. +pub struct CreateArgs<'a> { + pub app: &'a str, + pub image_file: Option<&'a str>, + pub size: &'a str, + pub timeout: u64, + pub env: &'a [String], + pub name: Option<&'a str>, + pub tags: &'a [String], +} + +/// Create a sandbox and print its ID: on stdout alone, so scripts can take it. +pub fn create(args: &CreateArgs) { + let image = args.image_file.map(|file| { + std::fs::read_to_string(file).unwrap_or_else(|e| { + output::error( + &format!("Could not read the Dockerfile '{file}': {e}"), + &ErrorCode::FileError, + None, + ); + process::exit(1); + }) + }); + let body = serde_json::json!({ + "app": args.app, + "image": image, + "size": args.size, + "timeout": args.timeout, + "env": pairs(args.env, "--env", "PORT=8000"), + "name": args.name, + "tags": pairs(args.tags, "--tag", "task=build"), + }); + if !output::is_json_mode() { + output::info( + "Creating the sandbox. A new image's first build takes a few minutes.", + None, + ); + } + let created = call(|client| client.create_sandbox(&body)); + if output::is_json_mode() { + output::success("Created the sandbox.", Some(created)); + return; + } + output::raw_value(&field(&created, "id")); +} + +/// Run a command in a sandbox and wait for it. Its stdout and stderr are printed +/// where it wrote them, and the CLI exits with its exit code. +pub fn exec( + sandbox_id: &str, + command: &[String], + workdir: Option<&str>, + env: &[String], + timeout: u64, +) { + let body = serde_json::json!({ + "command": command, + "workdir": workdir, + "env": pairs(env, "--env", "DEBUG=1"), + "timeout": timeout, + }); + let result = call(|client| client.exec_in_sandbox(sandbox_id, &body, timeout)); + let code = result.get("exit_code").and_then(Value::as_i64).unwrap_or(1); + if output::is_json_mode() { + output::success("Ran the command.", Some(result)); + } else { + output::printed( + result.get("stdout").and_then(Value::as_str).unwrap_or(""), + false, + ); + output::printed( + result.get("stderr").and_then(Value::as_str).unwrap_or(""), + true, + ); + if result.get("timed_out").and_then(Value::as_bool) == Some(true) { + output::warn(&format!( + "The command ran past its {timeout} s timeout and was ended." + )); + } + if result.get("truncated").and_then(Value::as_bool) == Some(true) { + output::warn("It printed more than 1 MiB to a stream: only the last MiB is shown."); + } + } + let _ = std::io::stdout().flush(); + // A shell takes an exit code modulo 256: -1 (timed out) exits 255. + process::exit(i32::try_from(code.rem_euclid(256)).unwrap_or(1)); +} + +/// List what a directory in a sandbox holds. +pub fn ls(sandbox_id: &str, path: &str) { + let result = call(|client| client.list_sandbox_files(sandbox_id, path)); + if output::is_json_mode() { + output::success("Files.", Some(result)); + return; + } + let files = result + .get("files") + .and_then(Value::as_array) + .cloned() + .unwrap_or_default(); + if files.is_empty() { + output::info(&format!("{path} is empty."), None); + return; + } + let rows: Vec> = files + .iter() + .map(|f| { + let name = field(f, "name"); + let kind = field(f, "type"); + let shown = if kind == "dir" { + format!("{name}/") + } else { + name + }; + vec![shown, kind, number(f, "size")] + }) + .collect(); + output::table(&["Name", "Type", "Bytes"], &rows, None); +} + +/// Copy one file into or out of a sandbox. The sandbox side is written +/// `sb-ID:/path`; the other is a local path, or `-` for stdin or stdout. +pub fn cp(source: &str, destination: &str) { + match (remote(source), remote(destination)) { + (Some((sandbox_id, path)), None) => download(sandbox_id, path, destination), + (None, Some((sandbox_id, path))) => upload(source, sandbox_id, path), + _ => { + output::error( + "One side of `floo sandboxes cp` is a sandbox path and the other a local one.", + &ErrorCode::InvalidFormat, + Some("For example: floo sandboxes cp ./app.py sb-abc123:/work/app.py"), + ); + process::exit(1); + } + } +} + +/// `sb-ID:/path` as the sandbox's ID and the path in it. +fn remote(spec: &str) -> Option<(&str, &str)> { + let (id, path) = spec.split_once(':')?; + (id.starts_with("sb-") && path.starts_with('/')).then_some((id, path)) +} + +fn download(sandbox_id: &str, path: &str, destination: &str) { + let result = call(|client| client.read_sandbox_file(sandbox_id, path)); + if destination == "-" && output::is_json_mode() { + // An agent reads the file as JSON, through the redactor, not as raw bytes. + output::success(&format!("Read {sandbox_id}:{path}."), Some(result)); + return; + } + let content = result.get("content").and_then(Value::as_str).unwrap_or(""); + let bytes = if result.get("encoding").and_then(Value::as_str) == Some("base64") { + base64::engine::general_purpose::STANDARD + .decode(content) + .unwrap_or_default() + } else { + content.as_bytes().to_vec() + }; + let written = if destination == "-" { + std::io::stdout().lock().write_all(&bytes) + } else { + std::fs::write(destination, &bytes) + }; + if let Err(e) = written { + output::error( + &format!("Could not write '{destination}': {e}"), + &ErrorCode::FileError, + None, + ); + process::exit(1); + } + if destination != "-" { + output::success( + &format!("Copied {sandbox_id}:{path} to {destination}."), + Some(serde_json::json!({ "bytes": bytes.len() })), + ); + } +} + +fn upload(source: &str, sandbox_id: &str, path: &str) { + let mut bytes = Vec::new(); + let read = if source == "-" { + std::io::stdin().lock().read_to_end(&mut bytes).map(|_| ()) + } else { + std::fs::read(source).map(|b| bytes = b) + }; + if let Err(e) = read { + output::error( + &format!("Could not read '{source}': {e}"), + &ErrorCode::FileError, + None, + ); + process::exit(1); + } + let body = match String::from_utf8(bytes) { + Ok(text) => serde_json::json!({ "content": text, "encoding": "utf-8" }), + Err(e) => serde_json::json!({ + "content": base64::engine::general_purpose::STANDARD.encode(e.into_bytes()), + "encoding": "base64", + }), + }; + call(|client| { + client + .write_sandbox_file(sandbox_id, path, &body) + .map(|()| Value::Null) + }); + output::success(&format!("Copied {source} to {sandbox_id}:{path}."), None); +} + +/// `NAME=VALUE` pairs as a JSON object, or exit naming the flag. +fn pairs(given: &[String], flag: &str, example: &str) -> Value { + let mut map = serde_json::Map::new(); + for pair in given { + match pair.split_once('=') { + Some((name, value)) if !name.is_empty() => { + map.insert(name.to_string(), Value::String(value.to_string())); + } + _ => { + output::error( + &format!("{flag} is written NAME=VALUE, not '{pair}'."), + &ErrorCode::InvalidFormat, + Some(&format!("For example: {flag} {example}")), + ); + process::exit(1); + } + } + } + Value::Object(map) +} + /// List the org's sandboxes that have not finished, newest first: of one app /// with `--app`, and with every `--tag name=value` given. pub fn list(app: Option<&str>, tags: &[String]) { @@ -33,7 +266,7 @@ pub fn list(app: Option<&str>, tags: &[String]) { .unwrap_or_default(); if sandboxes.is_empty() { output::info( - "No running sandboxes. Programs start them with the floo-sandbox SDK.", + "No running sandboxes. Start one with `floo sandboxes create --app NAME`.", None, ); return; diff --git a/src/redact.rs b/src/redact.rs index 9d771b0..d326a35 100644 --- a/src/redact.rs +++ b/src/redact.rs @@ -906,8 +906,8 @@ mod snapshots { ); } - /// `floo sandboxes logs --json` and `floo sandboxes list --json`: what a - /// sandbox's command printed, and its tags, are a program's own text. + /// `floo sandboxes logs`, `list`, `exec` and `cp` in JSON mode: what a sandbox's + /// command printed, its tags and its files are a program's own text. #[test] fn floo_sandboxes_logs_and_tags_redacted() { let _g = lock_default_redact(); @@ -931,7 +931,22 @@ mod snapshots { "vcpus_limit": 16 } }); - for payload in [logs, listed] { + // `floo sandboxes exec --json` and `floo sandboxes cp sb-ID:/path - --json`. + let ran = json!({ + "success": true, + "data": { + "exit_code": 0, + "stdout": "DATABASE_URL=postgres://u:postgres-backed-pass-bd7fb@h/db\n", + "stderr": "using key floo_aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n", + "timed_out": false, + "truncated": false + } + }); + let read = json!({ + "success": true, + "data": {"content": "aws_access_key_id = AKIAIOSFODNN7EXAMPLE\n", "encoding": "utf-8"} + }); + for payload in [logs, listed, ran, read] { let out = through_print_json(payload); let leaks = collect_leaks(&out); assert!(leaks.is_empty(), "sandbox credentials leaked: {leaks:?}"); diff --git a/tests/sandboxes_tests.rs b/tests/sandboxes_tests.rs index 528dd2f..28aa76a 100644 --- a/tests/sandboxes_tests.rs +++ b/tests/sandboxes_tests.rs @@ -228,3 +228,177 @@ fn terminate_without_confirmation_or_in_preflight_calls_nothing() { .stdout(predicate::str::contains("Would terminate sandbox")); ended.assert(); } + +#[test] +fn create_sends_what_was_asked_and_prints_only_the_id_on_stdout() { + let mut server = Server::new(); + let home = setup_config(&server); + let created = server + .mock("POST", "/v1/orgs/sandboxes") + .match_body(Matcher::PartialJsonString( + r#"{"app":"agents","size":"medium","timeout":900,"env":{"DEBUG":"1"},"tags":{"task":"build"}}"# + .to_string(), + )) + .with_status(201) + .with_header("content-type", "application/json") + .with_body(format!( + r#"{{"id":"{SANDBOX}","app_id":"00000000-0000-0000-0000-000000000001","app_name":"agents"}}"# + )) + .create(); + + floo() + .args(["sandboxes", "create", "--app", "agents", "--size", "medium"]) + .args([ + "--timeout", + "900", + "--env", + "DEBUG=1", + "--tag", + "task=build", + ]) + .env("HOME", home.path()) + .assert() + .success() + .stdout(format!("{SANDBOX}\n")); + created.assert(); +} + +#[test] +fn exec_prints_each_stream_and_exits_with_the_commands_code() { + let mut server = Server::new(); + let home = setup_config(&server); + let ran = server + .mock("POST", format!("/v1/orgs/sandboxes/{SANDBOX}/exec").as_str()) + .match_body(Matcher::PartialJsonString( + r#"{"command":["sh","-c","exit 3"],"workdir":"/work","timeout":300}"#.to_string(), + )) + .with_status(200) + .with_header("content-type", "application/json") + .with_body( + r#"{"exit_code":3,"stdout":"out\n","stderr":"err\n","timed_out":false,"truncated":false}"#, + ) + .create(); + + floo() + .args(["sandboxes", "exec", SANDBOX, "--workdir", "/work"]) + .args(["--", "sh", "-c", "exit 3"]) + .env("HOME", home.path()) + .assert() + .code(3) + .stdout("out\n") + .stderr(predicate::str::contains("err\n")); + ran.assert(); +} + +#[test] +fn cp_uploads_text_and_downloads_bytes_as_they_were() { + let mut server = Server::new(); + let home = setup_config(&server); + let local = home.path().join("app.py"); + std::fs::write(&local, "print(1)\n").unwrap(); + let wrote = server + .mock( + "PUT", + format!("/v1/orgs/sandboxes/{SANDBOX}/files/content").as_str(), + ) + .match_query(Matcher::UrlEncoded("path".into(), "/work/app.py".into())) + .match_body(Matcher::Json( + serde_json::json!({"content": "print(1)\n", "encoding": "utf-8"}), + )) + .with_status(204) + .create(); + let read = server + .mock( + "GET", + format!("/v1/orgs/sandboxes/{SANDBOX}/files/content").as_str(), + ) + .match_query(Matcher::UrlEncoded("path".into(), "/work/logo.bin".into())) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(r#"{"content":"/wA=","encoding":"base64"}"#) + .create(); + let copied = home.path().join("logo.bin"); + + floo() + .args(["sandboxes", "cp", local.to_str().unwrap()]) + .arg(format!("{SANDBOX}:/work/app.py")) + .env("HOME", home.path()) + .assert() + .success(); + floo() + .args(["sandboxes", "cp", &format!("{SANDBOX}:/work/logo.bin")]) + .arg(copied.to_str().unwrap()) + .env("HOME", home.path()) + .assert() + .success(); + + wrote.assert(); + read.assert(); + assert_eq!(std::fs::read(&copied).unwrap(), vec![0xff, 0x00]); +} + +#[test] +fn cp_to_stdout_in_json_mode_answers_json_with_secrets_redacted() { + let mut server = Server::new(); + let home = setup_config(&server); + let read = server + .mock( + "GET", + format!("/v1/orgs/sandboxes/{SANDBOX}/files/content").as_str(), + ) + .match_query(Matcher::UrlEncoded("path".into(), "/work/.env".into())) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(r#"{"content":"KEY=floo_aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n","encoding":"utf-8"}"#) + .create(); + + let out = floo() + .args([ + "--json", + "sandboxes", + "cp", + &format!("{SANDBOX}:/work/.env"), + "-", + ]) + .env("HOME", home.path()) + .assert() + .success() + .get_output() + .stdout + .clone(); + + read.assert(); + let answer: serde_json::Value = serde_json::from_slice(&out).unwrap(); + assert_eq!(answer["contains_secrets"], true); + assert!(!String::from_utf8_lossy(&out).contains("floo_aaaa")); +} + +#[test] +fn cp_between_two_local_paths_is_refused_before_any_call() { + floo() + .args(["sandboxes", "cp", "./a", "./b"]) + .assert() + .failure() + .stderr(predicate::str::contains("One side of `floo sandboxes cp`")); +} + +#[test] +fn ls_shows_each_entry_with_directories_marked() { + let mut server = Server::new(); + let home = setup_config(&server); + let _listed = server + .mock("GET", format!("/v1/orgs/sandboxes/{SANDBOX}/files").as_str()) + .match_query(Matcher::UrlEncoded("path".into(), "/work".into())) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(r#"{"files":[{"name":"src","type":"dir","size":0},{"name":"app.py","type":"file","size":9}]}"#) + .create(); + + floo() + .args(["sandboxes", "ls", SANDBOX, "/work"]) + .env("HOME", home.path()) + .assert() + .success() + .stderr(predicate::str::contains("src/")) + .stderr(predicate::str::contains("app.py")); +}