diff --git a/crates/openhuman-core/src/artifacts/box_source.rs b/crates/openhuman-core/src/artifacts/box_source.rs index fbea09f49c7..a3f3c79fcf8 100644 --- a/crates/openhuman-core/src/artifacts/box_source.rs +++ b/crates/openhuman-core/src/artifacts/box_source.rs @@ -22,7 +22,7 @@ use std::sync::Arc; use async_trait::async_trait; use serde_json::Value; -use tiny_artifacts::{ArtifactKind, Artifacts}; +use tiny_artifacts::{ArtifactKind, Artifacts, FileStore}; use tinytools::{PermissionLevel, Tool, ToolResult}; use super::tiny_store::version_files_dir; @@ -253,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) { + let staged = match stage(&self.staging, &path, bytes).await { Ok(staged) => staged, Err(error) => { tracing::warn!(%error, "[artifacts] could not stage a sandbox file"); @@ -294,9 +294,23 @@ impl Drop for Staged { /// 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 { +/// The bytes go in through the artifact crate's [`FileStore`] port, like every +/// other artifact file, not a raw filesystem write. +/// +/// The write runs in a task of its own that finishes whether or not the caller +/// is still waiting. The [`Staged`] guard lives in that task, so a call +/// cancelled mid-write still has its folder removed, and only after the write +/// has settled (a removal racing the storage layer's directory creation could +/// otherwise leave the folder behind). +async fn stage(staging: &Path, box_path: &str, bytes: Vec) -> std::io::Result { + let staging = staging.to_path_buf(); + let box_path = box_path.to_owned(); + tokio::spawn(async move { stage_now(&staging, &box_path, &bytes).await }) + .await + .map_err(std::io::Error::other)? +} + +async fn stage_now(staging: &Path, box_path: &str, bytes: &[u8]) -> std::io::Result { let name = match Path::new(box_path) .extension() .and_then(|extension| extension.to_str()) @@ -308,11 +322,13 @@ fn stage(staging: &Path, box_path: &str, bytes: &[u8]) -> std::io::Result String { body["artifact_id"].as_str().unwrap().to_owned() } +/// Keeps the security module's path floor scripted for the test's lifetime +/// when that module is built; a build without it has no floor to script. +#[cfg(feature = "security-module")] +fn path_floor() -> Box { + Box::new(crate::modules::security::gap::install_path_floor_port( + crate::modules::security::gap::ScriptedPathFloorPort::new([], vec![]), + )) +} + +#[cfg(not(feature = "security-module"))] +fn path_floor() -> Box { + Box::new(()) +} + #[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 _floor = path_floor(); let fixture = Fixture::new(); let bytes: Vec = (0..=255u8).cycle().take(5000).collect(); fixture.the_box_holds(&bytes); @@ -208,9 +220,7 @@ async fn a_path_is_read_from_the_callers_box_when_the_backend_keeps_boxes() { #[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 _floor = path_floor(); let fixture = Fixture::new(); fixture.the_box_holds(b"pdf"); let tool = fixture.tool(true, user("u1")); @@ -240,9 +250,7 @@ async fn a_path_elsewhere_in_the_box_is_refused() { #[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 _floor = path_floor(); let fixture = Fixture::new(); std::fs::write(fixture.action.join("report.pdf"), b"host bytes").unwrap(); let tool = fixture.tool(false, user("u1")); @@ -258,9 +266,7 @@ async fn a_path_is_read_from_the_host_when_the_backend_keeps_no_boxes() { #[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 _floor = path_floor(); 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(); @@ -316,9 +322,7 @@ async fn a_call_with_no_tenant_is_refused_without_touching_a_box_or_the_host() { #[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 _floor = path_floor(); let fixture = Fixture::new(); let tool = fixture.tool(true, user("u1")); @@ -369,9 +373,7 @@ fn a_box_path_is_the_name_relative_to_the_work_folder() { #[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 _floor = path_floor(); let fixture = Fixture::new(); fixture.the_box_holds(b"first"); let id = created_id(&fixture.tool(true, user("u1")), file_args("a.pdf")).await; @@ -419,7 +421,9 @@ 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").unwrap(); + let staged = stage(staging.path(), "out/a.pdf", b"bytes".to_vec()) + .await + .unwrap(); let dir = staged.dir.clone(); assert!(dir.join("file.pdf").is_file()); @@ -432,9 +436,15 @@ async fn a_staged_copy_is_removed_when_its_call_is_dropped_before_it_finishes() 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(); + let odd = stage(staging.path(), "out/re?port*.pdf", b"x".to_vec()) + .await + .unwrap(); + let no_extension = stage(staging.path(), "out/Makefile", b"x".to_vec()) + .await + .unwrap(); + let hostile = stage(staging.path(), "out/a.p?f", b"x".to_vec()) + .await + .unwrap(); assert!(odd.file.ends_with("file.pdf")); assert!(no_extension.file.ends_with("file")); @@ -453,9 +463,7 @@ impl RecordKinds for BrokenRecords { #[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 _floor = path_floor(); let fixture = Fixture::new(); std::fs::write(fixture.action.join("a.pdf"), b"host bytes").unwrap(); let tool = fixture.update_tool(true, user("u1")); @@ -477,3 +485,19 @@ async fn an_update_whose_record_cannot_be_read_fails_instead_of_reading_the_host ); assert!(fixture.driver.calls().is_empty(), "no box was touched"); } + +#[tokio::test] +async fn a_call_cancelled_while_staging_leaves_no_copy_behind() { + let staging = tempfile::tempdir().unwrap(); + + // Poll the staging future once, so its write is started, then drop it. + tokio::select! { + biased; + _ = stage(staging.path(), "out/a.pdf", b"bytes".to_vec()) => unreachable!("staging cannot finish on its first poll"), + _ = std::future::ready(()) => {} + } + // The write finishes in its own task and its guard then removes the folder. + tokio::time::sleep(std::time::Duration::from_millis(500)).await; + + assert_eq!(std::fs::read_dir(staging.path()).unwrap().count(), 0); +} diff --git a/crates/openhuman-core/src/artifacts/tiny_store.rs b/crates/openhuman-core/src/artifacts/tiny_store.rs index 8cf92f66001..b8106a91ffd 100644 --- a/crates/openhuman-core/src/artifacts/tiny_store.rs +++ b/crates/openhuman-core/src/artifacts/tiny_store.rs @@ -30,13 +30,12 @@ use std::sync::Arc; use async_trait::async_trait; use tiny_artifacts::{ ArtifactEvent, ArtifactEventKind, ArtifactKind, ArtifactObserver, ArtifactRecord, - ArtifactStore, Artifacts, Author, Content, FileRef, FileStore, + ArtifactStore, Artifacts, FileRef, FileStore, }; use super::files::FileRoots; use super::types::ArtifactKind as LegacyArtifactKind; use crate::security::approval::ApprovalChatContext; -use crate::tools::per_call::{context as per_call_context, PerCallTool}; /// Subdirectory under the artifacts root holding versioned records. const VERSIONED_SUBDIR: &str = "versioned"; @@ -607,145 +606,9 @@ pub fn stored_file_path(workspace_dir: &Path, file: &tiny_artifacts::FileRef) -> version_files_dir(workspace_dir).join(&file.key) } -/// Build the artifact tools bound to this workspace's service: the crate's -/// default set (`create_artifact`, `read_artifact`, `update_artifact`, -/// `list_artifacts`), `delete_artifact` (default-off through its -/// `tools::user_filter` family), and — only when a `publisher` exists, i.e. the -/// user can use cloud file storage — `share_artifact`. -/// -/// The crate's tools run without a run context, so each call builds its tool -/// around a service whose UI bridge carries that call's chat routing -/// ([`PerCallTool`]); the card then reaches the chat the agent is answering. -pub fn registered_tools( - workspace_dir: &Path, - files: FileRoots, - action_dir: &Path, - publisher: Option, -) -> Vec> { - let can_publish = publisher.is_some(); - let service = { - let workspace_dir = workspace_dir.to_path_buf(); - let action_dir = action_dir.to_path_buf(); - Arc::new(move |chat: Option<&ApprovalChatContext>| { - Arc::new(artifacts_service_with_publisher( - &workspace_dir, - files.clone(), - Some(&action_dir), - chat, - publisher.as_ref(), - )) - }) - }; - let author = Author::agent(AGENT_AUTHOR_ID); - 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| { - 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(), - ) - }, - ))); - } - tools.push(Box::new(tiny_artifacts::ReadArtifactTool::new(service( - None, - )))); - { - 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| { - 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(), - ) - }, - ))); - } - tools.push(Box::new(tiny_artifacts::ListArtifactsTool::new(service( - None, - )))); - { - let service = service.clone(); - tools.push(Box::new(PerCallTool::new( - per_call_context, - move |context| tiny_artifacts::DeleteArtifactTool::new(service(context.chat.as_ref())), - ))); - } - if can_publish { - tools.push(Box::new(PerCallTool::new( - per_call_context, - move |context| tiny_artifacts::ShareArtifactTool::new(service(context.chat.as_ref())), - ))); - } - tools -} - -/// Author id stamped on versions the user writes in the desktop editor. -pub const OPERATOR_AUTHOR_ID: &str = "operator"; - -/// Author id stamped on versions OpenHuman's agent writes — through the -/// artifact tools and through producer tools alike. A tool run carries no -/// agent identity, so every agent-written version is attributed to this one. -pub const AGENT_AUTHOR_ID: &str = "openhuman"; - -/// Append the user's edit of artifact `id` as a new operator-authored version -/// (the preview panel's autosave). The UI bridge writes it to the files folder -/// and updates the card. A body identical to the newest version appends -/// nothing. -pub async fn save_operator_version( - workspace_dir: &Path, - files: FileRoots, - id: &str, - body: &str, - ctx: &crate::core::runtime::DispatchCtx, -) -> Result { - let saved = artifacts_service(workspace_dir, files, None, None, ctx) - .revise( - id, - Content::Text(body.to_string()), - &Author::operator(OPERATOR_AUTHOR_ID), - None, - ) - .await - .map_err(|e| e.to_string())?; - if let Some(notice) = &saved.notice { - tracing::warn!(target: "tiny-artifacts", artifact_id = %id, "[tiny-artifacts] {notice}"); - } - Ok(SavedVersion { - version: saved.version, - saved: saved.appended, - }) -} - -/// Result of [`save_operator_version`]. -#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)] -pub struct SavedVersion { - /// The newest version number after the call. - pub version: u32, - /// Whether a version was appended. - pub saved: bool, -} +#[path = "tiny_store_tools.rs"] +mod tools; +pub use tools::*; #[cfg(test)] #[path = "tiny_store_tests.rs"] diff --git a/crates/openhuman-core/src/artifacts/tiny_store_tools.rs b/crates/openhuman-core/src/artifacts/tiny_store_tools.rs new file mode 100644 index 00000000000..089420ded57 --- /dev/null +++ b/crates/openhuman-core/src/artifacts/tiny_store_tools.rs @@ -0,0 +1,158 @@ +//! The artifact tools and the operator-save entry point, split from +//! [`super`] (`tiny_store.rs`) to keep that file under the layout limit. +//! Re-exported there, so callers keep using `artifacts::tiny_store::*`. + +use std::path::Path; +use std::sync::Arc; + +use tiny_artifacts::{Author, Content}; + +use super::artifacts_service; +use super::artifacts_service_with_publisher; +use crate::artifacts::files::FileRoots; +use crate::security::approval::ApprovalChatContext; +use crate::tools::per_call::{context as per_call_context, PerCallTool}; + +/// Build the artifact tools bound to this workspace's service: the crate's +/// default set (`create_artifact`, `read_artifact`, `update_artifact`, +/// `list_artifacts`), `delete_artifact` (default-off through its +/// `tools::user_filter` family), and — only when a `publisher` exists, i.e. the +/// user can use cloud file storage — `share_artifact`. +/// +/// The crate's tools run without a run context, so each call builds its tool +/// around a service whose UI bridge carries that call's chat routing +/// ([`PerCallTool`]); the card then reaches the chat the agent is answering. +pub fn registered_tools( + workspace_dir: &Path, + files: FileRoots, + action_dir: &Path, + publisher: Option, +) -> Vec> { + let can_publish = publisher.is_some(); + let service = { + let workspace_dir = workspace_dir.to_path_buf(); + let action_dir = action_dir.to_path_buf(); + Arc::new(move |chat: Option<&ApprovalChatContext>| { + Arc::new(artifacts_service_with_publisher( + &workspace_dir, + files.clone(), + Some(&action_dir), + chat, + publisher.as_ref(), + )) + }) + }; + let author = Author::agent(AGENT_AUTHOR_ID); + let mut tools: Vec> = Vec::new(); + { + let (service, author) = (service.clone(), author.clone()); + let staging = crate::artifacts::box_source::staging_dir(workspace_dir); + tools.push(Box::new(PerCallTool::new( + per_call_context, + move |context| { + let create = tiny_artifacts::CreateArtifactTool::new( + service(context.chat.as_ref()), + author.clone(), + ); + let tenant = context.dispatch.tenant(); + crate::artifacts::box_source::BoxSourced::new( + create, + crate::artifacts::box_source::KindSource::Args, + Arc::new(crate::artifacts::box_source::SandboxBoxFiles::new( + context.dispatch, + )), + tenant, + staging.clone(), + ) + }, + ))); + } + tools.push(Box::new(tiny_artifacts::ReadArtifactTool::new(service( + None, + )))); + { + let (service, author) = (service.clone(), author.clone()); + let staging = crate::artifacts::box_source::staging_dir(workspace_dir); + tools.push(Box::new(PerCallTool::new( + per_call_context, + move |context| { + let artifacts = service(context.chat.as_ref()); + let update = + tiny_artifacts::UpdateArtifactTool::new(Arc::clone(&artifacts), author.clone()); + let tenant = context.dispatch.tenant(); + crate::artifacts::box_source::BoxSourced::new( + update, + crate::artifacts::box_source::KindSource::Record(artifacts), + Arc::new(crate::artifacts::box_source::SandboxBoxFiles::new( + context.dispatch, + )), + tenant, + staging.clone(), + ) + }, + ))); + } + tools.push(Box::new(tiny_artifacts::ListArtifactsTool::new(service( + None, + )))); + { + let service = service.clone(); + tools.push(Box::new(PerCallTool::new( + per_call_context, + move |context| tiny_artifacts::DeleteArtifactTool::new(service(context.chat.as_ref())), + ))); + } + if can_publish { + tools.push(Box::new(PerCallTool::new( + per_call_context, + move |context| tiny_artifacts::ShareArtifactTool::new(service(context.chat.as_ref())), + ))); + } + tools +} + +/// Author id stamped on versions the user writes in the desktop editor. +pub const OPERATOR_AUTHOR_ID: &str = "operator"; + +/// Author id stamped on versions OpenHuman's agent writes — through the +/// artifact tools and through producer tools alike. A tool run carries no +/// agent identity, so every agent-written version is attributed to this one. +pub const AGENT_AUTHOR_ID: &str = "openhuman"; + +/// Append the user's edit of artifact `id` as a new operator-authored version +/// (the preview panel's autosave). The UI bridge writes it to the files folder +/// and updates the card. A body identical to the newest version appends +/// nothing. +pub async fn save_operator_version( + workspace_dir: &Path, + files: FileRoots, + id: &str, + body: &str, + ctx: &crate::core::runtime::DispatchCtx, +) -> Result { + let saved = artifacts_service(workspace_dir, files, None, None, ctx) + .revise( + id, + Content::Text(body.to_string()), + &Author::operator(OPERATOR_AUTHOR_ID), + None, + ) + .await + .map_err(|e| e.to_string())?; + if let Some(notice) = &saved.notice { + tracing::warn!(target: "tiny-artifacts", artifact_id = %id, "[tiny-artifacts] {notice}"); + } + Ok(SavedVersion { + version: saved.version, + saved: saved.appended, + }) +} + +/// Result of [`save_operator_version`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)] +pub struct SavedVersion { + /// The newest version number after the call. + pub version: u32, + /// Whether a version was appended. + pub saved: bool, +} diff --git a/crates/openhuman-core/src/core/observability_reporting.rs b/crates/openhuman-core/src/core/observability_reporting.rs index 446e5f4046b..f24787849a9 100644 --- a/crates/openhuman-core/src/core/observability_reporting.rs +++ b/crates/openhuman-core/src/core/observability_reporting.rs @@ -532,9 +532,11 @@ const FS_ERROR_COOLDOWN: std::time::Duration = std::time::Duration::from_secs(30 /// unthrottled retry loops from flooding Sentry (TAURI-RUST-QT0: 6,050 events / /// 1 user). #[cfg(feature = "crash-reporting")] -static LAST_FS_LIMIT_REPORT: std::sync::LazyLock< - std::sync::Mutex>, -> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new())); +type FsLimitReports = + std::sync::Mutex>; + +#[cfg(feature = "crash-reporting")] +static LAST_FS_LIMIT_REPORT: std::sync::LazyLock = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new())); /// Returns `true` when `(kind, domain, operation)` was already reported /// within [`FS_ERROR_COOLDOWN`]. `kind` keeps the host-filesystem error diff --git a/crates/openhuman-core/src/sandbox/openshell/files.rs b/crates/openhuman-core/src/sandbox/openshell/files.rs index 2c82abd92f3..5294e93c9f5 100644 --- a/crates/openhuman-core/src/sandbox/openshell/files.rs +++ b/crates/openhuman-core/src/sandbox/openshell/files.rs @@ -384,3 +384,7 @@ fn failed_command(action: &'static str, path: &str, result: &SandboxExecResult) #[cfg(test)] #[path = "files_tests.rs"] mod tests; + +#[cfg(all(test, target_os = "linux"))] +#[path = "files_shell_tests.rs"] +mod on_a_real_shell; diff --git a/crates/openhuman-core/src/sandbox/openshell/files_shell_tests.rs b/crates/openhuman-core/src/sandbox/openshell/files_shell_tests.rs new file mode 100644 index 00000000000..1bca78e48aa --- /dev/null +++ b/crates/openhuman-core/src/sandbox/openshell/files_shell_tests.rs @@ -0,0 +1,422 @@ +//! Tests that run the transfer commands for real, in a directory standing in +//! for each box, so the quoting and the encoding are checked against a shell. + +use super::tests::*; +use super::*; +use crate::core::runtime::NoTenant; +use crate::sandbox::openshell::scripted_driver::{ExecStep, ScriptedDriver}; +use crate::sandbox::openshell::{BoxOutput, RegistryLimits}; +use std::sync::Arc; +use std::time::Duration; + +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/files_tests.rs b/crates/openhuman-core/src/sandbox/openshell/files_tests.rs index 8f7580e3d54..6e2ad5caf18 100644 --- a/crates/openhuman-core/src/sandbox/openshell/files_tests.rs +++ b/crates/openhuman-core/src/sandbox/openshell/files_tests.rs @@ -5,14 +5,14 @@ use crate::sandbox::openshell::{BoxOutput, RegistryLimits}; use std::sync::Arc; use std::time::Duration; -fn embedded(id: &str) -> Tenant { +pub(super) fn embedded(id: &str) -> Tenant { Tenant { profile: None, agent: Some(id.into()), } } -fn registry(driver: &Arc) -> Arc> { +pub(super) fn registry(driver: &Arc) -> Arc> { BoxRegistry::new( Arc::clone(driver), RegistryLimits { @@ -22,16 +22,16 @@ fn registry(driver: &Arc) -> Arc> { ) } -fn config() -> OpenShellRuntimeConfig { +pub(super) 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 { +pub(super) fn binary(len: usize) -> Vec { (0..len).map(|i| (i % 256) as u8).collect() } -fn reply(exit_code: i32, stdout: &str, stderr: &str) -> ExecStep { +pub(super) fn reply(exit_code: i32, stdout: &str, stderr: &str) -> ExecStep { ExecStep::Reply(BoxOutput { exit_code, stdout: stdout.as_bytes().to_vec(), @@ -39,12 +39,12 @@ fn reply(exit_code: i32, stdout: &str, stderr: &str) -> ExecStep { }) } -fn encoded(bytes: &[u8]) -> String { +pub(super) 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 { +pub(super) 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 @@ -58,7 +58,7 @@ fn part_in(command: &str) -> String { } /// The shell command of every exec the driver saw, in order. -fn commands(driver: &ScriptedDriver) -> Vec { +pub(super) fn commands(driver: &ScriptedDriver) -> Vec { driver .calls() .into_iter() @@ -437,422 +437,3 @@ async fn a_driver_failure_is_passed_through() { 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 5595a24510b..b461f0ed2ab 100644 --- a/crates/openhuman-core/src/sandbox/openshell/mod.rs +++ b/crates/openhuman-core/src/sandbox/openshell/mod.rs @@ -170,7 +170,7 @@ pub async fn write_file( path: &str, bytes: &[u8], ) -> Result<(), BoxError> { - let tenant = Ok(tenant_for_box(tenant)?); + let tenant: Result = Ok(tenant_for_box(tenant)?); #[cfg(feature = "modules")] { write_file_in( @@ -204,7 +204,7 @@ pub async fn read_file( path: &str, max_bytes: u64, ) -> Result, BoxError> { - let tenant = Ok(tenant_for_box(tenant)?); + let tenant: Result = Ok(tenant_for_box(tenant)?); #[cfg(feature = "modules")] { read_file_in( diff --git a/scripts/__tests__/stage-modules.test.mjs b/scripts/__tests__/stage-modules.test.mjs index 96aca5dec05..0314236a941 100644 --- a/scripts/__tests__/stage-modules.test.mjs +++ b/scripts/__tests__/stage-modules.test.mjs @@ -15,7 +15,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { createServer } from "node:http"; import { execFileSync } from "node:child_process"; -import { crc32, gzipSync } from "node:zlib"; +import { crc32, deflateRawSync, gzipSync } from "node:zlib"; import { test } from "node:test"; import { readRegistrySource } from "../ci/self-hosted/test-module-assets.mjs"; @@ -27,6 +27,7 @@ import { findWindowsVcRuntimeDir, hostKeyForTarget, extractWindowsZip, + extractZip, isWindowsHostKey, keepsArchive, normalizeStagedPermissions, @@ -494,25 +495,28 @@ test("stageWindowsAppLocalRuntime refuses a non-PE source file", () => { * CRC, while Windows `System.IO.Compression.ZipFile` tolerates it (which is * why an earlier revision passed on win32 and failed on every other CI leg). */ -function makeSingleEntryZip(entryPath, payload) { +function makeSingleEntryZip(entryPath, payload, { deflate = false } = {}) { const name = Buffer.from(entryPath); const payloadCrc = crc32(payload); + const uncompressed = payload.length; + if (deflate) payload = deflateRawSync(payload); const localHeader = Buffer.alloc(30); localHeader.writeUInt32LE(0x04034b50, 0); localHeader.writeUInt16LE(20, 4); localHeader.writeUInt16LE(0, 6); - localHeader.writeUInt16LE(0, 8); + localHeader.writeUInt16LE(deflate ? 8 : 0, 8); localHeader.writeUInt32LE(payloadCrc, 14); localHeader.writeUInt32LE(payload.length, 18); - localHeader.writeUInt32LE(payload.length, 22); + localHeader.writeUInt32LE(uncompressed, 22); localHeader.writeUInt16LE(name.length, 26); const central = Buffer.alloc(46); central.writeUInt32LE(0x02014b50, 0); central.writeUInt16LE(20, 4); central.writeUInt16LE(20, 6); + central.writeUInt16LE(deflate ? 8 : 0, 10); central.writeUInt32LE(payloadCrc, 16); central.writeUInt32LE(payload.length, 20); - central.writeUInt32LE(payload.length, 24); + central.writeUInt32LE(uncompressed, 24); central.writeUInt16LE(name.length, 28); const localSize = localHeader.length + name.length + payload.length; const end = Buffer.alloc(22); @@ -524,6 +528,47 @@ function makeSingleEntryZip(entryPath, payload) { return Buffer.concat([localHeader, name, payload, central, name, end]); } +// extractZip is what stages a `.zip` off Windows. It must not need an `unzip` +// binary (the CI image has none), and it must keep unzip's refusals. +function extractedFrom(entryPath, payload, options) { + const root = mkdtempSync(join(tmpdir(), "openhuman-extract-zip-")); + const archive = join(root, "a.zip"); + writeFileSync(archive, makeSingleEntryZip(entryPath, payload, options)); + const out = join(root, "out"); + mkdirSync(out); + return { root, archive, out }; +} + +test("extractZip extracts stored and deflated entries, including nested paths", () => { + for (const options of [{}, { deflate: true }]) { + const { archive, out } = extractedFrom("nested/demo.dll", Buffer.from("library bytes ".repeat(50)), options); + extractZip(archive, out); + assert.equal(readFileSync(join(out, "nested", "demo.dll"), "utf8"), "library bytes ".repeat(50)); + } +}); + +test("extractZip refuses an entry that would land outside the destination", () => { + for (const name of ["../escape.dll", "a/../../escape.dll", "/abs.dll", "a\\b.dll"]) { + const { root, archive, out } = extractedFrom(name, Buffer.from("x")); + assert.throws(() => extractZip(archive, out), /outside the destination/, name); + assert.ok(!existsSync(join(root, "escape.dll")), `${name} did not escape`); + } +}); + +test("extractZip refuses an entry whose bytes do not match its checksum", () => { + const { archive, out } = extractedFrom("demo.dll", Buffer.from("library bytes")); + const bytes = readFileSync(archive); + bytes[30 + "demo.dll".length] ^= 0xff; + writeFileSync(archive, bytes); + assert.throws(() => extractZip(archive, out), /checksum mismatch/); +}); + +test("extractZip refuses a file that is not a ZIP", () => { + const { archive, out } = extractedFrom("demo.dll", Buffer.from("x")); + writeFileSync(archive, "not a zip"); + assert.throws(() => extractZip(archive, out), /not a ZIP archive/); +}); + // stageModules asserts exactly one native library per archive. The staged VC // runtime files are also `.dll`s; they must not count toward that invariant or // every Windows module would fail the check. diff --git a/scripts/ci/agent-runtime-boundary-baseline.json b/scripts/ci/agent-runtime-boundary-baseline.json index 677f6d7ae75..6cf2e26fc03 100644 --- a/scripts/ci/agent-runtime-boundary-baseline.json +++ b/scripts/ci/agent-runtime-boundary-baseline.json @@ -2,7 +2,7 @@ { "rule": "openhuman-task-local", "path": "crates/openhuman-core/src/agent_runs/agent_chat/session_turn.rs", - "line": 695, + "line": 705, "text": "let run = crate::core::runtime::turn_origin::with_origin(", "occurrence": 1 }, @@ -16,7 +16,7 @@ { "rule": "openhuman-task-local", "path": "crates/openhuman-core/src/agent/bus.rs", - "line": 306, + "line": 307, "text": "let outcome = turn_origin::with_origin(", "occurrence": 1 }, @@ -37,21 +37,28 @@ { "rule": "openhuman-task-local", "path": "crates/openhuman-core/src/core/runtime/turn_origin.rs", - "line": 272, + "line": 294, "text": "Some(origin) => with_origin(origin, fut).await,", "occurrence": 1 }, { "rule": "openhuman-task-local", "path": "crates/openhuman-core/src/core/runtime/turn_origin.rs", - "line": 368, + "line": 390, "text": "pub fn current_request_id() -> Option {", "occurrence": 1 }, + { + "rule": "openhuman-task-local", + "path": "crates/openhuman-core/src/credentials/profiles/keychain.rs", + "line": 25, + "text": "tokio::task_local! {", + "occurrence": 1 + }, { "rule": "openhuman-task-local", "path": "crates/openhuman-core/src/cron/scheduler/agent_run.rs", - "line": 304, + "line": 343, "text": "crate::core::runtime::turn_origin::with_origin(origin, Box::pin(agent.run_single(prompt)));", "occurrence": 1 }, @@ -219,14 +226,14 @@ { "rule": "openhuman-task-local", "path": "crates/openhuman-core/src/web_chat/ops/system_turn.rs", - "line": 20, + "line": 21, "text": "use crate::core::runtime::turn_origin::{with_origin, AgentTurnOrigin};", "occurrence": 1 }, { "rule": "openhuman-task-local", "path": "crates/openhuman-core/src/web_chat/ops/system_turn.rs", - "line": 88, + "line": 131, "text": "let result = with_origin(origin, agent.run_single(prompt))", "occurrence": 1 }, @@ -240,7 +247,7 @@ { "rule": "openhuman-task-local", "path": "crates/openhuman-embed/src/turn_control.rs", - "line": 417, + "line": 420, "text": "openhuman_core::core::runtime::turn_origin::with_origin(origin, dispatch).await", "occurrence": 1 }, @@ -324,56 +331,56 @@ { "rule": "openhuman-upstream-reexport", "path": "crates/openhuman-embed/src/lib.rs", - "line": 87, + "line": 89, "text": "pub use tinyinference_llm::model::ReasoningEffort;", "occurrence": 1 }, { "rule": "openhuman-upstream-reexport", "path": "crates/openhuman-embed/src/lib.rs", - "line": 229, + "line": 232, "text": "pub use tinyagents_harness::host::{LearningSink, TurnSummary};", "occurrence": 1 }, { "rule": "openhuman-upstream-reexport", "path": "crates/openhuman-embed/src/lib.rs", - "line": 231, + "line": 234, "text": "pub use tinyagents_hooks::stop::BudgetStopHook;", "occurrence": 1 }, { "rule": "openhuman-upstream-reexport", "path": "crates/openhuman-embed/src/lib.rs", - "line": 232, + "line": 235, "text": "pub use tinyagents_hooks::stop::{StopDecision, StopHook};", "occurrence": 1 }, { "rule": "openhuman-upstream-reexport", "path": "crates/openhuman-embed/src/lib.rs", - "line": 233, + "line": 236, "text": "pub use tinyagents_hooks::tool::{", "occurrence": 1 }, { "rule": "openhuman-upstream-reexport", "path": "crates/openhuman-embed/src/lib.rs", - "line": 257, + "line": 260, "text": "pub use tinyagents_session::port::{AppendStore, Store, TurnStates};", "occurrence": 1 }, { "rule": "openhuman-upstream-reexport", "path": "crates/openhuman-embed/src/lib.rs", - "line": 260, + "line": 263, "text": "pub use tinyagents_session::port::{", "occurrence": 1 }, { "rule": "openhuman-upstream-reexport", "path": "crates/openhuman-embed/src/lib.rs", - "line": 265, + "line": 268, "text": "pub use tinyagents_session::port::{SessionStoreLease, SessionStoreLeaseError};", "occurrence": 1 }, @@ -709,7 +716,7 @@ { "rule": "tinyagents-tool-calling-facade", "path": "vendor/tinyagents/crates/tinyagents-harness/src/agent_loop/tools.rs", - "line": 2781, + "line": 2808, "text": "use tinytools_agent::repair::args;", "occurrence": 1 }, @@ -737,7 +744,7 @@ { "rule": "tinyagents-tool-calling-facade", "path": "vendor/tinyagents/crates/tinyagents-harness/src/lib.rs", - "line": 116, + "line": 118, "text": "pub use tinytools_agent;", "occurrence": 1 }, @@ -786,7 +793,7 @@ { "rule": "tinyagents-upstream-reexport", "path": "vendor/tinyagents/crates/tinyagents-harness/src/tool/discover/mod.rs", - "line": 35, + "line": 37, "text": "pub use tinytools::rank::{Bm25Index, tokenize};", "occurrence": 1 }, diff --git a/scripts/ci/ignored-test-baseline.json b/scripts/ci/ignored-test-baseline.json index 5750b1984d0..5653c6ba42d 100644 --- a/scripts/ci/ignored-test-baseline.json +++ b/scripts/ci/ignored-test-baseline.json @@ -2,10 +2,10 @@ "openhuman-app": 5, "openhuman-cli": 0, "openhuman-core": 9, - "openhuman-embed": 0, + "openhuman-embed": 2, "openhuman-modules-linked": 0, "openhuman-rpc": 0, "openhuman-tinyhumans": 0, "openhuman-tui": 0, - "tests": 24 + "tests": 33 } diff --git a/scripts/ci/process-statics.json b/scripts/ci/process-statics.json index edfbd350977..af045c54921 100644 --- a/scripts/ci/process-statics.json +++ b/scripts/ci/process-statics.json @@ -603,7 +603,7 @@ "file": "crates/openhuman-core/src/core/observability_reporting.rs", "scope": "", "name": "LAST_FS_LIMIT_REPORT", - "type": "std::sync::LazyLock>, >", + "type": "std::sync::LazyLock", "count": 1, "category": "A", "reason": "A process-wide rate limiter keyed by the content-free error kind, domain and operation names prevents repeated filesystem-limit reports from flooding observability. Entries older than the five-minute cooldown are pruned on every access, and the map stores no tenant or user data.", diff --git a/scripts/ci/saas-ambient-baseline.json b/scripts/ci/saas-ambient-baseline.json index 5ef9d42e587..29ad329e890 100644 --- a/scripts/ci/saas-ambient-baseline.json +++ b/scripts/ci/saas-ambient-baseline.json @@ -9,24 +9,31 @@ { "rule": "ambient-config", "path": "crates/openhuman-core/src/agent_registry/host_definition.rs", - "line": 247, + "line": 262, "text": "let config = crate::config::Config::load_or_init().await?;", "occurrence": 1 }, { "rule": "ambient-context", "path": "crates/openhuman-core/src/agent_registry/host_definition.rs", - "line": 338, + "line": 353, "text": "crate::core::runtime::CoreContext::current()", "occurrence": 1 }, { "rule": "bare-spawn", "path": "crates/openhuman-core/src/agent_runs/agent_chat/session_turn.rs", - "line": 681, + "line": 691, "text": "tokio::spawn(async move { while rx.recv().await.is_some() {} });", "occurrence": 1 }, + { + "rule": "bare-spawn", + "path": "crates/openhuman-core/src/artifacts/box_source.rs", + "line": 308, + "text": "tokio::spawn(async move { stage_now(&staging, &box_path, &bytes).await })", + "occurrence": 1 + }, { "rule": "home-dir", "path": "crates/openhuman-core/src/channels/host/adapters.rs", @@ -331,7 +338,7 @@ { "rule": "bare-spawn", "path": "crates/openhuman-core/src/core/runtime/turn_origin.rs", - "line": 360, + "line": 382, "text": "tokio::spawn(propagate(fut))", "occurrence": 1 }, @@ -352,7 +359,7 @@ { "rule": "bare-spawn", "path": "crates/openhuman-core/src/cron/scheduler/dispatcher.rs", - "line": 615, + "line": 642, "text": "Ok(tokio::spawn(work))", "occurrence": 1 }, @@ -415,15 +422,15 @@ { "rule": "home-dir", "path": "crates/openhuman-core/src/hooks/host.rs", - "line": 30, + "line": 31, "text": "HookEnvironment::new(PRODUCT_NAME, dirs::home_dir())", "occurrence": 1 }, { "rule": "bare-spawn", "path": "crates/openhuman-core/src/hooks/host.rs", - "line": 58, - "text": "let loaded = tokio::task::spawn_blocking(move || {", + "line": 150, + "text": "let mut loaded = tokio::task::spawn_blocking(move || {", "occurrence": 1 }, { @@ -632,7 +639,7 @@ { "rule": "bare-spawn", "path": "crates/openhuman-core/src/sandbox/native_jail.rs", - "line": 97, + "line": 130, "text": "tokio::spawn(async move {", "occurrence": 1 }, @@ -646,7 +653,7 @@ { "rule": "home-dir", "path": "crates/openhuman-core/src/security/policy/native_commands.rs", - "line": 317, + "line": 333, "text": "home_dir: dirs::home_dir(),", "occurrence": 1 }, @@ -891,21 +898,21 @@ { "rule": "ambient-config", "path": "crates/openhuman-core/src/threads/ops/support.rs", - "line": 19, + "line": 20, "text": "Config::load_or_init()", "occurrence": 1 }, { "rule": "bare-spawn", "path": "crates/openhuman-core/src/threads/ops/support.rs", - "line": 137, + "line": 138, "text": "tokio::spawn(async move {", "occurrence": 1 }, { "rule": "ambient-config", "path": "crates/openhuman-core/src/threads/ops/title_generation.rs", - "line": 51, + "line": 54, "text": "let config = Config::load_or_init()", "occurrence": 1 }, diff --git a/scripts/release/stage-modules.mjs b/scripts/release/stage-modules.mjs index 45391f49fd5..8be3b2667ca 100644 --- a/scripts/release/stage-modules.mjs +++ b/scripts/release/stage-modules.mjs @@ -31,7 +31,8 @@ import { rmSync, writeFileSync, } from "node:fs"; -import { dirname, join, resolve } from "node:path"; +import { dirname, join, resolve, sep } from "node:path"; +import { crc32, inflateRawSync } from "node:zlib"; import { fileURLToPath } from "node:url"; import { parseAllList, parseRecords } from "../lib/module-pins.mjs"; @@ -507,11 +508,88 @@ export function extractWindowsZip(archive, dir) { ); } +/** + * Extract a ZIP into `dir` with Node alone, so staging a `.zip` on Linux or + * macOS needs no `unzip` binary (the CI image does not ship one). Handles the + * stored and deflate methods, verifies each entry's CRC-32, and refuses + * encrypted or ZIP64 archives, symlink entries, and any entry that would land + * outside `dir` (absolute paths, `..` segments, backslash separators). + */ +export function extractZip(archive, dir) { + const zip = readFileSync(archive); + let eocd = -1; + for (let i = zip.length - 22; i >= Math.max(0, zip.length - 22 - 0xffff); i--) { + if (zip.readUInt32LE(i) === 0x06054b50) { + eocd = i; + break; + } + } + if (eocd < 0) throw new Error(`${archive}: not a ZIP archive (no end-of-central-directory)`); + const count = zip.readUInt16LE(eocd + 10); + let cursor = zip.readUInt32LE(eocd + 16); + if (count === 0xffff || cursor === 0xffffffff) { + throw new Error(`${archive}: ZIP64 archives are not supported`); + } + const root = resolve(dir); + for (let n = 0; n < count; n++) { + if (zip.readUInt32LE(cursor) !== 0x02014b50) { + throw new Error(`${archive}: corrupt central directory`); + } + const flags = zip.readUInt16LE(cursor + 8); + const method = zip.readUInt16LE(cursor + 10); + const crc = zip.readUInt32LE(cursor + 16); + const compressedSize = zip.readUInt32LE(cursor + 20); + const size = zip.readUInt32LE(cursor + 24); + const nameLength = zip.readUInt16LE(cursor + 28); + const extraLength = zip.readUInt16LE(cursor + 30); + const commentLength = zip.readUInt16LE(cursor + 32); + const mode = zip.readUInt32LE(cursor + 38) >>> 16; + const localOffset = zip.readUInt32LE(cursor + 42); + const name = zip.toString("utf8", cursor + 46, cursor + 46 + nameLength); + cursor += 46 + nameLength + extraLength + commentLength; + + const segments = name.split("/"); + if ( + name.includes("\\") || + name.startsWith("/") || + /^[A-Za-z]:/.test(name) || + segments.includes("..") + ) { + throw new Error(`${archive}: refusing entry outside the destination: ${name}`); + } + const target = resolve(root, name); + if (target !== root && !target.startsWith(root + sep)) { + throw new Error(`${archive}: refusing entry outside the destination: ${name}`); + } + if (name.endsWith("/")) { + mkdirSync(target, { recursive: true }); + continue; + } + if (flags & 1) throw new Error(`${archive}: encrypted entry ${name}`); + if ((mode & 0o170000) === 0o120000) throw new Error(`${archive}: symlink entry ${name}`); + if (zip.readUInt32LE(localOffset) !== 0x04034b50) { + throw new Error(`${archive}: corrupt local header for ${name}`); + } + const dataStart = + localOffset + 30 + zip.readUInt16LE(localOffset + 26) + zip.readUInt16LE(localOffset + 28); + const raw = zip.subarray(dataStart, dataStart + compressedSize); + let bytes; + if (method === 0) bytes = raw; + else if (method === 8) bytes = inflateRawSync(raw); + else throw new Error(`${archive}: unsupported compression method ${method} for ${name}`); + if (bytes.length !== size || crc32(bytes) !== crc) { + throw new Error(`${archive}: checksum mismatch for ${name}`); + } + mkdirSync(dirname(target), { recursive: true }); + writeFileSync(target, bytes); + } +} + /** Extract `archive` into `dir`; GNU and BSD tar both refuse `..` entries. */ export function extractArchive(archive, dir) { if (archive.endsWith(".zip")) { if (process.platform === "win32") return extractWindowsZip(archive, dir); - execFileSync("unzip", ["-q", "-o", archive, "-d", dir], { stdio: "pipe" }); + extractZip(archive, dir); return; } execFileSync("tar", ["-xzf", archive, "-C", dir], { stdio: "pipe" });