From ae2558bc0c01f976077bbc6562dbf3ff25f0412a Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 5 Nov 2026 19:30:58 +0000 Subject: [PATCH 01/37] test(sandbox): back scripted driver boxes with host directories The scripted driver can now keep each box as a directory on the test host, and execs the script does not answer run their program there with the system shell. This lets file transfer be tested against the commands a real box would run instead of canned output. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../openshell/scripted_driver_fixture.rs | 53 +++++++++++++++++-- 1 file changed, 48 insertions(+), 5 deletions(-) diff --git a/crates/openhuman-core/src/sandbox/openshell/scripted_driver_fixture.rs b/crates/openhuman-core/src/sandbox/openshell/scripted_driver_fixture.rs index 90017a1a0c2..8af3159df32 100644 --- a/crates/openhuman-core/src/sandbox/openshell/scripted_driver_fixture.rs +++ b/crates/openhuman-core/src/sandbox/openshell/scripted_driver_fixture.rs @@ -1,7 +1,13 @@ //! Test-only [`BoxDriver`] stand-in: records every call and answers execs from //! a script, so the registry's lifecycle is testable without a TinyBox module. +//! +//! A driver can also keep real boxes on the test host ([`ScriptedDriver::keep_boxes_in`]): +//! each box is a directory, and an exec past the end of the script runs its +//! program there with the system shell, so file transfer is tested against +//! the commands a real box would run. use std::collections::VecDeque; +use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; use std::time::Duration; @@ -43,6 +49,7 @@ pub(crate) struct ScriptedDriver { create_delay: Mutex, create_failures: AtomicUsize, close_fails: AtomicBool, + box_root: Mutex>, } impl ScriptedDriver { @@ -62,6 +69,21 @@ impl ScriptedDriver { self.create_failures.store(count, Ordering::SeqCst); } + /// Back every box with a directory under `root`, and run execs the script + /// does not answer in it. + pub(crate) fn keep_boxes_in(&self, root: &Path) { + *self.box_root.lock().unwrap() = Some(root.to_path_buf()); + } + + /// Where `resource`'s files are, when boxes are kept on the host. + pub(crate) fn box_dir(&self, resource: &str) -> Option { + self.box_root + .lock() + .unwrap() + .as_ref() + .map(|root| root.join(resource)) + } + pub(crate) fn fail_closes(&self) { self.close_fails.store(true, Ordering::SeqCst); } @@ -128,10 +150,11 @@ impl BoxDriver for ScriptedDriver { self.create_failures.store(failures - 1, Ordering::SeqCst); return Err(BoxError::Driver("create refused".into())); } - Ok(format!( - "box-{}", - self.next_id.fetch_add(1, Ordering::SeqCst) - )) + let resource = format!("box-{}", self.next_id.fetch_add(1, Ordering::SeqCst)); + if let Some(dir) = self.box_dir(&resource) { + std::fs::create_dir_all(dir).expect("create a box directory"); + } + Ok(resource) } async fn exec(&self, resource: &str, exec: &BoxExec) -> Result { @@ -141,7 +164,10 @@ impl BoxDriver for ScriptedDriver { }); let step = self.script.lock().unwrap().pop_front(); match step { - None => Ok(ok_output()), + None => match self.box_dir(resource) { + Some(dir) => run_on_host(&dir, exec).await, + None => Ok(ok_output()), + }, Some(ExecStep::Reply(output)) => Ok(output), Some(ExecStep::Fail(error)) => Err(error), Some(ExecStep::Hang) => std::future::pending().await, @@ -164,3 +190,20 @@ impl BoxDriver for ScriptedDriver { Ok(()) } } + +/// Run `exec` in `dir`, standing in for the box's work folder. +async fn run_on_host(dir: &Path, exec: &BoxExec) -> Result { + let (program, args) = exec.argv.split_first().expect("an exec names a program"); + let output = tokio::process::Command::new(program) + .args(args) + .current_dir(dir) + .envs(&exec.env) + .output() + .await + .map_err(|error| BoxError::Driver(error.to_string()))?; + Ok(BoxOutput { + exit_code: output.status.code().unwrap_or(-1), + stdout: output.stdout, + stderr: output.stderr, + }) +} From 937e1f12e2beac2fda3812280991b587bbc81dde Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 5 Nov 2026 19:31:44 +0000 Subject: [PATCH 02/37] chore(sandbox): register files module in openshell sandbox Adds the files module to the openshell sandbox so its file handling code is compiled as part of the crate. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/sandbox/openshell/files_tests.rs | 539 ++++++++++++++++++ .../src/sandbox/openshell/mod.rs | 1 + 2 files changed, 540 insertions(+) create mode 100644 crates/openhuman-core/src/sandbox/openshell/files_tests.rs diff --git a/crates/openhuman-core/src/sandbox/openshell/files_tests.rs b/crates/openhuman-core/src/sandbox/openshell/files_tests.rs new file mode 100644 index 00000000000..79dfc094665 --- /dev/null +++ b/crates/openhuman-core/src/sandbox/openshell/files_tests.rs @@ -0,0 +1,539 @@ +use super::*; +use crate::core::runtime::NoTenant; +use crate::sandbox::openshell::scripted_driver::{Call, ExecStep, ScriptedDriver}; +use base64::Engine as _; + +fn embedded(id: &str) -> Tenant { + Tenant { + profile: None, + agent: Some(id.into()), + } +} + +fn registry(driver: &Arc) -> Arc> { + BoxRegistry::new( + Arc::clone(driver), + RegistryLimits { + idle_ttl: Duration::from_secs(900), + max_live: 10, + }, + ) +} + +fn config() -> OpenShellRuntimeConfig { + OpenShellRuntimeConfig::default() +} + +/// Every byte value, so NUL and bytes that are not UTF-8 are in the file. +fn binary(len: usize) -> Vec { + (0..len).map(|i| (i % 256) as u8).collect() +} + +fn reply(exit_code: i32, stdout: &str, stderr: &str) -> ExecStep { + ExecStep::Reply(BoxOutput { + exit_code, + stdout: stdout.as_bytes().to_vec(), + stderr: stderr.as_bytes().to_vec(), + }) +} + +fn encoded(bytes: &[u8]) -> String { + base64::engine::general_purpose::STANDARD.encode(bytes) +} + +/// The shell command of every exec the driver saw, in order. +fn commands(driver: &ScriptedDriver) -> Vec { + driver + .calls() + .into_iter() + .filter_map(|call| match call { + Call::Exec { exec, .. } => exec.argv.last().cloned(), + _ => None, + }) + .collect() +} + +#[tokio::test] +async fn a_call_with_no_tenant_is_refused_before_any_box_is_touched() { + let driver = ScriptedDriver::new(); + let boxes = registry(&driver); + + let wrote = write_file_in(&boxes, Err(NoTenant), &config(), "a.txt", b"x").await; + let read = read_file_in(&boxes, Err(NoTenant), &config(), "a.txt", 10).await; + + assert_eq!(wrote, Err(BoxError::NoTenant)); + assert_eq!(read, Err(BoxError::NoTenant)); + assert!(driver.calls().is_empty()); +} + +#[tokio::test] +async fn paths_outside_the_work_folder_are_refused_before_any_box_is_touched() { + let driver = ScriptedDriver::new(); + let boxes = registry(&driver); + let refused = [ + ("", "empty"), + ("/etc/passwd", "absolute"), + ("../escape.txt", "dotdot"), + ("a/../../escape.txt", "nested dotdot"), + ("a\0b", "NUL"), + ("dir/", "trailing slash"), + ("..", "bare dotdot"), + ]; + + for (path, why) in refused { + let wrote = write_file_in(&boxes, Ok(embedded("u1")), &config(), path, b"x").await; + let read = read_file_in(&boxes, Ok(embedded("u1")), &config(), path, 10).await; + assert!(matches!(wrote, Err(BoxError::InvalidPath(_))), "{why}"); + assert!(matches!(read, Err(BoxError::InvalidPath(_))), "{why}"); + } + assert!(driver.calls().is_empty()); +} + +#[test] +fn a_refused_path_says_what_to_use_instead() { + let message = BoxError::InvalidPath("it must be relative").to_string(); + assert_eq!( + message, + "the sandbox file path is not allowed: it must be relative" + ); +} + +#[tokio::test] +async fn a_file_over_the_host_limit_is_refused_before_any_box_is_touched() { + let driver = ScriptedDriver::new(); + let boxes = registry(&driver); + let too_big = vec![0u8; MAX_FILE_BYTES as usize + 1]; + + let wrote = write_file_in(&boxes, Ok(embedded("u1")), &config(), "big.bin", &too_big).await; + + assert_eq!( + wrote, + Err(BoxError::FileTooLarge { + size: MAX_FILE_BYTES + 1, + limit: MAX_FILE_BYTES, + }) + ); + assert!(driver.calls().is_empty()); +} + +#[tokio::test] +async fn a_small_file_is_one_command_that_writes_a_part_file_and_renames_it() { + let driver = ScriptedDriver::new(); + let boxes = registry(&driver); + + write_file_in(&boxes, Ok(embedded("u1")), &config(), "out/a.txt", b"hi") + .await + .unwrap(); + + let sent = commands(&driver); + assert_eq!(sent.len(), 1, "{sent:?}"); + assert!(sent[0].contains("mkdir -p -- 'out'"), "{}", sent[0]); + assert!( + sent[0].contains(&format!("printf %s '{}' | base64 -d", encoded(b"hi"))), + "{}", + sent[0] + ); + assert!(sent[0].contains("'out/a.txt.part'"), "{}", sent[0]); + assert!( + sent[0].contains("mv -f -- 'out/a.txt.part' 'out/a.txt'"), + "{}", + sent[0] + ); +} + +#[tokio::test] +async fn a_large_file_is_sent_in_chunks_that_fit_one_argument() { + let driver = ScriptedDriver::new(); + let boxes = registry(&driver); + let bytes = binary(WRITE_CHUNK_BYTES * 2 + 5); + + write_file_in(&boxes, Ok(embedded("u1")), &config(), "a.bin", &bytes) + .await + .unwrap(); + + let sent = commands(&driver); + assert_eq!(sent.len(), 3); + assert!(sent.iter().all(|command| command.len() < 128 * 1024)); + // The first chunk starts the part file; the rest append; only the last renames. + assert!(sent[0].contains("base64 -d > 'a.bin.part'"), "{}", sent[0]); + assert!(sent[1].contains("base64 -d >> 'a.bin.part'")); + assert!(!sent[0].contains("mv -f") && !sent[1].contains("mv -f")); + assert!(sent[2].contains("mv -f")); +} + +#[tokio::test] +async fn a_failed_chunk_removes_the_part_file_and_reports_what_the_box_said() { + let driver = ScriptedDriver::new(); + let boxes = registry(&driver); + driver.then(reply(0, "", "")); + driver.then(reply(1, "", "sh: write error: No space left on device\n")); + let bytes = binary(WRITE_CHUNK_BYTES * 2); + + let wrote = write_file_in(&boxes, Ok(embedded("u1")), &config(), "a.bin", &bytes).await; + + assert_eq!( + wrote, + Err(BoxError::FileTransfer { + action: "write", + path: "a.bin".into(), + detail: "sh: write error: No space left on device".into(), + }) + ); + let sent = commands(&driver); + assert_eq!(sent.len(), 3, "{sent:?}"); + assert_eq!(sent[2], "rm -f -- 'a.bin.part'"); +} + +#[test] +fn a_failed_transfer_reads_well_as_a_tool_result() { + let error = BoxError::FileTransfer { + action: "write", + path: "a.bin".into(), + detail: "No space left on device".into(), + }; + assert_eq!( + error.to_string(), + "could not write `a.bin` in the sandbox: No space left on device" + ); + assert_eq!( + BoxError::FileNotFound("a.bin".into()).to_string(), + "there is no file `a.bin` in the sandbox" + ); + assert_eq!( + BoxError::FileTooLarge { size: 10, limit: 4 }.to_string(), + "the file is 10 bytes, over the 4 byte limit" + ); + assert_eq!( + BoxError::ShortRead { + expected: 10, + got: 4 + } + .to_string(), + "the sandbox returned 4 of the file's 10 bytes" + ); +} + +#[tokio::test] +async fn a_file_over_the_callers_limit_is_refused_before_any_chunk_is_read() { + let driver = ScriptedDriver::new(); + let boxes = registry(&driver); + driver.then(reply(0, "1000\n", "")); + + let read = read_file_in(&boxes, Ok(embedded("u1")), &config(), "a.bin", 999).await; + + assert_eq!( + read, + Err(BoxError::FileTooLarge { + size: 1000, + limit: 999 + }) + ); + // Only the size check ran. + assert_eq!(commands(&driver).len(), 1); +} + +#[tokio::test] +async fn the_host_limit_caps_a_callers_larger_limit() { + let driver = ScriptedDriver::new(); + let boxes = registry(&driver); + driver.then(reply(0, &format!("{}\n", MAX_FILE_BYTES + 1), "")); + + let read = read_file_in(&boxes, Ok(embedded("u1")), &config(), "a.bin", u64::MAX).await; + + assert_eq!( + read, + Err(BoxError::FileTooLarge { + size: MAX_FILE_BYTES + 1, + limit: MAX_FILE_BYTES + }) + ); + assert_eq!(commands(&driver).len(), 1); +} + +#[tokio::test] +async fn a_missing_file_is_reported_by_name() { + let driver = ScriptedDriver::new(); + let boxes = registry(&driver); + driver.then(reply(66, "", "")); + + let read = read_file_in(&boxes, Ok(embedded("u1")), &config(), "gone.pdf", 100).await; + + assert_eq!(read, Err(BoxError::FileNotFound("gone.pdf".into()))); + assert!(commands(&driver)[0].starts_with("test -f -- 'gone.pdf' || exit 66")); +} + +#[tokio::test] +async fn a_short_chunk_fails_the_read_instead_of_returning_a_short_file() { + let driver = ScriptedDriver::new(); + let boxes = registry(&driver); + driver.then(reply(0, "10\n", "")); + driver.then(reply(0, &encoded(b"1234"), "")); + + let read = read_file_in(&boxes, Ok(embedded("u1")), &config(), "a.bin", 100).await; + + assert_eq!( + read, + Err(BoxError::ShortRead { + expected: 10, + got: 4 + }) + ); +} + +#[tokio::test] +async fn a_chunk_that_is_not_base64_fails_the_read() { + let driver = ScriptedDriver::new(); + let boxes = registry(&driver); + driver.then(reply(0, "4\n", "")); + driver.then(reply(0, "!!!!", "")); + + let read = read_file_in(&boxes, Ok(embedded("u1")), &config(), "a.bin", 100).await; + + assert!(matches!(read, Err(BoxError::FileTransfer { .. })), "{read:?}"); +} + +#[tokio::test] +async fn a_failing_chunk_command_fails_the_read_with_the_boxs_message() { + let driver = ScriptedDriver::new(); + let boxes = registry(&driver); + driver.then(reply(0, "4\n", "")); + driver.then(reply(1, "", "tail: error reading 'a.bin': Input/output error\n")); + + let read = read_file_in(&boxes, Ok(embedded("u1")), &config(), "a.bin", 100).await; + + assert_eq!( + read, + Err(BoxError::FileTransfer { + action: "read", + path: "a.bin".into(), + detail: "tail: error reading 'a.bin': Input/output error".into(), + }) + ); +} + +#[tokio::test] +async fn a_size_the_box_does_not_report_as_a_number_fails_the_read() { + let driver = ScriptedDriver::new(); + let boxes = registry(&driver); + driver.then(reply(0, "lots", "")); + + let read = read_file_in(&boxes, Ok(embedded("u1")), &config(), "a.bin", 100).await; + + assert!(matches!(read, Err(BoxError::FileTransfer { .. })), "{read:?}"); +} + +#[tokio::test] +async fn an_empty_file_reads_as_no_bytes_without_a_chunk() { + let driver = ScriptedDriver::new(); + let boxes = registry(&driver); + driver.then(reply(0, "0\n", "")); + + let read = read_file_in(&boxes, Ok(embedded("u1")), &config(), "a.bin", 100).await; + + assert_eq!(read, Ok(Vec::new())); + assert_eq!(commands(&driver).len(), 1); +} + +#[tokio::test] +async fn a_command_that_times_out_is_a_failed_transfer() { + let driver = ScriptedDriver::new(); + let boxes = registry(&driver); + driver.then(reply(124, "", "")); + + let read = read_file_in(&boxes, Ok(embedded("u1")), &config(), "a.bin", 100).await; + + assert_eq!( + read, + Err(BoxError::FileTransfer { + action: "read", + path: "a.bin".into(), + detail: "the sandbox took too long".into(), + }) + ); +} + +#[tokio::test] +async fn a_failure_with_no_message_still_names_the_exit_status() { + let driver = ScriptedDriver::new(); + let boxes = registry(&driver); + driver.then(reply(2, "", " \n")); + + let wrote = write_file_in(&boxes, Ok(embedded("u1")), &config(), "a.bin", b"x").await; + + assert_eq!( + wrote, + Err(BoxError::FileTransfer { + action: "write", + path: "a.bin".into(), + detail: "the command exited with status 2".into(), + }) + ); +} + +#[tokio::test] +async fn a_driver_failure_is_passed_through() { + let driver = ScriptedDriver::new(); + let boxes = registry(&driver); + driver.then(ExecStep::Fail(BoxError::Driver("gateway down".into()))); + + let read = read_file_in(&boxes, Ok(embedded("u1")), &config(), "a.bin", 100).await; + + assert_eq!(read, Err(BoxError::Driver("gateway down".into()))); +} + +/// Tests that run the commands for real, in a directory standing in for each +/// box, so the quoting and the encoding are checked against a shell. +#[cfg(target_os = "linux")] +mod on_a_real_shell { + use super::*; + + fn host_boxes() -> ( + tempfile::TempDir, + Arc, + Arc>, + ) { + let root = tempfile::tempdir().unwrap(); + let driver = ScriptedDriver::new(); + driver.keep_boxes_in(root.path()); + let boxes = registry(&driver); + (root, driver, boxes) + } + + #[tokio::test] + async fn binary_bytes_spanning_several_chunks_round_trip() { + let (_root, driver, boxes) = host_boxes(); + let bytes = binary(READ_CHUNK_BYTES * 2 + WRITE_CHUNK_BYTES + 17); + assert!(bytes.contains(&0) && std::str::from_utf8(&bytes).is_err()); + + write_file_in(&boxes, Ok(embedded("u1")), &config(), "work/out.bin", &bytes) + .await + .unwrap(); + let back = read_file_in(&boxes, Ok(embedded("u1")), &config(), "work/out.bin", MAX_FILE_BYTES) + .await + .unwrap(); + + assert_eq!(back, bytes); + let on_disk = driver.box_dir("box-0").unwrap().join("work/out.bin"); + assert_eq!(std::fs::read(on_disk).unwrap(), bytes); + assert!(!driver.box_dir("box-0").unwrap().join("work/out.bin.part").exists()); + } + + #[tokio::test] + async fn a_path_with_a_space_and_a_quote_is_one_file() { + let (_root, driver, boxes) = host_boxes(); + let path = "my files/it's; $(touch pwned) here.txt"; + + write_file_in(&boxes, Ok(embedded("u1")), &config(), path, b"hello") + .await + .unwrap(); + let back = read_file_in(&boxes, Ok(embedded("u1")), &config(), path, 100) + .await + .unwrap(); + + assert_eq!(back, b"hello"); + let dir = driver.box_dir("box-0").unwrap(); + assert!(dir.join(path).is_file()); + assert!(!dir.join("pwned").exists()); + } + + #[tokio::test] + async fn a_name_that_looks_like_an_option_is_a_file() { + let (_root, driver, boxes) = host_boxes(); + + write_file_in(&boxes, Ok(embedded("u1")), &config(), "-rf", b"x") + .await + .unwrap(); + let back = read_file_in(&boxes, Ok(embedded("u1")), &config(), "-rf", 10) + .await + .unwrap(); + + assert_eq!(back, b"x"); + assert!(driver.box_dir("box-0").unwrap().join("-rf").is_file()); + } + + #[tokio::test] + async fn an_empty_file_round_trips() { + let (_root, _driver, boxes) = host_boxes(); + + write_file_in(&boxes, Ok(embedded("u1")), &config(), "empty", b"") + .await + .unwrap(); + let back = read_file_in(&boxes, Ok(embedded("u1")), &config(), "empty", 10) + .await + .unwrap(); + + assert!(back.is_empty()); + } + + #[tokio::test] + async fn writing_again_replaces_the_file() { + let (_root, _driver, boxes) = host_boxes(); + + for body in [&b"first and longer"[..], b"second"] { + write_file_in(&boxes, Ok(embedded("u1")), &config(), "a.txt", body) + .await + .unwrap(); + } + let back = read_file_in(&boxes, Ok(embedded("u1")), &config(), "a.txt", 100) + .await + .unwrap(); + + assert_eq!(back, b"second"); + } + + #[tokio::test] + async fn a_directory_is_not_overwritten_and_is_not_a_readable_file() { + let (_root, _driver, boxes) = host_boxes(); + write_file_in(&boxes, Ok(embedded("u1")), &config(), "d/a.txt", b"x") + .await + .unwrap(); + + let wrote = write_file_in(&boxes, Ok(embedded("u1")), &config(), "d", b"y").await; + let read = read_file_in(&boxes, Ok(embedded("u1")), &config(), "d", 10).await; + + assert!(matches!(wrote, Err(BoxError::FileTransfer { .. })), "{wrote:?}"); + assert_eq!(read, Err(BoxError::FileNotFound("d".into()))); + } + + #[tokio::test] + async fn a_missing_file_is_not_found() { + let (_root, _driver, boxes) = host_boxes(); + + let read = read_file_in(&boxes, Ok(embedded("u1")), &config(), "nope.txt", 10).await; + + assert_eq!(read, Err(BoxError::FileNotFound("nope.txt".into()))); + } + + #[tokio::test] + async fn tenants_never_share_a_box_or_its_files() { + let (_root, driver, boxes) = host_boxes(); + write_file_in(&boxes, Ok(embedded("u1")), &config(), "secret.txt", b"mine") + .await + .unwrap(); + + let theirs = read_file_in(&boxes, Ok(embedded("u2")), &config(), "secret.txt", 10).await; + let mine = read_file_in(&boxes, Ok(embedded("u1")), &config(), "secret.txt", 10).await; + + assert_eq!(theirs, Err(BoxError::FileNotFound("secret.txt".into()))); + assert_eq!(mine, Ok(b"mine".to_vec())); + assert_eq!(driver.created(), 2); + assert!(driver.box_dir("box-0").unwrap().join("secret.txt").is_file()); + assert!(!driver.box_dir("box-1").unwrap().join("secret.txt").exists()); + } + + #[tokio::test] + async fn a_box_replaced_mid_write_never_leaves_a_truncated_file() { + let (_root, driver, boxes) = host_boxes(); + // The box is lost after the first chunk: the registry retries the + // second in a fresh box, which has none of the first. + driver.then(reply(0, "", "")); + driver.then(ExecStep::Fail(BoxError::UnknownResource)); + let bytes = binary(WRITE_CHUNK_BYTES * 2); + + let wrote = write_file_in(&boxes, Ok(embedded("u1")), &config(), "a.bin", &bytes).await; + + assert!(matches!(wrote, Err(BoxError::FileTransfer { .. })), "{wrote:?}"); + assert_eq!(driver.created(), 2); + assert!(!driver.box_dir("box-1").unwrap().join("a.bin").exists()); + } +} diff --git a/crates/openhuman-core/src/sandbox/openshell/mod.rs b/crates/openhuman-core/src/sandbox/openshell/mod.rs index c3f4d382a47..f4018327921 100644 --- a/crates/openhuman-core/src/sandbox/openshell/mod.rs +++ b/crates/openhuman-core/src/sandbox/openshell/mod.rs @@ -25,6 +25,7 @@ #[cfg(feature = "modules")] mod bus_driver; +mod files; mod registry; mod types; From 8335f3ff5dd3756bd22aeae0b4990823944d59bc Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 5 Nov 2026 19:34:56 +0000 Subject: [PATCH 03/37] feat(sandbox): add file transfer helpers for sandbox boxes Adds read_file_in and write_file_in to move files into and out of a box's work folder in chunks, with a MAX_FILE_BYTES limit and new BoxError variants for invalid paths and oversized files. The helpers are re-exported from the openshell module so callers can use them directly. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/sandbox/openshell/files.rs | 297 ++++++++++++++++++ .../src/sandbox/openshell/files_tests.rs | 65 +++- .../src/sandbox/openshell/mod.rs | 1 + .../src/sandbox/openshell/types.rs | 32 ++ 4 files changed, 382 insertions(+), 13 deletions(-) create mode 100644 crates/openhuman-core/src/sandbox/openshell/files.rs diff --git a/crates/openhuman-core/src/sandbox/openshell/files.rs b/crates/openhuman-core/src/sandbox/openshell/files.rs new file mode 100644 index 00000000000..c67377565b7 --- /dev/null +++ b/crates/openhuman-core/src/sandbox/openshell/files.rs @@ -0,0 +1,297 @@ +//! Moving a file into or out of a tenant's box, over plain command execution. +//! +//! Nothing here needs more than [`BoxDriver::exec`]: a file travels as base64 +//! inside the argument of a `sh -c` command, so every box driver supports it +//! and no box contract grows. Paths are relative to the box's work folder +//! ([`BOX_WORKDIR`](super::registry::BOX_WORKDIR), the directory every command +//! runs in), and every path that reaches the shell is single-quoted. +//! +//! - **Write** sends [`WRITE_CHUNK_BYTES`] at a time (a Linux argument is at +//! most 128 KiB; the encoding adds a third), appending to `.part`. +//! The last command checks the part file's length and only then renames it +//! over ``, so a reader never sees half a file, and a box replaced +//! mid-write (it forgets the earlier chunks) fails the length check instead +//! of keeping a truncated file. A failure removes the part file. +//! - **Read** checks the file exists and reads its size first, refuses a file +//! over the limit before moving any of it, then reads +//! [`READ_CHUNK_BYTES`] at a time (a hosted exec keeps at most 512 KB of +//! output per stream) and checks the total. A read that comes back short is +//! an error, never a short file. +//! +//! Both are keyed on the whole tenant like a command is; a call with no tenant +//! is refused before a box is touched. + +use std::collections::BTreeMap; +use std::time::Duration; + +use base64::Engine as _; + +use super::{tenant_for_box, BoxDriver, BoxError, BoxRegistry, BoxRequest, BoxSettings}; +use crate::config::OpenShellRuntimeConfig; +use crate::core::runtime::{NoTenant, Tenant}; +use crate::sandbox::types::SandboxExecResult; + +/// The largest file the host moves into or out of a box: 8 MiB. +pub const MAX_FILE_BYTES: u64 = 8 * 1024 * 1024; + +/// Raw bytes per write command: 64 KiB once encoded, under a Linux +/// argument's 128 KiB. +pub(crate) const WRITE_CHUNK_BYTES: usize = 48 * 1024; + +/// Raw bytes per read command: about 342 KB once encoded, under a hosted +/// exec's 512 KB of output per stream. +pub(crate) const READ_CHUNK_BYTES: usize = 256 * 1024; + +/// How long one transfer command may run. +const COMMAND_TIMEOUT: Duration = Duration::from_secs(60); + +/// The exit status the size check uses for "not a regular file". +const NOT_A_FILE_EXIT: i32 = 66; + +/// The longest box message kept in an error. +const DETAIL_MAX_CHARS: usize = 200; + +/// Write `bytes` to `path` in the box of the tenant `tenant` resolves to, +/// creating parent folders and replacing any file already there. +/// +/// `path` is relative to the box's work folder. +/// +/// # Errors +/// +/// [`BoxError::NoTenant`], [`BoxError::InvalidPath`] and +/// [`BoxError::FileTooLarge`] (over [`MAX_FILE_BYTES`]) before any box is +/// touched; [`BoxError::FileTransfer`] when a command fails (the part file is +/// removed); otherwise the settings and registry errors. +pub async fn write_file_in( + registry: &BoxRegistry, + tenant: Result, + openshell: &OpenShellRuntimeConfig, + path: &str, + bytes: &[u8], +) -> Result<(), BoxError> { + let tenant = tenant_for_box(tenant)?; + check_path(path)?; + let size = bytes.len() as u64; + if size > MAX_FILE_BYTES { + return Err(BoxError::FileTooLarge { + size, + limit: MAX_FILE_BYTES, + }); + } + let settings = BoxSettings::from_config(openshell)?; + let target = Target { + registry, + tenant: &tenant, + settings: &settings, + path, + }; + + let part = format!("{path}.part"); + let chunks: Vec<&[u8]> = if bytes.is_empty() { + vec![bytes] + } else { + bytes.chunks(WRITE_CHUNK_BYTES).collect() + }; + for (index, chunk) in chunks.iter().enumerate() { + let command = write_command(path, &part, chunk, index, chunks.len(), size); + let failed = match target.run(&command).await { + Ok(result) if result.exit_code == 0 => continue, + Ok(result) => failed_command("write", path, &result), + Err(error) => error, + }; + // Best effort: the box may be gone, and the transfer failed already. + let _ = target.run(&format!("rm -f -- {}", quote(&part))).await; + return Err(failed); + } + Ok(()) +} + +/// Read the file at `path` from the box of the tenant `tenant` resolves to. +/// +/// `path` is relative to the box's work folder. A file over `max_bytes`, or +/// over [`MAX_FILE_BYTES`], is refused before any of it is transferred. +/// +/// # Errors +/// +/// [`BoxError::NoTenant`] and [`BoxError::InvalidPath`] before any box is +/// touched; [`BoxError::FileNotFound`] when `path` is not a regular file; +/// [`BoxError::FileTooLarge`] over the limit; [`BoxError::ShortRead`] when +/// fewer bytes arrive than the file's size; [`BoxError::FileTransfer`] when a +/// command fails; otherwise the settings and registry errors. +pub async fn read_file_in( + registry: &BoxRegistry, + tenant: Result, + openshell: &OpenShellRuntimeConfig, + path: &str, + max_bytes: u64, +) -> Result, BoxError> { + let tenant = tenant_for_box(tenant)?; + check_path(path)?; + let settings = BoxSettings::from_config(openshell)?; + let target = Target { + registry, + tenant: &tenant, + settings: &settings, + path, + }; + + let quoted = quote(path); + let sized = target + .run(&format!( + "test -f -- {quoted} || exit {NOT_A_FILE_EXIT}; wc -c < {quoted}" + )) + .await?; + if sized.exit_code == NOT_A_FILE_EXIT { + return Err(BoxError::FileNotFound(path.to_owned())); + } + if sized.exit_code != 0 { + return Err(failed_command("read", path, &sized)); + } + let size: u64 = sized + .stdout + .trim() + .parse() + .map_err(|_| BoxError::FileTransfer { + action: "read", + path: path.to_owned(), + detail: "the sandbox did not report the file's size".to_owned(), + })?; + let limit = max_bytes.min(MAX_FILE_BYTES); + if size > limit { + return Err(BoxError::FileTooLarge { size, limit }); + } + + let mut bytes = Vec::with_capacity(usize::try_from(size).unwrap_or(0)); + while (bytes.len() as u64) < size { + let want = (size - bytes.len() as u64).min(READ_CHUNK_BYTES as u64); + let command = format!( + "tail -c +{} -- {quoted} | head -c {want} | base64 -w0", + bytes.len() + 1 + ); + let chunk = target.run(&command).await?; + if chunk.exit_code != 0 { + return Err(failed_command("read", path, &chunk)); + } + let decoded = base64::engine::general_purpose::STANDARD + .decode(chunk.stdout.trim()) + .map_err(|_| BoxError::FileTransfer { + action: "read", + path: path.to_owned(), + detail: "the sandbox returned data that could not be decoded".to_owned(), + })?; + if decoded.len() as u64 != want { + return Err(BoxError::ShortRead { + expected: size, + got: bytes.len() as u64 + decoded.len() as u64, + }); + } + bytes.extend_from_slice(&decoded); + } + Ok(bytes) +} + +/// One transfer's box and path, to run its commands against. +struct Target<'a, D: BoxDriver> { + registry: &'a BoxRegistry, + tenant: &'a Tenant, + settings: &'a BoxSettings, + path: &'a str, +} + +impl Target<'_, D> { + async fn run(&self, command: &str) -> Result { + tracing::debug!( + path_len = self.path.len(), + "[sandbox:openshell] running a file transfer command" + ); + let request = BoxRequest { + command: command.to_owned(), + env: BTreeMap::new(), + timeout: COMMAND_TIMEOUT, + }; + self.registry + .exec(self.tenant, self.settings, &request) + .await + } +} + +/// The command for chunk `index` of `count`. The first starts the part file +/// (and its folders); the rest append; the last checks the part file holds all +/// `size` bytes and renames it into place. +fn write_command( + path: &str, + part: &str, + chunk: &[u8], + index: usize, + count: usize, + size: u64, +) -> String { + let (quoted_path, quoted_part) = (quote(path), quote(part)); + let encoded = base64::engine::general_purpose::STANDARD.encode(chunk); + let mut command = String::new(); + if index == 0 { + command.push_str(&format!( + "if test -d {quoted_path}; then echo 'it is a folder' >&2; exit 1; fi; " + )); + if let Some((folder, _)) = path.rsplit_once('/') { + command.push_str(&format!("mkdir -p -- {} && ", quote(folder))); + } + } + let redirect = if index == 0 { ">" } else { ">>" }; + command.push_str(&format!( + "printf %s '{encoded}' | base64 -d {redirect} {quoted_part}" + )); + if index + 1 == count { + command.push_str(&format!( + " && test \"$(wc -c < {quoted_part})\" -eq {size} && mv -f -- {quoted_part} {quoted_path}" + )); + } + command +} + +/// Refuse a path that is not a file inside the box's work folder. +fn check_path(path: &str) -> Result<(), BoxError> { + let refusal = if path.is_empty() { + "it is empty" + } else if path.contains('\0') { + "it contains a NUL byte" + } else if path.starts_with('/') { + "it must be relative to the sandbox work folder" + } else if path.split('/').any(|part| part == "..") { + "it must not contain `..`" + } else if matches!(path.rsplit('/').next(), Some("" | ".")) { + "it names a folder, not a file" + } else { + return Ok(()); + }; + Err(BoxError::InvalidPath(refusal)) +} + +/// `value` as one single-quoted shell word. +fn quote(value: &str) -> String { + format!("'{}'", value.replace('\'', r"'\''")) +} + +/// A failed command as an error: the box's first message line, else why. +fn failed_command(action: &'static str, path: &str, result: &SandboxExecResult) -> BoxError { + let message = result + .stderr + .lines() + .map(str::trim) + .find(|line| !line.is_empty()) + .map(|line| line.chars().take(DETAIL_MAX_CHARS).collect::()); + let detail = if result.timed_out { + "the sandbox took too long".to_owned() + } else { + message.unwrap_or_else(|| format!("the command exited with status {}", result.exit_code)) + }; + BoxError::FileTransfer { + action, + path: path.to_owned(), + detail, + } +} + +#[cfg(test)] +#[path = "files_tests.rs"] +mod tests; diff --git a/crates/openhuman-core/src/sandbox/openshell/files_tests.rs b/crates/openhuman-core/src/sandbox/openshell/files_tests.rs index 79dfc094665..0fdc548e732 100644 --- a/crates/openhuman-core/src/sandbox/openshell/files_tests.rs +++ b/crates/openhuman-core/src/sandbox/openshell/files_tests.rs @@ -1,7 +1,10 @@ use super::*; use crate::core::runtime::NoTenant; use crate::sandbox::openshell::scripted_driver::{Call, ExecStep, ScriptedDriver}; +use crate::sandbox::openshell::{BoxOutput, RegistryLimits}; use base64::Engine as _; +use std::sync::Arc; +use std::time::Duration; fn embedded(id: &str) -> Tenant { Tenant { @@ -289,7 +292,10 @@ async fn a_chunk_that_is_not_base64_fails_the_read() { let read = read_file_in(&boxes, Ok(embedded("u1")), &config(), "a.bin", 100).await; - assert!(matches!(read, Err(BoxError::FileTransfer { .. })), "{read:?}"); + assert!( + matches!(read, Err(BoxError::FileTransfer { .. })), + "{read:?}" + ); } #[tokio::test] @@ -297,7 +303,11 @@ async fn a_failing_chunk_command_fails_the_read_with_the_boxs_message() { let driver = ScriptedDriver::new(); let boxes = registry(&driver); driver.then(reply(0, "4\n", "")); - driver.then(reply(1, "", "tail: error reading 'a.bin': Input/output error\n")); + driver.then(reply( + 1, + "", + "tail: error reading 'a.bin': Input/output error\n", + )); let read = read_file_in(&boxes, Ok(embedded("u1")), &config(), "a.bin", 100).await; @@ -319,7 +329,10 @@ async fn a_size_the_box_does_not_report_as_a_number_fails_the_read() { let read = read_file_in(&boxes, Ok(embedded("u1")), &config(), "a.bin", 100).await; - assert!(matches!(read, Err(BoxError::FileTransfer { .. })), "{read:?}"); + assert!( + matches!(read, Err(BoxError::FileTransfer { .. })), + "{read:?}" + ); } #[tokio::test] @@ -405,17 +418,33 @@ mod on_a_real_shell { let bytes = binary(READ_CHUNK_BYTES * 2 + WRITE_CHUNK_BYTES + 17); assert!(bytes.contains(&0) && std::str::from_utf8(&bytes).is_err()); - write_file_in(&boxes, Ok(embedded("u1")), &config(), "work/out.bin", &bytes) - .await - .unwrap(); - let back = read_file_in(&boxes, Ok(embedded("u1")), &config(), "work/out.bin", MAX_FILE_BYTES) - .await - .unwrap(); + write_file_in( + &boxes, + Ok(embedded("u1")), + &config(), + "work/out.bin", + &bytes, + ) + .await + .unwrap(); + let back = read_file_in( + &boxes, + Ok(embedded("u1")), + &config(), + "work/out.bin", + MAX_FILE_BYTES, + ) + .await + .unwrap(); assert_eq!(back, bytes); let on_disk = driver.box_dir("box-0").unwrap().join("work/out.bin"); assert_eq!(std::fs::read(on_disk).unwrap(), bytes); - assert!(!driver.box_dir("box-0").unwrap().join("work/out.bin.part").exists()); + assert!(!driver + .box_dir("box-0") + .unwrap() + .join("work/out.bin.part") + .exists()); } #[tokio::test] @@ -491,7 +520,10 @@ mod on_a_real_shell { let wrote = write_file_in(&boxes, Ok(embedded("u1")), &config(), "d", b"y").await; let read = read_file_in(&boxes, Ok(embedded("u1")), &config(), "d", 10).await; - assert!(matches!(wrote, Err(BoxError::FileTransfer { .. })), "{wrote:?}"); + assert!( + matches!(wrote, Err(BoxError::FileTransfer { .. })), + "{wrote:?}" + ); assert_eq!(read, Err(BoxError::FileNotFound("d".into()))); } @@ -517,7 +549,11 @@ mod on_a_real_shell { assert_eq!(theirs, Err(BoxError::FileNotFound("secret.txt".into()))); assert_eq!(mine, Ok(b"mine".to_vec())); assert_eq!(driver.created(), 2); - assert!(driver.box_dir("box-0").unwrap().join("secret.txt").is_file()); + assert!(driver + .box_dir("box-0") + .unwrap() + .join("secret.txt") + .is_file()); assert!(!driver.box_dir("box-1").unwrap().join("secret.txt").exists()); } @@ -532,7 +568,10 @@ mod on_a_real_shell { let wrote = write_file_in(&boxes, Ok(embedded("u1")), &config(), "a.bin", &bytes).await; - assert!(matches!(wrote, Err(BoxError::FileTransfer { .. })), "{wrote:?}"); + assert!( + matches!(wrote, Err(BoxError::FileTransfer { .. })), + "{wrote:?}" + ); assert_eq!(driver.created(), 2); assert!(!driver.box_dir("box-1").unwrap().join("a.bin").exists()); } diff --git a/crates/openhuman-core/src/sandbox/openshell/mod.rs b/crates/openhuman-core/src/sandbox/openshell/mod.rs index f4018327921..5ccb065aa6e 100644 --- a/crates/openhuman-core/src/sandbox/openshell/mod.rs +++ b/crates/openhuman-core/src/sandbox/openshell/mod.rs @@ -35,6 +35,7 @@ use std::time::Duration; #[cfg(feature = "modules")] pub use bus_driver::BusBoxDriver; +pub use files::{read_file_in, write_file_in, MAX_FILE_BYTES}; pub use registry::BoxRegistry; pub use types::{BoxDriver, BoxError, BoxExec, BoxOutput, BoxRequest, BoxSettings, RegistryLimits}; diff --git a/crates/openhuman-core/src/sandbox/openshell/types.rs b/crates/openhuman-core/src/sandbox/openshell/types.rs index 1908a514e9d..c2a88cfee26 100644 --- a/crates/openhuman-core/src/sandbox/openshell/types.rs +++ b/crates/openhuman-core/src/sandbox/openshell/types.rs @@ -134,6 +134,38 @@ pub enum BoxError { /// A variable for the command is not UTF-8. #[error("sandbox environment is not UTF-8")] NonUtf8Env, + /// A file path for the box is not a file inside its work folder. + #[error("the sandbox file path is not allowed: {0}")] + InvalidPath(&'static str), + /// A file is over the transfer limit. + #[error("the file is {size} bytes, over the {limit} byte limit")] + FileTooLarge { + /// The file's size in bytes. + size: u64, + /// The limit it is over. + limit: u64, + }, + /// The box has no regular file at the path. + #[error("there is no file `{0}` in the sandbox")] + FileNotFound(String), + /// Fewer bytes of a file arrived than it holds. + #[error("the sandbox returned {got} of the file's {expected} bytes")] + ShortRead { + /// The file's size in bytes. + expected: u64, + /// The bytes that arrived. + got: u64, + }, + /// A command moving a file failed in the box. + #[error("could not {action} `{path}` in the sandbox: {detail}")] + FileTransfer { + /// `read` or `write`. + action: &'static str, + /// The path, relative to the work folder. + path: String, + /// What the box said, or why the command failed. + detail: String, + }, /// The driver failed for another reason. #[error("the sandbox service failed: {0}")] Driver(String), From 5c5102bc3f4f0db459c8f264abf41eb6c1f084da Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 5 Nov 2026 19:39:13 +0000 Subject: [PATCH 04/37] fix(sandbox): report incomplete writes and drop unsupported test flag The file-size check before renaming a written file now emits a clear error and exits non-zero instead of silently skipping the move, so partial writes surface as failures. The `--` flag was also removed from the `test -f` invocation since the shell used in the sandbox does not accept it. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-core/src/sandbox/openshell/files.rs | 6 ++++-- crates/openhuman-core/src/sandbox/openshell/files_tests.rs | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/crates/openhuman-core/src/sandbox/openshell/files.rs b/crates/openhuman-core/src/sandbox/openshell/files.rs index c67377565b7..a7b2c16ed46 100644 --- a/crates/openhuman-core/src/sandbox/openshell/files.rs +++ b/crates/openhuman-core/src/sandbox/openshell/files.rs @@ -138,7 +138,7 @@ pub async fn read_file_in( let quoted = quote(path); let sized = target .run(&format!( - "test -f -- {quoted} || exit {NOT_A_FILE_EXIT}; wc -c < {quoted}" + "test -f {quoted} || exit {NOT_A_FILE_EXIT}; wc -c < {quoted}" )) .await?; if sized.exit_code == NOT_A_FILE_EXIT { @@ -243,7 +243,9 @@ fn write_command( )); if index + 1 == count { command.push_str(&format!( - " && test \"$(wc -c < {quoted_part})\" -eq {size} && mv -f -- {quoted_part} {quoted_path}" + " && if test \"$(wc -c < {quoted_part})\" -eq {size}; \ + then mv -f -- {quoted_part} {quoted_path}; \ + else echo 'the file was not written in full' >&2; exit 1; fi" )); } command diff --git a/crates/openhuman-core/src/sandbox/openshell/files_tests.rs b/crates/openhuman-core/src/sandbox/openshell/files_tests.rs index 0fdc548e732..591f9d81876 100644 --- a/crates/openhuman-core/src/sandbox/openshell/files_tests.rs +++ b/crates/openhuman-core/src/sandbox/openshell/files_tests.rs @@ -262,7 +262,7 @@ async fn a_missing_file_is_reported_by_name() { let read = read_file_in(&boxes, Ok(embedded("u1")), &config(), "gone.pdf", 100).await; assert_eq!(read, Err(BoxError::FileNotFound("gone.pdf".into()))); - assert!(commands(&driver)[0].starts_with("test -f -- 'gone.pdf' || exit 66")); + assert!(commands(&driver)[0].starts_with("test -f 'gone.pdf' || exit 66")); } #[tokio::test] From f8aec810fdf1a738741530f96e7a3cb3c9c405d4 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 5 Nov 2026 19:43:31 +0000 Subject: [PATCH 05/37] feat(sandbox): expose openshell file read and write helpers Add public read_file and write_file entry points that resolve the tenant and process registry before delegating to the existing in-box helpers, and re-export them from the sandbox module. Builds without module support return a clear driver error instead of failing obscurely. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-core/src/sandbox/mod.rs | 4 + .../src/sandbox/openshell/files_tests.rs | 10 ++- .../src/sandbox/openshell/mod.rs | 74 +++++++++++++++++++ .../src/sandbox/openshell/mod_tests.rs | 12 +++ 4 files changed, 97 insertions(+), 3 deletions(-) diff --git a/crates/openhuman-core/src/sandbox/mod.rs b/crates/openhuman-core/src/sandbox/mod.rs index b282568e2f8..309c1881ffd 100644 --- a/crates/openhuman-core/src/sandbox/mod.rs +++ b/crates/openhuman-core/src/sandbox/mod.rs @@ -28,6 +28,10 @@ pub(crate) mod shell_progress; pub(crate) mod spawn_plan; pub mod types; +pub use openshell::{ + read_file as read_box_file, write_file as write_box_file, BoxError, + MAX_FILE_BYTES as MAX_BOX_FILE_BYTES, +}; pub use ops::{create_sandbox_backend, execute_in_sandbox}; pub use schemas::{ all_controller_schemas as all_sandbox_controller_schemas, diff --git a/crates/openhuman-core/src/sandbox/openshell/files_tests.rs b/crates/openhuman-core/src/sandbox/openshell/files_tests.rs index 591f9d81876..82f214a3fd9 100644 --- a/crates/openhuman-core/src/sandbox/openshell/files_tests.rs +++ b/crates/openhuman-core/src/sandbox/openshell/files_tests.rs @@ -568,9 +568,13 @@ mod on_a_real_shell { let wrote = write_file_in(&boxes, Ok(embedded("u1")), &config(), "a.bin", &bytes).await; - assert!( - matches!(wrote, Err(BoxError::FileTransfer { .. })), - "{wrote:?}" + assert_eq!( + wrote, + Err(BoxError::FileTransfer { + action: "write", + path: "a.bin".into(), + detail: "the file was not written in full".into(), + }) ); assert_eq!(driver.created(), 2); assert!(!driver.box_dir("box-1").unwrap().join("a.bin").exists()); diff --git a/crates/openhuman-core/src/sandbox/openshell/mod.rs b/crates/openhuman-core/src/sandbox/openshell/mod.rs index 5ccb065aa6e..c373e84d718 100644 --- a/crates/openhuman-core/src/sandbox/openshell/mod.rs +++ b/crates/openhuman-core/src/sandbox/openshell/mod.rs @@ -151,6 +151,80 @@ pub(crate) async fn execute( } } +/// Write `bytes` to `path` (relative to the box's work folder) in the box of +/// `tenant`, replacing any file there and creating its folders. The box comes +/// from the process's registry, built from `config` on first use. +/// +/// # Errors +/// +/// Every [`BoxError`] [`write_file_in`] returns, and a refusal when this build +/// has no module support. +pub async fn write_file( + tenant: Result, + config: &Config, + path: &str, + bytes: &[u8], +) -> Result<(), BoxError> { + let tenant = Ok(tenant_for_box(tenant)?); + #[cfg(feature = "modules")] + { + write_file_in( + registry(config), + tenant, + &config.runtime.openshell, + path, + bytes, + ) + .await + } + #[cfg(not(feature = "modules"))] + { + let _ = (tenant, config, path, bytes); + Err(modules_disabled()) + } +} + +/// Read the file at `path` (relative to the box's work folder) from the box of +/// `tenant`. A file over `max_bytes`, or over [`MAX_FILE_BYTES`], is refused +/// before any of it is transferred. The box comes from the process's registry, +/// built from `config` on first use. +/// +/// # Errors +/// +/// Every [`BoxError`] [`read_file_in`] returns, and a refusal when this build +/// has no module support. +pub async fn read_file( + tenant: Result, + config: &Config, + path: &str, + max_bytes: u64, +) -> Result, BoxError> { + let tenant = Ok(tenant_for_box(tenant)?); + #[cfg(feature = "modules")] + { + read_file_in( + registry(config), + tenant, + &config.runtime.openshell, + path, + max_bytes, + ) + .await + } + #[cfg(not(feature = "modules"))] + { + let _ = (tenant, config, path, max_bytes); + Err(modules_disabled()) + } +} + +#[cfg(not(feature = "modules"))] +fn modules_disabled() -> BoxError { + BoxError::Driver( + "TinyBox module support is disabled; OpenShell sandbox files are unavailable".to_owned(), + ) +} + /// Close `tenant`'s box, if the process has one. pub async fn release(tenant: &Tenant) { #[cfg(feature = "modules")] diff --git a/crates/openhuman-core/src/sandbox/openshell/mod_tests.rs b/crates/openhuman-core/src/sandbox/openshell/mod_tests.rs index c5475ca0e7c..ade45b4e8f2 100644 --- a/crates/openhuman-core/src/sandbox/openshell/mod_tests.rs +++ b/crates/openhuman-core/src/sandbox/openshell/mod_tests.rs @@ -201,3 +201,15 @@ async fn release_and_shutdown_before_any_box_exists_are_no_ops() { release(&embedded("u1")).await; shutdown().await; } + +#[cfg(feature = "modules")] +#[tokio::test] +async fn files_are_refused_without_a_tenant() { + let config = Config::default(); + + let wrote = write_file(Err(NoTenant), &config, "a.txt", b"x").await; + let read = read_file(Err(NoTenant), &config, "a.txt", 10).await; + + assert_eq!(wrote, Err(BoxError::NoTenant)); + assert_eq!(read, Err(BoxError::NoTenant)); +} From f02e55ede8400a32e04c4a89c019d2efce0c1e44 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 5 Nov 2026 19:44:22 +0000 Subject: [PATCH 06/37] test(sandbox): cover which backends keep boxes between commands Added tests asserting that only the OpenShell backend keeps a box alive between commands, both at the config level and on the backend kind, and that disabling the sandbox in config overrides it. The config helper is re-exported for tests so these cases can be exercised. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-core/src/sandbox/ops.rs | 4 ++- .../openhuman-core/src/sandbox/ops_tests.rs | 30 +++++++++++++++++++ .../openhuman-core/src/sandbox/types_tests.rs | 13 ++++++++ 3 files changed, 46 insertions(+), 1 deletion(-) diff --git a/crates/openhuman-core/src/sandbox/ops.rs b/crates/openhuman-core/src/sandbox/ops.rs index 98c8ffae0de..1d89cb97553 100644 --- a/crates/openhuman-core/src/sandbox/ops.rs +++ b/crates/openhuman-core/src/sandbox/ops.rs @@ -10,7 +10,9 @@ pub(crate) use exec::{execute_resolved, resolve_sandbox}; #[cfg(any(feature = "modules", test))] pub(crate) use policy::local_status_for_jail; #[cfg(test)] -pub(crate) use policy::{config_disables_sandbox, sandbox_disabled_by_host, sandbox_off_value}; +pub(crate) use policy::{ + config_disables_sandbox, config_keeps_boxes, sandbox_disabled_by_host, sandbox_off_value, +}; pub use policy::{create_sandbox_backend, SANDBOX_ENV_PASSTHROUGH, SANDBOX_OFF_ENV}; pub(crate) use policy::{create_sandbox_backend_with_config, sandbox_component_off}; diff --git a/crates/openhuman-core/src/sandbox/ops_tests.rs b/crates/openhuman-core/src/sandbox/ops_tests.rs index 406c13e80e1..0fe11440d46 100644 --- a/crates/openhuman-core/src/sandbox/ops_tests.rs +++ b/crates/openhuman-core/src/sandbox/ops_tests.rs @@ -456,3 +456,33 @@ fn security_disabled_jails_with_the_policys_own_grants() { assert!(jail.deny_read.is_empty()); assert!(!jail.require_process_isolation); } + +fn config_with_backend(backend: crate::config::SandboxBackend) -> crate::config::Config { + let mut config = crate::config::Config::default(); + config.sandbox.backend = backend; + config +} + +#[test] +fn a_config_naming_the_openshell_backend_keeps_boxes() { + use crate::config::SandboxBackend; + assert!(config_keeps_boxes(&config_with_backend( + SandboxBackend::OpenShell + ))); + for backend in [ + SandboxBackend::Auto, + SandboxBackend::None, + SandboxBackend::Docker, + SandboxBackend::Landlock, + SandboxBackend::Agent37, + ] { + assert!(!config_keeps_boxes(&config_with_backend(backend))); + } +} + +#[test] +fn a_config_that_turns_the_sandbox_off_keeps_no_boxes() { + let mut config = config_with_backend(crate::config::SandboxBackend::OpenShell); + config.sandbox.enabled = Some(false); + assert!(!config_keeps_boxes(&config)); +} diff --git a/crates/openhuman-core/src/sandbox/types_tests.rs b/crates/openhuman-core/src/sandbox/types_tests.rs index 6a4cabf4544..f4b256a28ed 100644 --- a/crates/openhuman-core/src/sandbox/types_tests.rs +++ b/crates/openhuman-core/src/sandbox/types_tests.rs @@ -71,3 +71,16 @@ fn the_openshell_kind_is_named_openshell_on_the_wire() { let back: SandboxBackendKind = serde_json::from_value(serde_json::json!("openshell")).unwrap(); assert_eq!(back, SandboxBackendKind::OpenShell); } + +#[test] +fn only_the_openshell_backend_keeps_a_box_between_commands() { + assert!(SandboxBackendKind::OpenShell.keeps_boxes()); + for backend in [ + SandboxBackendKind::None, + SandboxBackendKind::Local, + SandboxBackendKind::Docker, + SandboxBackendKind::Agent37, + ] { + assert!(!backend.keeps_boxes(), "{backend:?}"); + } +} From 75888e3a4d05c47b6daea8ad4583b3778a7f6ac8 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 5 Nov 2026 19:44:51 +0000 Subject: [PATCH 07/37] test(artifacts): add tests for box source resolution Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/artifacts/box_source_tests.rs | 320 ++++++++++++++++++ 1 file changed, 320 insertions(+) create mode 100644 crates/openhuman-core/src/artifacts/box_source_tests.rs diff --git a/crates/openhuman-core/src/artifacts/box_source_tests.rs b/crates/openhuman-core/src/artifacts/box_source_tests.rs new file mode 100644 index 00000000000..5fd0cb2b461 --- /dev/null +++ b/crates/openhuman-core/src/artifacts/box_source_tests.rs @@ -0,0 +1,320 @@ +use super::*; +use crate::artifacts::tiny_store::{artifacts_service, version_files_dir}; +use crate::artifacts::{read_artifact_bytes, FileRoots}; +use crate::config::OpenShellRuntimeConfig; +use crate::core::runtime::DispatchCtx; +use crate::sandbox::openshell::scripted_driver::{Call, ExecStep, ScriptedDriver}; +use crate::sandbox::openshell::{read_file_in, BoxOutput, BoxRegistry, RegistryLimits}; +use base64::Engine as _; +use serde_json::{json, Value}; +use std::time::Duration; +use tiny_artifacts::Author; + +/// Box files from a registry over a scripted driver, so a test says what the +/// box holds and sees every command sent to it. +struct ScriptedBoxes { + keeps: bool, + registry: Arc>, +} + +#[async_trait] +impl BoxFiles for ScriptedBoxes { + async fn keeps_boxes(&self) -> bool { + self.keeps + } + + async fn read( + &self, + tenant: Result, + path: &str, + max_bytes: u64, + ) -> Result, BoxError> { + read_file_in( + &self.registry, + tenant, + &OpenShellRuntimeConfig::default(), + path, + max_bytes, + ) + .await + } +} + +struct Fixture { + workspace: PathBuf, + files: PathBuf, + action: PathBuf, + driver: Arc, + _root: tempfile::TempDir, +} + +impl Fixture { + fn new() -> Self { + let root = tempfile::tempdir().unwrap(); + let (workspace, files, action) = ( + root.path().join("workspace"), + root.path().join("Files"), + root.path().join("home"), + ); + for dir in [&workspace, &files, &action] { + std::fs::create_dir_all(dir).unwrap(); + } + Self { + workspace, + files, + action, + driver: ScriptedDriver::new(), + _root: root, + } + } + + fn tool(&self, keeps: bool, tenant: Result) -> BoxSourcedCreate { + let ctx = DispatchCtx::process_default(); + let service = artifacts_service( + &self.workspace, + FileRoots::new(&self.files), + Some(&self.action), + None, + &ctx, + ); + let registry = BoxRegistry::new( + Arc::clone(&self.driver), + RegistryLimits { + idle_ttl: Duration::from_secs(900), + max_live: 10, + }, + ); + BoxSourcedCreate::new( + CreateArtifactTool::new(Arc::new(service), Author::agent("agent")), + Arc::new(ScriptedBoxes { keeps, registry }), + tenant, + staging_dir(&self.workspace), + ) + } + + /// The box holds `bytes` at whatever path is asked for. + fn the_box_holds(&self, bytes: &[u8]) { + self.driver.then(ExecStep::Reply(BoxOutput { + exit_code: 0, + stdout: format!("{}\n", bytes.len()).into_bytes(), + stderr: Vec::new(), + })); + self.driver.then(ExecStep::Reply(BoxOutput { + exit_code: 0, + stdout: base64::engine::general_purpose::STANDARD + .encode(bytes) + .into_bytes(), + stderr: Vec::new(), + })); + } + + fn commands(&self) -> Vec { + self.driver + .calls() + .into_iter() + .filter_map(|call| match call { + Call::Exec { exec, .. } => exec.argv.last().cloned(), + _ => None, + }) + .collect() + } + + fn staged_files(&self) -> usize { + let root = staging_dir(&self.workspace); + walk(&root) + } +} + +fn walk(dir: &Path) -> usize { + std::fs::read_dir(dir) + .map(|entries| { + entries + .flatten() + .map(|entry| { + if entry.path().is_dir() { + walk(&entry.path()) + } else { + 1 + } + }) + .sum() + }) + .unwrap_or(0) +} + +fn user(id: &str) -> Result { + Ok(Tenant { + profile: None, + agent: Some(id.into()), + }) +} + +fn file_args(path: &str) -> Value { + json!({"kind": "file", "title": "Report", "path": path}) +} + +async fn created_id(tool: &BoxSourcedCreate, args: Value) -> String { + let result = tool.execute(args).await.unwrap(); + assert!(!result.is_error, "{}", result.output()); + let body: Value = serde_json::from_str(&result.output()).unwrap(); + body["artifact_id"].as_str().unwrap().to_owned() +} + +#[tokio::test] +async fn a_path_is_read_from_the_callers_box_when_the_backend_keeps_boxes() { + let _floor = crate::modules::security::gap::install_path_floor_port( + crate::modules::security::gap::ScriptedPathFloorPort::new([], vec![]), + ); + let fixture = Fixture::new(); + let bytes: Vec = (0..=255u8).cycle().take(5000).collect(); + fixture.the_box_holds(&bytes); + let tool = fixture.tool(true, user("u1")); + + let id = created_id(&tool, file_args("out/report.pdf")).await; + + let stored = read_artifact_bytes(&fixture.workspace, FileRoots::new(&fixture.files), &id) + .await + .unwrap(); + assert_eq!(stored, bytes); + assert!(fixture.commands()[0].contains("'out/report.pdf'")); + assert!(!fixture.action.join("out/report.pdf").exists()); + assert_eq!(fixture.staged_files(), 0, "the host copy is not kept"); +} + +#[tokio::test] +async fn a_path_inside_the_boxs_work_folder_is_read_by_its_relative_name() { + let _floor = crate::modules::security::gap::install_path_floor_port( + crate::modules::security::gap::ScriptedPathFloorPort::new([], vec![]), + ); + let fixture = Fixture::new(); + fixture.the_box_holds(b"pdf"); + let tool = fixture.tool(true, user("u1")); + + created_id(&tool, file_args("/sandbox/out/report.pdf")).await; + + assert!(fixture.commands()[0].contains("'out/report.pdf'")); +} + +#[tokio::test] +async fn a_path_elsewhere_in_the_box_is_refused() { + let fixture = Fixture::new(); + let tool = fixture.tool(true, user("u1")); + + let result = tool.execute(file_args("/etc/passwd")).await.unwrap(); + + assert!(result.is_error); + assert!( + result.output().contains("relative to the sandbox work folder"), + "{}", + result.output() + ); + assert!(fixture.driver.calls().is_empty()); +} + +#[tokio::test] +async fn a_path_is_read_from_the_host_when_the_backend_keeps_no_boxes() { + let _floor = crate::modules::security::gap::install_path_floor_port( + crate::modules::security::gap::ScriptedPathFloorPort::new([], vec![]), + ); + let fixture = Fixture::new(); + std::fs::write(fixture.action.join("report.pdf"), b"host bytes").unwrap(); + let tool = fixture.tool(false, user("u1")); + + let id = created_id(&tool, file_args("report.pdf")).await; + + let stored = read_artifact_bytes(&fixture.workspace, FileRoots::new(&fixture.files), &id) + .await + .unwrap(); + assert_eq!(stored, b"host bytes"); + assert!(fixture.driver.calls().is_empty(), "no box was touched"); +} + +#[tokio::test] +async fn a_file_the_box_does_not_have_is_a_tool_error_naming_it() { + let fixture = Fixture::new(); + fixture.driver.then(ExecStep::Reply(BoxOutput { + exit_code: 66, + stdout: Vec::new(), + stderr: Vec::new(), + })); + let tool = fixture.tool(true, user("u1")); + + let result = tool.execute(file_args("missing.pdf")).await.unwrap(); + + assert!(result.is_error); + assert_eq!( + result.output(), + "there is no file `missing.pdf` in the sandbox" + ); + assert_eq!(fixture.staged_files(), 0); +} + +#[tokio::test] +async fn a_call_with_no_tenant_is_refused_without_touching_a_box_or_the_host() { + let fixture = Fixture::new(); + std::fs::write(fixture.action.join("report.pdf"), b"host bytes").unwrap(); + let tool = fixture.tool(true, Err(NoTenant)); + + let result = tool.execute(file_args("report.pdf")).await.unwrap(); + + assert!(result.is_error); + assert!( + result.output().contains("no tenant scope"), + "{}", + result.output() + ); + assert!(fixture.driver.calls().is_empty()); +} + +#[tokio::test] +async fn a_text_artifact_never_touches_a_box() { + let _floor = crate::modules::security::gap::install_path_floor_port( + crate::modules::security::gap::ScriptedPathFloorPort::new([], vec![]), + ); + let fixture = Fixture::new(); + let tool = fixture.tool(true, user("u1")); + + let id = created_id( + &tool, + json!({"kind": "markdown", "title": "Notes", "body": "# hi", "path": "ignored.md"}), + ) + .await; + + assert!(!id.is_empty()); + assert!(fixture.driver.calls().is_empty()); +} + +#[tokio::test] +async fn the_tool_keeps_the_artifact_tools_name_and_schema() { + let fixture = Fixture::new(); + let tool = fixture.tool(true, user("u1")); + let plain = CreateArtifactTool::new( + Arc::new(artifacts_service( + &fixture.workspace, + FileRoots::new(&fixture.files), + None, + None, + &DispatchCtx::process_default(), + )), + Author::agent("agent"), + ); + + assert_eq!(tool.name(), plain.name()); + assert_eq!(tool.description(), plain.description()); + assert_eq!(tool.parameters_schema(), plain.parameters_schema()); + assert_eq!(tool.permission_level(), plain.permission_level()); +} + +#[test] +fn staged_files_live_under_a_folder_artifacts_may_reference() { + let workspace = Path::new("/state"); + assert!(staging_dir(workspace).starts_with(version_files_dir(workspace))); +} + +#[test] +fn a_box_path_is_the_name_relative_to_the_work_folder() { + assert_eq!(box_path("report.pdf"), "report.pdf"); + assert_eq!(box_path("/sandbox/out/report.pdf"), "out/report.pdf"); + assert_eq!(box_path("/sandboxed/report.pdf"), "/sandboxed/report.pdf"); + assert_eq!(box_path("/sandbox"), "/sandbox"); +} From 50cabb62acf7bc3e572193bb255e795408cfdf74 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 5 Nov 2026 19:48:44 +0000 Subject: [PATCH 08/37] feat(artifacts): source created artifacts from the sandbox box Artifact creation now reads files from the tenant's persistent sandbox box instead of the host, so an agent's output stays inside the box it was produced in. A new sandbox_keeps_boxes policy helper decides when a backend keeps a box per tenant between commands, and the create-artifact tool is wrapped to stage box files through it. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/artifacts/box_source.rs | 223 ++++++++++++++++++ .../src/artifacts/box_source_tests.rs | 4 +- crates/openhuman-core/src/artifacts/mod.rs | 1 + .../src/artifacts/tiny_store.rs | 10 +- .../src/sandbox/openshell/mod.rs | 1 + crates/openhuman-core/src/sandbox/ops.rs | 4 +- .../openhuman-core/src/sandbox/ops/policy.rs | 15 ++ crates/openhuman-core/src/sandbox/policy.rs | 2 +- crates/openhuman-core/src/sandbox/types.rs | 10 + 9 files changed, 266 insertions(+), 4 deletions(-) create mode 100644 crates/openhuman-core/src/artifacts/box_source.rs diff --git a/crates/openhuman-core/src/artifacts/box_source.rs b/crates/openhuman-core/src/artifacts/box_source.rs new file mode 100644 index 00000000000..3a400a7cc1a --- /dev/null +++ b/crates/openhuman-core/src/artifacts/box_source.rs @@ -0,0 +1,223 @@ +//! `create_artifact` for a sandbox that keeps boxes: a file `path` names a file +//! in the calling tenant's box, not on the host. +//! +//! With a backend that keeps one box per tenant (`openshell`; see +//! [`SandboxBackendKind::keeps_boxes`](crate::sandbox::types::SandboxBackendKind::keeps_boxes)), +//! the files an agent makes live in its box, and the host has never seen +//! them. [`BoxSourcedCreate`] wraps the artifact crate's `create_artifact` +//! tool: for an `image` or `file` artifact it reads the file out of the +//! caller's box ([`crate::sandbox::openshell::read_file`]), stages the bytes in +//! a folder artifacts may reference, hands the staged path to the crate's tool +//! unchanged, and removes the staged copy. Everything after that is +//! [`create_artifact`](tiny_artifacts::CreateArtifactTool) as ever: the same +//! checks, the same versioned record, the same card. +//! +//! Every other call (text artifacts, and every call under a backend that keeps +//! no boxes) goes straight to the crate's tool and reads the host disk as it +//! always did. + +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use async_trait::async_trait; +use serde_json::Value; +use tiny_artifacts::{ArtifactKind, CreateArtifactTool}; +use tinytools::{PermissionLevel, Tool, ToolResult}; + +use super::tiny_store::version_files_dir; +use crate::core::runtime::{DispatchCtx, NoTenant, Tenant}; +use crate::sandbox::openshell::BoxError; +use crate::sandbox::MAX_BOX_FILE_BYTES; + +/// Where a call's box files are read from, and whether they are. +#[async_trait] +pub(crate) trait BoxFiles: Send + Sync { + /// Whether this call's sandbox keeps a box per tenant, so a file `path` + /// names a file in it. + async fn keeps_boxes(&self) -> bool; + + /// The file at `path` in `tenant`'s box. + async fn read( + &self, + tenant: Result, + path: &str, + max_bytes: u64, + ) -> Result, BoxError>; +} + +/// The process's own boxes, for the call running under `ctx`. +pub(crate) struct SandboxBoxFiles { + ctx: DispatchCtx, +} + +impl SandboxBoxFiles { + pub(crate) fn new(ctx: DispatchCtx) -> Self { + Self { ctx } + } +} + +#[async_trait] +impl BoxFiles for SandboxBoxFiles { + async fn keeps_boxes(&self) -> bool { + match self.ctx.load_config().await { + Ok(config) => crate::sandbox::ops::sandbox_keeps_boxes(&self.ctx, &config), + // Without a configuration there is no sandbox to ask: read the host. + Err(_) => false, + } + } + + async fn read( + &self, + tenant: Result, + path: &str, + max_bytes: u64, + ) -> Result, BoxError> { + let tenant = crate::sandbox::openshell::tenant_for_box(tenant)?; + let config = + self.ctx.load_config().await.map_err(|error| { + BoxError::Driver(format!("cannot read the configuration: {error}")) + })?; + crate::sandbox::read_box_file(Ok(tenant), &config, path, max_bytes).await + } +} + +/// Where a box file is staged on the host: a folder under the kept copies, +/// which artifacts may always reference. +pub(crate) fn staging_dir(workspace_dir: &Path) -> PathBuf { + version_files_dir(workspace_dir).join(".box-incoming") +} + +/// `path` as a name relative to the box's work folder: an agent in the box +/// knows that folder by its absolute name, so one under it is accepted. +fn box_path(path: &str) -> &str { + let work_folder = crate::sandbox::openshell::BOX_WORKDIR; + path.strip_prefix(work_folder) + .and_then(|rest| rest.strip_prefix('/')) + .filter(|rest| !rest.is_empty()) + .unwrap_or(path) +} + +/// The crate's `create_artifact`, reading a file `path` from the caller's box +/// when the sandbox keeps one. +pub(crate) struct BoxSourcedCreate { + inner: CreateArtifactTool, + boxes: Arc, + tenant: Result, + staging: PathBuf, +} + +impl BoxSourcedCreate { + /// `tenant` is the calling tenant (its box is read); `staging` is the + /// folder (see [`staging_dir`]) a box file is copied into for the crate. + pub(crate) fn new( + inner: CreateArtifactTool, + boxes: Arc, + tenant: Result, + staging: PathBuf, + ) -> Self { + Self { + inner, + boxes, + tenant, + staging, + } + } + + /// The file to read from the box, when this call is one that does: an + /// `image` or `file` artifact, under a sandbox that keeps boxes. (A call + /// the crate would reject is left to it.) + async fn box_file(&self, args: &Value) -> Option { + let kind = ArtifactKind::parse(args.get("kind")?.as_str()?)?; + if !kind.holds_file() { + return None; + } + // The crate takes `body` as the path too, for callers that predate `path`. + let path = ["path", "body"] + .iter() + .filter_map(|key| args.get(key).and_then(Value::as_str)) + .map(str::trim) + .find(|path| !path.is_empty())?; + self.boxes + .keeps_boxes() + .await + .then(|| box_path(path).to_owned()) + } +} + +#[async_trait] +impl Tool for BoxSourcedCreate { + fn name(&self) -> &str { + self.inner.name() + } + + fn description(&self) -> &str { + self.inner.description() + } + + fn parameters_schema(&self) -> Value { + self.inner.parameters_schema() + } + + fn permission_level(&self) -> PermissionLevel { + self.inner.permission_level() + } + + fn is_concurrency_safe(&self, args: &Value) -> bool { + self.inner.is_concurrency_safe(args) + } + + async fn execute(&self, mut args: Value) -> anyhow::Result { + let Some(path) = self.box_file(&args).await else { + return self.inner.execute(args).await; + }; + let bytes = match self + .boxes + .read(self.tenant.clone(), &path, MAX_BOX_FILE_BYTES) + .await + { + Ok(bytes) => bytes, + Err(error) => return Ok(ToolResult::error(error.to_string())), + }; + let staged = match stage(&self.staging, &path, &bytes).await { + Ok(staged) => staged, + Err(error) => { + tracing::warn!(%error, "[artifacts] could not stage a sandbox file"); + return Ok(ToolResult::error( + "the file could not be copied out of the sandbox", + )); + } + }; + args["path"] = Value::String(staged.file.display().to_string()); + let created = self.inner.execute(args).await; + if let Err(error) = tokio::fs::remove_dir_all(&staged.dir).await { + tracing::warn!(%error, "[artifacts] could not remove a staged sandbox file"); + } + created + } +} + +/// A box file copied onto the host for one call. +struct Staged { + dir: PathBuf, + file: PathBuf, +} + +/// Copy `bytes` into a folder of its own under `staging`, keeping the file's +/// name (its extension decides the artifact's media type). +async fn stage(staging: &Path, box_path: &str, bytes: &[u8]) -> std::io::Result { + let name = Path::new(box_path) + .file_name() + .map_or_else(|| "file".into(), ToOwned::to_owned); + let dir = staging.join(uuid::Uuid::new_v4().simple().to_string()); + tokio::fs::create_dir_all(&dir).await?; + let file = dir.join(name); + if let Err(error) = tokio::fs::write(&file, bytes).await { + let _ = tokio::fs::remove_dir_all(&dir).await; + return Err(error); + } + Ok(Staged { dir, file }) +} + +#[cfg(test)] +#[path = "box_source_tests.rs"] +mod tests; diff --git a/crates/openhuman-core/src/artifacts/box_source_tests.rs b/crates/openhuman-core/src/artifacts/box_source_tests.rs index 5fd0cb2b461..3237fe18285 100644 --- a/crates/openhuman-core/src/artifacts/box_source_tests.rs +++ b/crates/openhuman-core/src/artifacts/box_source_tests.rs @@ -204,7 +204,9 @@ async fn a_path_elsewhere_in_the_box_is_refused() { assert!(result.is_error); assert!( - result.output().contains("relative to the sandbox work folder"), + result + .output() + .contains("relative to the sandbox work folder"), "{}", result.output() ); diff --git a/crates/openhuman-core/src/artifacts/mod.rs b/crates/openhuman-core/src/artifacts/mod.rs index a95663bb532..a7026fd1fb7 100644 --- a/crates/openhuman-core/src/artifacts/mod.rs +++ b/crates/openhuman-core/src/artifacts/mod.rs @@ -1,3 +1,4 @@ +mod box_source; pub mod files; pub mod migrate; pub mod ops; diff --git a/crates/openhuman-core/src/artifacts/tiny_store.rs b/crates/openhuman-core/src/artifacts/tiny_store.rs index b9a16c07ccd..bb6905ece3d 100644 --- a/crates/openhuman-core/src/artifacts/tiny_store.rs +++ b/crates/openhuman-core/src/artifacts/tiny_store.rs @@ -640,12 +640,20 @@ pub fn registered_tools( let mut tools: Vec> = Vec::new(); { let (service, author) = (service.clone(), author.clone()); + let staging = super::box_source::staging_dir(workspace_dir); tools.push(Box::new(PerCallTool::new( per_call_context, move |context| { - tiny_artifacts::CreateArtifactTool::new( + let create = tiny_artifacts::CreateArtifactTool::new( service(context.chat.as_ref()), author.clone(), + ); + let tenant = context.dispatch.tenant(); + super::box_source::BoxSourcedCreate::new( + create, + Arc::new(super::box_source::SandboxBoxFiles::new(context.dispatch)), + tenant, + staging.clone(), ) }, ))); diff --git a/crates/openhuman-core/src/sandbox/openshell/mod.rs b/crates/openhuman-core/src/sandbox/openshell/mod.rs index c373e84d718..03f7c4ea471 100644 --- a/crates/openhuman-core/src/sandbox/openshell/mod.rs +++ b/crates/openhuman-core/src/sandbox/openshell/mod.rs @@ -37,6 +37,7 @@ use std::time::Duration; pub use bus_driver::BusBoxDriver; pub use files::{read_file_in, write_file_in, MAX_FILE_BYTES}; pub use registry::BoxRegistry; +pub(crate) use registry::BOX_WORKDIR; pub use types::{BoxDriver, BoxError, BoxExec, BoxOutput, BoxRequest, BoxSettings, RegistryLimits}; use super::types::SandboxExecResult; diff --git a/crates/openhuman-core/src/sandbox/ops.rs b/crates/openhuman-core/src/sandbox/ops.rs index 1d89cb97553..79d2906f212 100644 --- a/crates/openhuman-core/src/sandbox/ops.rs +++ b/crates/openhuman-core/src/sandbox/ops.rs @@ -14,7 +14,9 @@ pub(crate) use policy::{ config_disables_sandbox, config_keeps_boxes, sandbox_disabled_by_host, sandbox_off_value, }; pub use policy::{create_sandbox_backend, SANDBOX_ENV_PASSTHROUGH, SANDBOX_OFF_ENV}; -pub(crate) use policy::{create_sandbox_backend_with_config, sandbox_component_off}; +pub(crate) use policy::{ + create_sandbox_backend_with_config, sandbox_component_off, sandbox_keeps_boxes, +}; #[cfg(test)] #[path = "ops_tests.rs"] diff --git a/crates/openhuman-core/src/sandbox/ops/policy.rs b/crates/openhuman-core/src/sandbox/ops/policy.rs index 4a7e069f147..f3c6adddb50 100644 --- a/crates/openhuman-core/src/sandbox/ops/policy.rs +++ b/crates/openhuman-core/src/sandbox/ops/policy.rs @@ -47,6 +47,21 @@ pub(crate) fn sandbox_component_off(ctx: &DispatchCtx) -> bool { off } +/// Whether a command on this call runs in a box the tenant keeps between +/// commands ([`SandboxBackendKind::keeps_boxes`]), the way the shell would +/// route it: not under SaaS (profiles run in containers), and not when the +/// host or the config turns the sandbox off. +pub(crate) fn sandbox_keeps_boxes(ctx: &DispatchCtx, config: &crate::config::Config) -> bool { + !crate::core::runtime::is_saas() && !sandbox_disabled_by_host(ctx) && config_keeps_boxes(config) +} + +/// [`sandbox_keeps_boxes`] for what the config alone says. +pub(crate) fn config_keeps_boxes(config: &crate::config::Config) -> bool { + !config_disables_sandbox(config) + && crate::sandbox::policy::named_backend(&config.sandbox, &config.runtime, false) + .keeps_boxes() +} + /// The saved config says no isolation: the legacy `enabled = false` flag or /// `[components] sandbox = false`. pub(crate) fn config_disables_sandbox(config: &crate::config::Config) -> bool { diff --git a/crates/openhuman-core/src/sandbox/policy.rs b/crates/openhuman-core/src/sandbox/policy.rs index 4319918f3b3..516cc3c3e67 100644 --- a/crates/openhuman-core/src/sandbox/policy.rs +++ b/crates/openhuman-core/src/sandbox/policy.rs @@ -15,7 +15,7 @@ use tinyagents_definition::SandboxMode; /// The executor `sandbox` and `runtime` name, if any. `remote` marks a channel, cron or /// remote session, which has always asked for a container. -fn named_backend( +pub(crate) fn named_backend( sandbox: &SandboxConfig, runtime: &RuntimeConfig, remote: bool, diff --git a/crates/openhuman-core/src/sandbox/types.rs b/crates/openhuman-core/src/sandbox/types.rs index fbb49e1adec..774422496bd 100644 --- a/crates/openhuman-core/src/sandbox/types.rs +++ b/crates/openhuman-core/src/sandbox/types.rs @@ -23,6 +23,16 @@ pub enum SandboxBackendKind { Agent37, } +impl SandboxBackendKind { + /// Whether the backend keeps a box per tenant between commands, so a file + /// an agent makes stays in that tenant's box and is not on the host. + /// Today only [`Self::OpenShell`] does; a backend that joins them answers + /// `true` here and gets the box-side behavior of every caller that asks. + pub fn keeps_boxes(self) -> bool { + matches!(self, Self::OpenShell) + } +} + /// Per-session sandbox policy resolved from agent definition, session /// origin, and global config. #[derive(Debug, Clone, Serialize, Deserialize)] From fef6ef756e3926c76ff2dd956c22e717b5585927 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 5 Nov 2026 19:54:22 +0000 Subject: [PATCH 09/37] feat(embed): add sandbox module for tenant-scoped file access Expose a new sandbox module that provides read_file and write_file helpers gated on a tenant, along with a BoxError type and a MAX_FILE_BYTES limit. A facade test confirms both operations are refused with NoTenant when no tenant is supplied. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-embed/src/lib.rs | 1 + crates/openhuman-embed/src/sandbox.rs | 28 +++++++++++++++++++++++++ crates/openhuman-embed/tests/facades.rs | 12 +++++++++++ 3 files changed, 41 insertions(+) create mode 100644 crates/openhuman-embed/src/sandbox.rs diff --git a/crates/openhuman-embed/src/lib.rs b/crates/openhuman-embed/src/lib.rs index 8a757f23c27..4a7e7cff8be 100644 --- a/crates/openhuman-embed/src/lib.rs +++ b/crates/openhuman-embed/src/lib.rs @@ -151,6 +151,7 @@ pub mod profiles; /// Explicit ordered fallback and truncation policies. pub mod routing; mod runtime; +pub mod sandbox; pub mod secret_storage; mod security; mod turn; diff --git a/crates/openhuman-embed/src/sandbox.rs b/crates/openhuman-embed/src/sandbox.rs new file mode 100644 index 00000000000..a15823213b6 --- /dev/null +++ b/crates/openhuman-embed/src/sandbox.rs @@ -0,0 +1,28 @@ +//! Files in and out of a tenant's sandbox box, for hosts whose sandbox keeps +//! one box per tenant (`[security.sandbox] backend = "openshell"`). +//! +//! A user's upload lives on the host and is not in the box; a file an agent +//! makes in the box is not on the host. These two calls move bytes across, +//! over plain command execution, so they work with any box driver: +//! +//! - [`write_file`] puts bytes at a path, creating folders and replacing any +//! file there, atomically (a reader never sees half a file); +//! - [`read_file`] reads a file back, refusing one over the caller's limit +//! before any of it moves, and failing rather than returning a short file. +//! +//! Paths are relative to the box's work folder. An absolute path, `..`, a NUL +//! byte or an empty path is refused. Files are limited to +//! [`MAX_FILE_BYTES`]. The box is the one of the `tenant` passed in, so +//! tenants never share files; a call with no tenant is refused with +//! [`BoxError::NoTenant`] before a box is touched. A host tool passes +//! [`current_tenant()`](crate::current_tenant) for the tenant the running +//! turn acts for. +//! +//! The registry that holds the boxes is built from `config` on first use, as +//! it is for a shell command, so `[runtime.openshell]` settings apply from +//! then on. [`load_host_config`](crate::config::load_host_config) loads one. + +pub use openhuman_core::sandbox::{ + read_box_file as read_file, write_box_file as write_file, BoxError, + MAX_BOX_FILE_BYTES as MAX_FILE_BYTES, +}; diff --git a/crates/openhuman-embed/tests/facades.rs b/crates/openhuman-embed/tests/facades.rs index ab69389ac01..21d11e85947 100644 --- a/crates/openhuman-embed/tests/facades.rs +++ b/crates/openhuman-embed/tests/facades.rs @@ -10,6 +10,7 @@ use openhuman_embed::artifacts::{ use openhuman_embed::chat_surface::{ publish_web_channel_event, subscribe_web_channel_events, WebChannelEvent, WebEventContext, }; +use openhuman_embed::sandbox::{read_file, write_file, BoxError, MAX_FILE_BYTES}; use openhuman_embed::identity::{peek_credential_user_identity, UserIdentity}; #[tokio::test] @@ -166,3 +167,14 @@ fn the_bundled_releases_dir_is_set_once() { assert!(set_bundled_releases_dir(first).is_ok()); assert_eq!(set_bundled_releases_dir(second.clone()), Err(second)); } + +#[tokio::test] +async fn sandbox_files_are_refused_without_a_tenant() { + let config = openhuman_embed::RuntimeConfig::default(); + + let wrote = write_file(Err(openhuman_embed::NoTenant), &config, "a.txt", b"x").await; + let read = read_file(Err(openhuman_embed::NoTenant), &config, "a.txt", MAX_FILE_BYTES).await; + + assert_eq!(wrote, Err(BoxError::NoTenant)); + assert_eq!(read, Err(BoxError::NoTenant)); +} From a90d99ed0a631ba0cb69369dee125c240696691d Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 5 Nov 2026 19:54:43 +0000 Subject: [PATCH 10/37] docs(sandbox): document moving files in and out of a box Added a README section and module docs explaining how write_file and read_file transfer bytes between host and box over plain command execution, covering path rules, chunking, size limits, typed errors, and how create_artifact uses this for backends that keep boxes. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-core/src/sandbox/README.md | 32 +++++++++++++++++++ .../src/sandbox/openshell/mod.rs | 4 +++ 2 files changed, 36 insertions(+) diff --git a/crates/openhuman-core/src/sandbox/README.md b/crates/openhuman-core/src/sandbox/README.md index 1fc824d9bf7..a0bbc07c9ed 100644 --- a/crates/openhuman-core/src/sandbox/README.md +++ b/crates/openhuman-core/src/sandbox/README.md @@ -20,6 +20,38 @@ and agent), creates each one once under concurrent first commands, reaps idle boxes and caps live ones; a command with no tenant (`NoTenant`) is refused, never run in a shared box. +## Files in and out of a box + +A box has its own disk: a user's upload on the host is not in it, and a file the +agent makes in it is not on the host. `openshell::write_file` and +`openshell::read_file` (re-exported as `sandbox::write_box_file` / +`read_box_file`, and as `openhuman_embed::sandbox::{write_file, read_file}`) +move bytes across over plain command execution (`BoxDriver::exec`), so any box +driver supports them and no box contract grows. The generic forms +`write_file_in` / `read_file_in` take the registry, for tests and drivers. + +- Paths are relative to the box work folder (`BOX_WORKDIR`, the one place that + names it). Absolute paths, `..`, NUL and empty paths are refused; every path + that reaches the shell is single-quoted. Files over `MAX_FILE_BYTES` (8 MiB) + are refused, and a read also honours the caller's `max_bytes`. +- Write: 48 KiB raw per command (`printf %s '' | base64 -d >> .part`; + a Linux argument is at most 128 KiB). The last command checks the part file's + length and renames it over the target, so a box replaced mid-write fails + instead of keeping a truncated file. A failure removes the part file. +- Read: `test -f` and `wc -c` first, a file over the limit is refused before any + chunk moves, then 256 KiB raw per `tail | head | base64 -w0` (a hosted exec + keeps 512 KB of output per stream). A short read is an error. +- Failures are typed `BoxError`s (`InvalidPath`, `FileTooLarge`, `FileNotFound`, + `ShortRead`, `FileTransfer`) whose messages read as a tool result; none names a + host path. +- Keyed on the whole tenant like a command; no tenant (`NoTenant`) is refused. + +`create_artifact` with a file `path` uses this when the backend keeps boxes +(`SandboxBackendKind::keeps_boxes`, `openshell` today): `artifacts::box_source` +reads the file from the calling tenant's box, stages it under the artifacts +kept-copies folder for the call, and hands it to the artifact service like any +file. Other backends read the host disk as before. + The host keeps the `SANDBOX_ENV_PASSTHROUGH` allowlist, configuration switches, status RPC, and executor lifecycle. The sandbox cannot be disabled for SaaS. Local grants for stdio MCP servers use the same TinySecurity floor and TinyBox diff --git a/crates/openhuman-core/src/sandbox/openshell/mod.rs b/crates/openhuman-core/src/sandbox/openshell/mod.rs index 03f7c4ea471..5595a24510b 100644 --- a/crates/openhuman-core/src/sandbox/openshell/mod.rs +++ b/crates/openhuman-core/src/sandbox/openshell/mod.rs @@ -18,6 +18,10 @@ //! variables the request carries. A box that does not answer shortly after //! the deadline is closed and the command reported as timed out. //! +//! - **Files cross over commands too.** [`write_file`] and [`read_file`] move a +//! file between the host and a tenant's box with plain `exec`s (base64 in +//! chunks), relative to the work folder. +//! //! [`BoxDriver`] is the seam: [`BusBoxDriver`] reaches the TinyBox module //! (behind the `modules` feature); tests use a scripted stand-in. The process //! holds one registry, built from the config of the first command that needs From 84adc721ef5cab94544d4602d5b3328e4e19d10d Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 5 Nov 2026 19:54:56 +0000 Subject: [PATCH 11/37] docs(artifacts): document box-sourced artifact creation Add a README entry for box_source.rs describing how image and file artifacts are read from the calling tenant's box on backends that keep boxes, and reflow the sandbox facade test imports and call for formatting. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-core/src/artifacts/README.md | 1 + crates/openhuman-embed/tests/facades.rs | 10 ++++++++-- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/crates/openhuman-core/src/artifacts/README.md b/crates/openhuman-core/src/artifacts/README.md index 83d53a8a43c..d76a77a1392 100644 --- a/crates/openhuman-core/src/artifacts/README.md +++ b/crates/openhuman-core/src/artifacts/README.md @@ -24,6 +24,7 @@ renders artifact content itself. | [`ops.rs`](./ops.rs) | RPC business logic returning `Outcome`: `ai_list_artifacts`, `ai_get_artifact`, `ai_delete_artifact`, `ai_regenerate`. `DEFAULT_LIMIT = 50`, `MAX_LIMIT = 200`. The regenerate path that re-runs `PresentationTool` is `#[cfg(feature = "documents")]`; without the feature `ai_regenerate` returns an error. | | [`schemas.rs`](./schemas.rs) | `ControllerSchema`s and `handle_*` fns for the four `ai.*` controllers; param helpers `read_required`, `read_optional_u64`, `read_optional_string` (whitespace-only → absent), `type_name`. | | [`tiny_store.rs`](./tiny_store.rs) | OpenHuman's side of the versioned artifacts (`tiny-artifacts`): `versioned_store` (records in the configured storage backend: [`version_documents.rs`](./version_documents.rs); older JSON records are imported once), the acting tenant's scoped blob-backed file store, guarded migration of old path references, `text_extension_of_title` (a `text` artifact keeps the inert extension its title names: csv, ics, vcf, json and the like; anything else stays `txt`), `LegacyUiBridge` (shows the newest version through the legacy row, events and visible files folder), `artifacts_service`, the agent tools, and `save_operator_version` (the preview panel's autosave). | +| [`box_source.rs`](./box_source.rs) | `BoxSourcedCreate`: wraps the crate's `create_artifact`. When the sandbox backend keeps boxes (`SandboxBackendKind::keeps_boxes`, `openshell` today), a file `path` on an `image` / `file` artifact is read from the calling tenant's box (`sandbox::read_box_file`, relative to the box work folder; `/sandbox/...` is accepted), staged for the call under the kept-copies folder, filed, and removed. No tenant, a missing file or an over-limit file is a tool error. Other backends and text artifacts are untouched. | | [`production.rs`](./production.rs) | `Production`: how producer tools (deck, document, generated media) file their output — reserve the file and the card, open the versioned record under the same id, then complete or fail it. | | `*_tests.rs` | Sibling test files for each of the above (`#[path]`). | diff --git a/crates/openhuman-embed/tests/facades.rs b/crates/openhuman-embed/tests/facades.rs index 21d11e85947..dbbe4989cac 100644 --- a/crates/openhuman-embed/tests/facades.rs +++ b/crates/openhuman-embed/tests/facades.rs @@ -10,8 +10,8 @@ use openhuman_embed::artifacts::{ use openhuman_embed::chat_surface::{ publish_web_channel_event, subscribe_web_channel_events, WebChannelEvent, WebEventContext, }; -use openhuman_embed::sandbox::{read_file, write_file, BoxError, MAX_FILE_BYTES}; use openhuman_embed::identity::{peek_credential_user_identity, UserIdentity}; +use openhuman_embed::sandbox::{read_file, write_file, BoxError, MAX_FILE_BYTES}; #[tokio::test] async fn an_artifact_resolves_only_once_ready_and_only_under_its_roots() { @@ -173,7 +173,13 @@ async fn sandbox_files_are_refused_without_a_tenant() { let config = openhuman_embed::RuntimeConfig::default(); let wrote = write_file(Err(openhuman_embed::NoTenant), &config, "a.txt", b"x").await; - let read = read_file(Err(openhuman_embed::NoTenant), &config, "a.txt", MAX_FILE_BYTES).await; + let read = read_file( + Err(openhuman_embed::NoTenant), + &config, + "a.txt", + MAX_FILE_BYTES, + ) + .await; assert_eq!(wrote, Err(BoxError::NoTenant)); assert_eq!(read, Err(BoxError::NoTenant)); From eb13f0235d62f07f846a535ac0f97094c9f6fd09 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 5 Nov 2026 19:58:15 +0000 Subject: [PATCH 12/37] test(openshell): remove unused base64 import from files tests Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-core/src/sandbox/openshell/files_tests.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/openhuman-core/src/sandbox/openshell/files_tests.rs b/crates/openhuman-core/src/sandbox/openshell/files_tests.rs index 82f214a3fd9..481661375f6 100644 --- a/crates/openhuman-core/src/sandbox/openshell/files_tests.rs +++ b/crates/openhuman-core/src/sandbox/openshell/files_tests.rs @@ -2,7 +2,6 @@ use super::*; use crate::core::runtime::NoTenant; use crate::sandbox::openshell::scripted_driver::{Call, ExecStep, ScriptedDriver}; use crate::sandbox::openshell::{BoxOutput, RegistryLimits}; -use base64::Engine as _; use std::sync::Arc; use std::time::Duration; From a32200c3a551ee5a4fa72e617d66ed8868af0121 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 5 Nov 2026 20:25:17 +0000 Subject: [PATCH 13/37] fix(sandbox): harden openshell file transfers against path and race attacks Write and read now resolve paths inside the box and refuse any that escape the work folder, including via symlinks, and prefix paths with `./` so a file named `-` is treated as a file. Writes use a uniquely named, exclusively created part file so existing files and concurrent uploads cannot be clobbered, and reads capture the file's device, inode and mtime and re-check it around every chunk so a file swapped mid-read is an error rather than a mix of versions. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/sandbox/openshell/files.rs | 140 +++++++++++++----- 1 file changed, 101 insertions(+), 39 deletions(-) diff --git a/crates/openhuman-core/src/sandbox/openshell/files.rs b/crates/openhuman-core/src/sandbox/openshell/files.rs index a7b2c16ed46..043a9bf6dac 100644 --- a/crates/openhuman-core/src/sandbox/openshell/files.rs +++ b/crates/openhuman-core/src/sandbox/openshell/files.rs @@ -4,19 +4,29 @@ //! inside the argument of a `sh -c` command, so every box driver supports it //! and no box contract grows. Paths are relative to the box's work folder //! ([`BOX_WORKDIR`](super::registry::BOX_WORKDIR), the directory every command -//! runs in), and every path that reaches the shell is single-quoted. +//! runs in), and every path that reaches the shell is single-quoted and +//! written as `./`, so a file named `-` is a file and not an option or +//! standard input. Every command first resolves the path inside the box and +//! refuses one that leaves the work folder (a symlink pointing out of it +//! included). //! //! - **Write** sends [`WRITE_CHUNK_BYTES`] at a time (a Linux argument is at -//! most 128 KiB; the encoding adds a third), appending to `.part`. -//! The last command checks the part file's length and only then renames it -//! over ``, so a reader never sees half a file, and a box replaced -//! mid-write (it forgets the earlier chunks) fails the length check instead -//! of keeping a truncated file. A failure removes the part file. +//! most 128 KiB; the encoding adds a third), appending to a part file +//! beside `` whose name is unique to the transfer and created +//! exclusively, so neither a file the user already has nor another +//! upload's chunks can be overwritten. The last command checks the part +//! file's length and only then renames it over ``, so a reader never +//! sees half a file, and a box replaced mid-write (it forgets the earlier +//! chunks) fails the length check instead of keeping a truncated file. A +//! failure removes the part file. //! - **Read** checks the file exists and reads its size first, refuses a file //! over the limit before moving any of it, then reads //! [`READ_CHUNK_BYTES`] at a time (a hosted exec keeps at most 512 KB of -//! output per stream) and checks the total. A read that comes back short is -//! an error, never a short file. +//! output per stream) and checks the total. The file's identity (device, +//! inode and modification time) is taken with its size and checked before +//! and after every chunk, so a file replaced mid-read is an error rather +//! than a mix of two versions. A read that comes back short is an error, +//! never a short file. //! //! Both are keyed on the whole tenant like a command is; a call with no tenant //! is refused before a box is touched. @@ -86,7 +96,7 @@ pub async fn write_file_in( path, }; - let part = format!("{path}.part"); + let part = part_path(path); let chunks: Vec<&[u8]> = if bytes.is_empty() { vec![bytes] } else { @@ -100,7 +110,9 @@ pub async fn write_file_in( Err(error) => error, }; // Best effort: the box may be gone, and the transfer failed already. - let _ = target.run(&format!("rm -f -- {}", quote(&part))).await; + let _ = target + .run(&format!("rm -f -- {}", quote(&relative(&part)))) + .await; return Err(failed); } Ok(()) @@ -135,10 +147,11 @@ pub async fn read_file_in( path, }; - let quoted = quote(path); + let quoted = quote(&relative(path)); let sized = target .run(&format!( - "test -f {quoted} || exit {NOT_A_FILE_EXIT}; wc -c < {quoted}" + "test -f {quoted} || exit {NOT_A_FILE_EXIT}; {GUARD} \ + inside \"$(realpath -- {quoted})\"; stat -c '%s %d:%i:%Y' -- {quoted}" )) .await?; if sized.exit_code == NOT_A_FILE_EXIT { @@ -147,15 +160,17 @@ pub async fn read_file_in( if sized.exit_code != 0 { return Err(failed_command("read", path, &sized)); } - let size: u64 = sized - .stdout - .trim() - .parse() - .map_err(|_| BoxError::FileTransfer { - action: "read", - path: path.to_owned(), - detail: "the sandbox did not report the file's size".to_owned(), - })?; + let unreported = || BoxError::FileTransfer { + action: "read", + path: path.to_owned(), + detail: "the sandbox did not report the file's size".to_owned(), + }; + let mut fields = sized.stdout.split_whitespace(); + let size: u64 = fields + .next() + .and_then(|size| size.parse().ok()) + .ok_or_else(unreported)?; + let identity = fields.next().ok_or_else(unreported)?; let limit = max_bytes.min(MAX_FILE_BYTES); if size > limit { return Err(BoxError::FileTooLarge { size, limit }); @@ -164,10 +179,7 @@ pub async fn read_file_in( let mut bytes = Vec::with_capacity(usize::try_from(size).unwrap_or(0)); while (bytes.len() as u64) < size { let want = (size - bytes.len() as u64).min(READ_CHUNK_BYTES as u64); - let command = format!( - "tail -c +{} -- {quoted} | head -c {want} | base64 -w0", - bytes.len() + 1 - ); + let command = read_command("ed, identity, bytes.len() + 1, want); let chunk = target.run(&command).await?; if chunk.exit_code != 0 { return Err(failed_command("read", path, &chunk)); @@ -215,9 +227,16 @@ impl Target<'_, D> { } } -/// The command for chunk `index` of `count`. The first starts the part file -/// (and its folders); the rest append; the last checks the part file holds all -/// `size` bytes and renames it into place. +/// Shell that defines `inside`, which exits the command unless the path it is +/// given (already resolved) is the work folder or under it. +const GUARD: &str = "base=$(realpath .) || exit 1; \ + inside() { case \"$1\" in \"$base\"|\"$base\"/*) ;; \ + *) echo 'it resolves outside the sandbox work folder' >&2; exit 1;; esac; }; "; + +/// The command for chunk `index` of `count`. The first resolves the folder +/// inside the work folder, creates it, and starts the part file exclusively; +/// the rest append; the last checks the part file holds all `size` bytes and +/// renames it into place. fn write_command( path: &str, part: &str, @@ -226,24 +245,36 @@ fn write_command( count: usize, size: u64, ) -> String { - let (quoted_path, quoted_part) = (quote(path), quote(part)); + let (quoted_path, quoted_part) = (quote(&relative(path)), quote(&relative(part))); + let folder = quote(&relative(path.rsplit_once('/').map_or(".", |(folder, _)| folder))); let encoded = base64::engine::general_purpose::STANDARD.encode(chunk); + let last = index + 1 == count; let mut command = String::new(); - if index == 0 { + if index == 0 || last { + command.push_str(GUARD); command.push_str(&format!( "if test -d {quoted_path}; then echo 'it is a folder' >&2; exit 1; fi; " )); - if let Some((folder, _)) = path.rsplit_once('/') { - command.push_str(&format!("mkdir -p -- {} && ", quote(folder))); - } } - let redirect = if index == 0 { ">" } else { ">>" }; - command.push_str(&format!( - "printf %s '{encoded}' | base64 -d {redirect} {quoted_part}" - )); - if index + 1 == count { + if index == 0 { + // Check the deepest folder that exists already, then create the rest + // and check the whole again: nothing is made outside the work folder. + command.push_str(&format!( + "d={folder}; while ! test -e \"$d\" && ! test -L \"$d\"; do d=$(dirname \"$d\"); done; \ + inside \"$(realpath -- \"$d\")\"; mkdir -p -- {folder} || exit 1; \ + inside \"$(realpath -- {folder})\"; \ + ( set -C; printf %s '{encoded}' | base64 -d > {quoted_part} ) || exit 1" + )); + } else { + command.push_str(&format!( + "if test -L {quoted_part}; then echo 'the part file is a link' >&2; exit 1; fi; \ + printf %s '{encoded}' | base64 -d >> {quoted_part}" + )); + } + if last { command.push_str(&format!( - " && if test \"$(wc -c < {quoted_part})\" -eq {size}; \ + "; inside \"$(realpath -- {folder})\"; \ + if test \"$(wc -c < {quoted_part})\" -eq {size}; \ then mv -f -- {quoted_part} {quoted_path}; \ else echo 'the file was not written in full' >&2; exit 1; fi" )); @@ -251,6 +282,37 @@ fn write_command( command } +/// The command that reads `want` bytes of the file `quoted` from byte +/// `start` (1-based), failing if the file is not the one whose `identity` was +/// taken, before or after the read. +fn read_command(quoted: &str, identity: &str, start: usize, want: u64) -> String { + let same = format!( + "[ \"$(stat -c '%d:%i:%Y' -- {quoted})\" = {} ] || \ + {{ echo 'the file changed while it was read' >&2; exit 1; }}; ", + quote(identity) + ); + format!( + "{GUARD}inside \"$(realpath -- {quoted})\"; {same}\ + tail -c +{start} -- {quoted} | head -c {want} | base64 -w0; {same}" + ) +} + +/// A unique part-file path beside `path`: hidden, and named for this transfer +/// so no other file or transfer shares it. +fn part_path(path: &str) -> String { + let token = uuid::Uuid::new_v4().simple(); + match path.rsplit_once('/') { + Some((folder, name)) => format!("{folder}/.{name}.{token}.part"), + None => format!(".{path}.{token}.part"), + } +} + +/// `path` as an explicit relative path, so a name starting with `-` is never +/// read as an option, nor `-` as standard input. +fn relative(path: &str) -> String { + format!("./{path}") +} + /// Refuse a path that is not a file inside the box's work folder. fn check_path(path: &str) -> Result<(), BoxError> { let refusal = if path.is_empty() { From c5e5438b7b64a611013abf8902516b5964c44ff7 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 5 Nov 2026 20:25:31 +0000 Subject: [PATCH 14/37] fix(artifacts): fail closed when the sandbox configuration cannot be read `keeps_boxes` now returns a `Result` instead of silently treating an unreadable configuration as "no boxes", so a failed config load no longer falls back to reading the host's disk. `box_file` propagates that error and the tool surfaces it as an error result rather than executing the inner tool. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/artifacts/box_source.rs | 53 +++++++++++++------ 1 file changed, 37 insertions(+), 16 deletions(-) diff --git a/crates/openhuman-core/src/artifacts/box_source.rs b/crates/openhuman-core/src/artifacts/box_source.rs index 3a400a7cc1a..10455ea7190 100644 --- a/crates/openhuman-core/src/artifacts/box_source.rs +++ b/crates/openhuman-core/src/artifacts/box_source.rs @@ -34,7 +34,12 @@ use crate::sandbox::MAX_BOX_FILE_BYTES; pub(crate) trait BoxFiles: Send + Sync { /// Whether this call's sandbox keeps a box per tenant, so a file `path` /// names a file in it. - async fn keeps_boxes(&self) -> bool; + /// + /// # Errors + /// + /// When the configuration cannot be read: the call's source is then + /// unknown, and it must not fall back to reading the host's disk. + async fn keeps_boxes(&self) -> Result; /// The file at `path` in `tenant`'s box. async fn read( @@ -58,12 +63,12 @@ impl SandboxBoxFiles { #[async_trait] impl BoxFiles for SandboxBoxFiles { - async fn keeps_boxes(&self) -> bool { - match self.ctx.load_config().await { - Ok(config) => crate::sandbox::ops::sandbox_keeps_boxes(&self.ctx, &config), - // Without a configuration there is no sandbox to ask: read the host. - Err(_) => false, - } + async fn keeps_boxes(&self) -> Result { + let config = + self.ctx.load_config().await.map_err(|error| { + BoxError::Driver(format!("cannot read the configuration: {error}")) + })?; + Ok(crate::sandbox::ops::sandbox_keeps_boxes(&self.ctx, &config)) } async fn read( @@ -126,21 +131,35 @@ impl BoxSourcedCreate { /// The file to read from the box, when this call is one that does: an /// `image` or `file` artifact, under a sandbox that keeps boxes. (A call /// the crate would reject is left to it.) - async fn box_file(&self, args: &Value) -> Option { - let kind = ArtifactKind::parse(args.get("kind")?.as_str()?)?; + /// + /// # Errors + /// + /// When it cannot be told whether the sandbox keeps boxes. + async fn box_file(&self, args: &Value) -> Result, BoxError> { + let Some(kind) = args + .get("kind") + .and_then(Value::as_str) + .and_then(ArtifactKind::parse) + else { + return Ok(None); + }; if !kind.holds_file() { - return None; + return Ok(None); } // The crate takes `body` as the path too, for callers that predate `path`. let path = ["path", "body"] .iter() .filter_map(|key| args.get(key).and_then(Value::as_str)) .map(str::trim) - .find(|path| !path.is_empty())?; - self.boxes + .find(|path| !path.is_empty()); + let Some(path) = path else { + return Ok(None); + }; + Ok(self + .boxes .keeps_boxes() - .await - .then(|| box_path(path).to_owned()) + .await? + .then(|| box_path(path).to_owned())) } } @@ -167,8 +186,10 @@ impl Tool for BoxSourcedCreate { } async fn execute(&self, mut args: Value) -> anyhow::Result { - let Some(path) = self.box_file(&args).await else { - return self.inner.execute(args).await; + let path = match self.box_file(&args).await { + Ok(Some(path)) => path, + Ok(None) => return self.inner.execute(args).await, + Err(error) => return Ok(ToolResult::error(error.to_string())), }; let bytes = match self .boxes From 5ef1266f81c28d40eb5b96260fd118bf62741891 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 5 Nov 2026 20:25:43 +0000 Subject: [PATCH 15/37] test(artifacts): cover unreadable box configuration as a tool error The scripted box source now models an unreadable configuration and a new test asserts that it surfaces as a tool error without touching a box or falling back to a host file of the same name. The scripted listing output also gained a timestamp column to match the real format. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/artifacts/box_source_tests.rs | 36 +++++++++++++++++-- 1 file changed, 33 insertions(+), 3 deletions(-) diff --git a/crates/openhuman-core/src/artifacts/box_source_tests.rs b/crates/openhuman-core/src/artifacts/box_source_tests.rs index 3237fe18285..7b84fcc8a2f 100644 --- a/crates/openhuman-core/src/artifacts/box_source_tests.rs +++ b/crates/openhuman-core/src/artifacts/box_source_tests.rs @@ -13,14 +13,16 @@ use tiny_artifacts::Author; /// Box files from a registry over a scripted driver, so a test says what the /// box holds and sees every command sent to it. struct ScriptedBoxes { - keeps: bool, + /// `None`: the configuration cannot be read. + keeps: Option, registry: Arc>, } #[async_trait] impl BoxFiles for ScriptedBoxes { - async fn keeps_boxes(&self) -> bool { + async fn keeps_boxes(&self) -> Result { self.keeps + .ok_or_else(|| BoxError::Driver("cannot read the configuration: unreadable".into())) } async fn read( @@ -69,6 +71,14 @@ impl Fixture { } fn tool(&self, keeps: bool, tenant: Result) -> BoxSourcedCreate { + self.tool_with(Some(keeps), tenant) + } + + fn tool_with( + &self, + keeps: Option, + tenant: Result, + ) -> BoxSourcedCreate { let ctx = DispatchCtx::process_default(); let service = artifacts_service( &self.workspace, @@ -96,7 +106,7 @@ impl Fixture { fn the_box_holds(&self, bytes: &[u8]) { self.driver.then(ExecStep::Reply(BoxOutput { exit_code: 0, - stdout: format!("{}\n", bytes.len()).into_bytes(), + stdout: format!("{} 1:2:3\n", bytes.len()).into_bytes(), stderr: Vec::new(), })); self.driver.then(ExecStep::Reply(BoxOutput { @@ -231,6 +241,26 @@ async fn a_path_is_read_from_the_host_when_the_backend_keeps_no_boxes() { assert!(fixture.driver.calls().is_empty(), "no box was touched"); } +#[tokio::test] +async fn an_unreadable_configuration_is_a_tool_error_and_never_reads_the_host() { + let _floor = crate::modules::security::gap::install_path_floor_port( + crate::modules::security::gap::ScriptedPathFloorPort::new([], vec![]), + ); + let fixture = Fixture::new(); + // A host file of the same name: it must not be imported in the box's place. + std::fs::write(fixture.action.join("report.pdf"), b"host bytes").unwrap(); + let tool = fixture.tool_with(None, user("u1")); + + let result = tool.execute(file_args("report.pdf")).await.unwrap(); + + assert!(result.is_error, "{result:?}"); + assert!( + result.content.contains("cannot read the configuration"), + "{result:?}" + ); + assert!(fixture.driver.calls().is_empty(), "no box was touched"); +} + #[tokio::test] async fn a_file_the_box_does_not_have_is_a_tool_error_naming_it() { let fixture = Fixture::new(); From aaa1ef087d90307b0182be7e6839569222a911f8 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 5 Nov 2026 20:25:49 +0000 Subject: [PATCH 16/37] test(artifacts): assert on tool output text in box source test The unreadable-configuration test now checks the tool's output text instead of the raw result content, and drops the debug formatting from the first assertion. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-core/src/artifacts/box_source_tests.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/openhuman-core/src/artifacts/box_source_tests.rs b/crates/openhuman-core/src/artifacts/box_source_tests.rs index 7b84fcc8a2f..bb6ccab1378 100644 --- a/crates/openhuman-core/src/artifacts/box_source_tests.rs +++ b/crates/openhuman-core/src/artifacts/box_source_tests.rs @@ -253,10 +253,11 @@ async fn an_unreadable_configuration_is_a_tool_error_and_never_reads_the_host() let result = tool.execute(file_args("report.pdf")).await.unwrap(); - assert!(result.is_error, "{result:?}"); + assert!(result.is_error); assert!( - result.content.contains("cannot read the configuration"), - "{result:?}" + result.output().contains("cannot read the configuration"), + "{}", + result.output() ); assert!(fixture.driver.calls().is_empty(), "no box was touched"); } From 51cf68d68b4c1ca4338e6e03afcdadd0bd97ab6c Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 5 Nov 2026 20:26:23 +0000 Subject: [PATCH 17/37] test(openshell): update file transfer tests for relative paths and stat format The tests now expect commands to use `./`-prefixed paths and part files with a leading dot, and the stat replies include extra fields. A helper extracts the part file name so assertions track the actual generated path rather than a hardcoded one. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/sandbox/openshell/files_tests.rs | 164 ++++++++++++++++-- 1 file changed, 147 insertions(+), 17 deletions(-) diff --git a/crates/openhuman-core/src/sandbox/openshell/files_tests.rs b/crates/openhuman-core/src/sandbox/openshell/files_tests.rs index 481661375f6..6dc24004edb 100644 --- a/crates/openhuman-core/src/sandbox/openshell/files_tests.rs +++ b/crates/openhuman-core/src/sandbox/openshell/files_tests.rs @@ -43,6 +43,13 @@ fn encoded(bytes: &[u8]) -> String { base64::engine::general_purpose::STANDARD.encode(bytes) } +/// The part file a write's first command names: the quoted `./...part` word. +fn part_in(command: &str) -> String { + let end = command.find(".part'").expect("a part file") + ".part".len(); + let start = command[..end].rfind("'./").expect("a quoted path") + 1; + command[start..end].to_owned() +} + /// The shell command of every exec the driver saw, in order. fn commands(driver: &ScriptedDriver) -> Vec { driver @@ -129,15 +136,16 @@ async fn a_small_file_is_one_command_that_writes_a_part_file_and_renames_it() { let sent = commands(&driver); assert_eq!(sent.len(), 1, "{sent:?}"); - assert!(sent[0].contains("mkdir -p -- 'out'"), "{}", sent[0]); + assert!(sent[0].contains("mkdir -p -- './out'"), "{}", sent[0]); assert!( sent[0].contains(&format!("printf %s '{}' | base64 -d", encoded(b"hi"))), "{}", sent[0] ); - assert!(sent[0].contains("'out/a.txt.part'"), "{}", sent[0]); + let part = part_in(&sent[0]); + assert!(part.starts_with("./out/.a.txt.") && part.ends_with(".part"), "{part}"); assert!( - sent[0].contains("mv -f -- 'out/a.txt.part' 'out/a.txt'"), + sent[0].contains(&format!("mv -f -- '{part}' './out/a.txt'")), "{}", sent[0] ); @@ -157,8 +165,9 @@ async fn a_large_file_is_sent_in_chunks_that_fit_one_argument() { assert_eq!(sent.len(), 3); assert!(sent.iter().all(|command| command.len() < 128 * 1024)); // The first chunk starts the part file; the rest append; only the last renames. - assert!(sent[0].contains("base64 -d > 'a.bin.part'"), "{}", sent[0]); - assert!(sent[1].contains("base64 -d >> 'a.bin.part'")); + let part = part_in(&sent[0]); + assert!(sent[0].contains(&format!("base64 -d > '{part}'")), "{}", sent[0]); + assert!(sent[1].contains(&format!("base64 -d >> '{part}'"))); assert!(!sent[0].contains("mv -f") && !sent[1].contains("mv -f")); assert!(sent[2].contains("mv -f")); } @@ -183,7 +192,7 @@ async fn a_failed_chunk_removes_the_part_file_and_reports_what_the_box_said() { ); let sent = commands(&driver); assert_eq!(sent.len(), 3, "{sent:?}"); - assert_eq!(sent[2], "rm -f -- 'a.bin.part'"); + assert_eq!(sent[2], format!("rm -f -- '{}'", part_in(&sent[0]))); } #[test] @@ -219,7 +228,7 @@ fn a_failed_transfer_reads_well_as_a_tool_result() { async fn a_file_over_the_callers_limit_is_refused_before_any_chunk_is_read() { let driver = ScriptedDriver::new(); let boxes = registry(&driver); - driver.then(reply(0, "1000\n", "")); + driver.then(reply(0, "1000 1:2:3\n", "")); let read = read_file_in(&boxes, Ok(embedded("u1")), &config(), "a.bin", 999).await; @@ -238,7 +247,7 @@ async fn a_file_over_the_callers_limit_is_refused_before_any_chunk_is_read() { async fn the_host_limit_caps_a_callers_larger_limit() { let driver = ScriptedDriver::new(); let boxes = registry(&driver); - driver.then(reply(0, &format!("{}\n", MAX_FILE_BYTES + 1), "")); + driver.then(reply(0, &format!("{} 1:2:3\n", MAX_FILE_BYTES + 1), "")); let read = read_file_in(&boxes, Ok(embedded("u1")), &config(), "a.bin", u64::MAX).await; @@ -261,14 +270,14 @@ async fn a_missing_file_is_reported_by_name() { let read = read_file_in(&boxes, Ok(embedded("u1")), &config(), "gone.pdf", 100).await; assert_eq!(read, Err(BoxError::FileNotFound("gone.pdf".into()))); - assert!(commands(&driver)[0].starts_with("test -f 'gone.pdf' || exit 66")); + assert!(commands(&driver)[0].starts_with("test -f './gone.pdf' || exit 66")); } #[tokio::test] async fn a_short_chunk_fails_the_read_instead_of_returning_a_short_file() { let driver = ScriptedDriver::new(); let boxes = registry(&driver); - driver.then(reply(0, "10\n", "")); + driver.then(reply(0, "10 1:2:3\n", "")); driver.then(reply(0, &encoded(b"1234"), "")); let read = read_file_in(&boxes, Ok(embedded("u1")), &config(), "a.bin", 100).await; @@ -286,7 +295,7 @@ async fn a_short_chunk_fails_the_read_instead_of_returning_a_short_file() { async fn a_chunk_that_is_not_base64_fails_the_read() { let driver = ScriptedDriver::new(); let boxes = registry(&driver); - driver.then(reply(0, "4\n", "")); + driver.then(reply(0, "4 1:2:3\n", "")); driver.then(reply(0, "!!!!", "")); let read = read_file_in(&boxes, Ok(embedded("u1")), &config(), "a.bin", 100).await; @@ -301,7 +310,7 @@ async fn a_chunk_that_is_not_base64_fails_the_read() { async fn a_failing_chunk_command_fails_the_read_with_the_boxs_message() { let driver = ScriptedDriver::new(); let boxes = registry(&driver); - driver.then(reply(0, "4\n", "")); + driver.then(reply(0, "4 1:2:3\n", "")); driver.then(reply( 1, "", @@ -338,7 +347,7 @@ async fn a_size_the_box_does_not_report_as_a_number_fails_the_read() { async fn an_empty_file_reads_as_no_bytes_without_a_chunk() { let driver = ScriptedDriver::new(); let boxes = registry(&driver); - driver.then(reply(0, "0\n", "")); + driver.then(reply(0, "0 1:2:3\n", "")); let read = read_file_in(&boxes, Ok(embedded("u1")), &config(), "a.bin", 100).await; @@ -439,11 +448,11 @@ mod on_a_real_shell { assert_eq!(back, bytes); let on_disk = driver.box_dir("box-0").unwrap().join("work/out.bin"); assert_eq!(std::fs::read(on_disk).unwrap(), bytes); - assert!(!driver - .box_dir("box-0") + let left: Vec<_> = std::fs::read_dir(driver.box_dir("box-0").unwrap().join("work")) .unwrap() - .join("work/out.bin.part") - .exists()); + .map(|entry| entry.unwrap().file_name()) + .collect(); + assert_eq!(left, ["out.bin"], "no part file is left behind"); } #[tokio::test] @@ -578,4 +587,125 @@ mod on_a_real_shell { assert_eq!(driver.created(), 2); assert!(!driver.box_dir("box-1").unwrap().join("a.bin").exists()); } + + #[tokio::test] + async fn a_file_named_dash_is_a_file_and_not_standard_input() { + let (_root, _driver, boxes) = host_boxes(); + + write_file_in(&boxes, Ok(embedded("u1")), &config(), "-", b"dash") + .await + .unwrap(); + let back = read_file_in(&boxes, Ok(embedded("u1")), &config(), "-", 10).await; + + assert_eq!(back, Ok(b"dash".to_vec())); + } + + #[tokio::test] + async fn each_write_stages_in_a_part_file_of_its_own() { + let (_root, _driver, boxes) = host_boxes(); + let driver = ScriptedDriver::new(); + let recorded = registry(&driver); + for _ in 0..2 { + write_file_in(&recorded, Ok(embedded("u1")), &config(), "a.txt", b"x") + .await + .unwrap(); + } + let sent = commands(&driver); + assert_ne!(part_in(&sent[0]), part_in(&sent[1])); + drop(boxes); + } + + #[tokio::test] + async fn a_file_that_is_named_like_the_old_part_file_is_left_alone() { + let (_root, driver, boxes) = host_boxes(); + write_file_in(&boxes, Ok(embedded("u1")), &config(), "a.txt.part", b"mine") + .await + .unwrap(); + + write_file_in(&boxes, Ok(embedded("u1")), &config(), "a.txt", b"new") + .await + .unwrap(); + + let dir = driver.box_dir("box-0").unwrap(); + assert_eq!(std::fs::read(dir.join("a.txt.part")).unwrap(), b"mine"); + assert_eq!(std::fs::read(dir.join("a.txt")).unwrap(), b"new"); + } + + #[tokio::test] + async fn interleaved_uploads_of_one_path_never_publish_a_mix() { + let (_root, _driver, boxes) = host_boxes(); + let a = binary(WRITE_CHUNK_BYTES * 3); + let b: Vec = a.iter().map(|byte| byte.wrapping_add(1)).collect(); + + let (first, second) = tokio::join!( + write_file_in(&boxes, Ok(embedded("u1")), &config(), "a.bin", &a), + write_file_in(&boxes, Ok(embedded("u1")), &config(), "a.bin", &b), + ); + first.unwrap(); + second.unwrap(); + let back = read_file_in(&boxes, Ok(embedded("u1")), &config(), "a.bin", MAX_FILE_BYTES) + .await + .unwrap(); + + assert!(back == a || back == b, "the file is one upload or the other"); + } + + #[tokio::test] + async fn a_link_out_of_the_work_folder_is_not_followed_to_read_or_write() { + let (root, driver, boxes) = host_boxes(); + write_file_in(&boxes, Ok(embedded("u1")), &config(), "seed", b"x") + .await + .unwrap(); + let outside = root.path().join("outside"); + std::fs::create_dir_all(&outside).unwrap(); + std::fs::write(outside.join("passwd"), b"secret").unwrap(); + let dir = driver.box_dir("box-0").unwrap(); + std::os::unix::fs::symlink(&outside, dir.join("out")).unwrap(); + + let read = read_file_in(&boxes, Ok(embedded("u1")), &config(), "out/passwd", 100).await; + let wrote = + write_file_in(&boxes, Ok(embedded("u1")), &config(), "out/new.txt", b"x").await; + let nested = + write_file_in(&boxes, Ok(embedded("u1")), &config(), "out/deeper/new.txt", b"x").await; + + for result in [read.map(|_| ()), wrote, nested] { + let Err(BoxError::FileTransfer { detail, .. }) = result else { + panic!("expected a refusal, got {result:?}"); + }; + assert!(detail.contains("outside the sandbox work folder"), "{detail}"); + } + assert!(!outside.join("new.txt").exists()); + assert!(!outside.join("deeper").exists()); + } + + #[test] + fn a_file_replaced_between_chunks_fails_the_read() { + let dir = tempfile::tempdir().unwrap(); + std::fs::write(dir.path().join("a.bin"), b"abcd").unwrap(); + let identity = run_in(dir.path(), "stat -c '%d:%i:%Y' -- ./a.bin").0; + let command = read_command("'./a.bin'", identity.trim(), 1, 4); + assert_eq!(run_in(dir.path(), &command).0.trim(), encoded(b"abcd")); + + // Same length, new file: every size check would pass. + std::fs::write(dir.path().join("new"), b"wxyz").unwrap(); + std::fs::rename(dir.path().join("new"), dir.path().join("a.bin")).unwrap(); + let (_, stderr, code) = run_in(dir.path(), &command); + + assert_eq!(code, 1); + assert!(stderr.contains("changed while it was read"), "{stderr}"); + } + + /// Run `command` under `sh -c` in `dir`: its stdout, stderr and exit code. + fn run_in(dir: &std::path::Path, command: &str) -> (String, String, i32) { + let output = std::process::Command::new("sh") + .args(["-c", command]) + .current_dir(dir) + .output() + .unwrap(); + ( + String::from_utf8_lossy(&output.stdout).into_owned(), + String::from_utf8_lossy(&output.stderr).into_owned(), + output.status.code().unwrap_or(-1), + ) + } } From a5f9168d371c349096c4681c4849116095658910 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 5 Nov 2026 20:26:28 +0000 Subject: [PATCH 18/37] test(openshell): remove unused host boxes setup from staging test The test for per-write part files no longer creates a host boxes fixture it never used, so the setup and its matching drop were removed to keep the test focused on the scripted driver. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-core/src/sandbox/openshell/files_tests.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/crates/openhuman-core/src/sandbox/openshell/files_tests.rs b/crates/openhuman-core/src/sandbox/openshell/files_tests.rs index 6dc24004edb..2216ce1315d 100644 --- a/crates/openhuman-core/src/sandbox/openshell/files_tests.rs +++ b/crates/openhuman-core/src/sandbox/openshell/files_tests.rs @@ -602,7 +602,6 @@ mod on_a_real_shell { #[tokio::test] async fn each_write_stages_in_a_part_file_of_its_own() { - let (_root, _driver, boxes) = host_boxes(); let driver = ScriptedDriver::new(); let recorded = registry(&driver); for _ in 0..2 { @@ -612,7 +611,6 @@ mod on_a_real_shell { } let sent = commands(&driver); assert_ne!(part_in(&sent[0]), part_in(&sent[1])); - drop(boxes); } #[tokio::test] From d94161a8d59c3f4b046b1630a88c3a9168a94eff Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 5 Nov 2026 20:27:42 +0000 Subject: [PATCH 19/37] style: reformat openshell file transfer code and tests Reformatted the write command path handling and the file transfer tests to satisfy rustfmt line width limits. No behaviour changed. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/artifacts/box_source_tests.rs | 6 +-- .../src/sandbox/openshell/files.rs | 4 +- .../src/sandbox/openshell/files_tests.rs | 46 ++++++++++++++----- 3 files changed, 39 insertions(+), 17 deletions(-) diff --git a/crates/openhuman-core/src/artifacts/box_source_tests.rs b/crates/openhuman-core/src/artifacts/box_source_tests.rs index bb6ccab1378..20a339709a4 100644 --- a/crates/openhuman-core/src/artifacts/box_source_tests.rs +++ b/crates/openhuman-core/src/artifacts/box_source_tests.rs @@ -74,11 +74,7 @@ impl Fixture { self.tool_with(Some(keeps), tenant) } - fn tool_with( - &self, - keeps: Option, - tenant: Result, - ) -> BoxSourcedCreate { + fn tool_with(&self, keeps: Option, tenant: Result) -> BoxSourcedCreate { let ctx = DispatchCtx::process_default(); let service = artifacts_service( &self.workspace, diff --git a/crates/openhuman-core/src/sandbox/openshell/files.rs b/crates/openhuman-core/src/sandbox/openshell/files.rs index 043a9bf6dac..d9b0bff50d9 100644 --- a/crates/openhuman-core/src/sandbox/openshell/files.rs +++ b/crates/openhuman-core/src/sandbox/openshell/files.rs @@ -246,7 +246,9 @@ fn write_command( size: u64, ) -> String { let (quoted_path, quoted_part) = (quote(&relative(path)), quote(&relative(part))); - let folder = quote(&relative(path.rsplit_once('/').map_or(".", |(folder, _)| folder))); + let folder = quote(&relative( + path.rsplit_once('/').map_or(".", |(folder, _)| folder), + )); let encoded = base64::engine::general_purpose::STANDARD.encode(chunk); let last = index + 1 == count; let mut command = String::new(); diff --git a/crates/openhuman-core/src/sandbox/openshell/files_tests.rs b/crates/openhuman-core/src/sandbox/openshell/files_tests.rs index 2216ce1315d..39b272ae6e7 100644 --- a/crates/openhuman-core/src/sandbox/openshell/files_tests.rs +++ b/crates/openhuman-core/src/sandbox/openshell/files_tests.rs @@ -143,7 +143,10 @@ async fn a_small_file_is_one_command_that_writes_a_part_file_and_renames_it() { sent[0] ); let part = part_in(&sent[0]); - assert!(part.starts_with("./out/.a.txt.") && part.ends_with(".part"), "{part}"); + assert!( + part.starts_with("./out/.a.txt.") && part.ends_with(".part"), + "{part}" + ); assert!( sent[0].contains(&format!("mv -f -- '{part}' './out/a.txt'")), "{}", @@ -166,7 +169,11 @@ async fn a_large_file_is_sent_in_chunks_that_fit_one_argument() { assert!(sent.iter().all(|command| command.len() < 128 * 1024)); // The first chunk starts the part file; the rest append; only the last renames. let part = part_in(&sent[0]); - assert!(sent[0].contains(&format!("base64 -d > '{part}'")), "{}", sent[0]); + assert!( + sent[0].contains(&format!("base64 -d > '{part}'")), + "{}", + sent[0] + ); assert!(sent[1].contains(&format!("base64 -d >> '{part}'"))); assert!(!sent[0].contains("mv -f") && !sent[1].contains("mv -f")); assert!(sent[2].contains("mv -f")); @@ -641,11 +648,20 @@ mod on_a_real_shell { ); first.unwrap(); second.unwrap(); - let back = read_file_in(&boxes, Ok(embedded("u1")), &config(), "a.bin", MAX_FILE_BYTES) - .await - .unwrap(); + let back = read_file_in( + &boxes, + Ok(embedded("u1")), + &config(), + "a.bin", + MAX_FILE_BYTES, + ) + .await + .unwrap(); - assert!(back == a || back == b, "the file is one upload or the other"); + assert!( + back == a || back == b, + "the file is one upload or the other" + ); } #[tokio::test] @@ -661,16 +677,24 @@ mod on_a_real_shell { std::os::unix::fs::symlink(&outside, dir.join("out")).unwrap(); let read = read_file_in(&boxes, Ok(embedded("u1")), &config(), "out/passwd", 100).await; - let wrote = - write_file_in(&boxes, Ok(embedded("u1")), &config(), "out/new.txt", b"x").await; - let nested = - write_file_in(&boxes, Ok(embedded("u1")), &config(), "out/deeper/new.txt", b"x").await; + let wrote = write_file_in(&boxes, Ok(embedded("u1")), &config(), "out/new.txt", b"x").await; + let nested = write_file_in( + &boxes, + Ok(embedded("u1")), + &config(), + "out/deeper/new.txt", + b"x", + ) + .await; for result in [read.map(|_| ()), wrote, nested] { let Err(BoxError::FileTransfer { detail, .. }) = result else { panic!("expected a refusal, got {result:?}"); }; - assert!(detail.contains("outside the sandbox work folder"), "{detail}"); + assert!( + detail.contains("outside the sandbox work folder"), + "{detail}" + ); } assert!(!outside.join("new.txt").exists()); assert!(!outside.join("deeper").exists()); From 895dc09e973413cab7a8840f52f88e86c6c08285 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 5 Nov 2026 20:30:01 +0000 Subject: [PATCH 20/37] test(openshell): reuse a single config in the concurrent write test Hoist the config into a local so both concurrent write_file_in calls share one instance instead of building it twice. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-core/src/sandbox/openshell/files_tests.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/openhuman-core/src/sandbox/openshell/files_tests.rs b/crates/openhuman-core/src/sandbox/openshell/files_tests.rs index 39b272ae6e7..8fff7f51344 100644 --- a/crates/openhuman-core/src/sandbox/openshell/files_tests.rs +++ b/crates/openhuman-core/src/sandbox/openshell/files_tests.rs @@ -642,9 +642,10 @@ mod on_a_real_shell { let a = binary(WRITE_CHUNK_BYTES * 3); let b: Vec = a.iter().map(|byte| byte.wrapping_add(1)).collect(); + let cfg = config(); let (first, second) = tokio::join!( - write_file_in(&boxes, Ok(embedded("u1")), &config(), "a.bin", &a), - write_file_in(&boxes, Ok(embedded("u1")), &config(), "a.bin", &b), + write_file_in(&boxes, Ok(embedded("u1")), &cfg, "a.bin", &a), + write_file_in(&boxes, Ok(embedded("u1")), &cfg, "a.bin", &b), ); first.unwrap(); second.unwrap(); From f5e29eaa9353e50a0123136ccec835cf80d7d707 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 5 Nov 2026 20:33:09 +0000 Subject: [PATCH 21/37] test(artifacts): expect relative paths prefixed with ./ in box commands Updated the box source tests to assert that paths passed to box commands are prefixed with ./ so they are unambiguously relative, matching the new command construction. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-core/src/artifacts/box_source_tests.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/openhuman-core/src/artifacts/box_source_tests.rs b/crates/openhuman-core/src/artifacts/box_source_tests.rs index 20a339709a4..b473fb17df8 100644 --- a/crates/openhuman-core/src/artifacts/box_source_tests.rs +++ b/crates/openhuman-core/src/artifacts/box_source_tests.rs @@ -182,7 +182,7 @@ async fn a_path_is_read_from_the_callers_box_when_the_backend_keeps_boxes() { .await .unwrap(); assert_eq!(stored, bytes); - assert!(fixture.commands()[0].contains("'out/report.pdf'")); + assert!(fixture.commands()[0].contains("'./out/report.pdf'")); assert!(!fixture.action.join("out/report.pdf").exists()); assert_eq!(fixture.staged_files(), 0, "the host copy is not kept"); } @@ -198,7 +198,7 @@ async fn a_path_inside_the_boxs_work_folder_is_read_by_its_relative_name() { created_id(&tool, file_args("/sandbox/out/report.pdf")).await; - assert!(fixture.commands()[0].contains("'out/report.pdf'")); + assert!(fixture.commands()[0].contains("'./out/report.pdf'")); } #[tokio::test] From 7c49b9b79b393386d5178a0bc5394db04c0fb98e Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 5 Nov 2026 20:33:26 +0000 Subject: [PATCH 22/37] fix(sandbox): isolate box file transfers and fail closed on unreadable config Write through an exclusive per-transfer part file, keep every box path inside the work folder after symlink resolution, detect a file replaced between read chunks, read names like '-' as files, and make an unreadable configuration a tool error rather than a host-disk read. Co-authored-by: Medulla --- crates/openhuman-core/src/sandbox/README.md | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/crates/openhuman-core/src/sandbox/README.md b/crates/openhuman-core/src/sandbox/README.md index a0bbc07c9ed..400c9f323a2 100644 --- a/crates/openhuman-core/src/sandbox/README.md +++ b/crates/openhuman-core/src/sandbox/README.md @@ -32,15 +32,20 @@ driver supports them and no box contract grows. The generic forms - Paths are relative to the box work folder (`BOX_WORKDIR`, the one place that names it). Absolute paths, `..`, NUL and empty paths are refused; every path - that reaches the shell is single-quoted. Files over `MAX_FILE_BYTES` (8 MiB) + that reaches the shell is single-quoted and written `./`. Every command + resolves the path inside the box and refuses one that leaves the work folder + (a symlink out of it included). Files over `MAX_FILE_BYTES` (8 MiB) are refused, and a read also honours the caller's `max_bytes`. -- Write: 48 KiB raw per command (`printf %s '' | base64 -d >> .part`; - a Linux argument is at most 128 KiB). The last command checks the part file's +- Write: 48 KiB raw per command (`printf %s '' | base64 -d >> `; + a Linux argument is at most 128 KiB). The part file is beside the target, named + uniquely per transfer and created exclusively, so an existing file or a + concurrent upload is never overwritten. The last command checks the part file's length and renames it over the target, so a box replaced mid-write fails instead of keeping a truncated file. A failure removes the part file. -- Read: `test -f` and `wc -c` first, a file over the limit is refused before any +- Read: `test -f` and `stat` (size and identity) first, a file over the limit is refused before any chunk moves, then 256 KiB raw per `tail | head | base64 -w0` (a hosted exec - keeps 512 KB of output per stream). A short read is an error. + keeps 512 KB of output per stream). The identity is checked before and after + every chunk, so a file replaced mid-read fails. A short read is an error. - Failures are typed `BoxError`s (`InvalidPath`, `FileTooLarge`, `FileNotFound`, `ShortRead`, `FileTransfer`) whose messages read as a tool result; none names a host path. From 4957c02d81af3dfa3d8d291337ddc4a1ed530ef6 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 5 Nov 2026 20:46:40 +0000 Subject: [PATCH 23/37] fix(sandbox): stage part files under a fixed short name Part files are now named with a fixed `.openhuman-.tmp` prefix instead of embedding the target filename, so transfers to targets near the 255-byte filesystem name limit can still stage. The test helper was updated to match the new suffix. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-core/src/sandbox/openshell/files.rs | 9 +++++---- .../openhuman-core/src/sandbox/openshell/files_tests.rs | 2 +- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/crates/openhuman-core/src/sandbox/openshell/files.rs b/crates/openhuman-core/src/sandbox/openshell/files.rs index d9b0bff50d9..88a7b3c95fa 100644 --- a/crates/openhuman-core/src/sandbox/openshell/files.rs +++ b/crates/openhuman-core/src/sandbox/openshell/files.rs @@ -300,12 +300,13 @@ fn read_command(quoted: &str, identity: &str, start: usize, want: u64) -> String } /// A unique part-file path beside `path`: hidden, and named for this transfer -/// so no other file or transfer shares it. +/// alone (not for the target, so a target name near the filesystem's 255-byte +/// limit still stages) so no other file or transfer shares it. fn part_path(path: &str) -> String { - let token = uuid::Uuid::new_v4().simple(); + let name = format!(".openhuman-{}.tmp", uuid::Uuid::new_v4().simple()); match path.rsplit_once('/') { - Some((folder, name)) => format!("{folder}/.{name}.{token}.part"), - None => format!(".{path}.{token}.part"), + Some((folder, _)) => format!("{folder}/{name}"), + None => name, } } diff --git a/crates/openhuman-core/src/sandbox/openshell/files_tests.rs b/crates/openhuman-core/src/sandbox/openshell/files_tests.rs index 8fff7f51344..f2012e41d4f 100644 --- a/crates/openhuman-core/src/sandbox/openshell/files_tests.rs +++ b/crates/openhuman-core/src/sandbox/openshell/files_tests.rs @@ -45,7 +45,7 @@ fn encoded(bytes: &[u8]) -> String { /// The part file a write's first command names: the quoted `./...part` word. fn part_in(command: &str) -> String { - let end = command.find(".part'").expect("a part file") + ".part".len(); + let end = command.find(".tmp'").expect("a part file") + ".tmp".len(); let start = command[..end].rfind("'./").expect("a quoted path") + 1; command[start..end].to_owned() } From 2ffa9bd743733886669026e4e1997cf239d883dc Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 5 Nov 2026 20:47:22 +0000 Subject: [PATCH 24/37] feat(artifacts): extend box-sourced wrapper to update_artifact The box-sourced tool wrapper now also covers update_artifact, taking the artifact kind from the stored record when the call names an existing artifact rather than from its arguments. Staged box files are cleaned up on drop so a cancelled call no longer leaves copies behind. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/artifacts/box_source.rs | 75 +++++++++++++------ .../src/artifacts/box_source_tests.rs | 8 +- .../src/artifacts/tiny_store.rs | 17 ++++- 3 files changed, 68 insertions(+), 32 deletions(-) diff --git a/crates/openhuman-core/src/artifacts/box_source.rs b/crates/openhuman-core/src/artifacts/box_source.rs index 10455ea7190..77af7c8d645 100644 --- a/crates/openhuman-core/src/artifacts/box_source.rs +++ b/crates/openhuman-core/src/artifacts/box_source.rs @@ -1,11 +1,12 @@ -//! `create_artifact` for a sandbox that keeps boxes: a file `path` names a file -//! in the calling tenant's box, not on the host. +//! `create_artifact` and `update_artifact` for a sandbox that keeps boxes: a +//! file `path` names a file in the calling tenant's box, not on the host. //! //! With a backend that keeps one box per tenant (`openshell`; see //! [`SandboxBackendKind::keeps_boxes`](crate::sandbox::types::SandboxBackendKind::keeps_boxes)), //! the files an agent makes live in its box, and the host has never seen -//! them. [`BoxSourcedCreate`] wraps the artifact crate's `create_artifact` -//! tool: for an `image` or `file` artifact it reads the file out of the +//! them. [`BoxSourced`] wraps the artifact crate's `create_artifact` +//! tool (and likewise `update_artifact`, whose artifact kind comes from its +//! stored record): for an `image` or `file` artifact it reads the file out of the //! caller's box ([`crate::sandbox::openshell::read_file`]), stages the bytes in //! a folder artifacts may reference, hands the staged path to the crate's tool //! unchanged, and removes the staged copy. Everything after that is @@ -21,7 +22,7 @@ use std::sync::Arc; use async_trait::async_trait; use serde_json::Value; -use tiny_artifacts::{ArtifactKind, CreateArtifactTool}; +use tiny_artifacts::{ArtifactKind, Artifacts}; use tinytools::{PermissionLevel, Tool, ToolResult}; use super::tiny_store::version_files_dir; @@ -102,32 +103,55 @@ fn box_path(path: &str) -> &str { .unwrap_or(path) } -/// The crate's `create_artifact`, reading a file `path` from the caller's box -/// when the sandbox keeps one. -pub(crate) struct BoxSourcedCreate { - inner: CreateArtifactTool, +/// Where the kind of artifact a call writes comes from. +pub(crate) enum KindSource { + /// A new artifact: the call's own `kind`. + Args, + /// An existing artifact: the kind of the record `artifact_id` names. + Record(Arc), +} + +/// One of the crate's artifact tools (`create_artifact` or `update_artifact`), +/// reading a file `path` from the caller's box when the sandbox keeps one. +pub(crate) struct BoxSourced { + inner: Box, + kinds: KindSource, boxes: Arc, tenant: Result, staging: PathBuf, } -impl BoxSourcedCreate { +impl BoxSourced { /// `tenant` is the calling tenant (its box is read); `staging` is the /// folder (see [`staging_dir`]) a box file is copied into for the crate. pub(crate) fn new( - inner: CreateArtifactTool, + inner: impl Tool + 'static, + kinds: KindSource, boxes: Arc, tenant: Result, staging: PathBuf, ) -> Self { Self { - inner, + inner: Box::new(inner), + kinds, boxes, tenant, staging, } } + /// The kind of artifact this call writes, when it can be told. + async fn kind(&self, args: &Value) -> Option { + match &self.kinds { + KindSource::Args => ArtifactKind::parse(args.get("kind")?.as_str()?), + KindSource::Record(artifacts) => { + let id = args.get("artifact_id")?.as_str()?; + // A store failure or an unknown id is the crate's tool to report. + artifacts.get(id).await.ok().flatten().map(|record| record.kind) + } + } + } + /// The file to read from the box, when this call is one that does: an /// `image` or `file` artifact, under a sandbox that keeps boxes. (A call /// the crate would reject is left to it.) @@ -136,11 +160,7 @@ impl BoxSourcedCreate { /// /// When it cannot be told whether the sandbox keeps boxes. async fn box_file(&self, args: &Value) -> Result, BoxError> { - let Some(kind) = args - .get("kind") - .and_then(Value::as_str) - .and_then(ArtifactKind::parse) - else { + let Some(kind) = self.kind(args).await else { return Ok(None); }; if !kind.holds_file() { @@ -164,7 +184,7 @@ impl BoxSourcedCreate { } #[async_trait] -impl Tool for BoxSourcedCreate { +impl Tool for BoxSourced { fn name(&self) -> &str { self.inner.name() } @@ -209,20 +229,27 @@ impl Tool for BoxSourcedCreate { } }; args["path"] = Value::String(staged.file.display().to_string()); - let created = self.inner.execute(args).await; - if let Err(error) = tokio::fs::remove_dir_all(&staged.dir).await { - tracing::warn!(%error, "[artifacts] could not remove a staged sandbox file"); - } - created + // `staged` removes its folder when dropped, so a call cancelled while + // the crate's tool runs leaves nothing behind either. + self.inner.execute(args).await } } -/// A box file copied onto the host for one call. +/// A box file copied onto the host for one call. Dropping it removes the copy, +/// whether the call finished or was cancelled. struct Staged { dir: PathBuf, file: PathBuf, } +impl Drop for Staged { + fn drop(&mut self) { + if let Err(error) = std::fs::remove_dir_all(&self.dir) { + tracing::warn!(%error, "[artifacts] could not remove a staged sandbox file"); + } + } +} + /// Copy `bytes` into a folder of its own under `staging`, keeping the file's /// name (its extension decides the artifact's media type). async fn stage(staging: &Path, box_path: &str, bytes: &[u8]) -> std::io::Result { diff --git a/crates/openhuman-core/src/artifacts/box_source_tests.rs b/crates/openhuman-core/src/artifacts/box_source_tests.rs index b473fb17df8..2651657d2a8 100644 --- a/crates/openhuman-core/src/artifacts/box_source_tests.rs +++ b/crates/openhuman-core/src/artifacts/box_source_tests.rs @@ -70,11 +70,11 @@ impl Fixture { } } - fn tool(&self, keeps: bool, tenant: Result) -> BoxSourcedCreate { + fn tool(&self, keeps: bool, tenant: Result) -> BoxSourced { self.tool_with(Some(keeps), tenant) } - fn tool_with(&self, keeps: Option, tenant: Result) -> BoxSourcedCreate { + fn tool_with(&self, keeps: Option, tenant: Result) -> BoxSourced { let ctx = DispatchCtx::process_default(); let service = artifacts_service( &self.workspace, @@ -90,7 +90,7 @@ impl Fixture { max_live: 10, }, ); - BoxSourcedCreate::new( + BoxSourced::new( CreateArtifactTool::new(Arc::new(service), Author::agent("agent")), Arc::new(ScriptedBoxes { keeps, registry }), tenant, @@ -159,7 +159,7 @@ fn file_args(path: &str) -> Value { json!({"kind": "file", "title": "Report", "path": path}) } -async fn created_id(tool: &BoxSourcedCreate, args: Value) -> String { +async fn created_id(tool: &BoxSourced, args: Value) -> String { let result = tool.execute(args).await.unwrap(); assert!(!result.is_error, "{}", result.output()); let body: Value = serde_json::from_str(&result.output()).unwrap(); diff --git a/crates/openhuman-core/src/artifacts/tiny_store.rs b/crates/openhuman-core/src/artifacts/tiny_store.rs index bb6905ece3d..8cf92f66001 100644 --- a/crates/openhuman-core/src/artifacts/tiny_store.rs +++ b/crates/openhuman-core/src/artifacts/tiny_store.rs @@ -649,8 +649,9 @@ pub fn registered_tools( author.clone(), ); let tenant = context.dispatch.tenant(); - super::box_source::BoxSourcedCreate::new( + super::box_source::BoxSourced::new( create, + super::box_source::KindSource::Args, Arc::new(super::box_source::SandboxBoxFiles::new(context.dispatch)), tenant, staging.clone(), @@ -663,12 +664,20 @@ pub fn registered_tools( )))); { let (service, author) = (service.clone(), author.clone()); + let staging = super::box_source::staging_dir(workspace_dir); tools.push(Box::new(PerCallTool::new( per_call_context, move |context| { - tiny_artifacts::UpdateArtifactTool::new( - service(context.chat.as_ref()), - author.clone(), + let artifacts = service(context.chat.as_ref()); + let update = + tiny_artifacts::UpdateArtifactTool::new(Arc::clone(&artifacts), author.clone()); + let tenant = context.dispatch.tenant(); + super::box_source::BoxSourced::new( + update, + super::box_source::KindSource::Record(artifacts), + Arc::new(super::box_source::SandboxBoxFiles::new(context.dispatch)), + tenant, + staging.clone(), ) }, ))); From 555dddfb378f21204b4849e362e509e3b8ad12b5 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 5 Nov 2026 20:47:41 +0000 Subject: [PATCH 25/37] test(artifacts): cover box-sourced updates and staged copy cleanup Extend the box source tests to exercise update_artifact through the same scripted box, asserting that an update reads its new bytes from the caller's box rather than a same-named host file and that text artifacts never touch a box. Also add a test that a staged copy's directory is removed when its call is dropped before finishing. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/artifacts/box_source_tests.rs | 94 +++++++++++++++++-- 1 file changed, 87 insertions(+), 7 deletions(-) diff --git a/crates/openhuman-core/src/artifacts/box_source_tests.rs b/crates/openhuman-core/src/artifacts/box_source_tests.rs index 2651657d2a8..367fb15162c 100644 --- a/crates/openhuman-core/src/artifacts/box_source_tests.rs +++ b/crates/openhuman-core/src/artifacts/box_source_tests.rs @@ -8,7 +8,7 @@ use crate::sandbox::openshell::{read_file_in, BoxOutput, BoxRegistry, RegistryLi use base64::Engine as _; use serde_json::{json, Value}; use std::time::Duration; -use tiny_artifacts::Author; +use tiny_artifacts::{Author, UpdateArtifactTool}; /// Box files from a registry over a scripted driver, so a test says what the /// box holds and sees every command sent to it. @@ -75,6 +75,20 @@ impl Fixture { } fn tool_with(&self, keeps: Option, tenant: Result) -> BoxSourced { + self.build(keeps, tenant, false) + } + + /// `update_artifact` over the same stores, behind the same box files. + fn update_tool(&self, keeps: bool, tenant: Result) -> BoxSourced { + self.build(Some(keeps), tenant, true) + } + + fn build( + &self, + keeps: Option, + tenant: Result, + update: bool, + ) -> BoxSourced { let ctx = DispatchCtx::process_default(); let service = artifacts_service( &self.workspace, @@ -90,12 +104,17 @@ impl Fixture { max_live: 10, }, ); - BoxSourced::new( - CreateArtifactTool::new(Arc::new(service), Author::agent("agent")), - Arc::new(ScriptedBoxes { keeps, registry }), - tenant, - staging_dir(&self.workspace), - ) + let service = Arc::new(service); + let boxes = Arc::new(ScriptedBoxes { keeps, registry }); + let staging = staging_dir(&self.workspace); + let author = Author::agent("agent"); + if update { + let tool = UpdateArtifactTool::new(Arc::clone(&service), author); + BoxSourced::new(tool, KindSource::Record(service), boxes, tenant, staging) + } else { + let tool = CreateArtifactTool::new(service, author); + BoxSourced::new(tool, KindSource::Args, boxes, tenant, staging) + } } /// The box holds `bytes` at whatever path is asked for. @@ -347,3 +366,64 @@ fn a_box_path_is_the_name_relative_to_the_work_folder() { assert_eq!(box_path("/sandboxed/report.pdf"), "/sandboxed/report.pdf"); assert_eq!(box_path("/sandbox"), "/sandbox"); } + +#[tokio::test] +async fn an_update_reads_its_new_file_from_the_callers_box() { + let _floor = crate::modules::security::gap::install_path_floor_port( + crate::modules::security::gap::ScriptedPathFloorPort::new([], vec![]), + ); + let fixture = Fixture::new(); + fixture.the_box_holds(b"first"); + let id = created_id(&fixture.tool(true, user("u1")), file_args("a.pdf")).await; + // A host file of the same name must not be what the update files. + std::fs::write(fixture.action.join("a.pdf"), b"host bytes").unwrap(); + fixture.the_box_holds(b"second"); + let update = fixture.update_tool(true, user("u1")); + + let result = update + .execute(json!({"artifact_id": id, "path": "a.pdf"})) + .await + .unwrap(); + + assert!(!result.is_error, "{}", result.output()); + let stored = read_artifact_bytes(&fixture.workspace, FileRoots::new(&fixture.files), &id) + .await + .unwrap(); + assert_eq!(stored, b"second"); + assert_eq!(fixture.staged_files(), 0, "the host copy is not kept"); +} + +#[tokio::test] +async fn an_update_of_a_text_artifact_never_touches_a_box() { + let fixture = Fixture::new(); + let created = fixture + .tool(true, user("u1")) + .execute(json!({"kind": "markdown", "title": "Notes", "body": "one"})) + .await + .unwrap(); + let id = serde_json::from_str::(&created.output()).unwrap()["artifact_id"] + .as_str() + .unwrap() + .to_owned(); + + let result = fixture + .update_tool(true, user("u1")) + .execute(json!({"artifact_id": id, "body": "two", "path": "ignored.pdf"})) + .await + .unwrap(); + + assert!(!result.is_error, "{}", result.output()); + assert!(fixture.driver.calls().is_empty(), "no box was touched"); +} + +#[tokio::test] +async fn a_staged_copy_is_removed_when_its_call_is_dropped_before_it_finishes() { + let staging = tempfile::tempdir().unwrap(); + let staged = stage(staging.path(), "out/a.pdf", b"bytes").await.unwrap(); + let dir = staged.dir.clone(); + assert!(dir.join("a.pdf").is_file()); + + drop(staged); + + assert!(!dir.exists()); +} From a62659d8bcd16f462a21833955fd3d2d8f15470b Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 5 Nov 2026 20:48:57 +0000 Subject: [PATCH 26/37] refactor(artifacts): rename box source wrapper to box sourced The wrapper type is now called `BoxSourced` rather than `BoxSourcedCreate`, and the README entry follows the rename. The kind lookup in `box_source.rs` was reformatted without changing behaviour, and the sandbox file tests were updated to expect the new staging name pattern plus a case covering a 255-character filename. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-core/src/artifacts/README.md | 2 +- crates/openhuman-core/src/artifacts/box_source.rs | 7 ++++++- .../src/sandbox/openshell/files_tests.rs | 15 ++++++++++++++- 3 files changed, 21 insertions(+), 3 deletions(-) diff --git a/crates/openhuman-core/src/artifacts/README.md b/crates/openhuman-core/src/artifacts/README.md index d76a77a1392..127efcb7e77 100644 --- a/crates/openhuman-core/src/artifacts/README.md +++ b/crates/openhuman-core/src/artifacts/README.md @@ -24,7 +24,7 @@ renders artifact content itself. | [`ops.rs`](./ops.rs) | RPC business logic returning `Outcome`: `ai_list_artifacts`, `ai_get_artifact`, `ai_delete_artifact`, `ai_regenerate`. `DEFAULT_LIMIT = 50`, `MAX_LIMIT = 200`. The regenerate path that re-runs `PresentationTool` is `#[cfg(feature = "documents")]`; without the feature `ai_regenerate` returns an error. | | [`schemas.rs`](./schemas.rs) | `ControllerSchema`s and `handle_*` fns for the four `ai.*` controllers; param helpers `read_required`, `read_optional_u64`, `read_optional_string` (whitespace-only → absent), `type_name`. | | [`tiny_store.rs`](./tiny_store.rs) | OpenHuman's side of the versioned artifacts (`tiny-artifacts`): `versioned_store` (records in the configured storage backend: [`version_documents.rs`](./version_documents.rs); older JSON records are imported once), the acting tenant's scoped blob-backed file store, guarded migration of old path references, `text_extension_of_title` (a `text` artifact keeps the inert extension its title names: csv, ics, vcf, json and the like; anything else stays `txt`), `LegacyUiBridge` (shows the newest version through the legacy row, events and visible files folder), `artifacts_service`, the agent tools, and `save_operator_version` (the preview panel's autosave). | -| [`box_source.rs`](./box_source.rs) | `BoxSourcedCreate`: wraps the crate's `create_artifact`. When the sandbox backend keeps boxes (`SandboxBackendKind::keeps_boxes`, `openshell` today), a file `path` on an `image` / `file` artifact is read from the calling tenant's box (`sandbox::read_box_file`, relative to the box work folder; `/sandbox/...` is accepted), staged for the call under the kept-copies folder, filed, and removed. No tenant, a missing file or an over-limit file is a tool error. Other backends and text artifacts are untouched. | +| [`box_source.rs`](./box_source.rs) | `BoxSourced`: wraps the crate's `create_artifact`. When the sandbox backend keeps boxes (`SandboxBackendKind::keeps_boxes`, `openshell` today), a file `path` on an `image` / `file` artifact is read from the calling tenant's box (`sandbox::read_box_file`, relative to the box work folder; `/sandbox/...` is accepted), staged for the call under the kept-copies folder, filed, and removed. No tenant, a missing file or an over-limit file is a tool error. Other backends and text artifacts are untouched. | | [`production.rs`](./production.rs) | `Production`: how producer tools (deck, document, generated media) file their output — reserve the file and the card, open the versioned record under the same id, then complete or fail it. | | `*_tests.rs` | Sibling test files for each of the above (`#[path]`). | diff --git a/crates/openhuman-core/src/artifacts/box_source.rs b/crates/openhuman-core/src/artifacts/box_source.rs index 77af7c8d645..b4dd35710a4 100644 --- a/crates/openhuman-core/src/artifacts/box_source.rs +++ b/crates/openhuman-core/src/artifacts/box_source.rs @@ -147,7 +147,12 @@ impl BoxSourced { KindSource::Record(artifacts) => { let id = args.get("artifact_id")?.as_str()?; // A store failure or an unknown id is the crate's tool to report. - artifacts.get(id).await.ok().flatten().map(|record| record.kind) + artifacts + .get(id) + .await + .ok() + .flatten() + .map(|record| record.kind) } } } diff --git a/crates/openhuman-core/src/sandbox/openshell/files_tests.rs b/crates/openhuman-core/src/sandbox/openshell/files_tests.rs index f2012e41d4f..b5234e8df7f 100644 --- a/crates/openhuman-core/src/sandbox/openshell/files_tests.rs +++ b/crates/openhuman-core/src/sandbox/openshell/files_tests.rs @@ -144,7 +144,7 @@ async fn a_small_file_is_one_command_that_writes_a_part_file_and_renames_it() { ); let part = part_in(&sent[0]); assert!( - part.starts_with("./out/.a.txt.") && part.ends_with(".part"), + part.starts_with("./out/.openhuman-") && part.ends_with(".tmp"), "{part}" ); assert!( @@ -595,6 +595,19 @@ mod on_a_real_shell { assert!(!driver.box_dir("box-1").unwrap().join("a.bin").exists()); } + #[tokio::test] + async fn a_name_at_the_filesystem_limit_still_stages() { + let (_root, _driver, boxes) = host_boxes(); + let name = "n".repeat(255); + + write_file_in(&boxes, Ok(embedded("u1")), &config(), &name, b"long") + .await + .unwrap(); + let back = read_file_in(&boxes, Ok(embedded("u1")), &config(), &name, 10).await; + + assert_eq!(back, Ok(b"long".to_vec())); + } + #[tokio::test] async fn a_file_named_dash_is_a_file_and_not_standard_input() { let (_root, _driver, boxes) = host_boxes(); From ee82b86e8e097e7bde5a90c8b4a6fd080ed8b948 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 5 Nov 2026 20:51:10 +0000 Subject: [PATCH 27/37] test(artifacts): import create artifact tool in box source tests Adds the missing CreateArtifactTool import to the box source test module so the tests can reference it alongside UpdateArtifactTool. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-core/src/artifacts/box_source_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/openhuman-core/src/artifacts/box_source_tests.rs b/crates/openhuman-core/src/artifacts/box_source_tests.rs index 367fb15162c..b062e1c1026 100644 --- a/crates/openhuman-core/src/artifacts/box_source_tests.rs +++ b/crates/openhuman-core/src/artifacts/box_source_tests.rs @@ -8,7 +8,7 @@ use crate::sandbox::openshell::{read_file_in, BoxOutput, BoxRegistry, RegistryLi use base64::Engine as _; use serde_json::{json, Value}; use std::time::Duration; -use tiny_artifacts::{Author, UpdateArtifactTool}; +use tiny_artifacts::{Author, CreateArtifactTool, UpdateArtifactTool}; /// Box files from a registry over a scripted driver, so a test says what the /// box holds and sees every command sent to it. From 7bfee1c0a68f6fedc2ebd3b05813ea4e0e1c717c Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 5 Nov 2026 20:51:30 +0000 Subject: [PATCH 28/37] docs(artifacts): note box_source also wraps update_artifact The box_source entry now documents that BoxSourced wraps update_artifact as well as create_artifact, with the update's kind taken from its record, so the README matches the module's current behaviour. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-core/src/artifacts/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/openhuman-core/src/artifacts/README.md b/crates/openhuman-core/src/artifacts/README.md index 127efcb7e77..aaa9fcd8209 100644 --- a/crates/openhuman-core/src/artifacts/README.md +++ b/crates/openhuman-core/src/artifacts/README.md @@ -24,7 +24,7 @@ renders artifact content itself. | [`ops.rs`](./ops.rs) | RPC business logic returning `Outcome`: `ai_list_artifacts`, `ai_get_artifact`, `ai_delete_artifact`, `ai_regenerate`. `DEFAULT_LIMIT = 50`, `MAX_LIMIT = 200`. The regenerate path that re-runs `PresentationTool` is `#[cfg(feature = "documents")]`; without the feature `ai_regenerate` returns an error. | | [`schemas.rs`](./schemas.rs) | `ControllerSchema`s and `handle_*` fns for the four `ai.*` controllers; param helpers `read_required`, `read_optional_u64`, `read_optional_string` (whitespace-only → absent), `type_name`. | | [`tiny_store.rs`](./tiny_store.rs) | OpenHuman's side of the versioned artifacts (`tiny-artifacts`): `versioned_store` (records in the configured storage backend: [`version_documents.rs`](./version_documents.rs); older JSON records are imported once), the acting tenant's scoped blob-backed file store, guarded migration of old path references, `text_extension_of_title` (a `text` artifact keeps the inert extension its title names: csv, ics, vcf, json and the like; anything else stays `txt`), `LegacyUiBridge` (shows the newest version through the legacy row, events and visible files folder), `artifacts_service`, the agent tools, and `save_operator_version` (the preview panel's autosave). | -| [`box_source.rs`](./box_source.rs) | `BoxSourced`: wraps the crate's `create_artifact`. When the sandbox backend keeps boxes (`SandboxBackendKind::keeps_boxes`, `openshell` today), a file `path` on an `image` / `file` artifact is read from the calling tenant's box (`sandbox::read_box_file`, relative to the box work folder; `/sandbox/...` is accepted), staged for the call under the kept-copies folder, filed, and removed. No tenant, a missing file or an over-limit file is a tool error. Other backends and text artifacts are untouched. | +| [`box_source.rs`](./box_source.rs) | `BoxSourced`: wraps the crate's `create_artifact` and `update_artifact` (the update's kind comes from its record). When the sandbox backend keeps boxes (`SandboxBackendKind::keeps_boxes`, `openshell` today), a file `path` on an `image` / `file` artifact is read from the calling tenant's box (`sandbox::read_box_file`, relative to the box work folder; `/sandbox/...` is accepted), staged for the call under the kept-copies folder, filed, and removed. No tenant, a missing file or an over-limit file is a tool error. Other backends and text artifacts are untouched. | | [`production.rs`](./production.rs) | `Production`: how producer tools (deck, document, generated media) file their output — reserve the file and the card, open the versioned record under the same id, then complete or fail it. | | `*_tests.rs` | Sibling test files for each of the above (`#[path]`). | From cde4e9028c3b83b85e072cc07f49861714912ddb Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 5 Nov 2026 20:58:12 +0000 Subject: [PATCH 29/37] fix(sandbox): follow symlinks when statting files for reads The size and identity checks now use stat -L so that a symlink pointing at a file inside the work folder is read as the file it targets rather than being rejected or compared against the link's own metadata. A test covers reading through such a link. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/sandbox/openshell/files.rs | 4 ++-- .../src/sandbox/openshell/files_tests.rs | 22 ++++++++++++++++++- 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/crates/openhuman-core/src/sandbox/openshell/files.rs b/crates/openhuman-core/src/sandbox/openshell/files.rs index 88a7b3c95fa..5374287f4df 100644 --- a/crates/openhuman-core/src/sandbox/openshell/files.rs +++ b/crates/openhuman-core/src/sandbox/openshell/files.rs @@ -151,7 +151,7 @@ pub async fn read_file_in( let sized = target .run(&format!( "test -f {quoted} || exit {NOT_A_FILE_EXIT}; {GUARD} \ - inside \"$(realpath -- {quoted})\"; stat -c '%s %d:%i:%Y' -- {quoted}" + inside \"$(realpath -- {quoted})\"; stat -L -c '%s %d:%i:%Y' -- {quoted}" )) .await?; if sized.exit_code == NOT_A_FILE_EXIT { @@ -289,7 +289,7 @@ fn write_command( /// taken, before or after the read. fn read_command(quoted: &str, identity: &str, start: usize, want: u64) -> String { let same = format!( - "[ \"$(stat -c '%d:%i:%Y' -- {quoted})\" = {} ] || \ + "[ \"$(stat -L -c '%d:%i:%Y' -- {quoted})\" = {} ] || \ {{ echo 'the file changed while it was read' >&2; exit 1; }}; ", quote(identity) ); diff --git a/crates/openhuman-core/src/sandbox/openshell/files_tests.rs b/crates/openhuman-core/src/sandbox/openshell/files_tests.rs index b5234e8df7f..80f8cad5b6b 100644 --- a/crates/openhuman-core/src/sandbox/openshell/files_tests.rs +++ b/crates/openhuman-core/src/sandbox/openshell/files_tests.rs @@ -608,6 +608,26 @@ mod on_a_real_shell { assert_eq!(back, Ok(b"long".to_vec())); } + #[tokio::test] + async fn a_link_to_a_file_inside_the_work_folder_reads_the_files_bytes() { + let (_root, driver, boxes) = host_boxes(); + write_file_in( + &boxes, + Ok(embedded("u1")), + &config(), + "target.bin", + b"real bytes", + ) + .await + .unwrap(); + let dir = driver.box_dir("box-0").unwrap(); + std::os::unix::fs::symlink("target.bin", dir.join("alias.bin")).unwrap(); + + let back = read_file_in(&boxes, Ok(embedded("u1")), &config(), "alias.bin", 100).await; + + assert_eq!(back, Ok(b"real bytes".to_vec())); + } + #[tokio::test] async fn a_file_named_dash_is_a_file_and_not_standard_input() { let (_root, _driver, boxes) = host_boxes(); @@ -718,7 +738,7 @@ mod on_a_real_shell { fn a_file_replaced_between_chunks_fails_the_read() { let dir = tempfile::tempdir().unwrap(); std::fs::write(dir.path().join("a.bin"), b"abcd").unwrap(); - let identity = run_in(dir.path(), "stat -c '%d:%i:%Y' -- ./a.bin").0; + let identity = run_in(dir.path(), "stat -L -c '%d:%i:%Y' -- ./a.bin").0; let command = read_command("'./a.bin'", identity.trim(), 1, 4); assert_eq!(run_in(dir.path(), &command).0.trim(), encoded(b"abcd")); From 4ffa74cfa58740057ce3dce155a7ff1e478fc88e Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 5 Nov 2026 21:01:18 +0000 Subject: [PATCH 30/37] fix(sandbox): drop stat -L so symlink reads report the link's own size The file read path now stats without dereferencing symlinks, so the size and identity check reflects the link itself rather than its target. The symlink test payload was lengthened to make the distinction observable. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-core/src/sandbox/openshell/files.rs | 2 +- crates/openhuman-core/src/sandbox/openshell/files_tests.rs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/openhuman-core/src/sandbox/openshell/files.rs b/crates/openhuman-core/src/sandbox/openshell/files.rs index 5374287f4df..bbaf5502722 100644 --- a/crates/openhuman-core/src/sandbox/openshell/files.rs +++ b/crates/openhuman-core/src/sandbox/openshell/files.rs @@ -151,7 +151,7 @@ pub async fn read_file_in( let sized = target .run(&format!( "test -f {quoted} || exit {NOT_A_FILE_EXIT}; {GUARD} \ - inside \"$(realpath -- {quoted})\"; stat -L -c '%s %d:%i:%Y' -- {quoted}" + inside \"$(realpath -- {quoted})\"; stat -c '%s %d:%i:%Y' -- {quoted}" )) .await?; if sized.exit_code == NOT_A_FILE_EXIT { diff --git a/crates/openhuman-core/src/sandbox/openshell/files_tests.rs b/crates/openhuman-core/src/sandbox/openshell/files_tests.rs index 80f8cad5b6b..aaf3d4ac804 100644 --- a/crates/openhuman-core/src/sandbox/openshell/files_tests.rs +++ b/crates/openhuman-core/src/sandbox/openshell/files_tests.rs @@ -616,7 +616,7 @@ mod on_a_real_shell { Ok(embedded("u1")), &config(), "target.bin", - b"real bytes", + b"the real bytes of the target", ) .await .unwrap(); @@ -625,7 +625,7 @@ mod on_a_real_shell { let back = read_file_in(&boxes, Ok(embedded("u1")), &config(), "alias.bin", 100).await; - assert_eq!(back, Ok(b"real bytes".to_vec())); + assert_eq!(back, Ok(b"the real bytes of the target".to_vec())); } #[tokio::test] From b8c5d69daa28c5aa4add68db8b641481954a5243 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 5 Nov 2026 21:04:36 +0000 Subject: [PATCH 31/37] fix(sandbox): dereference symlinks when statting files for reads The read path now passes -L to stat so that symlinked files report the size and identity of their target rather than the link itself, keeping the size check consistent with the realpath guard that already resolves links. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-core/src/sandbox/openshell/files.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/openhuman-core/src/sandbox/openshell/files.rs b/crates/openhuman-core/src/sandbox/openshell/files.rs index bbaf5502722..5374287f4df 100644 --- a/crates/openhuman-core/src/sandbox/openshell/files.rs +++ b/crates/openhuman-core/src/sandbox/openshell/files.rs @@ -151,7 +151,7 @@ pub async fn read_file_in( let sized = target .run(&format!( "test -f {quoted} || exit {NOT_A_FILE_EXIT}; {GUARD} \ - inside \"$(realpath -- {quoted})\"; stat -c '%s %d:%i:%Y' -- {quoted}" + inside \"$(realpath -- {quoted})\"; stat -L -c '%s %d:%i:%Y' -- {quoted}" )) .await?; if sized.exit_code == NOT_A_FILE_EXIT { From 448b9406e89b7395fcbff90900c7857613f37659 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 5 Nov 2026 21:14:16 +0000 Subject: [PATCH 32/37] fix(artifacts): fail the call when the artifact record cannot be read Reading the stored record now surfaces store errors as a driver error instead of silently falling back to the host's disk, and a missing or unknown artifact id is left for the crate's tool to report. Staging also generates the file name from the box file's extension so names the host filesystem rejects still stage, and a cancelled stage no longer leaves a copy behind. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/artifacts/box_source.rs | 101 +++++++++++++----- .../src/artifacts/box_source_tests.rs | 54 +++++++++- .../src/sandbox/openshell/files.rs | 16 +-- .../src/sandbox/openshell/files_tests.rs | 19 +++- 4 files changed, 152 insertions(+), 38 deletions(-) diff --git a/crates/openhuman-core/src/artifacts/box_source.rs b/crates/openhuman-core/src/artifacts/box_source.rs index b4dd35710a4..fbea09f49c7 100644 --- a/crates/openhuman-core/src/artifacts/box_source.rs +++ b/crates/openhuman-core/src/artifacts/box_source.rs @@ -103,12 +103,33 @@ fn box_path(path: &str) -> &str { .unwrap_or(path) } +/// The kind of an existing artifact, from its stored record. +#[async_trait] +pub(crate) trait RecordKinds: Send + Sync { + /// The kind of artifact `id` names; `None` when there is no such artifact. + /// + /// # Errors + /// + /// The store's message when it cannot be read. + async fn kind_of(&self, id: &str) -> Result, String>; +} + +#[async_trait] +impl RecordKinds for Artifacts { + async fn kind_of(&self, id: &str) -> Result, String> { + self.get(id) + .await + .map(|record| record.map(|record| record.kind)) + .map_err(|error| error.to_string()) + } +} + /// Where the kind of artifact a call writes comes from. pub(crate) enum KindSource { /// A new artifact: the call's own `kind`. Args, /// An existing artifact: the kind of the record `artifact_id` names. - Record(Arc), + Record(Arc), } /// One of the crate's artifact tools (`create_artifact` or `update_artifact`), @@ -141,18 +162,26 @@ impl BoxSourced { } /// The kind of artifact this call writes, when it can be told. - async fn kind(&self, args: &Value) -> Option { + /// + /// # Errors + /// + /// When the stored record cannot be read: the call must then fail, not + /// fall back to the host's disk. + async fn kind(&self, args: &Value) -> Result, BoxError> { match &self.kinds { - KindSource::Args => ArtifactKind::parse(args.get("kind")?.as_str()?), - KindSource::Record(artifacts) => { - let id = args.get("artifact_id")?.as_str()?; - // A store failure or an unknown id is the crate's tool to report. - artifacts - .get(id) + KindSource::Args => Ok(args + .get("kind") + .and_then(Value::as_str) + .and_then(ArtifactKind::parse)), + KindSource::Record(records) => { + // A missing argument or an unknown id is the crate's tool to report. + let Some(id) = args.get("artifact_id").and_then(Value::as_str) else { + return Ok(None); + }; + records + .kind_of(id) .await - .ok() - .flatten() - .map(|record| record.kind) + .map_err(|error| BoxError::Driver(format!("cannot read the artifact: {error}"))) } } } @@ -165,7 +194,7 @@ impl BoxSourced { /// /// When it cannot be told whether the sandbox keeps boxes. async fn box_file(&self, args: &Value) -> Result, BoxError> { - let Some(kind) = self.kind(args).await else { + let Some(kind) = self.kind(args).await? else { return Ok(None); }; if !kind.holds_file() { @@ -224,7 +253,7 @@ impl Tool for BoxSourced { Ok(bytes) => bytes, Err(error) => return Ok(ToolResult::error(error.to_string())), }; - let staged = match stage(&self.staging, &path, &bytes).await { + let staged = match stage(&self.staging, &path, &bytes) { Ok(staged) => staged, Err(error) => { tracing::warn!(%error, "[artifacts] could not stage a sandbox file"); @@ -249,26 +278,42 @@ struct Staged { impl Drop for Staged { fn drop(&mut self) { - if let Err(error) = std::fs::remove_dir_all(&self.dir) { - tracing::warn!(%error, "[artifacts] could not remove a staged sandbox file"); + match std::fs::remove_dir_all(&self.dir) { + Ok(()) => {} + // Nothing was made yet (a failed or cancelled stage). + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => { + tracing::warn!(%error, "[artifacts] could not remove a staged sandbox file") + } } } } -/// Copy `bytes` into a folder of its own under `staging`, keeping the file's -/// name (its extension decides the artifact's media type). -async fn stage(staging: &Path, box_path: &str, bytes: &[u8]) -> std::io::Result { - let name = Path::new(box_path) - .file_name() - .map_or_else(|| "file".into(), ToOwned::to_owned); +/// Copy `bytes` into a folder of its own under `staging`, as `file` plus the +/// box file's extension (which decides the artifact's media type). The name is +/// generated, so a box name the host's filesystem rejects (`?` on Windows) +/// still stages. +/// +/// The folder is owned by the returned [`Staged`] from before it exists, and +/// nothing here awaits, so a call cancelled at any point leaves no copy behind. +fn stage(staging: &Path, box_path: &str, bytes: &[u8]) -> std::io::Result { + let name = match Path::new(box_path) + .extension() + .and_then(|extension| extension.to_str()) + .filter(|extension| { + extension.len() <= 16 && extension.chars().all(|c| c.is_ascii_alphanumeric()) + }) { + Some(extension) => format!("file.{extension}"), + None => "file".to_owned(), + }; let dir = staging.join(uuid::Uuid::new_v4().simple().to_string()); - tokio::fs::create_dir_all(&dir).await?; - let file = dir.join(name); - if let Err(error) = tokio::fs::write(&file, bytes).await { - let _ = tokio::fs::remove_dir_all(&dir).await; - return Err(error); - } - Ok(Staged { dir, file }) + let staged = Staged { + file: dir.join(name), + dir, + }; + std::fs::create_dir_all(&staged.dir)?; + std::fs::write(&staged.file, bytes)?; + Ok(staged) } #[cfg(test)] diff --git a/crates/openhuman-core/src/artifacts/box_source_tests.rs b/crates/openhuman-core/src/artifacts/box_source_tests.rs index b062e1c1026..fce67169b90 100644 --- a/crates/openhuman-core/src/artifacts/box_source_tests.rs +++ b/crates/openhuman-core/src/artifacts/box_source_tests.rs @@ -419,11 +419,61 @@ async fn an_update_of_a_text_artifact_never_touches_a_box() { #[tokio::test] async fn a_staged_copy_is_removed_when_its_call_is_dropped_before_it_finishes() { let staging = tempfile::tempdir().unwrap(); - let staged = stage(staging.path(), "out/a.pdf", b"bytes").await.unwrap(); + let staged = stage(staging.path(), "out/a.pdf", b"bytes").unwrap(); let dir = staged.dir.clone(); - assert!(dir.join("a.pdf").is_file()); + assert!(dir.join("file.pdf").is_file()); drop(staged); assert!(!dir.exists()); } + +#[tokio::test] +async fn a_box_name_the_host_cannot_hold_still_stages_with_its_extension() { + let staging = tempfile::tempdir().unwrap(); + + let odd = stage(staging.path(), "out/re?port*.pdf", b"x").unwrap(); + let no_extension = stage(staging.path(), "out/Makefile", b"x").unwrap(); + let hostile = stage(staging.path(), "out/a.p?f", b"x").unwrap(); + + assert!(odd.file.ends_with("file.pdf")); + assert!(no_extension.file.ends_with("file")); + assert!(hostile.file.ends_with("file")); +} + +/// A store that cannot be read. +struct BrokenRecords; + +#[async_trait] +impl RecordKinds for BrokenRecords { + async fn kind_of(&self, _id: &str) -> Result, String> { + Err("the store is down".into()) + } +} + +#[tokio::test] +async fn an_update_whose_record_cannot_be_read_fails_instead_of_reading_the_host() { + let _floor = crate::modules::security::gap::install_path_floor_port( + crate::modules::security::gap::ScriptedPathFloorPort::new([], vec![]), + ); + let fixture = Fixture::new(); + std::fs::write(fixture.action.join("a.pdf"), b"host bytes").unwrap(); + let tool = fixture.update_tool(true, user("u1")); + let tool = BoxSourced { + kinds: KindSource::Record(Arc::new(BrokenRecords)), + ..tool + }; + + let result = tool + .execute(json!({"artifact_id": "a1", "path": "a.pdf"})) + .await + .unwrap(); + + assert!(result.is_error); + assert!( + result.output().contains("the store is down"), + "{}", + result.output() + ); + assert!(fixture.driver.calls().is_empty(), "no box was touched"); +} diff --git a/crates/openhuman-core/src/sandbox/openshell/files.rs b/crates/openhuman-core/src/sandbox/openshell/files.rs index 5374287f4df..267d9863911 100644 --- a/crates/openhuman-core/src/sandbox/openshell/files.rs +++ b/crates/openhuman-core/src/sandbox/openshell/files.rs @@ -151,7 +151,7 @@ pub async fn read_file_in( let sized = target .run(&format!( "test -f {quoted} || exit {NOT_A_FILE_EXIT}; {GUARD} \ - inside \"$(realpath -- {quoted})\"; stat -L -c '%s %d:%i:%Y' -- {quoted}" + inside \"$(realpath -- {quoted})\"; stat -L -c '%s %d:%i:%y:%z' -- {quoted}" )) .await?; if sized.exit_code == NOT_A_FILE_EXIT { @@ -165,12 +165,14 @@ pub async fn read_file_in( path: path.to_owned(), detail: "the sandbox did not report the file's size".to_owned(), }; - let mut fields = sized.stdout.split_whitespace(); - let size: u64 = fields - .next() - .and_then(|size| size.parse().ok()) + // The size, then the identity: the rest of the line (its times hold spaces). + let (size, identity) = sized + .stdout + .trim() + .split_once(char::is_whitespace) .ok_or_else(unreported)?; - let identity = fields.next().ok_or_else(unreported)?; + let size: u64 = size.parse().map_err(|_| unreported())?; + let identity = identity.trim(); let limit = max_bytes.min(MAX_FILE_BYTES); if size > limit { return Err(BoxError::FileTooLarge { size, limit }); @@ -289,7 +291,7 @@ fn write_command( /// taken, before or after the read. fn read_command(quoted: &str, identity: &str, start: usize, want: u64) -> String { let same = format!( - "[ \"$(stat -L -c '%d:%i:%Y' -- {quoted})\" = {} ] || \ + "[ \"$(stat -L -c '%d:%i:%y:%z' -- {quoted})\" = {} ] || \ {{ echo 'the file changed while it was read' >&2; exit 1; }}; ", quote(identity) ); diff --git a/crates/openhuman-core/src/sandbox/openshell/files_tests.rs b/crates/openhuman-core/src/sandbox/openshell/files_tests.rs index aaf3d4ac804..a995dad9d36 100644 --- a/crates/openhuman-core/src/sandbox/openshell/files_tests.rs +++ b/crates/openhuman-core/src/sandbox/openshell/files_tests.rs @@ -738,7 +738,7 @@ mod on_a_real_shell { fn a_file_replaced_between_chunks_fails_the_read() { let dir = tempfile::tempdir().unwrap(); std::fs::write(dir.path().join("a.bin"), b"abcd").unwrap(); - let identity = run_in(dir.path(), "stat -L -c '%d:%i:%Y' -- ./a.bin").0; + let identity = run_in(dir.path(), "stat -L -c '%d:%i:%y:%z' -- ./a.bin").0; let command = read_command("'./a.bin'", identity.trim(), 1, 4); assert_eq!(run_in(dir.path(), &command).0.trim(), encoded(b"abcd")); @@ -751,6 +751,23 @@ mod on_a_real_shell { assert!(stderr.contains("changed while it was read"), "{stderr}"); } + #[test] + fn a_file_rewritten_in_place_at_the_same_size_fails_the_read() { + let dir = tempfile::tempdir().unwrap(); + std::fs::write(dir.path().join("a.bin"), b"abcd").unwrap(); + let identity = run_in(dir.path(), "stat -L -c '%d:%i:%y:%z' -- ./a.bin").0; + let command = read_command("'./a.bin'", identity.trim(), 1, 4); + assert_eq!(run_in(dir.path(), &command).2, 0); + + // The same inode, the same size and the same second. + std::thread::sleep(Duration::from_millis(30)); + std::fs::write(dir.path().join("a.bin"), b"wxyz").unwrap(); + let (_, stderr, code) = run_in(dir.path(), &command); + + assert_eq!(code, 1); + assert!(stderr.contains("changed while it was read"), "{stderr}"); + } + /// Run `command` under `sh -c` in `dir`: its stdout, stderr and exit code. fn run_in(dir: &std::path::Path, command: &str) -> (String, String, i32) { let output = std::process::Command::new("sh") From 36875ee1111124a7d7ad3ac6d5593450eca746bc Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 5 Nov 2026 21:29:34 +0000 Subject: [PATCH 33/37] fix(sandbox): reclaim stale part files on the next write A cancelled or abandoned upload could leave its part file behind forever, so a write into the folder now removes part files older than an hour before starting, while leaving recent ones alone since they may be transfers still in flight. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/sandbox/openshell/files.rs | 12 ++++++++- .../src/sandbox/openshell/files_tests.rs | 25 +++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/crates/openhuman-core/src/sandbox/openshell/files.rs b/crates/openhuman-core/src/sandbox/openshell/files.rs index 267d9863911..01773b79383 100644 --- a/crates/openhuman-core/src/sandbox/openshell/files.rs +++ b/crates/openhuman-core/src/sandbox/openshell/files.rs @@ -18,7 +18,8 @@ //! file's length and only then renames it over ``, so a reader never //! sees half a file, and a box replaced mid-write (it forgets the earlier //! chunks) fails the length check instead of keeping a truncated file. A -//! failure removes the part file. +//! failure removes the part file; one abandoned by a cancelled transfer is +//! removed by the next write into its folder once it is an hour old. //! - **Read** checks the file exists and reads its size first, refuses a file //! over the limit before moving any of it, then reads //! [`READ_CHUNK_BYTES`] at a time (a hosted exec keeps at most 512 KB of @@ -58,6 +59,13 @@ const COMMAND_TIMEOUT: Duration = Duration::from_secs(60); /// The exit status the size check uses for "not a regular file". const NOT_A_FILE_EXIT: i32 = 66; +/// A part file this old was abandoned (its transfer was cancelled or its host +/// went away, so nothing removed it); the next write into the folder removes it. +const STALE_PART_MINUTES: u32 = 60; + +/// The pattern every part file's name matches (see [`part_path`]). +const STALE_PART_GLOB: &str = ".openhuman-*.tmp"; + /// The longest box message kept in an error. const DETAIL_MAX_CHARS: usize = 200; @@ -267,6 +275,8 @@ fn write_command( "d={folder}; while ! test -e \"$d\" && ! test -L \"$d\"; do d=$(dirname \"$d\"); done; \ inside \"$(realpath -- \"$d\")\"; mkdir -p -- {folder} || exit 1; \ inside \"$(realpath -- {folder})\"; \ + find {folder} -maxdepth 1 -type f -name '{STALE_PART_GLOB}' -mmin +{STALE_PART_MINUTES} \ + -exec rm -f -- {{}} + 2>/dev/null; \ ( set -C; printf %s '{encoded}' | base64 -d > {quoted_part} ) || exit 1" )); } else { diff --git a/crates/openhuman-core/src/sandbox/openshell/files_tests.rs b/crates/openhuman-core/src/sandbox/openshell/files_tests.rs index a995dad9d36..1783b2dbc6b 100644 --- a/crates/openhuman-core/src/sandbox/openshell/files_tests.rs +++ b/crates/openhuman-core/src/sandbox/openshell/files_tests.rs @@ -628,6 +628,31 @@ mod on_a_real_shell { assert_eq!(back, Ok(b"the real bytes of the target".to_vec())); } + #[tokio::test] + async fn a_part_file_abandoned_by_a_cancelled_upload_is_reclaimed_by_the_next_write() { + let (_root, driver, boxes) = host_boxes(); + write_file_in(&boxes, Ok(embedded("u1")), &config(), "out/seed.txt", b"x") + .await + .unwrap(); + let dir = driver.box_dir("box-0").unwrap().join("out"); + let (old, fresh) = ( + dir.join(".openhuman-old.tmp"), + dir.join(".openhuman-new.tmp"), + ); + std::fs::write(&old, b"half").unwrap(); + std::fs::write(&fresh, b"in flight").unwrap(); + let (_, _, code) = run_in(&dir, "touch -d '3 hours ago' .openhuman-old.tmp"); + assert_eq!(code, 0); + + write_file_in(&boxes, Ok(embedded("u1")), &config(), "out/a.txt", b"y") + .await + .unwrap(); + + assert!(!old.exists(), "an hour-old part file is removed"); + assert!(fresh.exists(), "a recent one may be an upload in flight"); + assert!(dir.join("a.txt").is_file()); + } + #[tokio::test] async fn a_file_named_dash_is_a_file_and_not_standard_input() { let (_root, _driver, boxes) = host_boxes(); From 8df5bd4c628d5169c8505c59ce2d2f7724bf9b6a Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 5 Nov 2026 21:31:50 +0000 Subject: [PATCH 34/37] test(openshell): locate part file by uuid marker in write commands The test helper now finds the part file by its `.openhuman-` marker and skips the glob used by the stale-file sweep, so it no longer mistakes the sweep's pattern for the write's actual part file. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../openhuman-core/src/sandbox/openshell/files_tests.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/openhuman-core/src/sandbox/openshell/files_tests.rs b/crates/openhuman-core/src/sandbox/openshell/files_tests.rs index 1783b2dbc6b..eede9ee1985 100644 --- a/crates/openhuman-core/src/sandbox/openshell/files_tests.rs +++ b/crates/openhuman-core/src/sandbox/openshell/files_tests.rs @@ -45,7 +45,14 @@ fn encoded(bytes: &[u8]) -> String { /// The part file a write's first command names: the quoted `./...part` word. fn part_in(command: &str) -> String { - let end = command.find(".tmp'").expect("a part file") + ".tmp".len(); + // The part file's name carries a UUID; the stale-file sweep names a glob. + let marker = ".openhuman-"; + let name = command + .match_indices(marker) + .map(|(at, _)| at) + .find(|at| !command[at + marker.len()..].starts_with('*')) + .expect("a part file"); + let end = name + command[name..].find(".tmp'").expect("a part file") + ".tmp".len(); let start = command[..end].rfind("'./").expect("a quoted path") + 1; command[start..end].to_owned() } From 877a0be3487ebcb10f02f2fe6c0430555541c432 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 5 Nov 2026 21:42:26 +0000 Subject: [PATCH 35/37] fix(sandbox): narrow stale part-file sweep to transfer files The stale part-file glob now matches only the exact transfer naming pattern, and paths whose file name starts with the reserved transfer prefix are refused, so a user file that merely resembles a part file is never swept. Tests cover the new glob and the reserved-name rejection. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/sandbox/openshell/files.rs | 14 ++++++++-- .../src/sandbox/openshell/files_tests.rs | 27 +++++++++++++++---- 2 files changed, 34 insertions(+), 7 deletions(-) diff --git a/crates/openhuman-core/src/sandbox/openshell/files.rs b/crates/openhuman-core/src/sandbox/openshell/files.rs index 01773b79383..2c82abd92f3 100644 --- a/crates/openhuman-core/src/sandbox/openshell/files.rs +++ b/crates/openhuman-core/src/sandbox/openshell/files.rs @@ -64,7 +64,11 @@ const NOT_A_FILE_EXIT: i32 = 66; const STALE_PART_MINUTES: u32 = 60; /// The pattern every part file's name matches (see [`part_path`]). -const STALE_PART_GLOB: &str = ".openhuman-*.tmp"; +const STALE_PART_GLOB: &str = ".openhuman-transfer-????????????????????????????????.tmp"; + +/// The file-name prefix reserved for part files: a path naming one is refused, +/// so the stale sweep only ever meets files a transfer made. +const PART_PREFIX: &str = ".openhuman-transfer-"; /// The longest box message kept in an error. const DETAIL_MAX_CHARS: usize = 200; @@ -315,7 +319,7 @@ fn read_command(quoted: &str, identity: &str, start: usize, want: u64) -> String /// alone (not for the target, so a target name near the filesystem's 255-byte /// limit still stages) so no other file or transfer shares it. fn part_path(path: &str) -> String { - let name = format!(".openhuman-{}.tmp", uuid::Uuid::new_v4().simple()); + let name = format!("{PART_PREFIX}{}.tmp", uuid::Uuid::new_v4().simple()); match path.rsplit_once('/') { Some((folder, _)) => format!("{folder}/{name}"), None => name, @@ -340,6 +344,12 @@ fn check_path(path: &str) -> Result<(), BoxError> { "it must not contain `..`" } else if matches!(path.rsplit('/').next(), Some("" | ".")) { "it names a folder, not a file" + } else if path + .rsplit('/') + .next() + .is_some_and(|name| name.starts_with(PART_PREFIX)) + { + "that file name is reserved for transfers" } else { return Ok(()); }; diff --git a/crates/openhuman-core/src/sandbox/openshell/files_tests.rs b/crates/openhuman-core/src/sandbox/openshell/files_tests.rs index eede9ee1985..6f916edc3fe 100644 --- a/crates/openhuman-core/src/sandbox/openshell/files_tests.rs +++ b/crates/openhuman-core/src/sandbox/openshell/files_tests.rs @@ -46,7 +46,7 @@ fn encoded(bytes: &[u8]) -> String { /// The part file a write's first command names: the quoted `./...part` word. fn part_in(command: &str) -> String { // The part file's name carries a UUID; the stale-file sweep names a glob. - let marker = ".openhuman-"; + let marker = ".openhuman-transfer-"; let name = command .match_indices(marker) .map(|(at, _)| at) @@ -151,7 +151,7 @@ async fn a_small_file_is_one_command_that_writes_a_part_file_and_renames_it() { ); let part = part_in(&sent[0]); assert!( - part.starts_with("./out/.openhuman-") && part.ends_with(".tmp"), + part.starts_with("./out/.openhuman-transfer-") && part.ends_with(".tmp"), "{part}" ); assert!( @@ -643,12 +643,12 @@ mod on_a_real_shell { .unwrap(); let dir = driver.box_dir("box-0").unwrap().join("out"); let (old, fresh) = ( - dir.join(".openhuman-old.tmp"), - dir.join(".openhuman-new.tmp"), + dir.join(".openhuman-transfer-00000000000000000000000000000001.tmp"), + dir.join(".openhuman-transfer-00000000000000000000000000000002.tmp"), ); std::fs::write(&old, b"half").unwrap(); std::fs::write(&fresh, b"in flight").unwrap(); - let (_, _, code) = run_in(&dir, "touch -d '3 hours ago' .openhuman-old.tmp"); + let (_, _, code) = run_in(&dir, "touch -d '3 hours ago' .openhuman-transfer-00000000000000000000000000000001.tmp"); assert_eq!(code, 0); write_file_in(&boxes, Ok(embedded("u1")), &config(), "out/a.txt", b"y") @@ -660,6 +660,23 @@ mod on_a_real_shell { assert!(dir.join("a.txt").is_file()); } + #[tokio::test] + async fn a_user_file_that_only_looks_like_a_part_file_is_never_swept() { + let (_root, driver, boxes) = host_boxes(); + write_file_in(&boxes, Ok(embedded("u1")), &config(), "out/seed.txt", b"x") + .await + .unwrap(); + let dir = driver.box_dir("box-0").unwrap().join("out"); + std::fs::write(dir.join(".openhuman-report.tmp"), b"mine").unwrap(); + run_in(&dir, "touch -d '3 hours ago' .openhuman-report.tmp"); + + write_file_in(&boxes, Ok(embedded("u1")), &config(), "out/new.txt", b"y") + .await + .unwrap(); + + assert!(dir.join(".openhuman-report.tmp").exists()); + } + #[tokio::test] async fn a_file_named_dash_is_a_file_and_not_standard_input() { let (_root, _driver, boxes) = host_boxes(); From 3369e3a4c02d69d5968e1a58ee8fe6008ef65afd Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 5 Nov 2026 21:44:42 +0000 Subject: [PATCH 36/37] test(sandbox): cover refusal of transfer-reserved file names Adds a test asserting that reads and writes to a name reserved for transfers are rejected with an invalid-path error before the driver is invoked, and reformats an existing shell test call. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/sandbox/openshell/files_tests.rs | 27 ++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/crates/openhuman-core/src/sandbox/openshell/files_tests.rs b/crates/openhuman-core/src/sandbox/openshell/files_tests.rs index 6f916edc3fe..1ec1565c711 100644 --- a/crates/openhuman-core/src/sandbox/openshell/files_tests.rs +++ b/crates/openhuman-core/src/sandbox/openshell/files_tests.rs @@ -114,6 +114,28 @@ fn a_refused_path_says_what_to_use_instead() { ); } +#[tokio::test] +async fn a_name_reserved_for_transfers_is_refused_before_any_box_is_touched() { + let driver = ScriptedDriver::new(); + let boxes = registry(&driver); + let path = "out/.openhuman-transfer-0123.tmp"; + + let wrote = write_file_in(&boxes, Ok(embedded("u1")), &config(), path, b"x").await; + let read = read_file_in(&boxes, Ok(embedded("u1")), &config(), path, 10).await; + + let refusal = Err(BoxError::InvalidPath( + "that file name is reserved for transfers", + )); + assert_eq!(wrote, refusal); + assert_eq!( + read, + Err(BoxError::InvalidPath( + "that file name is reserved for transfers" + )) + ); + assert!(driver.calls().is_empty()); +} + #[tokio::test] async fn a_file_over_the_host_limit_is_refused_before_any_box_is_touched() { let driver = ScriptedDriver::new(); @@ -648,7 +670,10 @@ mod on_a_real_shell { ); std::fs::write(&old, b"half").unwrap(); std::fs::write(&fresh, b"in flight").unwrap(); - let (_, _, code) = run_in(&dir, "touch -d '3 hours ago' .openhuman-transfer-00000000000000000000000000000001.tmp"); + let (_, _, code) = run_in( + &dir, + "touch -d '3 hours ago' .openhuman-transfer-00000000000000000000000000000001.tmp", + ); assert_eq!(code, 0); write_file_in(&boxes, Ok(embedded("u1")), &config(), "out/a.txt", b"y") From a4f5d5f1dcdb54ba2c501c078cd15e23199fe520 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 5 Nov 2026 21:46:59 +0000 Subject: [PATCH 37/37] test(openshell): match part file marker against question mark The test helper now skips markers followed by a question mark instead of an asterisk, keeping the fixture parsing in line with the command format it exercises. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-core/src/sandbox/openshell/files_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/openhuman-core/src/sandbox/openshell/files_tests.rs b/crates/openhuman-core/src/sandbox/openshell/files_tests.rs index 1ec1565c711..8f7580e3d54 100644 --- a/crates/openhuman-core/src/sandbox/openshell/files_tests.rs +++ b/crates/openhuman-core/src/sandbox/openshell/files_tests.rs @@ -50,7 +50,7 @@ fn part_in(command: &str) -> String { let name = command .match_indices(marker) .map(|(at, _)| at) - .find(|at| !command[at + marker.len()..].starts_with('*')) + .find(|at| !command[at + marker.len()..].starts_with('?')) .expect("a part file"); let end = name + command[name..].find(".tmp'").expect("a part file") + ".tmp".len(); let start = command[..end].rfind("'./").expect("a quoted path") + 1;