diff --git a/crates/openhuman-core/src/artifacts/README.md b/crates/openhuman-core/src/artifacts/README.md index 83d53a8a43c..aaa9fcd8209 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) | `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]`). | 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..fbea09f49c7 --- /dev/null +++ b/crates/openhuman-core/src/artifacts/box_source.rs @@ -0,0 +1,321 @@ +//! `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. [`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 +//! [`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, Artifacts}; +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. + /// + /// # 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( + &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) -> 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( + &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 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), +} + +/// 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 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: impl Tool + 'static, + kinds: KindSource, + boxes: Arc, + tenant: Result, + staging: PathBuf, + ) -> Self { + Self { + inner: Box::new(inner), + kinds, + boxes, + tenant, + staging, + } + } + + /// The kind of artifact this call writes, when it can be told. + /// + /// # 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 => 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 + .map_err(|error| BoxError::Driver(format!("cannot read the artifact: {error}"))) + } + } + } + + /// 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.) + /// + /// # Errors + /// + /// 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 { + return Ok(None); + }; + if !kind.holds_file() { + 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()); + let Some(path) = path else { + return Ok(None); + }; + Ok(self + .boxes + .keeps_boxes() + .await? + .then(|| box_path(path).to_owned())) + } +} + +#[async_trait] +impl Tool for BoxSourced { + 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 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 + .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) { + 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()); + // `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. 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) { + 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`, 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()); + 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)] +#[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 new file mode 100644 index 00000000000..fce67169b90 --- /dev/null +++ b/crates/openhuman-core/src/artifacts/box_source_tests.rs @@ -0,0 +1,479 @@ +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, 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. +struct ScriptedBoxes { + /// `None`: the configuration cannot be read. + keeps: Option, + registry: Arc>, +} + +#[async_trait] +impl BoxFiles for ScriptedBoxes { + async fn keeps_boxes(&self) -> Result { + self.keeps + .ok_or_else(|| BoxError::Driver("cannot read the configuration: unreadable".into())) + } + + 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) -> BoxSourced { + self.tool_with(Some(keeps), tenant) + } + + 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, + 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, + }, + ); + 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. + fn the_box_holds(&self, bytes: &[u8]) { + self.driver.then(ExecStep::Reply(BoxOutput { + exit_code: 0, + stdout: format!("{} 1:2:3\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: &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(); + 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 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); + assert!( + result.output().contains("cannot read the configuration"), + "{}", + result.output() + ); + 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"); +} + +#[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").unwrap(); + let dir = staged.dir.clone(); + 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/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..8cf92f66001 100644 --- a/crates/openhuman-core/src/artifacts/tiny_store.rs +++ b/crates/openhuman-core/src/artifacts/tiny_store.rs @@ -640,12 +640,21 @@ 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::BoxSourced::new( + create, + super::box_source::KindSource::Args, + Arc::new(super::box_source::SandboxBoxFiles::new(context.dispatch)), + tenant, + staging.clone(), ) }, ))); @@ -655,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(), ) }, ))); diff --git a/crates/openhuman-core/src/sandbox/README.md b/crates/openhuman-core/src/sandbox/README.md index 1fc824d9bf7..400c9f323a2 100644 --- a/crates/openhuman-core/src/sandbox/README.md +++ b/crates/openhuman-core/src/sandbox/README.md @@ -20,6 +20,43 @@ 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 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 >> `; + 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 `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). 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. +- 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/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.rs b/crates/openhuman-core/src/sandbox/openshell/files.rs new file mode 100644 index 00000000000..2c82abd92f3 --- /dev/null +++ b/crates/openhuman-core/src/sandbox/openshell/files.rs @@ -0,0 +1,386 @@ +//! 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 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 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; 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 +//! 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. + +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; + +/// 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-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; + +/// 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 = part_path(path); + 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(&relative(&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(&relative(path)); + let sized = target + .run(&format!( + "test -f {quoted} || exit {NOT_A_FILE_EXIT}; {GUARD} \ + inside \"$(realpath -- {quoted})\"; stat -L -c '%s %d:%i:%y:%z' -- {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 unreported = || BoxError::FileTransfer { + action: "read", + path: path.to_owned(), + detail: "the sandbox did not report the file's size".to_owned(), + }; + // 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 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 }); + } + + 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 = 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)); + } + 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 + } +} + +/// 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, + chunk: &[u8], + index: usize, + count: usize, + 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 encoded = base64::engine::general_purpose::STANDARD.encode(chunk); + let last = index + 1 == count; + let mut command = String::new(); + 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 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})\"; \ + 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 { + 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!( + "; 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" + )); + } + 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 -L -c '%d:%i:%y:%z' -- {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 +/// 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!("{PART_PREFIX}{}.tmp", uuid::Uuid::new_v4().simple()); + match path.rsplit_once('/') { + Some((folder, _)) => format!("{folder}/{name}"), + None => name, + } +} + +/// `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() { + "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 if path + .rsplit('/') + .next() + .is_some_and(|name| name.starts_with(PART_PREFIX)) + { + "that file name is reserved for transfers" + } 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 new file mode 100644 index 00000000000..8f7580e3d54 --- /dev/null +++ b/crates/openhuman-core/src/sandbox/openshell/files_tests.rs @@ -0,0 +1,858 @@ +use super::*; +use crate::core::runtime::NoTenant; +use crate::sandbox::openshell::scripted_driver::{Call, ExecStep, ScriptedDriver}; +use crate::sandbox::openshell::{BoxOutput, RegistryLimits}; +use std::sync::Arc; +use std::time::Duration; + +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 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-transfer-"; + 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() +} + +/// 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_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(); + 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] + ); + let part = part_in(&sent[0]); + assert!( + part.starts_with("./out/.openhuman-transfer-") && part.ends_with(".tmp"), + "{part}" + ); + assert!( + sent[0].contains(&format!("mv -f -- '{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. + 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")); +} + +#[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], format!("rm -f -- '{}'", part_in(&sent[0]))); +} + +#[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 1:2:3\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!("{} 1:2:3\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 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; + + 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 1:2:3\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 1:2:3\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 1:2:3\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); + let left: Vec<_> = std::fs::read_dir(driver.box_dir("box-0").unwrap().join("work")) + .unwrap() + .map(|entry| entry.unwrap().file_name()) + .collect(); + assert_eq!(left, ["out.bin"], "no part file is left behind"); + } + + #[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_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()); + } + + #[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_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"the real bytes of the target", + ) + .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"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-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-transfer-00000000000000000000000000000001.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_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(); + + 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 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])); + } + + #[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 cfg = config(); + let (first, second) = tokio::join!( + 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(); + 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 -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")); + + // 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}"); + } + + #[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") + .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), + ) + } +} diff --git a/crates/openhuman-core/src/sandbox/openshell/mod.rs b/crates/openhuman-core/src/sandbox/openshell/mod.rs index c3f4d382a47..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 @@ -25,6 +29,7 @@ #[cfg(feature = "modules")] mod bus_driver; +mod files; mod registry; mod types; @@ -34,7 +39,9 @@ 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(crate) use registry::BOX_WORKDIR; pub use types::{BoxDriver, BoxError, BoxExec, BoxOutput, BoxRequest, BoxSettings, RegistryLimits}; use super::types::SandboxExecResult; @@ -149,6 +156,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)); +} 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, + }) +} 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), diff --git a/crates/openhuman-core/src/sandbox/ops.rs b/crates/openhuman-core/src/sandbox/ops.rs index 98c8ffae0de..79d2906f212 100644 --- a/crates/openhuman-core/src/sandbox/ops.rs +++ b/crates/openhuman-core/src/sandbox/ops.rs @@ -10,9 +10,13 @@ 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}; +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/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/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)] 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:?}"); + } +} 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..dbbe4989cac 100644 --- a/crates/openhuman-embed/tests/facades.rs +++ b/crates/openhuman-embed/tests/facades.rs @@ -11,6 +11,7 @@ use openhuman_embed::chat_surface::{ publish_web_channel_event, subscribe_web_channel_events, WebChannelEvent, WebEventContext, }; 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() { @@ -166,3 +167,20 @@ 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)); +}