From 4ec463a64383d9a2fe7222d9883683df104448a2 Mon Sep 17 00:00:00 2001 From: Sean Smith Date: Mon, 23 Nov 2026 12:06:48 -0800 Subject: [PATCH 1/6] Add temporary local sandbox shells through managed Goblin runtimes --- Cargo.toml | 2 +- README.md | 17 ++ docs/cli-reference.md | 47 ++++- skills/adapt/SKILL.md | 9 + src/backend/local.rs | 235 +++++++++++++++++++++ src/backend/mod.rs | 67 ++++++ src/cli.rs | 14 +- src/commands.rs | 25 ++- src/local_runtime.rs | 280 +++++++++++++++++++++++++ src/main.rs | 2 + src/shell.rs | 84 +++++--- src/stream.rs | 58 +++++- tests/cli.rs | 5 + tests/local_shell/manager.py | 58 ++++++ tests/local_shell/mod.rs | 393 +++++++++++++++++++++++++++++++++++ tests/support/mod.rs | 2 + 16 files changed, 1259 insertions(+), 39 deletions(-) create mode 100644 src/backend/local.rs create mode 100644 src/backend/mod.rs create mode 100644 src/local_runtime.rs create mode 100644 tests/local_shell/manager.py create mode 100644 tests/local_shell/mod.rs diff --git a/Cargo.toml b/Cargo.toml index 33c49b3..df40960 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -26,7 +26,7 @@ tokio-tungstenite = { version = "0.29", features = ["rustls-tls-native-roots"] } url = "2.5" uuid = { version = "1.27", features = ["v4"] } -[target.'cfg(unix)'.dev-dependencies] +[target.'cfg(unix)'.dependencies] libc = "0.2" [profile.release] diff --git a/README.md b/README.md index 26bcbae..5f48680 100644 --- a/README.md +++ b/README.md @@ -84,6 +84,23 @@ Sandboxes expire after one hour by default. Use `--ttl SECONDS` to change this time. Use `--no-expiry` to disable automatic expiry. +### Run a temporary sandbox locally + +On Apple Silicon macOS or x86_64 Linux with KVM, point Adapt at a compatible +Goblin bundle containing `goblind` and an embedded-firmware `goblin-worker`: + +```sh +export ADAPT_LOCAL_RUNTIME=/path/to/goblin-release/bin +adapt sandbox sh --local --image ubuntu:24.04 -- uname -m +adapt sandbox sh --local +``` + +Adapt starts and reuses a private local manager without Platform login. The shell +or command runs in a local VM, which is deleted when the session ends. Existing +commands keep their cloud default; `sandbox sh --cloud` selects it explicitly. +This initial local workflow requires a manually supplied runtime bundle. See +[local sandbox options and limitations](docs/cli-reference.md#local-temporary-sandboxes). + ## Create a sandbox Create a sandbox that stays available after each command: diff --git a/docs/cli-reference.md b/docs/cli-reference.md index dbf8aa9..2c3fc0b 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -191,7 +191,7 @@ adapt sandbox sh --image ubuntu:24.04 --cpu 2 --memory 2048 --env EDITOR=vim adapt sandbox sh --image-id IMAGE_ID --variable-set VARIABLE_SET_ID ``` -`sandbox sh` accepts every `sandbox create` option, including `--data`. +Cloud `sandbox sh` accepts every `sandbox create` option, including `--data`. It always waits for the sandbox to run, even without `--wait`. Without a command, it requires a terminal and opens an interactive login shell. It selects the shell from the guest's `$SHELL` or passwd entry. @@ -223,6 +223,51 @@ The `--ttl` option sets expiry in seconds. The `--no-expiry` option disables automatic expiry. Shells have a maximum execution timeout of 24 hours. +### Local temporary sandboxes + +```sh +adapt sandbox sh --local --runtime-dir /path/to/goblin-release/bin --image ubuntu:24.04 -- uname -m +adapt sandbox sh --local --env EDITOR=vim +printf 'hello\n' | adapt sandbox sh --local -- cat +adapt sandbox sh --cloud -- uname -m +``` + +`--local` runs a temporary VM on Apple Silicon macOS or x86_64 Linux with KVM. +It does not read cloud profiles or use Platform tokens. `--local` and `--cloud` +are mutually exclusive; omitting both preserves the cloud default. These target +flags currently apply to `sandbox sh` only. `auth logout --local` keeps its +existing credential-removal meaning. + +Supply a compatible Goblin runtime with `--runtime-dir` or `ADAPT_LOCAL_RUNTIME`. +The directory must contain `goblind` with `--ready-file` support and a native +`goblin-worker` with matching embedded firmware. The macOS worker must be signed +with its hypervisor entitlement. Automatic bundle installation is not included +yet. Adapt discovers a running manager before requiring the bundle path again. + +State, image cache, the local token, discovery metadata, and `goblind.log` live in +`ADAPT_CONFIG_DIR/local` (using the usual config-directory default). Override this +with `--local-state-dir` or `ADAPT_LOCAL_STATE_DIR`; the directory must be private +and owned by the current user. The manager runs independently of the terminal, +binds an ephemeral loopback port, and uses a separate token. Adapt bypasses HTTP +proxies for its local management requests. Concurrent commands reuse one manager. + +Local shells accept `--image`, `--cpu`, `--memory`, `--disk`, and repeated `--env`. +Defaults are `ubuntu:24.04`, one CPU, 1024 MiB memory, and a 2048 MiB writable disk. +The guest can reach public internet destinations, with private/loopback egress +blocked by Goblin's public policy. No host directories are mounted. +`--wait` is redundant because a shell always waits; `--no-expiry` is accepted. +Local `--env` values apply to the shell or command. `--data`, cloud image IDs, +labels, variable sets, image startup commands, TTL, and idempotency keys are +rejected before starting the runtime. + +Normal exit, Ctrl-], stream failure, and handled interruption trigger VM deletion. +The command has a 24-hour execution limit. Local sandboxes have no daemon-enforced +TTL in this first version, so a killed CLI or failed cleanup can leave a VM behind; +the diagnostic reports its UUID and state directory for local Goblin API cleanup. +Persistent local create/exec/files, stop/start, mounts, and local/cloud moves are +not exposed by this change. Local runtime logs and session output do not have +Platform's retained, redacted log service. + ### Sandbox options Memory and disk values use MiB. diff --git a/skills/adapt/SKILL.md b/skills/adapt/SKILL.md index 236add0..d389213 100644 --- a/skills/adapt/SKILL.md +++ b/skills/adapt/SKILL.md @@ -70,6 +70,15 @@ Use `exec --detach` to return execution metadata immediately, or `exec -it` for an interactive terminal. Normal command execution streams output and returns the remote exit code. +For a temporary local VM, use `adapt sandbox sh --local` on Apple Silicon macOS +or x86_64 Linux with KVM. Set `ADAPT_LOCAL_RUNTIME` to a compatible Goblin bundle's +`bin` directory, or pass `--runtime-dir`. This works without Platform login and +supports image, CPU, memory, disk, and environment flags. Local TTL, cloud image +IDs, variable sets, labels, `--data`, image startup, and idempotency keys are not +supported. Only `sandbox sh` currently accepts the local target; other resource +commands retain their cloud behavior. Local shells are deleted on exit and do not +mount host directories. `--cloud` explicitly selects the existing cloud shell. + ```sh adapt execs get EXEC_ID adapt execs logs EXEC_ID diff --git a/src/backend/local.rs b/src/backend/local.rs new file mode 100644 index 0000000..05db6f1 --- /dev/null +++ b/src/backend/local.rs @@ -0,0 +1,235 @@ +use super::Sandbox; +use crate::{ + api, + cli::{ExecArgs, SandboxCreate}, + output, stream, +}; +use anyhow::{Context, Result, bail}; +use reqwest::{Client, Method, StatusCode, header::HeaderMap}; +use serde_json::{Value, json}; +use std::{path::PathBuf, time::Duration}; +use tokio::time::{Instant, sleep}; +use tokio_tungstenite::tungstenite::client::IntoClientRequest; +use url::Url; +use uuid::Uuid; + +pub struct LocalBackend { + client: Client, + origin: Url, + headers: HeaderMap, + pub state_dir: PathBuf, + timeout: Duration, +} + +pub fn validate(args: &SandboxCreate) -> Result<()> { + for (present, flag) in [ + (args.data.is_some(), "--data"), + (args.image_id.is_some(), "--image-id"), + (args.ttl.is_some(), "--ttl"), + (!args.labels.is_empty(), "--label"), + (!args.variable_set.is_empty(), "--variable-set"), + (args.run_image, "--run-image"), + (args.creation.idempotency_key.is_some(), "--idempotency-key"), + ] { + if present { + bail!("{flag} is not supported by local temporary sandboxes"); + } + } + Ok(()) +} + +impl LocalBackend { + #[cfg(unix)] + pub fn new(origin: Url, token: &str, state_dir: PathBuf, timeout: Duration) -> Result { + let mut headers = HeaderMap::new(); + let mut value = reqwest::header::HeaderValue::from_str(&format!("Bearer {token}"))?; + value.set_sensitive(true); + headers.insert(reqwest::header::AUTHORIZATION, value); + let client = Client::builder() + .no_proxy() + .redirect(reqwest::redirect::Policy::none()) + .default_headers(headers.clone()) + .timeout(timeout) + .build()?; + Ok(Self { + client, + origin, + headers, + state_dir, + timeout, + }) + } + + pub async fn request(&self, method: Method, path: &str, body: Option<&Value>) -> Result { + let mut request = self.client.request(method, self.origin.join(path)?); + if let Some(body) = body { + request = request.json(body); + } + let response = request.send().await?; + let status = response.status(); + let bytes = api::limited_bytes(response, 1024 * 1024).await?; + if !status.is_success() { + let message = serde_json::from_slice::(&bytes) + .ok() + .and_then(|v| v["error"].as_str().map(str::to_owned)) + .unwrap_or_else(|| status.to_string()); + return Err(LocalError { + status, + message: output::safe(&message), + } + .into()); + } + if bytes.is_empty() { + Ok(Value::Null) + } else { + Ok(serde_json::from_slice(&bytes)?) + } + } + + pub async fn create(&self, args: SandboxCreate) -> Result { + validate(&args)?; + let sandbox = Sandbox { + id: Uuid::new_v4(), + env: args.env.into_iter().collect(), + }; + eprintln!("Creating local sandbox: {}", sandbox.id); + let body = json!({ + "id": sandbox.id.to_string(), "image": args.image.unwrap_or_else(|| "ubuntu:24.04".into()), + "resources": {"vcpus": args.cpu.unwrap_or(1), "memory_mib": args.memory.unwrap_or(1024)}, + "state_size_mib": args.disk.unwrap_or(2048), + "network": {"mode": "user", "egress": "public", "dns": "1.1.1.1"} + }); + if let Err(error) = self.request(Method::POST, "/v1/vms", Some(&body)).await { + // The UUID is known even if an accepted request loses its response. + // Never delete a conflicting record owned by someone else. + if !error + .downcast_ref::() + .is_some_and(|e| e.status == StatusCode::CONFLICT) + && let Err(cleanup) = self.delete(sandbox.id).await + { + return Err(error.context(format!( + "Local create may have been accepted as {}; cleanup failed: {cleanup:#}", + sandbox.id + ))); + } + return Err(error); + } + Ok(sandbox) + } + + pub async fn wait(&self, id: Uuid) -> Result<()> { + eprintln!("Waiting for local sandbox {id}…"); + tokio::time::timeout(Duration::from_secs(600), async { + loop { + let value = self + .request(Method::GET, &format!("/v1/vms/{id}"), None) + .await?; + match value["state"].as_str() { + Some("ready" | "busy") => return Ok(()), + Some("starting") => {} + state => bail!( + "Local sandbox {id} reached {} before readiness: {}", + state.unwrap_or("unknown"), + output::safe( + value["error"] + .as_str() + .unwrap_or("inspect the local runtime log") + ) + ), + } + sleep(Duration::from_millis(200)).await; + } + }) + .await + .context("Timed out waiting for the local sandbox")? + } + + pub async fn execute( + &self, + sandbox: &Sandbox, + args: ExecArgs, + json_output: bool, + ) -> Result { + let session = Uuid::new_v4(); + let mut env = sandbox.env.clone(); + env.extend(args.env); + let mut body = json!({"id":session.to_string(), "argv":args.argv, "env":env, "cwd":args.cwd, + "stdin":true, "timeout_ms":args.timeout_ms}); + if args.tty { + let (cols, rows) = crossterm::terminal::size()?; + body["terminal"] = + json!({"size":{"rows":rows.max(1),"cols":cols.max(1)},"term":"xterm-256color"}); + } + let path = format!("/v1/vms/{}/sessions/{session}", sandbox.id); + self.request( + Method::POST, + &format!("/v1/vms/{}/sessions", sandbox.id), + Some(&body), + ) + .await?; + let mut url = self + .origin + .join(&format!("{path}/stream?after=0&read_only=false"))?; + url.set_scheme("ws") + .map_err(|_| anyhow::anyhow!("Invalid local stream URL"))?; + let mut request = url.as_str().into_client_request()?; + request.headers_mut().extend(self.headers.clone()); + let (socket, _) = + tokio::time::timeout(self.timeout, tokio_tungstenite::connect_async(request)) + .await + .context("Timed out attaching to local execution")??; + stream::terminal( + socket, + stream::Attachment { + after: 0, + input: true, + tty: args.tty, + json_output, + resume: "The temporary local sandbox will be deleted.".into(), + credit: Some(0), + }, + ) + .await + } + + pub async fn delete(&self, id: Uuid) -> Result<()> { + eprintln!("Deleting local sandbox {id}…"); + // Deletion can briefly contend with image preparation or a worker launch. + let deadline = Instant::now() + self.timeout; + loop { + match self + .request(Method::DELETE, &format!("/v1/vms/{id}"), None) + .await + { + Ok(_) => return Ok(()), + Err(error) => { + let status = error.downcast_ref::().map(|e| e.status); + if status == Some(StatusCode::NOT_FOUND) { + return Ok(()); + } + if matches!( + status, + Some(StatusCode::CONFLICT | StatusCode::TOO_MANY_REQUESTS) + ) && Instant::now() < deadline + { + sleep(Duration::from_millis(100)).await; + } else { + return Err(error); + } + } + } + } + } +} + +#[derive(Debug)] +struct LocalError { + status: StatusCode, + message: String, +} +impl std::fmt::Display for LocalError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "Local runtime: {} ({})", self.message, self.status) + } +} +impl std::error::Error for LocalError {} diff --git a/src/backend/mod.rs b/src/backend/mod.rs new file mode 100644 index 0000000..8185c3c --- /dev/null +++ b/src/backend/mod.rs @@ -0,0 +1,67 @@ +//! Shared temporary-sandbox lifecycle. Backend-specific wire formats stay here. +pub mod local; + +use crate::{ + api::Api, + cli::{ExecArgs, SandboxCreate}, + commands, shell, +}; +use anyhow::Result; +use std::collections::BTreeMap; +use uuid::Uuid; + +pub struct Sandbox { + pub id: Uuid, + pub env: BTreeMap, +} + +pub enum SandboxBackend<'a> { + Cloud(&'a Api), + Local(&'a local::LocalBackend), +} + +impl SandboxBackend<'_> { + pub async fn create(&self, args: SandboxCreate) -> Result { + match self { + Self::Cloud(api) => Ok(Sandbox { + id: commands::resource_id(&commands::create_sandbox(api, args).await?)?, + env: BTreeMap::new(), + }), + Self::Local(local) => local.create(args).await, + } + } + + pub async fn wait(&self, id: Uuid) -> Result<()> { + match self { + Self::Cloud(api) => { + commands::wait_for(api, "sandboxes", id, "running", 600).await?; + Ok(()) + } + Self::Local(local) => local.wait(id).await, + } + } + + pub async fn execute(&self, sandbox: &Sandbox, args: ExecArgs, json: bool) -> Result { + match self { + Self::Cloud(api) => commands::execute(api, args, json).await, + Self::Local(local) => local.execute(sandbox, args, json).await, + } + } + + pub async fn delete(&self, id: Uuid) -> Result<()> { + match self { + Self::Cloud(api) => shell::cleanup_cloud(api, id).await, + Self::Local(local) => local.delete(id).await, + } + } + + pub fn cleanup_hint(&self, id: Uuid) -> String { + match self { + Self::Cloud(_) => format!("retry with `adapt sandbox delete {id}`"), + Self::Local(local) => format!( + "local sandbox {id} remains in {}; remove it through the local Goblin API", + local.state_dir.display() + ), + } + } +} diff --git a/src/cli.rs b/src/cli.rs index 766a270..341a623 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -270,7 +270,7 @@ pub enum SandboxCommand { Create(SandboxCreate), /// Run a login shell or command in a temporary sandbox, then delete it #[command( - after_help = "Accepts all sandbox create options. Always waits for the sandbox to run.\nWithout COMMAND, opens an interactive login shell (requires a terminal).\nWith COMMAND, forwards stdin and streams output. Returns the remote exit code.\nThe sandbox is deleted when the shell or command exits." + after_help = "Cloud sandboxes accept all sandbox create options; local options are limited. Always waits for the sandbox to run.\nWithout COMMAND, opens an interactive login shell (requires a terminal).\nWith COMMAND, forwards stdin and streams output. Returns the remote exit code.\nThe sandbox is deleted when the shell or command exits." )] Sh(SandboxShell), Start { @@ -311,6 +311,18 @@ pub struct SandboxList { #[derive(Args)] pub struct SandboxShell { + /// Run a temporary sandbox on this computer (requires a Goblin runtime bundle) + #[arg(long = "local", conflicts_with = "cloud_target")] + pub local_target: bool, + /// Run on Adapt Platform (the default) + #[arg(long = "cloud")] + pub cloud_target: bool, + /// Directory containing goblind and goblin-worker + #[arg(long, env = "ADAPT_LOCAL_RUNTIME")] + pub runtime_dir: Option, + /// Private local runtime state (defaults to ADAPT_CONFIG_DIR/local) + #[arg(long, env = "ADAPT_LOCAL_STATE_DIR")] + pub local_state_dir: Option, #[command(flatten)] pub create: SandboxCreate, /// Command and literal arguments to run instead of an interactive login shell diff --git a/src/commands.rs b/src/commands.rs index 1969a0e..eac227e 100644 --- a/src/commands.rs +++ b/src/commands.rs @@ -27,6 +27,29 @@ pub async fn run(cli: Cli) -> Result { skill::run(command, cli.json)?; return Ok(0); } + if matches!(&cli.command, Command::Sandbox(SandboxCommand::Sh(args)) if args.local_target) { + let Command::Sandbox(SandboxCommand::Sh(args)) = cli.command else { + unreachable!() + }; + crate::backend::local::validate(&args.create)?; + shell::validate(&args, cli.json)?; + let dir = match &args.local_state_dir { + Some(dir) => dir.clone(), + None => config::directory(cli.config_dir.as_deref())?.join("local"), + }; + let local = crate::local_runtime::connect( + &dir, + args.runtime_dir.as_deref(), + Duration::from_secs(cli.timeout), + ) + .await?; + return shell::run( + &crate::backend::SandboxBackend::Local(&local), + args, + cli.json, + ) + .await; + } let dir = config::directory(cli.config_dir.as_deref())?; let mut config = Config::load(&dir)?; // --profile and ADAPT_PROFILE share one value (the flag wins), so one check covers both. @@ -162,7 +185,7 @@ pub async fn run(cli: Cli) -> Result { OrgCommand::Members(command) => members(&api, command).await?, OrgCommand::Invitations(command) => invitations(&api, command).await?, }, - Command::Sandbox(SandboxCommand::Sh(args)) => return shell::run(&api, args, cli.json).await, + Command::Sandbox(SandboxCommand::Sh(args)) => return shell::run(&crate::backend::SandboxBackend::Cloud(&api), args, cli.json).await, Command::Sandbox(SandboxCommand::List(args)) => return list_sandboxes(&api, args, cli.json).await, Command::Sandbox(SandboxCommand::Usage { id, hours }) => return sandbox_usage(&api, id, hours, cli.json).await, Command::Sandbox(command) => sandbox(&api, command).await?, diff --git a/src/local_runtime.rs b/src/local_runtime.rs new file mode 100644 index 0000000..0a0117c --- /dev/null +++ b/src/local_runtime.rs @@ -0,0 +1,280 @@ +//! Per-user Goblin discovery and bootstrap. No Platform credentials are loaded here. +use crate::backend::local::LocalBackend; +use anyhow::{Result, bail}; +use std::{path::Path, time::Duration}; + +pub async fn connect( + state: &Path, + runtime: Option<&Path>, + timeout: Duration, +) -> Result { + if !cfg!(any( + all(target_os = "macos", target_arch = "aarch64"), + all(target_os = "linux", target_arch = "x86_64") + )) { + bail!("Local sandboxes currently require Apple Silicon macOS or x86_64 Linux with KVM"); + } + #[cfg(unix)] + { + unix::connect(state, runtime, timeout).await + } + #[cfg(not(unix))] + { + let _ = (state, runtime, timeout); + unreachable!() + } +} + +#[cfg(unix)] +mod unix { + use super::*; + use anyhow::Context; + use reqwest::Method; + use serde::Deserialize; + use std::{ + fs::{self, File, OpenOptions}, + io::{Read, Write}, + net::SocketAddr, + os::{ + fd::AsRawFd, + unix::{ + fs::{DirBuilderExt, MetadataExt, OpenOptionsExt}, + process::CommandExt, + }, + }, + process::{Command, Stdio}, + }; + use tokio::time::{Instant, sleep}; + use uuid::Uuid; + + #[derive(Deserialize)] + struct Ready { + version: u32, + address: SocketAddr, + instance_id: String, + runtime_version: String, + } + + fn private_metadata(path: &Path, directory: bool) -> Result<()> { + let meta = fs::symlink_metadata(path)?; + // SAFETY: geteuid has no arguments or memory effects. + if meta.uid() != unsafe { libc::geteuid() } + || meta.mode() & 0o077 != 0 + || (directory && !meta.is_dir()) + || (!directory && !meta.is_file()) + { + bail!( + "{} must be a private, user-owned {}", + path.display(), + if directory { + "directory" + } else { + "regular file" + } + ); + } + Ok(()) + } + + fn open(path: &Path, create: bool) -> Result { + let file = OpenOptions::new() + .read(true) + .write(create) + .create(create) + .truncate(false) + .append(create) + .mode(0o600) + .custom_flags(libc::O_NOFOLLOW) + .open(path)?; + private_metadata(path, false)?; + Ok(file) + } + + fn read(path: &Path) -> Result> { + let mut bytes = Vec::new(); + open(path, false)?.take(65537).read_to_end(&mut bytes)?; + if bytes.len() > 65536 { + bail!("Local runtime metadata is too large"); + } + Ok(bytes) + } + + async fn discover( + state: &Path, + token: &str, + timeout: Duration, + ) -> Result> { + let path = state.join("ready.json"); + let bytes = match read(&path) { + Ok(bytes) => bytes, + Err(error) + if error + .downcast_ref::() + .is_some_and(|e| e.kind() == std::io::ErrorKind::NotFound) => + { + return Ok(None); + } + Err(error) => return Err(error), + }; + let ready: Ready = + serde_json::from_slice(&bytes).context("Invalid local runtime discovery file")?; + if ready.version != 1 + || !ready.address.ip().is_loopback() + || ready.address.port() == 0 + || ready.instance_id.len() != 32 + || !ready.instance_id.bytes().all(|b| b.is_ascii_hexdigit()) + { + bail!("Unsupported or invalid local runtime discovery metadata"); + } + let origin = format!("http://{}/", ready.address).parse()?; + let probe = LocalBackend::new(origin, token, state.to_owned(), Duration::from_secs(2))?; + let spec = match probe.request(Method::GET, "/v1/spec", None).await { + Ok(spec) => spec, + Err(error) + if error + .downcast_ref::() + .is_some_and(|e| e.is_connect() || e.is_timeout()) => + { + return Ok(None); + } + Err(error) => { + return Err(error).context("Cannot authenticate the discovered local runtime"); + } + }; + if spec["instance_id"].as_str() != Some(&ready.instance_id) { + return Ok(None); + } + if spec["version"] != 1 + || spec["runtime_version"].as_str() != Some(&ready.runtime_version) + || spec["features"]["sessions"] != true + || spec["features"]["image_pull"] != true + { + bail!( + "Local runtime is incompatible or has no embedded image firmware; use a compatible Goblin bundle" + ); + } + Ok(Some(LocalBackend::new( + format!("http://{}/", ready.address).parse()?, + token, + state.to_owned(), + timeout, + )?)) + } + + pub async fn connect( + state: &Path, + runtime: Option<&Path>, + timeout: Duration, + ) -> Result { + fs::DirBuilder::new() + .recursive(true) + .mode(0o700) + .create(state)?; + private_metadata(state, true)?; + let state = state.canonicalize()?; + let lock = open(&state.join("bootstrap.lock"), true)?; + let deadline = Instant::now() + Duration::from_secs(30); + loop { + // SAFETY: the descriptor is live and exclusively owned by this scope. + if unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } == 0 { + break; + } + let error = std::io::Error::last_os_error(); + if error.kind() != std::io::ErrorKind::WouldBlock { + return Err(error.into()); + } + if Instant::now() >= deadline { + bail!("Timed out waiting for local runtime startup"); + } + sleep(Duration::from_millis(50)).await; + } + let token_path = state.join("token"); + if !token_path.try_exists()? { + let mut file = tempfile::NamedTempFile::new_in(&state)?; + write!( + file, + "{}{}", + Uuid::new_v4().simple(), + Uuid::new_v4().simple() + )?; + file.as_file().sync_all()?; + file.persist_noclobber(&token_path)?; + } + let token = String::from_utf8(read(&token_path)?)?; + let token = token.trim(); + if token.len() < 32 || token.len() > 4096 || token.chars().any(char::is_whitespace) { + bail!("Invalid local runtime token file"); + } + if let Some(local) = discover(&state, token, timeout).await? { + return Ok(local); + } + let runtime = runtime.context("Set ADAPT_LOCAL_RUNTIME or --runtime-dir to a directory containing goblind and an embedded-firmware goblin-worker; automatic runtime installation is not available yet")?.canonicalize()?; + let manager = runtime + .join("goblind") + .canonicalize() + .context("Runtime directory is missing goblind")?; + let worker = runtime + .join("goblin-worker") + .canonicalize() + .context("Runtime directory is missing goblin-worker")?; + let log_path = state.join("goblind.log"); + let log = open(&log_path, true)?; + let mut command = Command::new(manager); + command + .args([ + "--state-dir", + state.to_str().context("Local runtime path must be UTF-8")?, + "--listen", + "127.0.0.1:0", + ]) + .arg("--worker") + .arg(worker) + .arg("--token-file") + .arg(token_path) + .arg("--ready-file") + .arg(state.join("ready.json")) + .current_dir(&state) + .env_clear() + .stdin(Stdio::null()) + .stdout(log.try_clone()?) + .stderr(log); + // These support system helper lookup and temporary files, without forwarding + // ADAPT_TOKEN or the user's other credentials to the daemon. + for key in ["PATH", "TMPDIR"] { + if let Some(value) = std::env::var_os(key) { + command.env(key, value); + } + } + // SAFETY: setsid is an async-signal-safe syscall and the closure has no locks. + unsafe { + command.pre_exec(|| { + if libc::setsid() < 0 { + return Err(std::io::Error::last_os_error()); + } + Ok(()) + }); + } + eprintln!("Starting local runtime; log: {}", log_path.display()); + let mut child = command.spawn().context("Cannot start goblind")?; + loop { + if let Some(local) = discover(&state, token, timeout).await? { + return Ok(local); + } + if let Some(status) = child.try_wait()? { + bail!( + "Local runtime exited with {status}; inspect {}", + log_path.display() + ); + } + if Instant::now() >= deadline { + // Startup is independent of the CLI. A later command can discover + // a slow recovery; do not kill a daemon that may own live workers. + bail!( + "Local runtime is still starting; inspect {} and retry", + log_path.display() + ); + } + sleep(Duration::from_millis(50)).await; + } + } +} diff --git a/src/main.rs b/src/main.rs index a5ec6a2..162b08b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,9 +1,11 @@ mod api; mod auth; +mod backend; mod cli; mod commands; mod config; mod input; +mod local_runtime; mod mcp; mod output; mod shell; diff --git a/src/shell.rs b/src/shell.rs index 2f4347b..bba3746 100644 --- a/src/shell.rs +++ b/src/shell.rs @@ -1,7 +1,8 @@ use crate::{ api::{Api, ApiError}, + backend::{Sandbox, SandboxBackend}, cli::{Creation, ExecArgs, SandboxShell}, - commands::{create_sandbox, execute, resource_id, wait_for}, + commands::wait_for, stream, }; use anyhow::{Context, Result, bail}; @@ -20,7 +21,7 @@ if [ -z "$shell" ] || [ ! -x "$shell" ]; then fi exec "$shell" -il"#; -pub async fn run(api: &Api, args: SandboxShell, json_output: bool) -> Result { +pub fn validate(args: &SandboxShell, json_output: bool) -> Result<()> { let interactive = args.argv.is_empty(); if interactive && json_output { bail!("sandbox sh cannot be combined with --json"); @@ -30,9 +31,19 @@ pub async fn run(api: &Api, args: SandboxShell, json_output: bool) -> Result // Fail before creating a sandbox if terminal dimensions cannot be read. crossterm::terminal::size()?; } + Ok(()) +} + +pub async fn run( + backend: &SandboxBackend<'_>, + args: SandboxShell, + json_output: bool, +) -> Result { + validate(&args, json_output)?; + let interactive = args.argv.is_empty(); let mut shutdown = Shutdown::new()?; - let creation = create_sandbox(api, args.create); + let creation = backend.create(args.create); tokio::pin!(creation); let (created, interrupted) = tokio::select! { biased; @@ -44,7 +55,8 @@ pub async fn run(api: &Api, args: SandboxShell, json_output: bool) -> Result } created = &mut creation => (created, None), }; - let id = resource_id(&created?)?; + let sandbox = created?; + let id = sandbox.id; eprintln!("Temporary sandbox: {id}"); if interactive { eprintln!("Exiting the shell or pressing Ctrl-] deletes this sandbox."); @@ -58,11 +70,14 @@ pub async fn run(api: &Api, args: SandboxShell, json_output: bool) -> Result tokio::select! { biased; code = shutdown.wait() => Ok(code), - result = session(api, id, args.argv, json_output) => result, + result = session(backend, &sandbox, args.argv, json_output) => result, } }; - let cleanup = cleanup(api, id).await.with_context(|| { - format!("Could not delete temporary sandbox {id}; retry with `adapt sandbox delete {id}`") + let cleanup = backend.delete(id).await.with_context(|| { + format!( + "Could not delete temporary sandbox {id}; {}", + backend.cleanup_hint(id) + ) }); match (result, cleanup) { (result, Ok(())) => result, @@ -75,34 +90,41 @@ pub async fn run(api: &Api, args: SandboxShell, json_output: bool) -> Result } } -async fn session(api: &Api, id: Uuid, argv: Vec, json_output: bool) -> Result { +async fn session( + backend: &SandboxBackend<'_>, + sandbox: &Sandbox, + argv: Vec, + json_output: bool, +) -> Result { + let id = sandbox.id; let interactive = argv.is_empty(); - wait_for(api, "sandboxes", id, "running", 600).await?; - execute( - api, - ExecArgs { - sandbox: id.into(), - cwd: None, - env: vec![], - // The API's ordinary command default is ten minutes. An interactive - // shell should instead last up to the API maximum or sandbox expiry. - timeout_ms: Some(86_400_000), - detach: false, - stdin: true, - tty: interactive, - creation: Creation::default(), - argv: if interactive { - vec!["/bin/sh".into(), "-c".into(), LOGIN_SHELL.into()] - } else { - argv + backend.wait(id).await?; + backend + .execute( + sandbox, + ExecArgs { + sandbox: id.into(), + cwd: None, + env: vec![], + // The API's ordinary command default is ten minutes. An interactive + // shell should instead last up to the API maximum or sandbox expiry. + timeout_ms: Some(86_400_000), + detach: false, + stdin: true, + tty: interactive, + creation: Creation::default(), + argv: if interactive { + vec!["/bin/sh".into(), "-c".into(), LOGIN_SHELL.into()] + } else { + argv + }, }, - }, - json_output, - ) - .await + json_output, + ) + .await } -async fn cleanup(api: &Api, id: Uuid) -> Result<()> { +pub(crate) async fn cleanup_cloud(api: &Api, id: Uuid) -> Result<()> { eprintln!("Deleting temporary sandbox {id}…"); let result: Result<()> = async { let response = api diff --git a/src/stream.rs b/src/stream.rs index 2cd43f9..a9953b8 100644 --- a/src/stream.rs +++ b/src/stream.rs @@ -274,6 +274,37 @@ pub async fn attach( let (socket, _) = tokio::time::timeout(api.timeout, tokio_tungstenite::connect_async(request)) .await .context("Timed out attaching to execution")??; + terminal(socket, Attachment { + after, input, tty, json_output, + resume: format!("Resume with `adapt execs attach {id} --after {{sequence}}` (input is never replayed)"), + credit: None, + }).await +} + +pub struct Attachment { + pub after: u64, + pub input: bool, + pub tty: bool, + pub json_output: bool, + pub resume: String, + /// Goblin grants a bounded stdin window; Platform handles flow control upstream. + pub credit: Option, +} + +pub async fn terminal( + socket: tokio_tungstenite::WebSocketStream< + tokio_tungstenite::MaybeTlsStream, + >, + attachment: Attachment, +) -> Result { + let Attachment { + after, + input, + tty, + json_output, + resume, + mut credit, + } = attachment; let (mut writer, mut reader) = socket.split(); let _raw = if tty { crossterm::terminal::enable_raw_mode()?; @@ -282,7 +313,7 @@ pub async fn attach( None }; if tty { - eprintln!("Attached. Ctrl-] detaches; Ctrl-C is sent to the remote terminal.\r"); + eprintln!("Attached. Ctrl-] detaches; Ctrl-C is sent to the sandbox terminal.\r"); } let mut stdin = tokio::io::stdin(); let mut buffer = [0u8; 4096]; @@ -291,14 +322,32 @@ pub async fn attach( let mut last_size = crossterm::terminal::size().unwrap_or((80, 24)); let mut resize = tokio::time::interval(Duration::from_millis(250)); loop { + let capacity = credit.unwrap_or(buffer.len()).min(buffer.len()); tokio::select! { message = reader.next() => { - let Some(message) = message else { bail!("Attachment disconnected. Resume with `adapt execs attach {id} --after {last_sequence}` (input is never replayed)"); }; + let Some(message) = message else { bail!("Attachment disconnected. {}", resume.replace("{sequence}", &last_sequence.to_string())); }; match message? { Message::Text(text) => { let data: Value = serde_json::from_str(&text)?; let kind = data["kind"].as_str().unwrap_or(""); + if let Some(available) = credit.as_mut() { + match kind { + "attached" => { + *available = data["session"]["stdin_credit"].as_u64().context("Missing stdin credit")?.try_into()?; + input_open &= data["session"]["stdin_closed"] != true; + }, + "started" => *available = 32768, + "stdin_consumed" => { + let bytes: usize = data["bytes"].as_u64().context("Missing stdin consumption")?.try_into()?; + *available = available.checked_add(bytes).context("Invalid stdin credit")?; + }, + "stdin_closed" => input_open = false, + _ => {}, + } + if *available > 32768 { bail!("Invalid stdin credit window"); } + } match kind { + "error" | "rejected" => bail!("Execution failed: {}", output::safe(data["message"].as_str().unwrap_or("runtime rejected the stream"))), "stdout" | "stderr" => { let sequence = data["sequence"].as_u64().context("Missing live output sequence")?; if sequence <= last_sequence { continue; } @@ -319,11 +368,11 @@ pub async fn attach( } }, Message::Ping(bytes) => writer.send(Message::Pong(bytes)).await?, - Message::Close(_) => bail!("Attachment closed before a result. Resume with `adapt execs attach {id} --after {last_sequence}`"), + Message::Close(_) => bail!("Attachment closed before a result. {}", resume.replace("{sequence}", &last_sequence.to_string())), _ => {}, } }, - count = stdin.read(&mut buffer), if input_open => { + count = stdin.read(&mut buffer[..capacity]), if input_open && capacity > 0 => { let count = count?; if count == 0 { input_open = false; @@ -333,6 +382,7 @@ pub async fn attach( writer.close().await?; return Ok(0); } + if let Some(available) = credit.as_mut() { *available -= count; } writer.send(Message::Binary(buffer[..count].to_vec().into())).await?; } }, diff --git a/tests/cli.rs b/tests/cli.rs index cabd707..5da2064 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -5,6 +5,11 @@ use support::*; mod endpoint_request; mod image_list; +#[cfg(any( + all(target_os = "macos", target_arch = "aarch64"), + all(target_os = "linux", target_arch = "x86_64") +))] +mod local_shell; mod mcp_tools; mod models; mod resource_prefixes; diff --git a/tests/local_shell/manager.py b/tests/local_shell/manager.py new file mode 100644 index 0000000..6f31419 --- /dev/null +++ b/tests/local_shell/manager.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Daemon fixture: exercise process bootstrap without requiring a hypervisor.""" +import argparse +import json +import os +from http.server import BaseHTTPRequestHandler, HTTPServer +from pathlib import Path + +parser = argparse.ArgumentParser() +for flag in ("state-dir", "listen", "worker", "token-file", "ready-file"): + parser.add_argument("--" + flag, required=True) +args = parser.parse_args() +assert "ADAPT_TOKEN" not in os.environ +state = Path(args.state_dir) +token = Path(args.token_file).read_text() +instance = "22222222222222222222222222222222" +with (state / "starts").open("a") as stream: + stream.write("started\n") + + +class Handler(BaseHTTPRequestHandler): + def respond(self, status, value): + assert self.headers["Authorization"] == "Bearer " + token + assert "X-Organization-Id" not in self.headers + body = json.dumps(value).encode() + self.send_response(status) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def do_GET(self): + self.respond(200, { + "version": 1, "instance_id": instance, "runtime_version": "fixture", + "features": {"sessions": True, "image_pull": True}, + }) + + def do_POST(self): + self.rfile.read(int(self.headers.get("Content-Length", 0))) + self.respond(400, {"error": "fixture rejected image"}) + + def do_DELETE(self): + self.respond(404, {"error": "no VM was created"}) + + def log_message(self, *_): + pass + + +host, port = args.listen.rsplit(":", 1) +server = HTTPServer((host, int(port)), Handler) +ready = Path(args.ready_file) +temporary = ready.with_suffix(".tmp") +temporary.write_text(json.dumps({ + "version": 1, "address": "%s:%s" % server.server_address, + "pid": os.getpid(), "instance_id": instance, "runtime_version": "fixture", +})) +temporary.chmod(0o600) +temporary.replace(ready) +server.serve_forever() diff --git a/tests/local_shell/mod.rs b/tests/local_shell/mod.rs new file mode 100644 index 0000000..0e0b85b --- /dev/null +++ b/tests/local_shell/mod.rs @@ -0,0 +1,393 @@ +use crate::support::*; +use serde_json::{Value, json}; +use std::{ + collections::HashMap, + fs, + os::unix::fs::PermissionsExt, + path::Path, + process::Command, + sync::{Arc, Mutex}, + time::Instant, +}; +use tokio_tungstenite::tungstenite::{self, Message}; + +const TOKEN: &str = "local-runtime-token-that-is-not-a-cloud-token"; +const INSTANCE: &str = "11111111111111111111111111111111"; + +fn private_file(path: &Path, bytes: &[u8]) { + fs::write(path, bytes).unwrap(); + fs::set_permissions(path, fs::Permissions::from_mode(0o600)).unwrap(); +} + +fn command_for(state: &Path) -> Command { + let mut cmd = command(state, "not-a-valid-cloud-origin"); + cmd.env("ADAPT_TOKEN", "cloud-secret-must-not-reach-goblin") + .env("ADAPT_ORG_ID", ORG) + .env("HTTP_PROXY", "http://127.0.0.1:1") + .env("ALL_PROXY", "http://127.0.0.1:1") + .args(["sandbox", "sh", "--local", "--local-state-dir"]) + .arg(state); + cmd +} + +fn discovery(state: &Path, url: &str) { + fs::set_permissions(state, fs::Permissions::from_mode(0o700)).unwrap(); + private_file(&state.join("token"), TOKEN.as_bytes()); + private_file(&state.join("ready.json"), json!({"version":1,"address":url.strip_prefix("http://").unwrap(),"instance_id":INSTANCE,"runtime_version":"test"}).to_string().as_bytes()); + // Local operation must not even deserialize the saved cloud profile. + private_file(&state.join("config.json"), b"not valid JSON"); +} + +fn local_auth(r: &Request) { + assert_eq!(r.headers["authorization"], format!("Bearer {TOKEN}")); + assert!(!r.headers.contains_key("x-organization-id")); +} + +fn spec() -> Exchange { + http(Box::new(|r| { + local_auth(r); + assert_eq!(r.target, "/v1/spec"); + Reply::json( + 200, + json!({"version":1,"instance_id":INSTANCE,"runtime_version":"test","features":{"sessions":true,"image_pull":true}}), + ) + })) +} + +#[derive(Default)] +struct Ids { + vm: String, + session: String, +} + +fn setup(ids: &Arc>) -> Vec { + let create_ids = ids.clone(); + let ready_ids = ids.clone(); + let exec_ids = ids.clone(); + vec![ + spec(), + http(Box::new(move |r| { + local_auth(r); + assert_eq!((r.method.as_str(), r.target.as_str()), ("POST", "/v1/vms")); + let mut body = r.json(); + let id = body.as_object_mut().unwrap().remove("id").unwrap(); + uuid::Uuid::parse_str(id.as_str().unwrap()).unwrap(); + create_ids.lock().unwrap().vm = id.as_str().unwrap().into(); + assert_eq!( + body, + json!({"image":"ubuntu:24.04","resources":{"vcpus":2,"memory_mib":512},"state_size_mib":128,"network":{"mode":"user","egress":"public","dns":"1.1.1.1"}}) + ); + Reply::json(202, json!({"id":id,"state":"starting"})) + })), + http(Box::new(move |r| { + local_auth(r); + assert_eq!( + r.target, + format!("/v1/vms/{}", ready_ids.lock().unwrap().vm) + ); + Reply::json(200, json!({"state":"ready"})) + })), + http(Box::new(move |r| { + local_auth(r); + let mut ids = exec_ids.lock().unwrap(); + assert_eq!(r.target, format!("/v1/vms/{}/sessions", ids.vm)); + let body = r.json(); + ids.session = body["id"].as_str().unwrap().into(); + uuid::Uuid::parse_str(&ids.session).unwrap(); + assert_eq!(body["argv"], json!(["cat"])); + assert_eq!(body["env"], json!({"LITERAL":" a=b\n$HOME "})); + assert_eq!(body["stdin"], true); + assert_eq!(body["timeout_ms"], 86_400_000); + assert!(body.get("terminal").is_none()); + Reply::json(202, json!({"id":ids.session,"state":"starting"})) + })), + ] +} + +#[allow(clippy::result_large_err)] +fn stream( + ids: Arc>, + body: impl FnOnce(tungstenite::WebSocket) + Send + 'static, +) -> Exchange { + Box::new(move |socket| { + let mut received = None; + let ws = tungstenite::accept_hdr( + socket, + |request: &tungstenite::handshake::server::Request, response| { + let ids = ids.lock().unwrap(); + assert_eq!( + request.uri().path(), + format!("/v1/vms/{}/sessions/{}/stream", ids.vm, ids.session) + ); + assert_eq!(request.uri().query(), Some("after=0&read_only=false")); + assert_eq!( + request.headers()["authorization"], + format!("Bearer {TOKEN}") + ); + assert!(!request.headers().contains_key("x-organization-id")); + received = Some(Request { + method: "GET".into(), + target: request.uri().to_string(), + headers: HashMap::new(), + body: vec![], + at: Instant::now(), + }); + Ok(response) + }, + ) + .unwrap(); + body(ws); + received.unwrap() + }) +} + +fn deleted(ids: Arc>) -> Exchange { + http(Box::new(move |r| { + local_auth(r); + assert_eq!(r.method, "DELETE"); + assert_eq!(r.target, format!("/v1/vms/{}", ids.lock().unwrap().vm)); + Reply::json(204, Value::Null) + })) +} + +fn send(ws: &mut tungstenite::WebSocket, value: Value) { + ws.send(Message::Text(value.to_string().into())).unwrap(); +} + +fn args(cmd: &mut Command) -> &mut Command { + cmd.args([ + "--cpu", + "2", + "--memory", + "512", + "--disk", + "128", + "--env", + "LITERAL= a=b\n$HOME ", + "--", + "cat", + ]) +} + +#[test] +fn local_shell_uses_its_own_credentials_honors_credit_and_cleans_up_on_nonzero_exit() { + let ids = Arc::new(Mutex::new(Ids::default())); + let mut steps = setup(&ids); + steps.push(stream(ids.clone(), |mut ws| { + // Begin with less than a frame of credit; later replenish each chunk. + send( + &mut ws, + json!({"kind":"attached","session":{"stdin_credit":1024,"stdin_closed":false}}), + ); + let mut total = 0; + loop { + match ws.read().unwrap() { + Message::Binary(bytes) => { + assert!(bytes.len() <= 1024); + assert!(bytes.iter().all(|b| *b == b'x')); + total += bytes.len(); + send( + &mut ws, + json!({"kind":"stdin_consumed","bytes":bytes.len()}), + ); + } + Message::Text(text) if text.contains("stdin_eof") => break, + message => panic!("Unexpected message: {message:?}"), + } + } + assert_eq!(total, 128 * 1024); + send( + &mut ws, + json!({"kind":"stdout","sequence":1,"data_base64":"aGVsbG8K"}), + ); + send(&mut ws, json!({"kind":"finished","exit":{"code":7}})); + while let Ok(message) = ws.read() { + if matches!(message, Message::Close(_)) { + break; + } + } + })); + steps.push(deleted(ids)); + let server = Server::script(steps); + let dir = tempfile::tempdir().unwrap(); + discovery(dir.path(), &server.url); + let mut cmd = command_for(dir.path()); + args(&mut cmd); + let output = with_stdin(cmd, &vec![b'x'; 128 * 1024]); + assert_eq!( + output.status.code(), + Some(7), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!(output.stdout, b"hello\n"); + assert!(!String::from_utf8_lossy(&output.stderr).contains("cloud-secret")); + server.finish(); +} + +#[test] +fn local_stream_failure_still_deletes_the_vm() { + let ids = Arc::new(Mutex::new(Ids::default())); + let mut steps = setup(&ids); + steps.push(stream(ids.clone(), |mut ws| { + send( + &mut ws, + json!({"kind":"error","message":"guest execution failed"}), + ); + })); + steps.push(deleted(ids)); + let server = Server::script(steps); + let dir = tempfile::tempdir().unwrap(); + discovery(dir.path(), &server.url); + let output = args(&mut command_for(dir.path())).output().unwrap(); + assert_eq!(output.status.code(), Some(1)); + assert!(String::from_utf8_lossy(&output.stderr).contains("guest execution failed")); + server.finish(); +} + +#[test] +fn local_preflight_rejects_unsupported_options_without_starting_a_runtime() { + let dir = tempfile::tempdir().unwrap(); + for flags in [ + vec!["--ttl", "60"], + vec!["--label", "a=b"], + vec!["--variable-set", ID], + vec!["--image-id", ID], + vec!["--data", "{}"], + vec!["--run-image"], + vec!["--idempotency-key", KEY], + ] { + let output = command_for(dir.path()) + .args(&flags) + .args(["--", "true"]) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(1)); + assert!( + String::from_utf8_lossy(&output.stderr) + .contains("not supported by local temporary sandboxes") + ); + assert!(!dir.path().join("bootstrap.lock").exists()); + } + assert_eq!( + command_for(dir.path()) + .args(["--cloud", "--", "true"]) + .output() + .unwrap() + .status + .code(), + Some(2) + ); + let output = command_for(dir.path()).output().unwrap(); + assert!(String::from_utf8_lossy(&output.stderr).contains("interactive terminal")); + assert!(!dir.path().join("bootstrap.lock").exists()); +} + +#[test] +fn saved_local_runtime_settings_do_not_change_an_explicit_cloud_target() { + let server = Server::start(vec![Box::new(|r| { + assert_eq!(r.target, "/v1/sandboxes"); + assert_eq!(r.headers["authorization"], "Bearer test-token"); + Reply::json( + 400, + json!({"error":{"message":"cloud request reached Platform"}}), + ) + })]); + let dir = tempfile::tempdir().unwrap(); + let output = command(dir.path(), &server.url) + .env("ADAPT_TOKEN", "test-token") + .env("ADAPT_LOCAL_RUNTIME", "/unused/local/bundle") + .env("ADAPT_LOCAL_STATE_DIR", "/unused/local/state") + .args(["sandbox", "sh", "--cloud", "--", "true"]) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(1)); + assert!(String::from_utf8_lossy(&output.stderr).contains("cloud request reached Platform")); + server.finish(); +} + +#[test] +fn rejects_untrusted_discovery_before_sending_a_token() { + let dir = tempfile::tempdir().unwrap(); + discovery(dir.path(), "http://192.0.2.1:1234"); + let output = command_for(dir.path()) + .args(["--", "true"]) + .output() + .unwrap(); + assert!(String::from_utf8_lossy(&output.stderr).contains("invalid local runtime discovery")); + fs::set_permissions(dir.path().join("token"), fs::Permissions::from_mode(0o644)).unwrap(); + let output = command_for(dir.path()) + .args(["--", "true"]) + .output() + .unwrap(); + assert!(String::from_utf8_lossy(&output.stderr).contains("private, user-owned")); +} + +struct ManagerGuard(std::path::PathBuf); +impl Drop for ManagerGuard { + fn drop(&mut self) { + if let Ok(bytes) = fs::read(self.0.join("ready.json")) + && let Ok(ready) = serde_json::from_slice::(&bytes) + && let Some(pid) = ready["pid"].as_i64() + { + // SAFETY: this fixture exclusively owns its private manager state. + unsafe { + libc::kill(pid as i32, libc::SIGTERM); + } + } + } +} + +#[test] +fn concurrent_clients_bootstrap_one_detached_manager_and_reuse_it() { + let dir = tempfile::tempdir().unwrap(); + let state = dir.path().join("state"); + let _manager = ManagerGuard(state.clone()); + fs::write(dir.path().join("goblind"), include_str!("manager.py")).unwrap(); + fs::set_permissions( + dir.path().join("goblind"), + fs::Permissions::from_mode(0o700), + ) + .unwrap(); + fs::write(dir.path().join("goblin-worker"), b"fixture").unwrap(); + let launch = || { + command_for(&state) + .arg("--runtime-dir") + .arg(dir.path()) + .args(["--", "true"]) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap() + }; + let one = launch(); + let two = launch(); + for child in [one, two] { + let output = child.wait_with_output().unwrap(); + assert_eq!(output.status.code(), Some(1)); + assert!( + String::from_utf8_lossy(&output.stderr).contains("fixture rejected image"), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + } + assert_eq!( + fs::read_to_string(state.join("starts")).unwrap(), + "started\n" + ); + // Discovery must work after the launching processes exit, without a bundle path. + let output = command_for(&state).args(["--", "true"]).output().unwrap(); + assert!(String::from_utf8_lossy(&output.stderr).contains("fixture rejected image")); + assert_eq!( + fs::read_to_string(state.join("starts")).unwrap(), + "started\n" + ); + assert_eq!( + fs::metadata(state.join("token")) + .unwrap() + .permissions() + .mode() + & 0o077, + 0 + ); +} diff --git a/tests/support/mod.rs b/tests/support/mod.rs index 32f181d..e7e8443 100644 --- a/tests/support/mod.rs +++ b/tests/support/mod.rs @@ -252,6 +252,8 @@ pub fn command_with_timeout(dir: &Path, url: &str, timeout: u64) -> Command { "ADAPT_API_URL", "ADAPT_ORG_ID", "ADAPT_CONFIG_DIR", + "ADAPT_LOCAL_RUNTIME", + "ADAPT_LOCAL_STATE_DIR", ] { cmd.env_remove(name); } From 6006df21837007e1564359cc605801873dd56981 Mon Sep 17 00:00:00 2001 From: Sean Smith Date: Mon, 23 Nov 2026 12:11:05 -0800 Subject: [PATCH 2/6] Parse local manager identities as UUIDs --- Cargo.lock | 1 + Cargo.toml | 2 +- src/local_runtime.rs | 13 +++++-------- tests/local_shell/manager.py | 2 +- tests/local_shell/mod.rs | 31 ++++++++++++++++++++++++++----- 5 files changed, 34 insertions(+), 15 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 76c016a..2632399 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1638,6 +1638,7 @@ checksum = "4a0e2d11620c50695fe12bbbfde96b3477fe606e7284c22d505c12ce51214514" dependencies = [ "getrandom 0.4.3", "js-sys", + "serde_core", "wasm-bindgen", ] diff --git a/Cargo.toml b/Cargo.toml index df40960..da46bcf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,7 +24,7 @@ tempfile = "3.27" tokio = { version = "1.53", features = ["macros", "rt-multi-thread", "time", "signal", "io-util", "io-std", "net"] } tokio-tungstenite = { version = "0.29", features = ["rustls-tls-native-roots"] } url = "2.5" -uuid = { version = "1.27", features = ["v4"] } +uuid = { version = "1.27", features = ["v4", "serde"] } [target.'cfg(unix)'.dependencies] libc = "0.2" diff --git a/src/local_runtime.rs b/src/local_runtime.rs index 0a0117c..71e71a9 100644 --- a/src/local_runtime.rs +++ b/src/local_runtime.rs @@ -51,7 +51,7 @@ mod unix { struct Ready { version: u32, address: SocketAddr, - instance_id: String, + instance_id: Uuid, runtime_version: String, } @@ -118,12 +118,7 @@ mod unix { }; let ready: Ready = serde_json::from_slice(&bytes).context("Invalid local runtime discovery file")?; - if ready.version != 1 - || !ready.address.ip().is_loopback() - || ready.address.port() == 0 - || ready.instance_id.len() != 32 - || !ready.instance_id.bytes().all(|b| b.is_ascii_hexdigit()) - { + if ready.version != 1 || !ready.address.ip().is_loopback() || ready.address.port() == 0 { bail!("Unsupported or invalid local runtime discovery metadata"); } let origin = format!("http://{}/", ready.address).parse()?; @@ -141,7 +136,9 @@ mod unix { return Err(error).context("Cannot authenticate the discovered local runtime"); } }; - if spec["instance_id"].as_str() != Some(&ready.instance_id) { + let instance_id: Uuid = serde_json::from_value(spec["instance_id"].clone()) + .context("Local runtime returned an invalid instance ID")?; + if instance_id != ready.instance_id { return Ok(None); } if spec["version"] != 1 diff --git a/tests/local_shell/manager.py b/tests/local_shell/manager.py index 6f31419..4a909a7 100644 --- a/tests/local_shell/manager.py +++ b/tests/local_shell/manager.py @@ -13,7 +13,7 @@ assert "ADAPT_TOKEN" not in os.environ state = Path(args.state_dir) token = Path(args.token_file).read_text() -instance = "22222222222222222222222222222222" +instance = "22222222-2222-4222-8222-222222222222" with (state / "starts").open("a") as stream: stream.write("started\n") diff --git a/tests/local_shell/mod.rs b/tests/local_shell/mod.rs index 0e0b85b..a0ea6b2 100644 --- a/tests/local_shell/mod.rs +++ b/tests/local_shell/mod.rs @@ -12,7 +12,7 @@ use std::{ use tokio_tungstenite::tungstenite::{self, Message}; const TOKEN: &str = "local-runtime-token-that-is-not-a-cloud-token"; -const INSTANCE: &str = "11111111111111111111111111111111"; +const INSTANCE: &str = "11111111-1111-4111-8111-111111111111"; fn private_file(path: &Path, bytes: &[u8]) { fs::write(path, bytes).unwrap(); @@ -315,6 +315,19 @@ fn rejects_untrusted_discovery_before_sending_a_token() { .output() .unwrap(); assert!(String::from_utf8_lossy(&output.stderr).contains("invalid local runtime discovery")); + private_file( + &dir.path().join("ready.json"), + json!({"version":1,"address":"127.0.0.1:1","instance_id":"not-a-uuid","runtime_version":"test"}) + .to_string() + .as_bytes(), + ); + let output = command_for(dir.path()) + .args(["--", "true"]) + .output() + .unwrap(); + assert!( + String::from_utf8_lossy(&output.stderr).contains("Invalid local runtime discovery file") + ); fs::set_permissions(dir.path().join("token"), fs::Permissions::from_mode(0o644)).unwrap(); let output = command_for(dir.path()) .args(["--", "true"]) @@ -362,13 +375,21 @@ fn concurrent_clients_bootstrap_one_detached_manager_and_reuse_it() { }; let one = launch(); let two = launch(); - for child in [one, two] { - let output = child.wait_with_output().unwrap(); + let outputs = [ + one.wait_with_output().unwrap(), + two.wait_with_output().unwrap(), + ]; + let diagnostics = format!( + "first client: {}\nsecond client: {}\nmanager log: {}", + String::from_utf8_lossy(&outputs[0].stderr), + String::from_utf8_lossy(&outputs[1].stderr), + fs::read_to_string(state.join("goblind.log")).unwrap_or_default() + ); + for output in outputs { assert_eq!(output.status.code(), Some(1)); assert!( String::from_utf8_lossy(&output.stderr).contains("fixture rejected image"), - "{}", - String::from_utf8_lossy(&output.stderr) + "{diagnostics}" ); } assert_eq!( From 0e195424a492f2875a2cd14e5d3197794dd13c3f Mon Sep 17 00:00:00 2001 From: Sean Smith Date: Mon, 23 Nov 2026 12:58:35 -0800 Subject: [PATCH 3/6] Secure local transport and keep terminal escape responsive without credit --- docs/cli-reference.md | 11 ++- src/backend/local.rs | 39 ++++++++-- src/local_runtime.rs | 35 ++++++--- src/stream.rs | 57 ++++++++++++--- tests/local_shell/manager.py | 13 ++-- tests/local_shell/mod.rs | 138 ++++++++++++++++++++++++++++++++--- tests/sandbox_sh/mod.rs | 18 +++-- tests/support/mod.rs | 49 ++++++++++++- 8 files changed, 303 insertions(+), 57 deletions(-) diff --git a/docs/cli-reference.md b/docs/cli-reference.md index 2c3fc0b..0c750cb 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -239,7 +239,7 @@ flags currently apply to `sandbox sh` only. `auth logout --local` keeps its existing credential-removal meaning. Supply a compatible Goblin runtime with `--runtime-dir` or `ADAPT_LOCAL_RUNTIME`. -The directory must contain `goblind` with `--ready-file` support and a native +The directory must contain `goblind` with `--ready-file` and `--unix-socket` support and a native `goblin-worker` with matching embedded firmware. The macOS worker must be signed with its hypervisor entitlement. Automatic bundle installation is not included yet. Adapt discovers a running manager before requiring the bundle path again. @@ -248,8 +248,10 @@ State, image cache, the local token, discovery metadata, and `goblind.log` live `ADAPT_CONFIG_DIR/local` (using the usual config-directory default). Override this with `--local-state-dir` or `ADAPT_LOCAL_STATE_DIR`; the directory must be private and owned by the current user. The manager runs independently of the terminal, -binds an ephemeral loopback port, and uses a separate token. Adapt bypasses HTTP -proxies for its local management requests. Concurrent commands reuse one manager. +listens on a private `goblind.sock` Unix socket inside that directory, and uses a +separate token. Adapt validates the socket path, ownership, and permissions before +sending credentials; HTTP and WebSocket requests both use the socket and bypass +proxies. Stale TCP discovery records are rejected. Concurrent commands reuse one manager. Local shells accept `--image`, `--cpu`, `--memory`, `--disk`, and repeated `--env`. Defaults are `ubuntu:24.04`, one CPU, 1024 MiB memory, and a 2048 MiB writable disk. @@ -261,6 +263,9 @@ labels, variable sets, image startup commands, TTL, and idempotency keys are rejected before starting the runtime. Normal exit, Ctrl-], stream failure, and handled interruption trigger VM deletion. +Ctrl-] remains available when the guest stops reading input. Interactive input +queues up to 32 KiB locally; additional input is discarded with a warning until +the guest resumes reading. Piped input is backpressured without discarding bytes. The command has a 24-hour execution limit. Local sandboxes have no daemon-enforced TTL in this first version, so a killed CLI or failed cleanup can leave a VM behind; the diagnostic reports its UUID and state directory for local Goblin API cleanup. diff --git a/src/backend/local.rs b/src/backend/local.rs index 05db6f1..9ea427f 100644 --- a/src/backend/local.rs +++ b/src/backend/local.rs @@ -1,14 +1,19 @@ use super::Sandbox; +#[cfg(unix)] +use crate::stream; use crate::{ api, cli::{ExecArgs, SandboxCreate}, - output, stream, + output, }; use anyhow::{Context, Result, bail}; -use reqwest::{Client, Method, StatusCode, header::HeaderMap}; +#[cfg(unix)] +use reqwest::header::HeaderMap; +use reqwest::{Client, Method, StatusCode}; use serde_json::{Value, json}; use std::{path::PathBuf, time::Duration}; use tokio::time::{Instant, sleep}; +#[cfg(unix)] use tokio_tungstenite::tungstenite::client::IntoClientRequest; use url::Url; use uuid::Uuid; @@ -16,7 +21,10 @@ use uuid::Uuid; pub struct LocalBackend { client: Client, origin: Url, + #[cfg(unix)] headers: HeaderMap, + #[cfg(unix)] + socket_path: PathBuf, pub state_dir: PathBuf, timeout: Duration, } @@ -40,21 +48,28 @@ pub fn validate(args: &SandboxCreate) -> Result<()> { impl LocalBackend { #[cfg(unix)] - pub fn new(origin: Url, token: &str, state_dir: PathBuf, timeout: Duration) -> Result { + pub fn new( + socket_path: PathBuf, + token: &str, + state_dir: PathBuf, + timeout: Duration, + ) -> Result { let mut headers = HeaderMap::new(); let mut value = reqwest::header::HeaderValue::from_str(&format!("Bearer {token}"))?; value.set_sensitive(true); headers.insert(reqwest::header::AUTHORIZATION, value); let client = Client::builder() .no_proxy() + .unix_socket(socket_path.clone()) .redirect(reqwest::redirect::Policy::none()) .default_headers(headers.clone()) .timeout(timeout) .build()?; Ok(Self { client, - origin, + origin: "http://localhost/".parse()?, headers, + socket_path, state_dir, timeout, }) @@ -144,6 +159,7 @@ impl LocalBackend { .context("Timed out waiting for the local sandbox")? } + #[cfg(unix)] pub async fn execute( &self, sandbox: &Sandbox, @@ -174,10 +190,12 @@ impl LocalBackend { .map_err(|_| anyhow::anyhow!("Invalid local stream URL"))?; let mut request = url.as_str().into_client_request()?; request.headers_mut().extend(self.headers.clone()); - let (socket, _) = - tokio::time::timeout(self.timeout, tokio_tungstenite::connect_async(request)) - .await - .context("Timed out attaching to local execution")??; + let (socket, _) = tokio::time::timeout(self.timeout, async { + let stream = tokio::net::UnixStream::connect(&self.socket_path).await?; + tokio_tungstenite::client_async(request, stream).await + }) + .await + .context("Timed out attaching to local execution")??; stream::terminal( socket, stream::Attachment { @@ -192,6 +210,11 @@ impl LocalBackend { .await } + #[cfg(not(unix))] + pub async fn execute(&self, _: &Sandbox, _: ExecArgs, _: bool) -> Result { + bail!("Local sandboxes require a Unix host") + } + pub async fn delete(&self, id: Uuid) -> Result<()> { eprintln!("Deleting local sandbox {id}…"); // Deletion can briefly contend with image preparation or a worker launch. diff --git a/src/local_runtime.rs b/src/local_runtime.rs index 71e71a9..adb0a15 100644 --- a/src/local_runtime.rs +++ b/src/local_runtime.rs @@ -34,11 +34,10 @@ mod unix { use std::{ fs::{self, File, OpenOptions}, io::{Read, Write}, - net::SocketAddr, os::{ fd::AsRawFd, unix::{ - fs::{DirBuilderExt, MetadataExt, OpenOptionsExt}, + fs::{DirBuilderExt, FileTypeExt, MetadataExt, OpenOptionsExt}, process::CommandExt, }, }, @@ -50,7 +49,7 @@ mod unix { #[derive(Deserialize)] struct Ready { version: u32, - address: SocketAddr, + socket_path: std::path::PathBuf, instance_id: Uuid, runtime_version: String, } @@ -118,11 +117,29 @@ mod unix { }; let ready: Ready = serde_json::from_slice(&bytes).context("Invalid local runtime discovery file")?; - if ready.version != 1 || !ready.address.ip().is_loopback() || ready.address.port() == 0 { + if ready.version != 1 || ready.socket_path != state.join("goblind.sock") { bail!("Unsupported or invalid local runtime discovery metadata"); } - let origin = format!("http://{}/", ready.address).parse()?; - let probe = LocalBackend::new(origin, token, state.to_owned(), Duration::from_secs(2))?; + let meta = match fs::symlink_metadata(&ready.socket_path) { + Ok(meta) => meta, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(error) => return Err(error.into()), + }; + // The private directory prevents other users from replacing this endpoint. + // Reject symlinks and foreign sockets before transmitting the bearer. + // SAFETY: geteuid has no arguments or memory effects. + if !meta.file_type().is_socket() + || meta.uid() != unsafe { libc::geteuid() } + || meta.mode() & 0o077 != 0 + { + bail!("Local runtime socket must be private and user-owned"); + } + let probe = LocalBackend::new( + ready.socket_path.clone(), + token, + state.to_owned(), + Duration::from_secs(2), + )?; let spec = match probe.request(Method::GET, "/v1/spec", None).await { Ok(spec) => spec, Err(error) @@ -151,7 +168,7 @@ mod unix { ); } Ok(Some(LocalBackend::new( - format!("http://{}/", ready.address).parse()?, + ready.socket_path, token, state.to_owned(), timeout, @@ -221,9 +238,9 @@ mod unix { .args([ "--state-dir", state.to_str().context("Local runtime path must be UTF-8")?, - "--listen", - "127.0.0.1:0", ]) + .arg("--unix-socket") + .arg(state.join("goblind.sock")) .arg("--worker") .arg(worker) .arg("--token-file") diff --git a/src/stream.rs b/src/stream.rs index a9953b8..0df914b 100644 --- a/src/stream.rs +++ b/src/stream.rs @@ -291,10 +291,8 @@ pub struct Attachment { pub credit: Option, } -pub async fn terminal( - socket: tokio_tungstenite::WebSocketStream< - tokio_tungstenite::MaybeTlsStream, - >, +pub async fn terminal( + socket: tokio_tungstenite::WebSocketStream, attachment: Attachment, ) -> Result { let Attachment { @@ -318,11 +316,41 @@ pub async fn terminal( let mut stdin = tokio::io::stdin(); let mut buffer = [0u8; 4096]; let mut input_open = input; + let mut remote_input_open = true; + let mut pending = VecDeque::new(); + let mut eof_pending = false; + let mut overflow_warned = false; + const MAX_PENDING_INPUT: usize = 32768; let mut last_sequence = after; let mut last_size = crossterm::terminal::size().unwrap_or((80, 24)); let mut resize = tokio::time::interval(Duration::from_millis(250)); loop { - let capacity = credit.unwrap_or(buffer.len()).min(buffer.len()); + while !pending.is_empty() && credit.is_none_or(|available| available > 0) { + let count = pending + .len() + .min(credit.unwrap_or(buffer.len())) + .min(buffer.len()); + let bytes: Vec = pending.drain(..count).collect(); + if let Some(available) = credit.as_mut() { + *available -= count; + } + writer.send(Message::Binary(bytes.into())).await?; + } + if eof_pending && pending.is_empty() { + eof_pending = false; + writer + .send(Message::Text( + json!({"kind":"stdin_eof"}).to_string().into(), + )) + .await?; + } + // TTY input must stay readable even with no remote credit so Ctrl-] + // can detach. Queue at most one window and report discarded overflow. + let capacity = if tty { + buffer.len() + } else { + credit.unwrap_or(buffer.len()).min(buffer.len()) + }; tokio::select! { message = reader.next() => { let Some(message) = message else { bail!("Attachment disconnected. {}", resume.replace("{sequence}", &last_sequence.to_string())); }; @@ -334,17 +362,18 @@ pub async fn terminal( match kind { "attached" => { *available = data["session"]["stdin_credit"].as_u64().context("Missing stdin credit")?.try_into()?; - input_open &= data["session"]["stdin_closed"] != true; + remote_input_open &= data["session"]["stdin_closed"] != true; }, "started" => *available = 32768, "stdin_consumed" => { let bytes: usize = data["bytes"].as_u64().context("Missing stdin consumption")?.try_into()?; *available = available.checked_add(bytes).context("Invalid stdin credit")?; }, - "stdin_closed" => input_open = false, + "stdin_closed" => remote_input_open = false, _ => {}, } if *available > 32768 { bail!("Invalid stdin credit window"); } + if !remote_input_open { pending.clear(); eof_pending = false; } } match kind { "error" | "rejected" => bail!("Execution failed: {}", output::safe(data["message"].as_str().unwrap_or("runtime rejected the stream"))), @@ -372,18 +401,24 @@ pub async fn terminal( _ => {}, } }, - count = stdin.read(&mut buffer[..capacity]), if input_open && capacity > 0 => { + count = stdin.read(&mut buffer[..capacity]), if input_open && (tty || remote_input_open) && capacity > 0 => { let count = count?; if count == 0 { input_open = false; - writer.send(Message::Text(json!({"kind":"stdin_eof"}).to_string().into())).await?; + eof_pending = remote_input_open; } else { if tty && buffer[..count].contains(&0x1d) { writer.close().await?; return Ok(0); } - if let Some(available) = credit.as_mut() { *available -= count; } - writer.send(Message::Binary(buffer[..count].to_vec().into())).await?; + if remote_input_open { + let queued = count.min(MAX_PENDING_INPUT - pending.len()); + pending.extend(&buffer[..queued]); + if queued < count && !overflow_warned { + eprintln!("Input buffer full; additional input is discarded until the sandbox reads again. Ctrl-] still detaches.\r"); + overflow_warned = true; + } + } } }, _ = resize.tick(), if tty => { diff --git a/tests/local_shell/manager.py b/tests/local_shell/manager.py index 4a909a7..76cc88e 100644 --- a/tests/local_shell/manager.py +++ b/tests/local_shell/manager.py @@ -3,11 +3,12 @@ import argparse import json import os -from http.server import BaseHTTPRequestHandler, HTTPServer +from http.server import BaseHTTPRequestHandler +from socketserver import UnixStreamServer from pathlib import Path parser = argparse.ArgumentParser() -for flag in ("state-dir", "listen", "worker", "token-file", "ready-file"): +for flag in ("state-dir", "unix-socket", "worker", "token-file", "ready-file"): parser.add_argument("--" + flag, required=True) args = parser.parse_args() assert "ADAPT_TOKEN" not in os.environ @@ -45,12 +46,14 @@ def log_message(self, *_): pass -host, port = args.listen.rsplit(":", 1) -server = HTTPServer((host, int(port)), Handler) +# UnixStreamServer avoids HTTPServer's blocking reverse-DNS lookup on startup. +server = UnixStreamServer(args.unix_socket, Handler) +Path(args.unix_socket).chmod(0o600) +print("fixture Unix socket bound", flush=True) ready = Path(args.ready_file) temporary = ready.with_suffix(".tmp") temporary.write_text(json.dumps({ - "version": 1, "address": "%s:%s" % server.server_address, + "version": 1, "socket_path": args.unix_socket, "pid": os.getpid(), "instance_id": instance, "runtime_version": "fixture", })) temporary.chmod(0o600) diff --git a/tests/local_shell/mod.rs b/tests/local_shell/mod.rs index a0ea6b2..3880aea 100644 --- a/tests/local_shell/mod.rs +++ b/tests/local_shell/mod.rs @@ -30,10 +30,10 @@ fn command_for(state: &Path) -> Command { cmd } -fn discovery(state: &Path, url: &str) { +fn discovery(state: &Path) { fs::set_permissions(state, fs::Permissions::from_mode(0o700)).unwrap(); private_file(&state.join("token"), TOKEN.as_bytes()); - private_file(&state.join("ready.json"), json!({"version":1,"address":url.strip_prefix("http://").unwrap(),"instance_id":INSTANCE,"runtime_version":"test"}).to_string().as_bytes()); + private_file(&state.join("ready.json"), json!({"version":1,"socket_path":state.canonicalize().unwrap().join("goblind.sock"),"instance_id":INSTANCE,"runtime_version":"test"}).to_string().as_bytes()); // Local operation must not even deserialize the saved cloud profile. private_file(&state.join("config.json"), b"not valid JSON"); } @@ -61,6 +61,10 @@ struct Ids { } fn setup(ids: &Arc>) -> Vec { + setup_with_tty(ids, false) +} + +fn setup_with_tty(ids: &Arc>, tty: bool) -> Vec { let create_ids = ids.clone(); let ready_ids = ids.clone(); let exec_ids = ids.clone(); @@ -94,11 +98,16 @@ fn setup(ids: &Arc>) -> Vec { let body = r.json(); ids.session = body["id"].as_str().unwrap().into(); uuid::Uuid::parse_str(&ids.session).unwrap(); - assert_eq!(body["argv"], json!(["cat"])); + if tty { + assert_eq!(body["argv"][0], "/bin/sh"); + assert_eq!(body["argv"][1], "-c"); + } else { + assert_eq!(body["argv"], json!(["cat"])); + } assert_eq!(body["env"], json!({"LITERAL":" a=b\n$HOME "})); assert_eq!(body["stdin"], true); assert_eq!(body["timeout_ms"], 86_400_000); - assert!(body.get("terminal").is_none()); + assert_eq!(body.get("terminal").is_some(), tty); Reply::json(202, json!({"id":ids.session,"state":"starting"})) })), ] @@ -208,9 +217,9 @@ fn local_shell_uses_its_own_credentials_honors_credit_and_cleans_up_on_nonzero_e } })); steps.push(deleted(ids)); - let server = Server::script(steps); let dir = tempfile::tempdir().unwrap(); - discovery(dir.path(), &server.url); + discovery(dir.path()); + let server = Server::unix(&dir.path().join("goblind.sock"), steps); let mut cmd = command_for(dir.path()); args(&mut cmd); let output = with_stdin(cmd, &vec![b'x'; 128 * 1024]); @@ -236,9 +245,9 @@ fn local_stream_failure_still_deletes_the_vm() { ); })); steps.push(deleted(ids)); - let server = Server::script(steps); let dir = tempfile::tempdir().unwrap(); - discovery(dir.path(), &server.url); + discovery(dir.path()); + let server = Server::unix(&dir.path().join("goblind.sock"), steps); let output = args(&mut command_for(dir.path())).output().unwrap(); assert_eq!(output.status.code(), Some(1)); assert!(String::from_utf8_lossy(&output.stderr).contains("guest execution failed")); @@ -309,15 +318,26 @@ fn saved_local_runtime_settings_do_not_change_an_explicit_cloud_target() { #[test] fn rejects_untrusted_discovery_before_sending_a_token() { let dir = tempfile::tempdir().unwrap(); - discovery(dir.path(), "http://192.0.2.1:1234"); + discovery(dir.path()); + // A stale TCP address may have been rebound by another local user. Never + // connect to it, even when the discovery record and token are private. + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + listener.set_nonblocking(true).unwrap(); + private_file(&dir.path().join("ready.json"), json!({"version":1,"address":listener.local_addr().unwrap(),"instance_id":INSTANCE,"runtime_version":"test"}).to_string().as_bytes()); let output = command_for(dir.path()) .args(["--", "true"]) .output() .unwrap(); - assert!(String::from_utf8_lossy(&output.stderr).contains("invalid local runtime discovery")); + assert!( + String::from_utf8_lossy(&output.stderr).contains("Invalid local runtime discovery file") + ); + assert_eq!( + listener.accept().unwrap_err().kind(), + std::io::ErrorKind::WouldBlock + ); private_file( &dir.path().join("ready.json"), - json!({"version":1,"address":"127.0.0.1:1","instance_id":"not-a-uuid","runtime_version":"test"}) + json!({"version":1,"socket_path":dir.path().canonicalize().unwrap().join("goblind.sock"),"instance_id":"not-a-uuid","runtime_version":"test"}) .to_string() .as_bytes(), ); @@ -412,3 +432,99 @@ fn concurrent_clients_bootstrap_one_detached_manager_and_reuse_it() { 0 ); } + +#[test] +fn terminal_detaches_with_zero_credit_even_after_the_input_queue_fills() { + use crate::sandbox_sh::unix::{Terminal, wait}; + use std::{io::Write, os::fd::AsRawFd, time::Duration}; + + for initial_credit in [0, 1] { + let terminal = Terminal::new(); + let mut master = terminal.master.try_clone().unwrap(); + let ids = Arc::new(Mutex::new(Ids::default())); + let mut steps = setup_with_tty(&ids, true); + steps.push(stream(ids.clone(), move |mut ws| { + send(&mut ws, json!({"kind":"attached","session":{"stdin_credit":initial_credit,"stdin_closed":false}})); + let deadline = Instant::now() + Duration::from_secs(5); + loop { + // SAFETY: the live PTY descriptor and output pointer are valid. + let raw = unsafe { + let mut state: libc::termios = std::mem::zeroed(); + assert_eq!(libc::tcgetattr(master.as_raw_fd(), &mut state), 0); + state.c_lflag & libc::ICANON == 0 + }; + if raw { break; } + assert!(Instant::now() < deadline, "terminal did not enter raw mode"); + std::thread::sleep(Duration::from_millis(5)); + } + if initial_credit > 0 { + master.write_all(b"x").unwrap(); + assert_eq!(ws.read().unwrap(), Message::Binary(vec![b'x'].into())); + } + // Fill beyond the bounded queue while no credit can arrive. Input + // must still be consumed so an escape behind it remains reachable. + let mut bytes = vec![b'y'; 64 * 1024]; + bytes.push(0x1d); + let mut written = 0; + while written < bytes.len() { + match master.write(&bytes[written..]) { + Ok(count) => written += count, + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => { + assert!(Instant::now() < deadline, "input stopped before escape"); + std::thread::sleep(Duration::from_millis(5)); + } + other => panic!("PTY write failed: {other:?}"), + } + } + assert!(matches!(ws.read().unwrap(), Message::Close(_))); + })); + steps.push(terminal.restored_then(deleted(ids))); + let dir = tempfile::tempdir().unwrap(); + discovery(dir.path()); + let server = Server::unix(&dir.path().join("goblind.sock"), steps); + let mut cmd = command_for(dir.path()); + cmd.args([ + "--cpu", + "2", + "--memory", + "512", + "--disk", + "128", + "--env", + "LITERAL= a=b\n$HOME ", + ]); + let (code, stderr) = wait(terminal.spawn(cmd), Some(&terminal)); + assert_eq!(code, 0, "{stderr}"); + assert!(stderr.contains("Input buffer full"), "{stderr}"); + server.finish(); + } +} + +#[test] +fn discovery_rejects_external_and_symlinked_unix_sockets_before_authentication() { + use std::os::unix::{fs::symlink, net::UnixListener}; + let dir = tempfile::tempdir().unwrap(); + let external = tempfile::tempdir().unwrap(); + let external_path = external.path().join("goblind.sock"); + let listener = UnixListener::bind(&external_path).unwrap(); + listener.set_nonblocking(true).unwrap(); + for socket_path in [ + external_path.clone(), + dir.path().canonicalize().unwrap().join("goblind.sock"), + ] { + discovery(dir.path()); + private_file(&dir.path().join("ready.json"), json!({"version":1,"socket_path":socket_path,"instance_id":INSTANCE,"runtime_version":"test"}).to_string().as_bytes()); + if socket_path.starts_with(dir.path().canonicalize().unwrap()) { + symlink(&external_path, &socket_path).unwrap(); + } + let output = command_for(dir.path()) + .args(["--", "true"]) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(1)); + assert_eq!( + listener.accept().unwrap_err().kind(), + std::io::ErrorKind::WouldBlock + ); + } +} diff --git a/tests/sandbox_sh/mod.rs b/tests/sandbox_sh/mod.rs index ec1cf1b..aad4a99 100644 --- a/tests/sandbox_sh/mod.rs +++ b/tests/sandbox_sh/mod.rs @@ -296,7 +296,7 @@ fn interactive_preflight_rejects_missing_terminal_and_json_before_creation() { } #[cfg(unix)] -mod unix { +pub(crate) mod unix { use super::*; use std::{ fs::File, @@ -309,14 +309,14 @@ mod unix { time::{Duration, Instant}, }; - struct Terminal { - master: File, + pub(crate) struct Terminal { + pub(crate) master: File, slave: File, original: libc::termios, } impl Terminal { - fn new() -> Self { + pub(crate) fn new() -> Self { let mut master = -1; let mut slave = -1; let mut size = libc::winsize { @@ -363,7 +363,7 @@ mod unix { } } - fn spawn(&self, mut cmd: Command) -> Child { + pub(crate) fn spawn(&self, mut cmd: Command) -> Child { cmd.stdin(self.slave.try_clone().unwrap()) .stdout(self.slave.try_clone().unwrap()) .stderr(Stdio::piped()); @@ -380,6 +380,10 @@ mod unix { } fn cleanup(&self) -> Exchange { + self.restored_then(deleted()) + } + + pub(crate) fn restored_then(&self, next: Exchange) -> Exchange { let slave = self.slave.try_clone().unwrap(); let original = self.original; Box::new(move |socket| { @@ -397,12 +401,12 @@ mod unix { assert_eq!(current.c_iflag, original.c_iflag); assert_eq!(current.c_oflag, original.c_oflag); } - deleted()(socket) + next(socket) }) } } - fn wait(mut child: Child, terminal: Option<&Terminal>) -> (i32, String) { + pub(crate) fn wait(mut child: Child, terminal: Option<&Terminal>) -> (i32, String) { let deadline = Instant::now() + Duration::from_secs(20); let mut master = terminal.map(|t| t.master.try_clone().unwrap()); let status = loop { diff --git a/tests/support/mod.rs b/tests/support/mod.rs index e7e8443..db242ef 100644 --- a/tests/support/mod.rs +++ b/tests/support/mod.rs @@ -2,7 +2,7 @@ use serde_json::{Value, json}; use std::{ collections::HashMap, io::{self, Read, Write}, - net::{TcpListener, TcpStream}, + net::TcpListener, path::Path, process::{Command, Output, Stdio}, thread::{self, JoinHandle}, @@ -56,7 +56,9 @@ impl Reply { pub type Handler = Box Reply + Send>; pub type Exchange = Box Request + Send>; -pub struct TestSocket(TcpStream); +trait SocketIo: Read + Write {} +impl SocketIo for T {} +pub struct TestSocket(Box); impl Read for TestSocket { fn read(&mut self, buffer: &mut [u8]) -> io::Result { @@ -171,7 +173,7 @@ impl Server { socket .set_read_timeout(Some(Duration::from_secs(10))) .unwrap(); - requests.push(step(TestSocket(socket))); + requests.push(step(TestSocket(Box::new(socket)))); } requests }); @@ -180,6 +182,47 @@ impl Server { pub fn finish(self) -> Vec { self.handle.join().unwrap() } + + #[cfg(any( + all(target_os = "macos", target_arch = "aarch64"), + all(target_os = "linux", target_arch = "x86_64") + ))] + pub fn unix(path: &Path, steps: Vec) -> Self { + use std::os::unix::{fs::PermissionsExt, net::UnixListener}; + let listener = UnixListener::bind(path).unwrap(); + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).unwrap(); + listener.set_nonblocking(true).unwrap(); + let handle = thread::spawn(move || { + steps + .into_iter() + .map(|step| { + let deadline = Instant::now() + Duration::from_secs(30); + let socket = loop { + match listener.accept() { + Ok((socket, _)) => break socket, + Err(e) if e.kind() == io::ErrorKind::Interrupted => continue, + Err(e) + if e.kind() == io::ErrorKind::WouldBlock + && Instant::now() < deadline => + { + thread::sleep(Duration::from_millis(5)) + } + other => panic!("Expected another Unix socket request, got {other:?}"), + } + }; + socket.set_nonblocking(false).unwrap(); + socket + .set_read_timeout(Some(Duration::from_secs(10))) + .unwrap(); + step(TestSocket(Box::new(socket))) + }) + .collect() + }); + Self { + url: "http://localhost".into(), + handle, + } + } } pub fn read_request(socket: &mut TestSocket) -> Request { From 353fe6492eae8e094fb0b72a481a037c8402fbae Mon Sep 17 00:00:00 2001 From: Sean Smith Date: Mon, 23 Nov 2026 13:00:28 -0800 Subject: [PATCH 4/6] Compile local sandbox environment only on Unix hosts --- src/backend/local.rs | 1 + src/backend/mod.rs | 3 +++ 2 files changed, 4 insertions(+) diff --git a/src/backend/local.rs b/src/backend/local.rs index 9ea427f..169606c 100644 --- a/src/backend/local.rs +++ b/src/backend/local.rs @@ -105,6 +105,7 @@ impl LocalBackend { validate(&args)?; let sandbox = Sandbox { id: Uuid::new_v4(), + #[cfg(unix)] env: args.env.into_iter().collect(), }; eprintln!("Creating local sandbox: {}", sandbox.id); diff --git a/src/backend/mod.rs b/src/backend/mod.rs index 8185c3c..954c73e 100644 --- a/src/backend/mod.rs +++ b/src/backend/mod.rs @@ -7,11 +7,13 @@ use crate::{ commands, shell, }; use anyhow::Result; +#[cfg(unix)] use std::collections::BTreeMap; use uuid::Uuid; pub struct Sandbox { pub id: Uuid, + #[cfg(unix)] pub env: BTreeMap, } @@ -25,6 +27,7 @@ impl SandboxBackend<'_> { match self { Self::Cloud(api) => Ok(Sandbox { id: commands::resource_id(&commands::create_sandbox(api, args).await?)?, + #[cfg(unix)] env: BTreeMap::new(), }), Self::Local(local) => local.create(args).await, From d98645c6e89ed5eb29bb6cd6447e67c3a9de7ea0 Mon Sep 17 00:00:00 2001 From: Sean Smith Date: Mon, 23 Nov 2026 13:22:23 -0800 Subject: [PATCH 5/6] Route resource operations through shared cloud and local backends --- Cargo.toml | 2 +- README.md | 12 +- docs/cli-reference.md | 127 +++++++----- skills/adapt/SKILL.md | 27 ++- src/backend/cloud.rs | 150 ++++++++++++++ src/backend/local.rs | 364 +++++++++++++++++++++++++++------ src/backend/mod.rs | 117 ++++++----- src/cli.rs | 34 ++-- src/commands.rs | 185 ++++++++--------- src/local_runtime.rs | 20 +- src/main.rs | 19 +- src/shell.rs | 59 +----- tests/backend/mod.rs | 138 +++++++++++++ tests/cli.rs | 1 + tests/local_shell/backend.rs | 377 +++++++++++++++++++++++++++++++++++ tests/local_shell/mod.rs | 4 +- tests/sandbox_sh/mod.rs | 3 +- 17 files changed, 1281 insertions(+), 358 deletions(-) create mode 100644 src/backend/cloud.rs create mode 100644 tests/backend/mod.rs create mode 100644 tests/local_shell/backend.rs diff --git a/Cargo.toml b/Cargo.toml index da46bcf..d5d5b7e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,7 +21,7 @@ reqwest = { version = "0.12", default-features = false, features = ["json", "rus serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" tempfile = "3.27" -tokio = { version = "1.53", features = ["macros", "rt-multi-thread", "time", "signal", "io-util", "io-std", "net"] } +tokio = { version = "1.53", features = ["macros", "rt-multi-thread", "time", "signal", "io-util", "io-std", "net", "sync"] } tokio-tungstenite = { version = "0.29", features = ["rustls-tls-native-roots"] } url = "2.5" uuid = { version = "1.27", features = ["v4", "serde"] } diff --git a/README.md b/README.md index 5f48680..8a73727 100644 --- a/README.md +++ b/README.md @@ -84,7 +84,7 @@ Sandboxes expire after one hour by default. Use `--ttl SECONDS` to change this time. Use `--no-expiry` to disable automatic expiry. -### Run a temporary sandbox locally +### Run sandboxes locally On Apple Silicon macOS or x86_64 Linux with KVM, point Adapt at a compatible Goblin bundle containing `goblind` and an embedded-firmware `goblin-worker`: @@ -93,13 +93,17 @@ Goblin bundle containing `goblind` and an embedded-firmware `goblin-worker`: export ADAPT_LOCAL_RUNTIME=/path/to/goblin-release/bin adapt sandbox sh --local --image ubuntu:24.04 -- uname -m adapt sandbox sh --local -``` +adapt --local sandbox create --image ubuntu:24.04 --wait +adapt --local sandbox list +adapt --local exec SANDBOX_ID -- uname -m +adapt --local sandbox delete SANDBOX_ID\``` Adapt starts and reuses a private local manager without Platform login. The shell -or command runs in a local VM, which is deleted when the session ends. Existing +or command from `sandbox sh` runs in a VM that is deleted when the session ends. +`sandbox create` keeps the VM for later commands until you stop or delete it. Existing commands keep their cloud default; `sandbox sh --cloud` selects it explicitly. This initial local workflow requires a manually supplied runtime bundle. See -[local sandbox options and limitations](docs/cli-reference.md#local-temporary-sandboxes). +[local sandbox options and limitations](docs/cli-reference.md#local-sandboxes). ## Create a sandbox diff --git a/docs/cli-reference.md b/docs/cli-reference.md index 0c750cb..6cbf00c 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -223,55 +223,85 @@ The `--ttl` option sets expiry in seconds. The `--no-expiry` option disables automatic expiry. Shells have a maximum execution timeout of 24 hours. -### Local temporary sandboxes - -```sh -adapt sandbox sh --local --runtime-dir /path/to/goblin-release/bin --image ubuntu:24.04 -- uname -m -adapt sandbox sh --local --env EDITOR=vim -printf 'hello\n' | adapt sandbox sh --local -- cat -adapt sandbox sh --cloud -- uname -m -``` - -`--local` runs a temporary VM on Apple Silicon macOS or x86_64 Linux with KVM. -It does not read cloud profiles or use Platform tokens. `--local` and `--cloud` -are mutually exclusive; omitting both preserves the cloud default. These target -flags currently apply to `sandbox sh` only. `auth logout --local` keeps its -existing credential-removal meaning. +### Local sandboxes + +```sh +export ADAPT_LOCAL_RUNTIME=/path/to/goblin-release/bin +adapt sandbox sh --local --image ubuntu:24.04 -- uname -m +adapt --local sandbox create --image ubuntu:24.04 --env EDITOR=vim --wait +adapt --local sandbox list +adapt --local sandbox get SANDBOX_ID +adapt --local exec SANDBOX_ID -- /bin/sh -c 'echo "$EDITOR"' +adapt --local exec SANDBOX_ID -it -- /bin/sh +adapt --local sandbox stop SANDBOX_ID --wait +adapt --local sandbox delete SANDBOX_ID +``` + +`--local` selects the local backend on Apple Silicon macOS or x86_64 Linux with +KVM. `--cloud` explicitly selects Platform, which remains the default. These are +global flags: they work before or after a subcommand and cannot be combined. +Runtime environment variables configure the local runtime without selecting it. +Local resource commands do not read cloud profiles or send Platform tokens. +Unsupported operations return an error before launching a runtime; they never +fall back to the cloud. `auth logout --local` retains its credential-removal +meaning, and `skill` commands remain offline. + +| Operation | Local support | +| --- | --- | +| `sandbox create`, `get`, `list`, `stop`, `delete`, `wait`, `sh` | Supported | +| `exec`, including stdin and PTY | Supported; sandbox remains after execution | +| `sandbox start`, `usage` | Not supported yet | +| `exec --detach`, `execs`, `files` | Not supported yet | +| `images`, `volumes`, `endpoints`, other Platform services | Not supported yet | + +Local resource IDs must be full UUIDs. `sandbox list` returns all UUID-addressed +VMs in the selected manager; `--query` filters UUID prefixes, and `--all` is +accepted. Named VMs created outside Adapt are omitted. `--limit` and `--cursor` +are not supported locally. Local responses expose common `id`, `status`, `cpu`, +and `memoryMiB` fields where available, alongside Goblin's diagnostics. Goblin's +`ready` and `busy` states both map to `running`. Local waits accept `running`, +`stopped`, `deleted`, `failed`, or `completed`, and respect `--wait-timeout`. +Stopping a VM ends its processes; restarting it is not implemented yet. Supply a compatible Goblin runtime with `--runtime-dir` or `ADAPT_LOCAL_RUNTIME`. -The directory must contain `goblind` with `--ready-file` and `--unix-socket` support and a native -`goblin-worker` with matching embedded firmware. The macOS worker must be signed -with its hypervisor entitlement. Automatic bundle installation is not included -yet. Adapt discovers a running manager before requiring the bundle path again. - -State, image cache, the local token, discovery metadata, and `goblind.log` live in -`ADAPT_CONFIG_DIR/local` (using the usual config-directory default). Override this -with `--local-state-dir` or `ADAPT_LOCAL_STATE_DIR`; the directory must be private -and owned by the current user. The manager runs independently of the terminal, -listens on a private `goblind.sock` Unix socket inside that directory, and uses a -separate token. Adapt validates the socket path, ownership, and permissions before -sending credentials; HTTP and WebSocket requests both use the socket and bypass -proxies. Stale TCP discovery records are rejected. Concurrent commands reuse one manager. - -Local shells accept `--image`, `--cpu`, `--memory`, `--disk`, and repeated `--env`. -Defaults are `ubuntu:24.04`, one CPU, 1024 MiB memory, and a 2048 MiB writable disk. -The guest can reach public internet destinations, with private/loopback egress -blocked by Goblin's public policy. No host directories are mounted. -`--wait` is redundant because a shell always waits; `--no-expiry` is accepted. -Local `--env` values apply to the shell or command. `--data`, cloud image IDs, -labels, variable sets, image startup commands, TTL, and idempotency keys are -rejected before starting the runtime. - -Normal exit, Ctrl-], stream failure, and handled interruption trigger VM deletion. +The directory must contain `goblind` with `--ready-file` and `--unix-socket` +support and a native `goblin-worker` with matching embedded firmware. The macOS +worker must be signed with its hypervisor entitlement. Automatic bundle +installation is not included yet. Adapt discovers a running manager before +requiring the bundle path again. + +State, image cache, the local token, discovery metadata, sandbox environment +files, and `goblind.log` live in `ADAPT_CONFIG_DIR/local` (using the usual config +directory default). Override this with `--local-state-dir` or +`ADAPT_LOCAL_STATE_DIR`; use the same directory on subsequent commands. It must +be private and owned by the current user. The manager runs independently of the +terminal, listens on a private `goblind.sock` Unix socket, and uses a separate +token. Adapt validates socket ownership and permissions before sending +credentials; HTTP and WebSocket requests bypass proxies. Stale TCP discovery +records are rejected. Concurrent commands reuse one manager. + +Local creation accepts `--image`, `--cpu`, `--memory`, `--disk`, and repeated +`--env`. Defaults are `ubuntu:24.04`, one CPU, 1024 MiB memory, and a 2048 MiB +writable disk. Environment values are stored in private files and applied by +later `adapt exec` commands; execution `--env` flags override them. They are not +image startup configuration. The guest can reach public internet destinations, +with private/loopback egress blocked by Goblin's public policy. Host mounts and +local/cloud moves are not implemented. + +`--wait` on create or stop waits for the requested state. `sandbox sh` always +waits, streams stdin/output, and deletes its VM on exit, Ctrl-], stream failure, +or handled interruption. Persistent `sandbox create` leaves the VM running until +explicitly stopped or deleted. Local sandboxes have no daemon-enforced expiry; +`--no-expiry` is accepted. `--data`, cloud image IDs, labels, variable sets, image +startup commands, TTL, and idempotency keys are rejected before runtime startup. + Ctrl-] remains available when the guest stops reading input. Interactive input -queues up to 32 KiB locally; additional input is discarded with a warning until -the guest resumes reading. Piped input is backpressured without discarding bytes. -The command has a 24-hour execution limit. Local sandboxes have no daemon-enforced -TTL in this first version, so a killed CLI or failed cleanup can leave a VM behind; -the diagnostic reports its UUID and state directory for local Goblin API cleanup. -Persistent local create/exec/files, stop/start, mounts, and local/cloud moves are -not exposed by this change. Local runtime logs and session output do not have -Platform's retained, redacted log service. +queues up to 32 KiB locally; further input is discarded with a warning until the +guest resumes reading. Piped input is backpressured without discarding bytes. +Temporary shells have a 24-hour execution limit. An uncatchable CLI kill or failed +cleanup can leave a VM behind; use `adapt --local sandbox list` and `delete` to +inspect and remove it. Local logs and session output do not have Platform's +retained, redacted log service. ### Sandbox options @@ -473,7 +503,7 @@ adapt models discover PROVIDER_ID ## Resource IDs -These resources accept full UUIDs or unique ID prefixes: +On the cloud backend, these resources accept full UUIDs or unique ID prefixes: - Sandboxes and executions. - Images and registry credentials. @@ -680,6 +710,9 @@ It does not retry this request automatically. | Setting | Option | Environment variable | | --- | --- | --- | +| Backend; default: cloud | `--local` / `--cloud` | None | +| Local runtime bundle | `--runtime-dir` | `ADAPT_LOCAL_RUNTIME` | +| Local state directory | `--local-state-dir` | `ADAPT_LOCAL_STATE_DIR` | | API origin | `--api-url` | `ADAPT_API_URL` | | Profile; default: `default` | `--profile` | `ADAPT_PROFILE` | | Organization for this request | `--org` | `ADAPT_ORG_ID` | diff --git a/skills/adapt/SKILL.md b/skills/adapt/SKILL.md index d389213..bfafd76 100644 --- a/skills/adapt/SKILL.md +++ b/skills/adapt/SKILL.md @@ -70,14 +70,25 @@ Use `exec --detach` to return execution metadata immediately, or `exec -it` for an interactive terminal. Normal command execution streams output and returns the remote exit code. -For a temporary local VM, use `adapt sandbox sh --local` on Apple Silicon macOS -or x86_64 Linux with KVM. Set `ADAPT_LOCAL_RUNTIME` to a compatible Goblin bundle's -`bin` directory, or pass `--runtime-dir`. This works without Platform login and -supports image, CPU, memory, disk, and environment flags. Local TTL, cloud image -IDs, variable sets, labels, `--data`, image startup, and idempotency keys are not -supported. Only `sandbox sh` currently accepts the local target; other resource -commands retain their cloud behavior. Local shells are deleted on exit and do not -mount host directories. `--cloud` explicitly selects the existing cloud shell. +Use the global `--local` flag for local sandboxes on Apple Silicon macOS or +x86_64 Linux with KVM. Set `ADAPT_LOCAL_RUNTIME` to a compatible Goblin bundle's +`bin` directory, or pass `--runtime-dir`. Local commands work without Platform +login. Cloud remains the default; `--cloud` selects it explicitly. Never retry an +unsupported local operation against the cloud unless the user chooses that target. + +Local `sandbox create`, `list`, `get`, `stop`, `delete`, `wait`, `sh`, and attached +`exec` are supported. Use full sandbox UUIDs. `sandbox create --wait` leaves the +VM running for later commands; `sandbox sh` deletes it on exit. Creation accepts +image, CPU, memory, disk, and environment flags. Local `--env` values persist for +later `exec` commands, whose environment flags override them. Use the same +`--local-state-dir` / `ADAPT_LOCAL_STATE_DIR` across commands when overriding it. + +Local start/restart, usage, `exec --detach`, `execs`, files, other resource +families, mounts, moves, TTL, cloud image IDs, variable sets, labels, `--data`, +image startup, and idempotency keys return unsupported errors. Local lists are +unpaginated; `--query` matches UUID prefixes, while `--limit` and `--cursor` are +unsupported. Local VMs do not expire automatically; use `adapt --local sandbox +list` and `adapt --local sandbox delete ID` to clean up a VM left after a killed CLI. ```sh adapt execs get EXEC_ID diff --git a/src/backend/cloud.rs b/src/backend/cloud.rs new file mode 100644 index 0000000..9678581 --- /dev/null +++ b/src/backend/cloud.rs @@ -0,0 +1,150 @@ +use super::Backend; +use crate::{ + api::{Api, ApiError}, + cli::*, + commands, + input::ResourceRef, + output, stream, +}; +use anyhow::Result; +use reqwest::{Method, StatusCode}; +use serde_json::{Value, json}; +use uuid::Uuid; + +pub struct CloudBackend<'a>(pub &'a Api); + +impl Backend for CloudBackend<'_> { + fn name(&self) -> &'static str { + "cloud" + } + + async fn sandbox_list(&self, args: SandboxList) -> Result { + let filters = args + .query + .iter() + .map(|text| ("query".into(), text.clone())) + .collect::>(); + self.0 + .list("/v1/sandboxes", "sandboxes", &args.page, true, &filters) + .await + } + async fn sandbox_get(&self, id: ResourceRef) -> Result { + self.0.get(&format!("/v1/sandboxes/{id}")).await + } + async fn sandbox_create(&self, args: SandboxCreate) -> Result { + commands::create_sandbox(self.0, args).await + } + async fn sandbox_start(&self, id: ResourceRef) -> Result { + self.0 + .post(&format!("/v1/sandboxes/{id}/start"), &json!({})) + .await + } + async fn sandbox_stop(&self, id: ResourceRef) -> Result { + self.0 + .post(&format!("/v1/sandboxes/{id}/stop"), &json!({})) + .await + } + async fn sandbox_delete(&self, id: ResourceRef) -> Result { + self.0 + .json( + Method::DELETE, + &format!("/v1/sandboxes/{id}"), + None, + &[], + None, + ) + .await + } + async fn sandbox_wait(&self, id: ResourceRef, status: &str, seconds: u64) -> Result { + commands::wait_for(self.0, "sandboxes", id, status, seconds).await + } + async fn sandbox_usage(&self, id: ResourceRef, hours: &str) -> Result { + self.0 + .json( + Method::GET, + &format!("/v1/sandboxes/{id}/usage"), + None, + &[("hours".into(), hours.into())], + None, + ) + .await + } + async fn execute(&self, args: ExecArgs, json: bool) -> Result { + commands::execute(self.0, args, json).await + } + async fn executions(&self, command: ExecCommand, json: bool) -> Result { + let result = match command { + ExecCommand::Get { id } => self.0.get(&format!("/v1/execs/{id}")).await?, + ExecCommand::Cancel { id } => { + self.0 + .post(&format!("/v1/execs/{id}/cancel"), &json!({})) + .await? + } + ExecCommand::Logs { id, cursor } => { + return stream::logs(self.0, id, cursor, json).await; + } + ExecCommand::Attach { + id, + after, + stdin, + tty, + } => return stream::attach(self.0, id, after, stdin || tty, tty, json).await, + }; + output::print(&result, json)?; + Ok(0) + } + async fn files(&self, command: FileCommand) -> Result { + commands::files(self.0, command).await + } + async fn volumes(&self, command: VolumeCommand) -> Result { + commands::volumes(self.0, command).await + } + async fn images(&self, command: ImageCommand, json: bool) -> Result { + if let ImageCommand::List(args) = command { + return commands::list_images(self.0, args, json).await; + } + output::print(&commands::images(self.0, command).await?, json)?; + Ok(0) + } + async fn endpoints(&self, command: EndpointCommand, json: bool) -> Result { + if let EndpointCommand::Request(args) = command { + return commands::request_endpoint(self.0, args).await; + } + output::print(&commands::endpoints(self.0, command).await?, json)?; + Ok(0) + } + async fn cleanup(&self, id: Uuid) -> Result<()> { + cleanup(self.0, id).await + } +} + +async fn cleanup(api: &Api, id: Uuid) -> Result<()> { + eprintln!("Deleting temporary sandbox {id}…"); + let result: Result<()> = async { + let response = api + .json( + Method::DELETE, + &format!("/v1/sandboxes/{id}"), + None, + &[], + None, + ) + .await?; + if response["status"] != 204 { + commands::wait_for(api, "sandboxes", id, "deleted", 600).await?; + } + Ok(()) + } + .await; + // Expiry or another client may already have removed the sandbox. + match result { + Err(error) + if error + .downcast_ref::() + .is_some_and(|e| e.status == StatusCode::NOT_FOUND) => + { + Ok(()) + } + result => result, + } +} diff --git a/src/backend/local.rs b/src/backend/local.rs index 169606c..11b10d6 100644 --- a/src/backend/local.rs +++ b/src/backend/local.rs @@ -1,9 +1,10 @@ -use super::Sandbox; +use super::Backend; #[cfg(unix)] use crate::stream; use crate::{ api, - cli::{ExecArgs, SandboxCreate}, + cli::{ExecArgs, SandboxCreate, SandboxList}, + input::ResourceRef, output, }; use anyhow::{Context, Result, bail}; @@ -12,20 +13,22 @@ use reqwest::header::HeaderMap; use reqwest::{Client, Method, StatusCode}; use serde_json::{Value, json}; use std::{path::PathBuf, time::Duration}; +use tokio::sync::OnceCell; use tokio::time::{Instant, sleep}; #[cfg(unix)] use tokio_tungstenite::tungstenite::client::IntoClientRequest; use url::Url; use uuid::Uuid; -pub struct LocalBackend { +pub struct Goblin { client: Client, origin: Url, #[cfg(unix)] headers: HeaderMap, #[cfg(unix)] socket_path: PathBuf, - pub state_dir: PathBuf, + #[cfg(unix)] + state_dir: PathBuf, timeout: Duration, } @@ -40,13 +43,13 @@ pub fn validate(args: &SandboxCreate) -> Result<()> { (args.creation.idempotency_key.is_some(), "--idempotency-key"), ] { if present { - bail!("{flag} is not supported by local temporary sandboxes"); + bail!("{flag} is not supported by the local backend"); } } Ok(()) } -impl LocalBackend { +impl Goblin { #[cfg(unix)] pub fn new( socket_path: PathBuf, @@ -101,86 +104,105 @@ impl LocalBackend { } } - pub async fn create(&self, args: SandboxCreate) -> Result { - validate(&args)?; - let sandbox = Sandbox { - id: Uuid::new_v4(), - #[cfg(unix)] - env: args.env.into_iter().collect(), - }; - eprintln!("Creating local sandbox: {}", sandbox.id); + pub async fn create(&self, args: SandboxCreate) -> Result { + let id = Uuid::new_v4(); + // Save exec defaults before creating a VM; a separate `adapt exec` process + // must see the same environment as the temporary shell workflow. + #[cfg(unix)] + metadata::save(&self.state_dir, id, &args.env)?; + eprintln!("Creating local sandbox: {id}"); let body = json!({ - "id": sandbox.id.to_string(), "image": args.image.unwrap_or_else(|| "ubuntu:24.04".into()), + "id": id.to_string(), "image": args.image.unwrap_or_else(|| "ubuntu:24.04".into()), "resources": {"vcpus": args.cpu.unwrap_or(1), "memory_mib": args.memory.unwrap_or(1024)}, "state_size_mib": args.disk.unwrap_or(2048), "network": {"mode": "user", "egress": "public", "dns": "1.1.1.1"} }); - if let Err(error) = self.request(Method::POST, "/v1/vms", Some(&body)).await { - // The UUID is known even if an accepted request loses its response. - // Never delete a conflicting record owned by someone else. - if !error - .downcast_ref::() - .is_some_and(|e| e.status == StatusCode::CONFLICT) - && let Err(cleanup) = self.delete(sandbox.id).await - { - return Err(error.context(format!( - "Local create may have been accepted as {}; cleanup failed: {cleanup:#}", - sandbox.id - ))); + match self + .request(Method::POST, "/v1/vms", Some(&body)) + .await + .and_then(|value| snapshot(value, id)) + { + Ok(value) => Ok(value), + Err(error) => { + // A lost response may hide an accepted create. Never delete a + // conflicting VM owned by someone else. + if error + .downcast_ref::() + .is_some_and(|e| e.status == StatusCode::CONFLICT) + { + #[cfg(unix)] + metadata::remove(&self.state_dir, id)?; + } else if let Err(cleanup) = self.delete(id).await { + return Err(error.context(format!( + "Local create may have been accepted as {id}; cleanup failed: {cleanup:#}" + ))); + } + Err(error) } - return Err(error); } - Ok(sandbox) } - pub async fn wait(&self, id: Uuid) -> Result<()> { - eprintln!("Waiting for local sandbox {id}…"); - tokio::time::timeout(Duration::from_secs(600), async { + pub async fn wait(&self, id: Uuid, target: &str, seconds: u64) -> Result { + eprintln!("Waiting for local sandbox {id} to become {target}…"); + tokio::time::timeout(Duration::from_secs(seconds), async { loop { - let value = self + let value = match self .request(Method::GET, &format!("/v1/vms/{id}"), None) - .await?; - match value["state"].as_str() { - Some("ready" | "busy") => return Ok(()), - Some("starting") => {} - state => bail!( - "Local sandbox {id} reached {} before readiness: {}", - state.unwrap_or("unknown"), + .await + { + Ok(value) => snapshot(value, id)?, + Err(error) + if target == "deleted" + && error + .downcast_ref::() + .is_some_and(|e| e.status == StatusCode::NOT_FOUND) => + { + return Ok(json!({"id":id,"status":"deleted"})); + } + Err(error) => return Err(error), + }; + let status = value["status"].as_str().unwrap_or("unknown"); + if status == target { + return Ok(value); + } + if matches!( + status, + "stopped" | "failed" | "completed" | "unknown" | "suspended" + ) && target != "deleted" + { + bail!( + "Local sandbox {id} reached {status} before {target}: {}", output::safe( value["error"] .as_str() .unwrap_or("inspect the local runtime log") ) - ), + ); } sleep(Duration::from_millis(200)).await; } }) .await - .context("Timed out waiting for the local sandbox")? + .context("Timed out waiting for the local sandbox; the operation continues locally")? } #[cfg(unix)] - pub async fn execute( - &self, - sandbox: &Sandbox, - args: ExecArgs, - json_output: bool, - ) -> Result { + pub async fn execute(&self, args: ExecArgs, json_output: bool) -> Result { let session = Uuid::new_v4(); - let mut env = sandbox.env.clone(); + let id = full_id(args.sandbox.clone())?; + let mut env = metadata::load(&self.state_dir, id)?; env.extend(args.env); let mut body = json!({"id":session.to_string(), "argv":args.argv, "env":env, "cwd":args.cwd, - "stdin":true, "timeout_ms":args.timeout_ms}); + "stdin":args.stdin || args.tty, "timeout_ms":args.timeout_ms}); if args.tty { let (cols, rows) = crossterm::terminal::size()?; body["terminal"] = json!({"size":{"rows":rows.max(1),"cols":cols.max(1)},"term":"xterm-256color"}); } - let path = format!("/v1/vms/{}/sessions/{session}", sandbox.id); + let path = format!("/v1/vms/{}/sessions/{session}", id); self.request( Method::POST, - &format!("/v1/vms/{}/sessions", sandbox.id), + &format!("/v1/vms/{}/sessions", id), Some(&body), ) .await?; @@ -201,10 +223,12 @@ impl LocalBackend { socket, stream::Attachment { after: 0, - input: true, + input: args.stdin || args.tty, tty: args.tty, json_output, - resume: "The temporary local sandbox will be deleted.".into(), + resume: format!( + "Local sandbox: {id}. Use `adapt --local sandbox delete {id}` to remove it." + ), credit: Some(0), }, ) @@ -212,7 +236,7 @@ impl LocalBackend { } #[cfg(not(unix))] - pub async fn execute(&self, _: &Sandbox, _: ExecArgs, _: bool) -> Result { + pub async fn execute(&self, _: ExecArgs, _: bool) -> Result { bail!("Local sandboxes require a Unix host") } @@ -225,11 +249,11 @@ impl LocalBackend { .request(Method::DELETE, &format!("/v1/vms/{id}"), None) .await { - Ok(_) => return Ok(()), + Ok(_) => break, Err(error) => { let status = error.downcast_ref::().map(|e| e.status); if status == Some(StatusCode::NOT_FOUND) { - return Ok(()); + break; } if matches!( status, @@ -243,6 +267,9 @@ impl LocalBackend { } } } + #[cfg(unix)] + metadata::remove(&self.state_dir, id)?; + Ok(()) } } @@ -257,3 +284,226 @@ impl std::fmt::Display for LocalError { } } impl std::error::Error for LocalError {} + +/// Runtime startup is lazy: an unsupported operation must not touch credentials, +/// create state directories or launch a manager. +pub struct LocalBackend { + state_dir: PathBuf, + runtime_dir: Option, + timeout: Duration, + client: OnceCell, +} + +impl LocalBackend { + pub fn new(state_dir: PathBuf, runtime_dir: Option, timeout: Duration) -> Self { + Self { + state_dir, + runtime_dir, + timeout, + client: OnceCell::new(), + } + } + + async fn client(&self) -> Result<&Goblin> { + self.client + .get_or_try_init(|| { + crate::local_runtime::connect( + &self.state_dir, + self.runtime_dir.as_deref(), + self.timeout, + ) + }) + .await + } +} + +impl Backend for LocalBackend { + fn name(&self) -> &'static str { + "local" + } + + async fn sandbox_list(&self, args: SandboxList) -> Result { + if args.page.limit.is_some() || args.page.cursor.is_some() { + return self.unsupported("sandbox list pagination (--limit/--cursor)"); + } + let value = self + .client() + .await? + .request(Method::GET, "/v1/vms", None) + .await?; + let query = args.query.as_deref().unwrap_or("").to_ascii_lowercase(); + let mut rows = Vec::new(); + for vm in value + .as_array() + .context("Invalid local sandbox inventory")? + { + // Adapt addresses UUID resources. Goblin also permits names for VMs + // created outside Adapt; leave those to Goblin's API. + if let Some(id) = vm["id"].as_str().and_then(|s| s.parse::().ok()) + && (id.to_string().starts_with(&query) + || id.simple().to_string().starts_with(&query)) + { + rows.push(snapshot(vm.clone(), id)?); + } + } + rows.sort_by(|a, b| a["id"].as_str().cmp(&b["id"].as_str())); + Ok(json!({"sandboxes":rows,"nextCursor":null})) + } + async fn sandbox_get(&self, id: ResourceRef) -> Result { + let id = full_id(id)?; + snapshot( + self.client() + .await? + .request(Method::GET, &format!("/v1/vms/{id}"), None) + .await?, + id, + ) + } + async fn sandbox_create(&self, args: SandboxCreate) -> Result { + validate(&args)?; + self.client().await?.create(args).await + } + async fn sandbox_stop(&self, id: ResourceRef) -> Result { + let id = full_id(id)?; + snapshot( + self.client() + .await? + .request( + Method::POST, + &format!("/v1/vms/{id}/stop"), + Some(&json!({})), + ) + .await?, + id, + ) + } + async fn sandbox_delete(&self, id: ResourceRef) -> Result { + let id = full_id(id)?; + self.client().await?.delete(id).await?; + Ok(json!({"id":id,"status":"deleted"})) + } + async fn sandbox_wait(&self, id: ResourceRef, status: &str, seconds: u64) -> Result { + let id = full_id(id)?; + if !matches!( + status, + "running" | "stopped" | "deleted" | "failed" | "completed" + ) { + return self.unsupported(&format!("sandbox wait --status {status}")); + } + self.client().await?.wait(id, status, seconds).await + } + async fn execute(&self, args: ExecArgs, json: bool) -> Result { + full_id(args.sandbox.clone())?; + if args.detach { + return self.unsupported("exec --detach"); + } + if args.creation.idempotency_key.is_some() { + return self.unsupported("exec --idempotency-key"); + } + if args.tty && json { + bail!("--tty cannot be combined with --json"); + } + if args.tty { + crate::stream::require_terminal()?; + } + self.client().await?.execute(args, json).await + } + fn cleanup_hint(&self, id: Uuid) -> String { + format!( + "retry `adapt --local sandbox delete {id}` with --local-state-dir {}", + output::safe(&self.state_dir.display().to_string()) + ) + } +} + +fn full_id(id: ResourceRef) -> Result { + id.uuid() + .context("Sandbox ID prefixes are not supported by the local backend; use the full UUID") +} + +/// Common ID/status/resource fields are consistent across backends. Preserve +/// Goblin's additional diagnostics, including its original state, in JSON. +fn snapshot(mut value: Value, id: Uuid) -> Result { + if !value.is_object() { + bail!("Invalid local sandbox response"); + } + value["id"] = json!(id); + value["status"] = json!(match value["state"].as_str() { + Some("ready" | "busy") => "running", + Some("starting") => "provisioning", + Some(state) => state, + None => "unknown", + }); + if let Some(cpu) = value["vcpus"].as_u64() { + value["cpu"] = json!(cpu); + } + if let Some(memory) = value["memory_mib"].as_u64() { + value["memoryMiB"] = json!(memory); + } + Ok(value) +} + +#[cfg(unix)] +mod metadata { + use anyhow::{Context, Result, bail}; + use std::{ + collections::BTreeMap, + fs::{self, OpenOptions}, + io::{Read, Write}, + os::unix::fs::{MetadataExt, OpenOptionsExt}, + path::{Path, PathBuf}, + }; + use uuid::Uuid; + + fn path(state: &Path, id: Uuid) -> PathBuf { + state.join(format!("adapt-{id}.json")) + } + + pub fn save(state: &Path, id: Uuid, pairs: &[(String, String)]) -> Result<()> { + let env: BTreeMap<_, _> = pairs.iter().cloned().collect(); + let bytes = serde_json::to_vec(&env)?; + if bytes.len() > 65536 { + bail!("Local sandbox environment exceeds 64 KiB"); + } + // State was validated as private by discovery. Atomic publication keeps + // a subsequent exec from reading a partially-written environment. + let mut file = tempfile::NamedTempFile::new_in(state)?; + file.write_all(&bytes)?; + file.as_file().sync_all()?; + file.persist_noclobber(path(state, id))?; + Ok(()) + } + + pub fn load(state: &Path, id: Uuid) -> Result> { + let file = match OpenOptions::new() + .read(true) + .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK) + .open(path(state, id)) + { + Ok(file) => file, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + return Ok(BTreeMap::new()); + } + Err(error) => return Err(error.into()), + }; + let meta = file.metadata()?; + // SAFETY: geteuid has no arguments or memory effects. + if !meta.is_file() || meta.uid() != unsafe { libc::geteuid() } || meta.mode() & 0o077 != 0 { + bail!("Local sandbox environment must be a private, user-owned regular file"); + } + let mut bytes = Vec::new(); + file.take(65537).read_to_end(&mut bytes)?; + if bytes.len() > 65536 { + bail!("Local sandbox environment exceeds 64 KiB"); + } + serde_json::from_slice(&bytes).context("Invalid local sandbox environment") + } + + pub fn remove(state: &Path, id: Uuid) -> Result<()> { + match fs::remove_file(path(state, id)) { + Ok(()) => Ok(()), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(error) => Err(error.into()), + } + } +} diff --git a/src/backend/mod.rs b/src/backend/mod.rs index 954c73e..31222a2 100644 --- a/src/backend/mod.rs +++ b/src/backend/mod.rs @@ -1,70 +1,77 @@ -//! Shared temporary-sandbox lifecycle. Backend-specific wire formats stay here. +//! Resource operations shared by CLI workflows. Implementations own transport, +//! credentials and wire formats; unsupported capabilities fail without side effects. +pub mod cloud; pub mod local; -use crate::{ - api::Api, - cli::{ExecArgs, SandboxCreate}, - commands, shell, -}; -use anyhow::Result; -#[cfg(unix)] -use std::collections::BTreeMap; +use crate::{cli::*, input::ResourceRef}; +use anyhow::{Result, bail}; +use serde_json::Value; use uuid::Uuid; -pub struct Sandbox { - pub id: Uuid, - #[cfg(unix)] - pub env: BTreeMap, -} - -pub enum SandboxBackend<'a> { - Cloud(&'a Api), - Local(&'a local::LocalBackend), -} +pub trait Backend { + fn name(&self) -> &'static str; -impl SandboxBackend<'_> { - pub async fn create(&self, args: SandboxCreate) -> Result { - match self { - Self::Cloud(api) => Ok(Sandbox { - id: commands::resource_id(&commands::create_sandbox(api, args).await?)?, - #[cfg(unix)] - env: BTreeMap::new(), - }), - Self::Local(local) => local.create(args).await, - } + fn unsupported(&self, operation: &str) -> Result { + bail!( + "{operation} is not supported by the {} backend", + self.name() + ) } - pub async fn wait(&self, id: Uuid) -> Result<()> { - match self { - Self::Cloud(api) => { - commands::wait_for(api, "sandboxes", id, "running", 600).await?; - Ok(()) - } - Self::Local(local) => local.wait(id).await, - } + async fn sandbox_list(&self, _args: SandboxList) -> Result { + self.unsupported("sandbox list") + } + async fn sandbox_get(&self, _id: ResourceRef) -> Result { + self.unsupported("sandbox get") + } + async fn sandbox_create(&self, _args: SandboxCreate) -> Result { + self.unsupported("sandbox create") + } + async fn sandbox_start(&self, _id: ResourceRef) -> Result { + self.unsupported("sandbox start") + } + async fn sandbox_stop(&self, _id: ResourceRef) -> Result { + self.unsupported("sandbox stop") + } + async fn sandbox_delete(&self, _id: ResourceRef) -> Result { + self.unsupported("sandbox delete") + } + async fn sandbox_wait(&self, _id: ResourceRef, _status: &str, _seconds: u64) -> Result { + self.unsupported("sandbox wait") + } + async fn sandbox_usage(&self, _id: ResourceRef, _hours: &str) -> Result { + self.unsupported("sandbox usage") + } + async fn execute(&self, _args: ExecArgs, _json: bool) -> Result { + self.unsupported("exec") + } + async fn executions(&self, _command: ExecCommand, _json: bool) -> Result { + self.unsupported("execs") + } + async fn files(&self, _command: FileCommand) -> Result { + self.unsupported("files") } - pub async fn execute(&self, sandbox: &Sandbox, args: ExecArgs, json: bool) -> Result { - match self { - Self::Cloud(api) => commands::execute(api, args, json).await, - Self::Local(local) => local.execute(sandbox, args, json).await, - } + // Resource families can gain a local implementation independently. Commands + // never fall back to another backend when a capability is unavailable. + async fn volumes(&self, _command: VolumeCommand) -> Result { + self.unsupported("volumes") + } + async fn images(&self, _command: ImageCommand, _json: bool) -> Result { + self.unsupported("images") + } + async fn endpoints(&self, _command: EndpointCommand, _json: bool) -> Result { + self.unsupported("endpoints") } - pub async fn delete(&self, id: Uuid) -> Result<()> { - match self { - Self::Cloud(api) => shell::cleanup_cloud(api, id).await, - Self::Local(local) => local.delete(id).await, - } + /// Temporary workflows must confirm deletion, even if ordinary deletion is + /// asynchronous. Backends may also tolerate an already-deleted resource here. + async fn cleanup(&self, id: Uuid) -> Result<()> { + self.sandbox_delete(id.into()).await?; + Ok(()) } - pub fn cleanup_hint(&self, id: Uuid) -> String { - match self { - Self::Cloud(_) => format!("retry with `adapt sandbox delete {id}`"), - Self::Local(local) => format!( - "local sandbox {id} remains in {}; remove it through the local Goblin API", - local.state_dir.display() - ), - } + fn cleanup_hint(&self, id: Uuid) -> String { + format!("retry with `adapt --{} sandbox delete {id}`", self.name()) } } diff --git a/src/cli.rs b/src/cli.rs index 341a623..9f2a7bb 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -11,6 +11,19 @@ use uuid::Uuid; after_help = "Start here: adapt auth login\nUse --json for scripting. Run any command with --help for details.\nCore resource IDs accept full UUIDs or unambiguous hexadecimal prefixes. Auth and organization IDs require full UUIDs." )] pub struct Cli { + /// Use the local backend (auth logout: remove only the saved credential) + #[arg(long = "local", global = true, conflicts_with = "cloud_target")] + pub local_target: bool, + /// Run on Adapt Platform (the default) + #[arg(long = "cloud", global = true)] + pub cloud_target: bool, + /// Directory containing goblind and goblin-worker + #[arg(long, global = true, env = "ADAPT_LOCAL_RUNTIME")] + pub runtime_dir: Option, + /// Private local runtime state (defaults to ADAPT_CONFIG_DIR/local) + #[arg(long, global = true, env = "ADAPT_LOCAL_STATE_DIR")] + pub local_state_dir: Option, + /// Saved connection profile #[arg(long, global = true, env = "ADAPT_PROFILE", default_value = "default")] pub profile: String, @@ -143,11 +156,10 @@ pub enum AuthCommand { token_stdin: bool, }, /// Revoke the saved CLI session and remove its local credential - Logout { - /// Remove only the local credential (for an unreachable server) - #[arg(long)] - local: bool, - }, + #[command( + after_help = "Use --local to remove only the saved credential when the server is unreachable." + )] + Logout, /// Verify authentication without printing credentials Status, } @@ -311,18 +323,6 @@ pub struct SandboxList { #[derive(Args)] pub struct SandboxShell { - /// Run a temporary sandbox on this computer (requires a Goblin runtime bundle) - #[arg(long = "local", conflicts_with = "cloud_target")] - pub local_target: bool, - /// Run on Adapt Platform (the default) - #[arg(long = "cloud")] - pub cloud_target: bool, - /// Directory containing goblind and goblin-worker - #[arg(long, env = "ADAPT_LOCAL_RUNTIME")] - pub runtime_dir: Option, - /// Private local runtime state (defaults to ADAPT_CONFIG_DIR/local) - #[arg(long, env = "ADAPT_LOCAL_STATE_DIR")] - pub local_state_dir: Option, #[command(flatten)] pub create: SandboxCreate, /// Command and literal arguments to run instead of an interactive login shell diff --git a/src/commands.rs b/src/commands.rs index eac227e..5a2444f 100644 --- a/src/commands.rs +++ b/src/commands.rs @@ -1,6 +1,7 @@ use crate::{ api::{self, Api}, auth, + backend::{Backend, cloud::CloudBackend, local::LocalBackend}, cli::*, config::{self, Config, Credential, CredentialKind}, input, mcp, output, shell, skill, stream, @@ -27,28 +28,17 @@ pub async fn run(cli: Cli) -> Result { skill::run(command, cli.json)?; return Ok(0); } - if matches!(&cli.command, Command::Sandbox(SandboxCommand::Sh(args)) if args.local_target) { - let Command::Sandbox(SandboxCommand::Sh(args)) = cli.command else { - unreachable!() - }; - crate::backend::local::validate(&args.create)?; - shell::validate(&args, cli.json)?; - let dir = match &args.local_state_dir { - Some(dir) => dir.clone(), - None => config::directory(cli.config_dir.as_deref())?.join("local"), - }; - let local = crate::local_runtime::connect( - &dir, - args.runtime_dir.as_deref(), + // --local on logout retains its established credential-only meaning. + if cli.local_target && !matches!(&cli.command, Command::Auth(AuthCommand::Logout)) { + let state = cli.local_state_dir.clone().map(Ok).unwrap_or_else(|| { + config::directory(cli.config_dir.as_deref()).map(|dir| dir.join("local")) + })?; + let backend = LocalBackend::new( + state, + cli.runtime_dir.clone(), Duration::from_secs(cli.timeout), - ) - .await?; - return shell::run( - &crate::backend::SandboxBackend::Local(&local), - args, - cli.json, - ) - .await; + ); + return resources(&backend, cli.command, cli.json).await; } let dir = config::directory(cli.config_dir.as_deref())?; let mut config = Config::load(&dir)?; @@ -97,7 +87,7 @@ pub async fn run(cli: Cli) -> Result { }); let token = if matches!( &cli.command, - Command::Auth(AuthCommand::Login { .. } | AuthCommand::Logout { .. }) + Command::Auth(AuthCommand::Login { .. } | AuthCommand::Logout) ) { None } else { @@ -145,7 +135,8 @@ pub async fn run(cli: Cli) -> Result { eprintln!("Signed in. Profile: {}", output::safe(&cli.profile)); json!({"authenticated":true,"profile":cli.profile,"apiUrl":authenticated.origin.as_str(),"organizationId":selected,"user":identity["user"]}) }, - Command::Auth(AuthCommand::Logout { local }) => { + Command::Auth(AuthCommand::Logout) => { + let local = cli.local_target; if !same_origin { bail!("This API URL does not match the saved profile; choose that profile's API URL to log out"); } // ADAPT_TOKEN must never change which saved credential logout revokes. if let Some(credential) = saved.credential.as_ref() { @@ -185,23 +176,9 @@ pub async fn run(cli: Cli) -> Result { OrgCommand::Members(command) => members(&api, command).await?, OrgCommand::Invitations(command) => invitations(&api, command).await?, }, - Command::Sandbox(SandboxCommand::Sh(args)) => return shell::run(&crate::backend::SandboxBackend::Cloud(&api), args, cli.json).await, - Command::Sandbox(SandboxCommand::List(args)) => return list_sandboxes(&api, args, cli.json).await, - Command::Sandbox(SandboxCommand::Usage { id, hours }) => return sandbox_usage(&api, id, hours, cli.json).await, - Command::Sandbox(command) => sandbox(&api, command).await?, - Command::Exec(args) => return execute(&api, args, cli.json).await, - Command::Execs(command) => match command { - ExecCommand::Get { id } => api.get(&format!("/v1/execs/{id}")).await?, - ExecCommand::Cancel { id } => api.post(&format!("/v1/execs/{id}/cancel"), &json!({})).await?, - ExecCommand::Logs { id, cursor } => return stream::logs(&api, id, cursor, cli.json).await, - ExecCommand::Attach { id, after, stdin, tty } => return stream::attach(&api, id, after, stdin || tty, tty, cli.json).await, - }, - Command::Files(command) => files(&api, command).await?, - Command::Volumes(command) => volumes(&api, command).await?, - Command::Endpoints(EndpointCommand::Request(args)) => return request_endpoint(&api, args).await, - Command::Endpoints(command) => endpoints(&api, command).await?, - Command::Images(ImageCommand::List(args)) => return list_images(&api, args, cli.json).await, - Command::Images(command) => images(&api, command).await?, + command @ (Command::Sandbox(_) | Command::Exec(_) | Command::Execs(_) | Command::Files(_) + | Command::Volumes(_) | Command::Endpoints(_) | Command::Images(_)) => + return resources(&CloudBackend(&api), command, cli.json).await, Command::Env(command) => match command { EnvCommand::List(page) => api.list("/v1/environment-variable-sets", "sets", &page, true, &[]).await?, EnvCommand::Get { id } => api.get(&format!("/v1/environment-variable-sets/{id}")).await?, @@ -275,28 +252,42 @@ async fn create(api: &Api, path: &str, body: Value, creation: Creation) -> Resul }) } -async fn list_sandboxes(api: &Api, args: SandboxList, json: bool) -> Result { - let filters: Vec<_> = args - .query - .iter() - .map(|text| ("query".to_owned(), text.clone())) - .collect(); - let no_match = args - .query - .map(|text| format!("No sandboxes match \"{}\".", output::safe(&text))); - filtered_list( - api, - "/v1/sandboxes", - "sandboxes", - &args.page, - &filters, - no_match, - json, - ) - .await +async fn resources(backend: &impl Backend, command: Command, json: bool) -> Result { + let result = match command { + Command::Sandbox(SandboxCommand::Sh(args)) => return shell::run(backend, args, json).await, + Command::Sandbox(SandboxCommand::List(args)) => { + let no_match = args + .query + .as_ref() + .map(|text| format!("No sandboxes match \"{}\".", output::safe(text))); + let result = backend.sandbox_list(args).await?; + return print_filtered_list(result, "sandboxes", no_match, json); + } + Command::Sandbox(SandboxCommand::Usage { id, hours }) => { + let usage = backend.sandbox_usage(id, &hours).await?; + if output::tables(json) { + write_usage(&mut io::stdout().lock(), &usage, &hours)?; + } else { + output::print(&usage, json)?; + } + return Ok(0); + } + Command::Sandbox(command) => sandbox(backend, command).await?, + Command::Exec(args) => return backend.execute(args, json).await, + Command::Execs(command) => return backend.executions(command, json).await, + Command::Files(command) => backend.files(command).await?, + Command::Volumes(command) => backend.volumes(command).await?, + Command::Images(command) => return backend.images(command, json).await, + Command::Endpoints(command) => return backend.endpoints(command, json).await, + _ => return backend.unsupported("This command"), + }; + if !result.is_null() { + output::print(&result, json)?; + } + Ok(0) } -async fn list_images(api: &Api, args: ImageList, json: bool) -> Result { +pub(crate) async fn list_images(api: &Api, args: ImageList, json: bool) -> Result { let status = args.status.map(choice); let mut filters = Vec::new(); if let Some(name) = &args.name { @@ -339,6 +330,15 @@ async fn filtered_list( json: bool, ) -> Result { let result = api.list(path, field, page, true, filters).await?; + print_filtered_list(result, field, no_match, json) +} + +fn print_filtered_list( + result: Value, + field: &str, + no_match: Option, + json: bool, +) -> Result { if let Some(message) = no_match && result[field].as_array().is_some_and(Vec::is_empty) { @@ -353,27 +353,26 @@ async fn filtered_list( Ok(0) } -async fn sandbox(api: &Api, command: SandboxCommand) -> Result { +async fn sandbox(backend: &impl Backend, command: SandboxCommand) -> Result { match command { - SandboxCommand::List(_) => unreachable!("Sandbox lists are dispatched separately"), - SandboxCommand::Get { id } => api.get(&format!("/v1/sandboxes/{id}")).await, - SandboxCommand::Delete { id } => delete(api, &format!("/v1/sandboxes/{id}")).await, + SandboxCommand::Get { id } => backend.sandbox_get(id).await, + SandboxCommand::Delete { id } => backend.sandbox_delete(id).await, SandboxCommand::Start { id, wait } => { - let result = api - .post(&format!("/v1/sandboxes/{id}/start"), &json!({})) - .await?; + let result = backend.sandbox_start(id).await?; if wait { - wait_for(api, "sandboxes", resource_id(&result)?, "running", 600).await + backend + .sandbox_wait(resource_id(&result)?.into(), "running", 600) + .await } else { Ok(result) } } SandboxCommand::Stop { id, wait } => { - let result = api - .post(&format!("/v1/sandboxes/{id}/stop"), &json!({})) - .await?; + let result = backend.sandbox_stop(id).await?; if wait { - wait_for(api, "sandboxes", resource_id(&result)?, "stopped", 600).await + backend + .sandbox_wait(resource_id(&result)?.into(), "stopped", 600) + .await } else { Ok(result) } @@ -382,38 +381,22 @@ async fn sandbox(api: &Api, command: SandboxCommand) -> Result { id, status, wait_timeout, - } => wait_for(api, "sandboxes", id, &status, wait_timeout).await, + } => backend.sandbox_wait(id, &status, wait_timeout).await, SandboxCommand::Create(args) => { let wait = args.wait; - let result = create_sandbox(api, args).await?; + let result = backend.sandbox_create(args).await?; if wait { - wait_for(api, "sandboxes", resource_id(&result)?, "running", 600).await + backend + .sandbox_wait(resource_id(&result)?.into(), "running", 600) + .await } else { Ok(result) } } - SandboxCommand::Sh(_) => unreachable!("Interactive shell is dispatched separately"), - SandboxCommand::Usage { .. } => unreachable!("Sandbox usage is dispatched separately"), - } -} - -async fn sandbox_usage(api: &Api, id: input::ResourceRef, hours: String, json: bool) -> Result { - let path = format!("/v1/sandboxes/{id}/usage"); - let usage = api - .json( - Method::GET, - &path, - None, - &[("hours".into(), hours.clone())], - None, - ) - .await?; - if output::tables(json) { - write_usage(&mut io::stdout().lock(), &usage, &hours)?; - } else { - output::print(&usage, json)?; + SandboxCommand::List(_) | SandboxCommand::Sh(_) | SandboxCommand::Usage { .. } => { + unreachable!("Dispatched separately") + } } - Ok(0) } const USAGE_COLUMNS: [&str; 7] = [ @@ -613,7 +596,7 @@ pub(crate) async fn execute(api: &Api, args: ExecArgs, json_output: bool) -> Res } } -async fn files(api: &Api, command: FileCommand) -> Result { +pub(crate) async fn files(api: &Api, command: FileCommand) -> Result { match command { FileCommand::Put { sandbox, @@ -685,7 +668,7 @@ async fn files(api: &Api, command: FileCommand) -> Result { } } -async fn volumes(api: &Api, command: VolumeCommand) -> Result { +pub(crate) async fn volumes(api: &Api, command: VolumeCommand) -> Result { match command { VolumeCommand::List(page) => api.list("/v1/volumes", "volumes", &page, true, &[]).await, VolumeCommand::Get { id } => api.get(&format!("/v1/volumes/{id}")).await, @@ -717,7 +700,7 @@ async fn volumes(api: &Api, command: VolumeCommand) -> Result { } } -async fn endpoints(api: &Api, command: EndpointCommand) -> Result { +pub(crate) async fn endpoints(api: &Api, command: EndpointCommand) -> Result { match command { EndpointCommand::List(page) => { api.list("/v1/ingresses", "ingresses", &page, true, &[]) @@ -769,7 +752,7 @@ async fn endpoints(api: &Api, command: EndpointCommand) -> Result { /// Sends one request to an endpoint's hosted application and streams the body to /// stdout. Platform credentials only look up the endpoint and create a token; the /// application receives the caller's headers and, at most, the endpoint token. -async fn request_endpoint(api: &Api, args: EndpointRequest) -> Result { +pub(crate) async fn request_endpoint(api: &Api, args: EndpointRequest) -> Result { let path = &args.path; if !path.starts_with('/') || path.starts_with("//") || path.contains('\\') || path.contains('#') { @@ -862,7 +845,7 @@ async fn request_endpoint(api: &Api, args: EndpointRequest) -> Result { bail!(message) } -async fn images(api: &Api, command: ImageCommand) -> Result { +pub(crate) async fn images(api: &Api, command: ImageCommand) -> Result { match command { ImageCommand::List(_) => unreachable!("Image lists are dispatched separately"), ImageCommand::Get { id } => api.get(&format!("/v1/images/{id}")).await, diff --git a/src/local_runtime.rs b/src/local_runtime.rs index adb0a15..af8d74d 100644 --- a/src/local_runtime.rs +++ b/src/local_runtime.rs @@ -1,13 +1,9 @@ //! Per-user Goblin discovery and bootstrap. No Platform credentials are loaded here. -use crate::backend::local::LocalBackend; +use crate::backend::local::Goblin; use anyhow::{Result, bail}; use std::{path::Path, time::Duration}; -pub async fn connect( - state: &Path, - runtime: Option<&Path>, - timeout: Duration, -) -> Result { +pub async fn connect(state: &Path, runtime: Option<&Path>, timeout: Duration) -> Result { if !cfg!(any( all(target_os = "macos", target_arch = "aarch64"), all(target_os = "linux", target_arch = "x86_64") @@ -98,11 +94,7 @@ mod unix { Ok(bytes) } - async fn discover( - state: &Path, - token: &str, - timeout: Duration, - ) -> Result> { + async fn discover(state: &Path, token: &str, timeout: Duration) -> Result> { let path = state.join("ready.json"); let bytes = match read(&path) { Ok(bytes) => bytes, @@ -134,7 +126,7 @@ mod unix { { bail!("Local runtime socket must be private and user-owned"); } - let probe = LocalBackend::new( + let probe = Goblin::new( ready.socket_path.clone(), token, state.to_owned(), @@ -167,7 +159,7 @@ mod unix { "Local runtime is incompatible or has no embedded image firmware; use a compatible Goblin bundle" ); } - Ok(Some(LocalBackend::new( + Ok(Some(Goblin::new( ready.socket_path, token, state.to_owned(), @@ -179,7 +171,7 @@ mod unix { state: &Path, runtime: Option<&Path>, timeout: Duration, - ) -> Result { + ) -> Result { fs::DirBuilder::new() .recursive(true) .mode(0o700) diff --git a/src/main.rs b/src/main.rs index 162b08b..af14adf 100644 --- a/src/main.rs +++ b/src/main.rs @@ -12,12 +12,22 @@ mod shell; mod skill; mod stream; -use clap::Parser; +use clap::{CommandFactory, Parser}; use cli::Cli; use std::process::ExitCode; fn main() -> ExitCode { let cli = Cli::parse(); + // Clap checks conflicts within each command before propagating global + // arguments; also catch flags placed at different command levels. + if cli.local_target && cli.cloud_target { + Cli::command() + .error( + clap::error::ErrorKind::ArgumentConflict, + "--local cannot be used with --cloud", + ) + .exit(); + } let runtime = tokio::runtime::Builder::new_multi_thread() .worker_threads(2) .enable_all() @@ -43,11 +53,16 @@ async fn run(cli: Cli) -> ExitCode { &cli.command, cli::Command::Endpoints(cli::EndpointCommand::Request(_)) ); + let local = cli.local_target; tokio::select! { result = commands::run(cli) => result, _ = tokio::signal::ctrl_c() => { if remote_work { - eprintln!("\nCancelled. Remote executions continue; use `adapt execs cancel ID` to stop one."); + if local { + eprintln!("\nCancelled. Local operations may continue; inspect with `adapt --local sandbox list` and use `adapt --local sandbox stop ID` to stop a VM."); + } else { + eprintln!("\nCancelled. Remote executions continue; use `adapt execs cancel ID` to stop one."); + } } return ExitCode::from(130); } diff --git a/src/shell.rs b/src/shell.rs index bba3746..ca0a6f0 100644 --- a/src/shell.rs +++ b/src/shell.rs @@ -1,12 +1,10 @@ use crate::{ - api::{Api, ApiError}, - backend::{Sandbox, SandboxBackend}, + backend::Backend, cli::{Creation, ExecArgs, SandboxShell}, - commands::wait_for, + commands::resource_id, stream, }; use anyhow::{Context, Result, bail}; -use reqwest::{Method, StatusCode}; use uuid::Uuid; // Honor an explicitly configured SHELL, then the guest user's passwd entry. @@ -34,16 +32,12 @@ pub fn validate(args: &SandboxShell, json_output: bool) -> Result<()> { Ok(()) } -pub async fn run( - backend: &SandboxBackend<'_>, - args: SandboxShell, - json_output: bool, -) -> Result { +pub async fn run(backend: &impl Backend, args: SandboxShell, json_output: bool) -> Result { validate(&args, json_output)?; let interactive = args.argv.is_empty(); let mut shutdown = Shutdown::new()?; - let creation = backend.create(args.create); + let creation = backend.sandbox_create(args.create); tokio::pin!(creation); let (created, interrupted) = tokio::select! { biased; @@ -56,7 +50,7 @@ pub async fn run( created = &mut creation => (created, None), }; let sandbox = created?; - let id = sandbox.id; + let id = resource_id(&sandbox)?; eprintln!("Temporary sandbox: {id}"); if interactive { eprintln!("Exiting the shell or pressing Ctrl-] deletes this sandbox."); @@ -70,10 +64,10 @@ pub async fn run( tokio::select! { biased; code = shutdown.wait() => Ok(code), - result = session(backend, &sandbox, args.argv, json_output) => result, + result = session(backend, id, args.argv, json_output) => result, } }; - let cleanup = backend.delete(id).await.with_context(|| { + let cleanup = backend.cleanup(id).await.with_context(|| { format!( "Could not delete temporary sandbox {id}; {}", backend.cleanup_hint(id) @@ -91,17 +85,15 @@ pub async fn run( } async fn session( - backend: &SandboxBackend<'_>, - sandbox: &Sandbox, + backend: &impl Backend, + id: Uuid, argv: Vec, json_output: bool, ) -> Result { - let id = sandbox.id; let interactive = argv.is_empty(); - backend.wait(id).await?; + backend.sandbox_wait(id.into(), "running", 600).await?; backend .execute( - sandbox, ExecArgs { sandbox: id.into(), cwd: None, @@ -124,37 +116,6 @@ async fn session( .await } -pub(crate) async fn cleanup_cloud(api: &Api, id: Uuid) -> Result<()> { - eprintln!("Deleting temporary sandbox {id}…"); - let result: Result<()> = async { - let response = api - .json( - Method::DELETE, - &format!("/v1/sandboxes/{id}"), - None, - &[], - None, - ) - .await?; - if response["status"] != 204 { - wait_for(api, "sandboxes", id, "deleted", 600).await?; - } - Ok(()) - } - .await; - // Expiry or another client may already have removed the sandbox. - match result { - Err(error) - if error - .downcast_ref::() - .is_some_and(|e| e.status == StatusCode::NOT_FOUND) => - { - Ok(()) - } - result => result, - } -} - #[cfg(unix)] struct Shutdown { interrupt: tokio::signal::unix::Signal, diff --git a/tests/backend/mod.rs b/tests/backend/mod.rs new file mode 100644 index 0000000..367cb13 --- /dev/null +++ b/tests/backend/mod.rs @@ -0,0 +1,138 @@ +use crate::support::*; +use serde_json::json; + +#[test] +fn local_unsupported_operations_fail_before_config_credentials_or_bootstrap() { + let dir = tempfile::tempdir().unwrap(); + std::fs::write(dir.path().join("config.json"), "invalid cloud config").unwrap(); + let state = dir.path().join("uncreated"); + let cases = [ + vec!["sandbox", "start", ID, "--wait"], + vec!["sandbox", "usage", ID], + vec!["sandbox", "wait", ID, "--status", "unsupported"], + vec!["sandbox", "list", "--limit", "10"], + vec!["sandbox", "list", "--cursor", ID], + vec!["sandbox", "get", "1111"], + vec!["sandbox", "stop", "1111"], + vec!["sandbox", "delete", "1111"], + vec!["sandbox", "wait", "1111"], + vec!["sandbox", "create", "--ttl", "60"], + vec!["sandbox", "create", "--image-id", ID], + vec!["sandbox", "create", "--label", "name=test"], + vec!["sandbox", "create", "--variable-set", ID], + vec!["sandbox", "create", "--data", "@missing.json"], + vec!["sandbox", "create", "--run-image"], + vec!["sandbox", "create", "--idempotency-key", ID], + vec!["exec", ID, "--detach", "--", "true"], + vec!["exec", ID, "--idempotency-key", ID, "--", "true"], + vec!["execs", "get", ID], + vec!["execs", "cancel", ID], + vec!["execs", "logs", ID], + vec!["execs", "attach", ID], + vec!["files", "put", ID, "missing.txt", "/remote"], + vec!["files", "get", ID, "/remote", "-"], + vec!["volumes", "list"], + vec!["images", "list"], + vec!["endpoints", "list"], + vec!["env", "list"], + vec!["registry", "list"], + vec!["connections", "list"], + vec!["models", "list"], + vec!["keys", "list"], + vec!["sessions", "list"], + vec!["mcp", "list"], + vec!["events"], + vec!["health"], + vec!["api", "DELETE", "/v1/sandboxes"], + vec!["auth", "status"], + vec!["auth", "login"], + vec!["whoami"], + vec!["org", "list"], + ]; + for args in cases { + let output = command(dir.path(), "not-a-cloud-origin") + .env("ADAPT_TOKEN", "cloud-secret") + .args(["--local", "--local-state-dir"]) + .arg(&state) + .args(&args) + .output() + .unwrap(); + let error = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(1), "{args:?}: {error}"); + assert!( + error.contains("not supported by the local backend"), + "{args:?}: {error}" + ); + assert!(output.stdout.is_empty()); + assert!(!error.contains("cloud-secret")); + assert!(!state.exists(), "{args:?} started a runtime"); + } +} + +#[test] +fn target_flags_are_global_and_mutually_exclusive() { + let dir = tempfile::tempdir().unwrap(); + for args in [ + vec!["sandbox", "usage", ID, "--local"], + vec!["sandbox", "--local", "usage", ID], + vec!["--local", "sandbox", "usage", ID], + ] { + let output = run(dir.path(), "invalid", &args); + assert!( + String::from_utf8_lossy(&output.stderr) + .contains("sandbox usage is not supported by the local backend") + ); + } + let output = run( + dir.path(), + "invalid", + &["--cloud", "sandbox", "list", "--local"], + ); + assert_eq!(output.status.code(), Some(2)); + + let server = Server::start(vec![Box::new(|r| { + assert_eq!(r.target, "/v1/sandboxes?limit=50"); + assert_eq!(r.headers["authorization"], "Bearer test-token"); + Reply::json(200, json!({"sandboxes":[],"nextCursor":null})) + })]); + let output = command(dir.path(), &server.url) + .env("ADAPT_TOKEN", "test-token") + .env("ADAPT_LOCAL_STATE_DIR", "/unused/local/state") + .args(["sandbox", "list", "--cloud"]) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + server.finish(); +} + +#[test] +fn local_logout_still_removes_only_the_saved_credential() { + let dir = tempfile::tempdir().unwrap(); + let config = json!({"profiles":{"default":{"api_url":"http://localhost:3000","organization_id":ORG,"credential":{"kind":"session","token":"saved-secret"}}}}); + let path = dir.path().join("config.json"); + std::fs::write(&path, config.to_string()).unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); + } + let output = run( + dir.path(), + "http://localhost:3000", + &["auth", "logout", "--local"], + ); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + assert!( + !std::fs::read_to_string(path) + .unwrap() + .contains("saved-secret") + ); +} diff --git a/tests/cli.rs b/tests/cli.rs index 5da2064..c61a222 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -3,6 +3,7 @@ use serde_json::{Value, json}; use std::time::Duration; use support::*; +mod backend; mod endpoint_request; mod image_list; #[cfg(any( diff --git a/tests/local_shell/backend.rs b/tests/local_shell/backend.rs new file mode 100644 index 0000000..0314d17 --- /dev/null +++ b/tests/local_shell/backend.rs @@ -0,0 +1,377 @@ +use super::*; + +fn local_command(state: &Path, args: &[&str]) -> Command { + let mut cmd = command(state, "not-a-valid-cloud-origin"); + cmd.env("ADAPT_TOKEN", "cloud-secret-must-not-reach-goblin") + .env("HTTP_PROXY", "http://127.0.0.1:1") + .args(["--local", "--local-state-dir"]) + .arg(state) + .args(args); + cmd +} + +fn result(state: &Path, args: &[&str]) -> Value { + let output = local_command(state, args).output().unwrap(); + assert!( + output.status.success(), + "{args:?}: {}", + String::from_utf8_lossy(&output.stderr) + ); + serde_json::from_slice(&output.stdout).unwrap() +} + +#[test] +fn persistent_sandbox_lifecycle_uses_one_backend_across_cli_invocations() { + let dir = tempfile::tempdir().unwrap(); + discovery(dir.path()); + let id = Arc::new(Mutex::new(String::new())); + let created = id.clone(); + let server = Server::unix( + &dir.path().join("goblind.sock"), + vec![ + spec(), + http(Box::new(move |r| { + local_auth(r); + assert_eq!((r.method.as_str(), r.target.as_str()), ("POST", "/v1/vms")); + let body = r.json(); + *created.lock().unwrap() = body["id"].as_str().unwrap().into(); + assert_eq!(body["image"], "alpine:latest"); + Reply::json( + 202, + json!({"id":body["id"],"state":"starting","vcpus":1,"memory_mib":1024}), + ) + })), + http(Box::new(|r| { + local_auth(r); + assert_eq!(r.method, "GET"); + Reply::json(200, json!({"state":"ready"})) + })), + ], + ); + let created = result( + dir.path(), + &[ + "sandbox", + "create", + "--wait", + "--image", + "alpine:latest", + "--env", + "BASE=literal value", + "--env", + "OVERRIDE=old", + ], + ); + let id = id.lock().unwrap().clone(); + assert_eq!(created["id"], id); + assert_eq!(created["status"], "running"); + server.finish(); + fs::remove_file(dir.path().join("goblind.sock")).unwrap(); + let metadata = dir.path().join(format!("adapt-{id}.json")); + assert_eq!( + fs::metadata(&metadata).unwrap().permissions().mode() & 0o077, + 0 + ); + + let ids = Arc::new(Mutex::new(Ids { + vm: id.clone(), + session: String::new(), + })); + let executing = ids.clone(); + let server = Server::unix( + &dir.path().join("goblind.sock"), + vec![ + spec(), + http(Box::new(move |r| { + local_auth(r); + let mut ids = executing.lock().unwrap(); + assert_eq!(r.target, format!("/v1/vms/{}/sessions", ids.vm)); + let body = r.json(); + ids.session = body["id"].as_str().unwrap().into(); + assert_eq!( + body["env"], + json!({"BASE":"literal value","OVERRIDE":"new"}) + ); + assert_eq!(body["cwd"], "/tmp"); + assert_eq!(body["timeout_ms"], 5000); + assert_eq!(body["stdin"], false); + assert_eq!(body["argv"], json!(["true"])); + Reply::json(202, json!({"id":ids.session,"state":"starting"})) + })), + stream(ids, |mut ws| { + send( + &mut ws, + json!({"kind":"attached","session":{"stdin_closed":true,"stdin_credit":0}}), + ); + send( + &mut ws, + json!({"kind":"stdout","sequence":1,"data_base64":"cGVyc2lzdGVudAo="}), + ); + send(&mut ws, json!({"kind":"finished","exit":{"code":7}})); + while let Ok(message) = ws.read() { + if matches!(message, Message::Close(_)) { + break; + } + } + }), + ], + ); + let output = local_command( + dir.path(), + &[ + "exec", + &id, + "--env", + "OVERRIDE=new", + "--cwd", + "/tmp", + "--timeout-ms", + "5000", + "--", + "true", + ], + ) + .output() + .unwrap(); + assert_eq!( + output.status.code(), + Some(7), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!(output.stdout, b"persistent\n"); + server.finish(); + fs::remove_file(dir.path().join("goblind.sock")).unwrap(); + assert!( + metadata.exists(), + "exec must not delete a persistent sandbox" + ); + + for (args, method, suffix, state) in [ + (vec!["sandbox", "get", &id], "GET", "", "busy"), + (vec!["sandbox", "wait", &id], "GET", "", "ready"), + (vec!["sandbox", "stop", &id], "POST", "/stop", "stopped"), + ] { + let path = format!("/v1/vms/{id}{suffix}"); + let server = Server::unix( + &dir.path().join("goblind.sock"), + vec![ + spec(), + http(Box::new(move |r| { + local_auth(r); + assert_eq!( + (r.method.as_str(), r.target.as_str()), + (method, path.as_str()) + ); + Reply::json(200, json!({"state":state,"vcpus":1,"memory_mib":1024})) + })), + ], + ); + let snapshot = result(dir.path(), &args); + assert_eq!(snapshot["id"], id); + assert_eq!( + snapshot["status"], + if state == "stopped" { + "stopped" + } else { + "running" + } + ); + assert_eq!(snapshot["cpu"], 1); + assert_eq!(snapshot["memoryMiB"], 1024); + server.finish(); + fs::remove_file(dir.path().join("goblind.sock")).unwrap(); + } + let deleted_id = id.clone(); + let server = Server::unix( + &dir.path().join("goblind.sock"), + vec![ + spec(), + http(Box::new(move |r| { + local_auth(r); + assert_eq!(r.method, "DELETE"); + assert_eq!(r.target, format!("/v1/vms/{deleted_id}")); + Reply::json(204, Value::Null) + })), + ], + ); + assert_eq!( + result(dir.path(), &["sandbox", "delete", &id])["status"], + "deleted" + ); + assert!(!metadata.exists()); + server.finish(); + fs::remove_file(dir.path().join("goblind.sock")).unwrap(); +} + +#[test] +fn local_inventory_is_normalized_and_filters_ids() { + let dir = tempfile::tempdir().unwrap(); + discovery(dir.path()); + for query in ["", "111111111111", "FFFFFF"] { + let server = Server::unix( + &dir.path().join("goblind.sock"), + vec![ + spec(), + http(Box::new(|r| { + local_auth(r); + assert_eq!(r.target, "/v1/vms"); + Reply::json( + 200, + json!([ + {"id":KEY,"state":"stopped"}, {"id":ID,"state":"ready"}, {"id":"external-name","state":"ready"} + ]), + ) + })), + ], + ); + let mut args = vec!["sandbox", "list", "--all"]; + if !query.is_empty() { + args.extend(["--query", query]); + } + let value = result(dir.path(), &args); + let rows = value["sandboxes"].as_array().unwrap(); + assert_eq!( + rows.len(), + match query { + "" => 2, + "111111111111" => 1, + _ => 0, + } + ); + if !rows.is_empty() { + assert_eq!(rows[0]["id"], ID); + assert_eq!(rows[0]["status"], "running"); + } + assert!(value["nextCursor"].is_null()); + server.finish(); + fs::remove_file(dir.path().join("goblind.sock")).unwrap(); + } +} + +#[test] +fn local_wait_handles_terminal_failure_deleted_resources_and_deadlines() { + let dir = tempfile::tempdir().unwrap(); + discovery(dir.path()); + for (state, target, succeeds) in [ + ("failed", "running", false), + ("stopped", "stopped", true), + ("missing", "deleted", true), + ] { + let server = Server::unix( + &dir.path().join("goblind.sock"), + vec![ + spec(), + http(Box::new(move |_| { + Reply::json( + if state == "missing" { 404 } else { 200 }, + json!({"state":state,"error":"fixture failure"}), + ) + })), + ], + ); + let output = local_command(dir.path(), &["sandbox", "wait", ID, "--status", target]) + .output() + .unwrap(); + assert_eq!( + output.status.success(), + succeeds, + "{}", + String::from_utf8_lossy(&output.stderr) + ); + if !succeeds { + assert!(String::from_utf8_lossy(&output.stderr).contains("fixture failure")); + } + server.finish(); + fs::remove_file(dir.path().join("goblind.sock")).unwrap(); + } + let server = Server::unix( + &dir.path().join("goblind.sock"), + vec![ + spec(), + Box::new(|mut socket| { + let request = read_request(&mut socket); + std::thread::sleep(std::time::Duration::from_millis(1200)); + request + }), + ], + ); + let start = Instant::now(); + let output = local_command(dir.path(), &["sandbox", "wait", ID, "--wait-timeout", "1"]) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(1)); + assert!(String::from_utf8_lossy(&output.stderr).contains("Timed out waiting")); + assert!(start.elapsed() < std::time::Duration::from_secs(3)); + server.finish(); + fs::remove_file(dir.path().join("goblind.sock")).unwrap(); +} + +#[test] +fn stop_wait_observes_the_final_state_and_delete_tolerates_missing_vms() { + let dir = tempfile::tempdir().unwrap(); + discovery(dir.path()); + let server = Server::unix( + &dir.path().join("goblind.sock"), + vec![ + spec(), + http(Box::new(|r| { + assert_eq!( + (r.method.as_str(), r.target.as_str()), + ("POST", format!("/v1/vms/{ID}/stop").as_str()) + ); + Reply::json(200, json!({"id":ID,"state":"stopped"})) + })), + http(Box::new(|r| { + assert_eq!( + (r.method.as_str(), r.target.as_str()), + ("GET", format!("/v1/vms/{ID}").as_str()) + ); + Reply::json(200, json!({"state":"stopped"})) + })), + spec(), + http(Box::new(|r| { + assert_eq!(r.method, "DELETE"); + Reply::json(404, json!({"error":"missing"})) + })), + ], + ); + assert_eq!( + result(dir.path(), &["sandbox", "stop", ID, "--wait"])["status"], + "stopped" + ); + assert_eq!( + result(dir.path(), &["sandbox", "delete", ID])["status"], + "deleted" + ); + server.finish(); +} + +#[test] +fn execution_refuses_public_or_symlinked_environment_metadata_before_creating_a_session() { + let dir = tempfile::tempdir().unwrap(); + discovery(dir.path()); + let path = dir.path().join(format!("adapt-{ID}.json")); + fs::write(&path, "{\"SECRET\":\"do-not-print\"}").unwrap(); + fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap(); + for symlinked in [false, true] { + if symlinked { + fs::remove_file(&path).unwrap(); + std::os::unix::fs::symlink(dir.path().join("token"), &path).unwrap(); + } + let server = Server::unix(&dir.path().join("goblind.sock"), vec![spec()]); + let output = local_command(dir.path(), &["exec", ID, "--", "true"]) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(1)); + let error = String::from_utf8_lossy(&output.stderr); + if !symlinked { + assert!(error.contains("private, user-owned regular file")); + } + assert!(!error.contains("do-not-print")); + assert!(!error.contains(TOKEN)); + assert!(output.stdout.is_empty()); + server.finish(); + fs::remove_file(dir.path().join("goblind.sock")).unwrap(); + } +} diff --git a/tests/local_shell/mod.rs b/tests/local_shell/mod.rs index 3880aea..755683e 100644 --- a/tests/local_shell/mod.rs +++ b/tests/local_shell/mod.rs @@ -1,3 +1,4 @@ +mod backend; use crate::support::*; use serde_json::{Value, json}; use std::{ @@ -273,8 +274,7 @@ fn local_preflight_rejects_unsupported_options_without_starting_a_runtime() { .unwrap(); assert_eq!(output.status.code(), Some(1)); assert!( - String::from_utf8_lossy(&output.stderr) - .contains("not supported by local temporary sandboxes") + String::from_utf8_lossy(&output.stderr).contains("not supported by the local backend") ); assert!(!dir.path().join("bootstrap.lock").exists()); } diff --git a/tests/sandbox_sh/mod.rs b/tests/sandbox_sh/mod.rs index aad4a99..e8ac5a9 100644 --- a/tests/sandbox_sh/mod.rs +++ b/tests/sandbox_sh/mod.rs @@ -270,7 +270,8 @@ fn reports_cleanup_failure_and_preserves_command_failure_status() { .unwrap(); assert_eq!(out.status.code(), Some(if code == 0 { 1 } else { 7 })); assert!( - String::from_utf8_lossy(&out.stderr).contains(&format!("adapt sandbox delete {ID}")) + String::from_utf8_lossy(&out.stderr) + .contains(&format!("adapt --cloud sandbox delete {ID}")) ); server.finish(); } From e0e435aecc267158466f7dff5fbc8f31e19480f5 Mon Sep 17 00:00:00 2001 From: Sean Smith Date: Mon, 23 Nov 2026 13:33:42 -0800 Subject: [PATCH 6/6] Release local execution sessions and validate environment defaults --- README.md | 3 +- docs/cli-reference.md | 13 +- src/backend/local.rs | 215 ++++++++++++++++++++++---- tests/backend/mod.rs | 43 ++++++ tests/local_shell/backend.rs | 75 +++++----- tests/local_shell/mod.rs | 31 ++++ tests/local_shell/sessions.rs | 274 ++++++++++++++++++++++++++++++++++ 7 files changed, 582 insertions(+), 72 deletions(-) create mode 100644 tests/local_shell/sessions.rs diff --git a/README.md b/README.md index 8a73727..1027e54 100644 --- a/README.md +++ b/README.md @@ -96,7 +96,8 @@ adapt sandbox sh --local adapt --local sandbox create --image ubuntu:24.04 --wait adapt --local sandbox list adapt --local exec SANDBOX_ID -- uname -m -adapt --local sandbox delete SANDBOX_ID\``` +adapt --local sandbox delete SANDBOX_ID +``` Adapt starts and reuses a private local manager without Platform login. The shell or command from `sandbox sh` runs in a VM that is deleted when the session ends. diff --git a/docs/cli-reference.md b/docs/cli-reference.md index 6cbf00c..4374331 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -283,8 +283,11 @@ records are rejected. Concurrent commands reuse one manager. Local creation accepts `--image`, `--cpu`, `--memory`, `--disk`, and repeated `--env`. Defaults are `ubuntu:24.04`, one CPU, 1024 MiB memory, and a 2048 MiB writable disk. Environment values are stored in private files and applied by -later `adapt exec` commands; execution `--env` flags override them. They are not -image startup configuration. The guest can reach public internet destinations, +later `adapt exec` commands; execution `--env` flags override them. Names must +match `[A-Za-z_][A-Za-z0-9_]*` and be at most 128 bytes. Goblin allows 128 variables +and 32 KiB of names and values combined; values cannot contain NUL. Adapt checks +these limits before creation and again after merging execution overrides. They +are not image startup configuration. The guest can reach public internet destinations, with private/loopback egress blocked by Goblin's public policy. Host mounts and local/cloud moves are not implemented. @@ -300,8 +303,10 @@ queues up to 32 KiB locally; further input is discarded with a warning until the guest resumes reading. Piped input is backpressured without discarding bytes. Temporary shells have a 24-hour execution limit. An uncatchable CLI kill or failed cleanup can leave a VM behind; use `adapt --local sandbox list` and `delete` to -inspect and remove it. Local logs and session output do not have Platform's -retained, redacted log service. +inspect and remove it. Adapt releases completed execution sessions after the +stream closes, retrying while Goblin processes the detach. A disconnect from a running command does not +cancel it; its retained session remains until sandbox deletion. Local logs and +session output do not have Platform's retained, redacted log service. ### Sandbox options diff --git a/src/backend/local.rs b/src/backend/local.rs index 11b10d6..5be7eb6 100644 --- a/src/backend/local.rs +++ b/src/backend/local.rs @@ -12,7 +12,7 @@ use anyhow::{Context, Result, bail}; use reqwest::header::HeaderMap; use reqwest::{Client, Method, StatusCode}; use serde_json::{Value, json}; -use std::{path::PathBuf, time::Duration}; +use std::{collections::BTreeMap, path::PathBuf, time::Duration}; use tokio::sync::OnceCell; use tokio::time::{Instant, sleep}; #[cfg(unix)] @@ -46,6 +46,41 @@ pub fn validate(args: &SandboxCreate) -> Result<()> { bail!("{flag} is not supported by the local backend"); } } + validate_environment(&args.env.iter().cloned().collect()) +} + +/// Match goblin-protocol's ExecRequest environment contract before accepting +/// persistent defaults. Validate the merged environment again before execution. +fn validate_environment(env: &BTreeMap) -> Result<()> { + if env.len() > 128 { + bail!("Local command environment supports at most 128 variables"); + } + if env + .iter() + .map(|(key, value)| key.len() + value.len()) + .sum::() + > 32768 + { + bail!("Local command environment exceeds 32768 bytes (names and values)"); + } + for (key, value) in env { + if key.is_empty() + || key.len() > 128 + || !key.bytes().enumerate().all(|(index, byte)| { + byte == b'_' || byte.is_ascii_alphabetic() || (index > 0 && byte.is_ascii_digit()) + }) + { + bail!( + "Invalid local environment variable name: use [A-Za-z_][A-Za-z0-9_]* with at most 128 bytes" + ); + } + if value.contains('\0') { + bail!("Local command environment values cannot contain NUL"); + } + } + if serde_json::to_vec(env)?.len() > 65536 { + bail!("Encoded local command environment exceeds 64 KiB"); + } Ok(()) } @@ -192,6 +227,7 @@ impl Goblin { let id = full_id(args.sandbox.clone())?; let mut env = metadata::load(&self.state_dir, id)?; env.extend(args.env); + validate_environment(&env)?; let mut body = json!({"id":session.to_string(), "argv":args.argv, "env":env, "cwd":args.cwd, "stdin":args.stdin || args.tty, "timeout_ms":args.timeout_ms}); if args.tty { @@ -206,33 +242,89 @@ impl Goblin { Some(&body), ) .await?; - let mut url = self - .origin - .join(&format!("{path}/stream?after=0&read_only=false"))?; - url.set_scheme("ws") - .map_err(|_| anyhow::anyhow!("Invalid local stream URL"))?; - let mut request = url.as_str().into_client_request()?; - request.headers_mut().extend(self.headers.clone()); - let (socket, _) = tokio::time::timeout(self.timeout, async { - let stream = tokio::net::UnixStream::connect(&self.socket_path).await?; - tokio_tungstenite::client_async(request, stream).await + // Finish dropping the WebSocket (and restoring the terminal) before + // deletion. Goblin may take another event-loop turn to observe detach. + let result: Result = async { + let mut url = self + .origin + .join(&format!("{path}/stream?after=0&read_only=false"))?; + url.set_scheme("ws") + .map_err(|_| anyhow::anyhow!("Invalid local stream URL"))?; + let mut request = url.as_str().into_client_request()?; + request.headers_mut().extend(self.headers.clone()); + let (socket, _) = tokio::time::timeout(self.timeout, async { + let stream = tokio::net::UnixStream::connect(&self.socket_path).await?; + tokio_tungstenite::client_async(request, stream).await + }) + .await + .context("Timed out attaching to local execution")??; + stream::terminal( + socket, + stream::Attachment { + after: 0, + input: args.stdin || args.tty, + tty: args.tty, + json_output, + resume: format!( + "Local sandbox: {id}. Use `adapt --local sandbox delete {id}` to remove it." + ), + credit: Some(0), + }, + ) + .await + } + .await; + let cleanup = self.cleanup_session(&path).await.with_context(|| { + format!("Could not release local execution session {session} in sandbox {id}") + }); + match (result, cleanup) { + (result, Ok(())) => result, + (Ok(0), Err(error)) => Err(error), + (Ok(code), Err(error)) => { + eprintln!("error: {error:#}"); + Ok(code) + } + (Err(error), Err(cleanup)) => Err(error.context(format!("{cleanup:#}"))), + } + } + + #[cfg(unix)] + async fn cleanup_session(&self, path: &str) -> Result<()> { + tokio::time::timeout(self.timeout, async { + let info = match self.request(Method::GET, path, None).await { + Ok(info) => info, + Err(error) + if error + .downcast_ref::() + .is_some_and(|e| e.status == StatusCode::NOT_FOUND) => + { + return Ok(()); + } + Err(error) => return Err(error), + }; + match info["state"].as_str() { + // Ctrl-] and lost connections detach without cancelling work. + Some("starting" | "running" | "stopping" | "deleted") => return Ok(()), + Some("exited" | "failed") => {} + _ => bail!("Local execution response has no recognized state"), + } + loop { + match self.request(Method::DELETE, path, None).await { + Ok(_) => return Ok(()), + Err(error) => match error.downcast_ref::().map(|e| e.status) { + Some(StatusCode::NOT_FOUND) => return Ok(()), + // A finished session remains pinned until Goblin has + // processed the closing stream. Never stop a live one. + Some(StatusCode::CONFLICT | StatusCode::TOO_MANY_REQUESTS) => { + sleep(Duration::from_millis(50)).await + } + _ => return Err(error), + }, + } + } }) .await - .context("Timed out attaching to local execution")??; - stream::terminal( - socket, - stream::Attachment { - after: 0, - input: args.stdin || args.tty, - tty: args.tty, - json_output, - resume: format!( - "Local sandbox: {id}. Use `adapt --local sandbox delete {id}` to remove it." - ), - credit: Some(0), - }, - ) - .await + .context("Timed out releasing the completed local execution session")? } #[cfg(not(unix))] @@ -394,6 +486,7 @@ impl Backend for LocalBackend { } async fn execute(&self, args: ExecArgs, json: bool) -> Result { full_id(args.sandbox.clone())?; + validate_environment(&args.env.iter().cloned().collect())?; if args.detach { return self.unsupported("exec --detach"); } @@ -461,10 +554,8 @@ mod metadata { pub fn save(state: &Path, id: Uuid, pairs: &[(String, String)]) -> Result<()> { let env: BTreeMap<_, _> = pairs.iter().cloned().collect(); + super::validate_environment(&env)?; let bytes = serde_json::to_vec(&env)?; - if bytes.len() > 65536 { - bail!("Local sandbox environment exceeds 64 KiB"); - } // State was validated as private by discovery. Atomic publication keeps // a subsequent exec from reading a partially-written environment. let mut file = tempfile::NamedTempFile::new_in(state)?; @@ -507,3 +598,69 @@ mod metadata { } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn environment_names_and_values_match_goblin_rules_without_echoing_secrets() { + for key in [ + "", + "BAD-NAME", + "0NAME", + "NAME.KEY", + "NÅME", + "A\0B", + &"A".repeat(129), + ] { + let error = + validate_environment(&BTreeMap::from([(key.into(), "do-not-print".into())])) + .unwrap_err(); + assert!(error.to_string().contains("environment variable name")); + assert!(!error.to_string().contains("do-not-print")); + } + assert!(validate_environment(&BTreeMap::from([("VALID".into(), "a\0b".into())])).is_err()); + validate_environment(&BTreeMap::from([ + ("_".into(), "".into()), + ("a_9".into(), " a=b\n$HOME 🦀 ".into()), + ("A".repeat(128), "ok".into()), + ])) + .unwrap(); + } + + #[test] + fn environment_count_and_size_boundaries_use_distinct_names_and_utf8_bytes() { + let mut env: BTreeMap<_, _> = (0..128).map(|i| (format!("KEY_{i}"), "x".into())).collect(); + validate_environment(&env).unwrap(); + env.insert("KEY_0".into(), "replacement".into()); + validate_environment(&env).unwrap(); + env.insert("EXTRA".into(), "x".into()); + assert!( + validate_environment(&env) + .unwrap_err() + .to_string() + .contains("128 variables") + ); + let mut env = BTreeMap::from([("KEY".into(), "é".repeat(16382) + "x")]); + validate_environment(&env).unwrap(); // 3 + 32764 + 1 = 32768 bytes + env.get_mut("KEY").unwrap().push('x'); + assert!( + validate_environment(&env) + .unwrap_err() + .to_string() + .contains("32768 bytes") + ); + } + + #[test] + fn encoded_environment_must_fit_private_metadata_before_creation() { + let env = BTreeMap::from([("KEY".into(), "\u{1}".repeat(12000))]); + assert!( + validate_environment(&env) + .unwrap_err() + .to_string() + .contains("64 KiB") + ); + } +} diff --git a/tests/backend/mod.rs b/tests/backend/mod.rs index 367cb13..950241d 100644 --- a/tests/backend/mod.rs +++ b/tests/backend/mod.rs @@ -136,3 +136,46 @@ fn local_logout_still_removes_only_the_saved_credential() { .contains("saved-secret") ); } + +#[test] +fn invalid_local_environments_fail_before_starting_a_manager_or_creating_state() { + let dir = tempfile::tempdir().unwrap(); + let state = dir.path().join("uncreated"); + let cases = [ + vec!["BAD-NAME=do-not-print".to_string()], + vec!["0NAME=do-not-print".to_string()], + vec!["NÅME=do-not-print".to_string()], + vec![format!("{}=do-not-print", "N".repeat(129))], + (0..129).map(|i| format!("KEY_{i}=do-not-print")).collect(), + ]; + #[cfg(unix)] + let cases = cases.into_iter().chain([ + vec![format!("KEY={}", "x".repeat(32766))], + vec![format!("KEY={}", "\u{1}".repeat(12000))], + ]); + for env in cases { + for args in [ + vec!["sandbox", "create"], + vec!["sandbox", "sh"], + vec!["exec", ID], + ] { + let mut cmd = command(dir.path(), "invalid-cloud-origin"); + cmd.args(["--local", "--local-state-dir"]) + .arg(&state) + .args(&args); + for entry in &env { + cmd.args(["--env", entry]); + } + if args[0] == "exec" || args[1] == "sh" { + cmd.args(["--", "true"]); + } + let output = cmd.output().unwrap(); + let error = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(1), "{args:?}: {error}"); + assert!(error.contains("environment"), "{error}"); + assert!(!error.contains("do-not-print")); + assert!(output.stdout.is_empty()); + assert!(!state.exists()); + } + } +} diff --git a/tests/local_shell/backend.rs b/tests/local_shell/backend.rs index 0314d17..ab33741 100644 --- a/tests/local_shell/backend.rs +++ b/tests/local_shell/backend.rs @@ -1,6 +1,6 @@ use super::*; -fn local_command(state: &Path, args: &[&str]) -> Command { +pub(super) fn local_command(state: &Path, args: &[&str]) -> Command { let mut cmd = command(state, "not-a-valid-cloud-origin"); cmd.env("ADAPT_TOKEN", "cloud-secret-must-not-reach-goblin") .env("HTTP_PROXY", "http://127.0.0.1:1") @@ -78,44 +78,43 @@ fn persistent_sandbox_lifecycle_uses_one_backend_across_cli_invocations() { session: String::new(), })); let executing = ids.clone(); - let server = Server::unix( - &dir.path().join("goblind.sock"), - vec![ - spec(), - http(Box::new(move |r| { - local_auth(r); - let mut ids = executing.lock().unwrap(); - assert_eq!(r.target, format!("/v1/vms/{}/sessions", ids.vm)); - let body = r.json(); - ids.session = body["id"].as_str().unwrap().into(); - assert_eq!( - body["env"], - json!({"BASE":"literal value","OVERRIDE":"new"}) - ); - assert_eq!(body["cwd"], "/tmp"); - assert_eq!(body["timeout_ms"], 5000); - assert_eq!(body["stdin"], false); - assert_eq!(body["argv"], json!(["true"])); - Reply::json(202, json!({"id":ids.session,"state":"starting"})) - })), - stream(ids, |mut ws| { - send( - &mut ws, - json!({"kind":"attached","session":{"stdin_closed":true,"stdin_credit":0}}), - ); - send( - &mut ws, - json!({"kind":"stdout","sequence":1,"data_base64":"cGVyc2lzdGVudAo="}), - ); - send(&mut ws, json!({"kind":"finished","exit":{"code":7}})); - while let Ok(message) = ws.read() { - if matches!(message, Message::Close(_)) { - break; - } + let mut steps = vec![ + spec(), + http(Box::new(move |r| { + local_auth(r); + let mut ids = executing.lock().unwrap(); + assert_eq!(r.target, format!("/v1/vms/{}/sessions", ids.vm)); + let body = r.json(); + ids.session = body["id"].as_str().unwrap().into(); + assert_eq!( + body["env"], + json!({"BASE":"literal value","OVERRIDE":"new"}) + ); + assert_eq!(body["cwd"], "/tmp"); + assert_eq!(body["timeout_ms"], 5000); + assert_eq!(body["stdin"], false); + assert_eq!(body["argv"], json!(["true"])); + Reply::json(202, json!({"id":ids.session,"state":"starting"})) + })), + stream(ids.clone(), |mut ws| { + send( + &mut ws, + json!({"kind":"attached","session":{"stdin_closed":true,"stdin_credit":0}}), + ); + send( + &mut ws, + json!({"kind":"stdout","sequence":1,"data_base64":"cGVyc2lzdGVudAo="}), + ); + send(&mut ws, json!({"kind":"finished","exit":{"code":7}})); + while let Ok(message) = ws.read() { + if matches!(message, Message::Close(_)) { + break; } - }), - ], - ); + } + }), + ]; + steps.extend(session_cleanup(ids, "exited")); + let server = Server::unix(&dir.path().join("goblind.sock"), steps); let output = local_command( dir.path(), &[ diff --git a/tests/local_shell/mod.rs b/tests/local_shell/mod.rs index 755683e..894b387 100644 --- a/tests/local_shell/mod.rs +++ b/tests/local_shell/mod.rs @@ -1,4 +1,5 @@ mod backend; +mod sessions; use crate::support::*; use serde_json::{Value, json}; use std::{ @@ -151,6 +152,33 @@ fn stream( }) } +fn session_cleanup(ids: Arc>, state: &'static str) -> Vec { + let inspected = ids.clone(); + let mut steps = vec![http(Box::new(move |r| { + local_auth(r); + let ids = inspected.lock().unwrap(); + assert_eq!(r.method, "GET"); + assert_eq!( + r.target, + format!("/v1/vms/{}/sessions/{}", ids.vm, ids.session) + ); + Reply::json(200, json!({"id":ids.session,"state":state})) + }))]; + if matches!(state, "exited" | "failed") { + steps.push(http(Box::new(move |r| { + local_auth(r); + let ids = ids.lock().unwrap(); + assert_eq!(r.method, "DELETE"); + assert_eq!( + r.target, + format!("/v1/vms/{}/sessions/{}", ids.vm, ids.session) + ); + Reply::json(204, Value::Null) + }))); + } + steps +} + fn deleted(ids: Arc>) -> Exchange { http(Box::new(move |r| { local_auth(r); @@ -217,6 +245,7 @@ fn local_shell_uses_its_own_credentials_honors_credit_and_cleans_up_on_nonzero_e } } })); + steps.extend(session_cleanup(ids.clone(), "exited")); steps.push(deleted(ids)); let dir = tempfile::tempdir().unwrap(); discovery(dir.path()); @@ -245,6 +274,7 @@ fn local_stream_failure_still_deletes_the_vm() { json!({"kind":"error","message":"guest execution failed"}), ); })); + steps.extend(session_cleanup(ids.clone(), "failed")); steps.push(deleted(ids)); let dir = tempfile::tempdir().unwrap(); discovery(dir.path()); @@ -478,6 +508,7 @@ fn terminal_detaches_with_zero_credit_even_after_the_input_queue_fills() { } assert!(matches!(ws.read().unwrap(), Message::Close(_))); })); + steps.extend(session_cleanup(ids.clone(), "running")); steps.push(terminal.restored_then(deleted(ids))); let dir = tempfile::tempdir().unwrap(); discovery(dir.path()); diff --git a/tests/local_shell/sessions.rs b/tests/local_shell/sessions.rs new file mode 100644 index 0000000..5ece0ea --- /dev/null +++ b/tests/local_shell/sessions.rs @@ -0,0 +1,274 @@ +use super::{backend::local_command, *}; +use std::sync::atomic::{AtomicUsize, Ordering}; + +fn create(ids: Arc>, retained: Arc) -> Exchange { + http(Box::new(move |r| { + local_auth(r); + assert_eq!( + (r.method.as_str(), r.target.as_str()), + ("POST", format!("/v1/vms/{ID}/sessions").as_str()) + ); + assert!( + retained.fetch_add(1, Ordering::SeqCst) < 64, + "Goblin's retained session capacity was exhausted" + ); + let mut ids = ids.lock().unwrap(); + ids.session = r.json()["id"].as_str().unwrap().into(); + Reply::json(202, json!({"id":ids.session,"state":"starting"})) + })) +} + +fn finished(ids: Arc>, code: u8) -> Exchange { + stream(ids, move |mut ws| { + send(&mut ws, json!({"kind":"finished","exit":{"code":code}})); + assert!(matches!(ws.read().unwrap(), Message::Close(_))); + }) +} + +fn session_reply(ids: Arc>, method: &'static str, status: u16, body: Value) -> Exchange { + http(Box::new(move |r| { + local_auth(r); + let ids = ids.lock().unwrap(); + assert_eq!(r.method, method); + assert_eq!( + r.target, + format!("/v1/vms/{}/sessions/{}", ids.vm, ids.session) + ); + Reply::json(status, body) + })) +} + +fn ids() -> Arc> { + Arc::new(Mutex::new(Ids { + vm: ID.into(), + session: String::new(), + })) +} + +#[test] +fn more_than_64_sequential_execs_release_sessions_and_preserve_exit_codes() { + let dir = tempfile::tempdir().unwrap(); + discovery(dir.path()); + let retained = Arc::new(AtomicUsize::new(0)); + let mut steps = Vec::new(); + for i in 0..70 { + let ids = ids(); + steps.extend([ + spec(), + create(ids.clone(), retained.clone()), + finished(ids.clone(), i % 2 * 7), + ]); + steps.push(session_reply( + ids.clone(), + "GET", + 200, + json!({"state":"exited"}), + )); + let count = retained.clone(); + steps.push(http(Box::new(move |r| { + local_auth(r); + assert_eq!(r.method, "DELETE"); + assert_eq!( + r.target, + format!("/v1/vms/{ID}/sessions/{}", ids.lock().unwrap().session) + ); + assert_eq!(count.fetch_sub(1, Ordering::SeqCst), 1); + Reply::json(204, Value::Null) + }))); + } + let server = Server::unix(&dir.path().join("goblind.sock"), steps); + for i in 0..70 { + let output = local_command(dir.path(), &["exec", ID, "--", "true"]) + .output() + .unwrap(); + assert_eq!( + output.status.code(), + Some(i % 2 * 7), + "execution {i}: {}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!(retained.load(Ordering::SeqCst), 0); + } + server.finish(); +} + +#[test] +fn finished_session_cleanup_retries_detach_races_and_tolerates_already_deleted_sessions() { + let dir = tempfile::tempdir().unwrap(); + discovery(dir.path()); + for state in ["exited", "failed"] { + let ids = ids(); + let server = Server::unix( + &dir.path().join("goblind.sock"), + vec![ + spec(), + create(ids.clone(), Arc::new(AtomicUsize::new(0))), + finished(ids.clone(), 7), + session_reply(ids.clone(), "GET", 200, json!({"state":state})), + session_reply( + ids.clone(), + "DELETE", + 409, + json!({"error":"stop and detach session before deleting"}), + ), + session_reply( + ids.clone(), + "DELETE", + 429, + json!({"error":"worker capacity reached"}), + ), + session_reply(ids, "DELETE", 404, json!({"error":"session not found"})), + ], + ); + let output = local_command(dir.path(), &["exec", ID, "--", "false"]) + .output() + .unwrap(); + assert_eq!( + output.status.code(), + Some(7), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + assert!(!String::from_utf8_lossy(&output.stderr).contains("Could not release")); + server.finish(); + fs::remove_file(dir.path().join("goblind.sock")).unwrap(); + } +} + +#[test] +fn failed_attachment_does_not_cancel_live_commands_or_mask_the_original_error() { + let dir = tempfile::tempdir().unwrap(); + discovery(dir.path()); + for state in ["starting", "running", "stopping", "failed"] { + let ids = ids(); + let mut steps = vec![ + spec(), + create(ids.clone(), Arc::new(AtomicUsize::new(0))), + stream(ids.clone(), |mut ws| { + send( + &mut ws, + json!({"kind":"error","message":"original stream failure"}), + ); + }), + ]; + steps.extend(session_cleanup(ids, state)); + let server = Server::unix(&dir.path().join("goblind.sock"), steps); + let output = local_command(dir.path(), &["exec", ID, "--", "sleep", "100"]) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(1)); + assert!(String::from_utf8_lossy(&output.stderr).contains("original stream failure")); + server.finish(); + fs::remove_file(dir.path().join("goblind.sock")).unwrap(); + } +} + +#[test] +fn session_cleanup_errors_preserve_failed_exit_codes_and_report_successful_command_leaks() { + let dir = tempfile::tempdir().unwrap(); + discovery(dir.path()); + for code in [0, 7] { + let ids = ids(); + let server = Server::unix( + &dir.path().join("goblind.sock"), + vec![ + spec(), + create(ids.clone(), Arc::new(AtomicUsize::new(0))), + finished(ids.clone(), code), + session_reply(ids.clone(), "GET", 200, json!({"state":"exited"})), + session_reply( + ids, + "DELETE", + 403, + json!({"error":"fixture denied cleanup"}), + ), + ], + ); + let output = local_command(dir.path(), &["exec", ID, "--", "true"]) + .output() + .unwrap(); + assert_eq!( + output.status.code(), + Some(if code == 0 { 1 } else { i32::from(code) }) + ); + let error = String::from_utf8_lossy(&output.stderr); + assert!(error.contains("Could not release local execution session")); + assert!(error.contains("fixture denied cleanup")); + server.finish(); + fs::remove_file(dir.path().join("goblind.sock")).unwrap(); + } +} + +#[test] +fn session_cleanup_deadline_includes_inspection_and_delete_retries() { + let dir = tempfile::tempdir().unwrap(); + discovery(dir.path()); + let ids = ids(); + let server = Server::unix( + &dir.path().join("goblind.sock"), + vec![ + spec(), + create(ids.clone(), Arc::new(AtomicUsize::new(0))), + finished(ids.clone(), 0), + session_reply(ids.clone(), "GET", 200, json!({"state":"exited"})), + session_reply(ids, "DELETE", 409, json!({"error":"still detaching"})), + Box::new(|mut socket| { + let request = read_request(&mut socket); + assert_eq!(request.method, "DELETE"); + std::thread::sleep(std::time::Duration::from_millis(1200)); + request + }), + ], + ); + let start = Instant::now(); + let output = command_with_timeout(dir.path(), "invalid-cloud-origin", 1) + .args(["--local", "--local-state-dir"]) + .arg(dir.path()) + .args(["exec", ID, "--", "true"]) + .output() + .unwrap(); + assert_eq!( + output.status.code(), + Some(1), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + assert!(String::from_utf8_lossy(&output.stderr).contains("Timed out releasing")); + assert!(start.elapsed() < std::time::Duration::from_secs(4)); + server.finish(); +} + +#[test] +fn invalid_persisted_or_merged_environments_never_create_an_execution() { + let dir = tempfile::tempdir().unwrap(); + discovery(dir.path()); + let mut full = serde_json::Map::new(); + for i in 0..128 { + full.insert(format!("KEY_{i}"), json!("default")); + } + for (defaults, extra) in [ + (json!({"BAD-NAME":"do-not-print"}), vec![]), + (json!({"KEY":"do-not-print\u{0}"}), vec![]), + (Value::Object(full), vec!["--env", "EXTRA=value"]), + ( + json!({"KEY":"x".repeat(32765)}), + vec!["--env", "EXTRA=value"], + ), + ] { + private_file( + &dir.path().join(format!("adapt-{ID}.json")), + defaults.to_string().as_bytes(), + ); + let server = Server::unix(&dir.path().join("goblind.sock"), vec![spec()]); + let mut args = vec!["exec", ID]; + args.extend(extra); + args.extend(["--", "true"]); + let output = local_command(dir.path(), &args).output().unwrap(); + assert_eq!(output.status.code(), Some(1)); + let error = String::from_utf8_lossy(&output.stderr); + assert!(error.contains("environment"), "{error}"); + assert!(!error.contains("do-not-print")); + server.finish(); + fs::remove_file(dir.path().join("goblind.sock")).unwrap(); + } +}