diff --git a/Cargo.lock b/Cargo.lock index a994e30bdfe..2c4b534af44 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5736,7 +5736,7 @@ dependencies = [ "tinyagents-session", "tinyagents-storage-kit", "tinyagents-tasks", - "tinybox-bus 0.2.5", + "tinybox-bus 0.2.6", "tinybus", "tinybus-module", "tinychannels", @@ -9271,7 +9271,7 @@ dependencies = [ [[package]] name = "tinybox-agent37" -version = "0.2.5" +version = "0.2.6" dependencies = [ "async-trait", "base64 0.22.1", @@ -9279,6 +9279,7 @@ dependencies = [ "serde", "serde_json", "tinybox-core", + "tokio", ] [[package]] @@ -9291,7 +9292,7 @@ dependencies = [ [[package]] name = "tinybox-bus" -version = "0.2.5" +version = "0.2.6" dependencies = [ "schemars", "serde", @@ -9300,22 +9301,22 @@ dependencies = [ [[package]] name = "tinybox-core" -version = "0.2.5" +version = "0.2.6" dependencies = [ "async-trait", "serde", "thiserror 2.0.21", - "tinybox-bus 0.2.5", + "tinybox-bus 0.2.6", ] [[package]] name = "tinybox-docker" -version = "0.2.5" +version = "0.2.6" dependencies = [ "async-trait", "ipnet", "serde_json", - "sha2 0.10.9", + "sha2 0.11.1", "tempfile", "tinybox-core", "tokio", @@ -9324,12 +9325,12 @@ dependencies = [ [[package]] name = "tinybox-drivers" -version = "0.2.5" +version = "0.2.6" dependencies = [ "log", "serde", "serde_json", - "tinybox-bus 0.2.5", + "tinybox-bus 0.2.6", "tinybox-core", "tinybox-jail", "tinystoragedrivers-api", @@ -9339,7 +9340,7 @@ dependencies = [ [[package]] name = "tinybox-host" -version = "0.2.5" +version = "0.2.6" dependencies = [ "async-trait", "cap-std", @@ -9347,7 +9348,7 @@ dependencies = [ "futures-timer", "futures-util", "nix 0.31.3", - "tinybox-bus 0.2.5", + "tinybox-bus 0.2.6", "tinybox-core", "tinybox-jail", "tokio", @@ -9355,13 +9356,13 @@ dependencies = [ [[package]] name = "tinybox-jail" -version = "0.2.5" +version = "0.2.6" dependencies = [ "landlock", "log", "serde", "serde_json", - "tinybox-bus 0.2.5", + "tinybox-bus 0.2.6", "tinybox-core", "tinybox-linux", "windows-sys 0.61.2", @@ -9369,7 +9370,7 @@ dependencies = [ [[package]] name = "tinybox-linux" -version = "0.2.5" +version = "0.2.6" dependencies = [ "async-trait", "tinybox-core", @@ -9377,7 +9378,7 @@ dependencies = [ [[package]] name = "tinybox-microvm" -version = "0.2.5" +version = "0.2.6" dependencies = [ "async-trait", "serde", @@ -9387,13 +9388,13 @@ dependencies = [ [[package]] name = "tinybox-module" -version = "0.2.5" +version = "0.2.6" dependencies = [ "log", "nix 0.31.3", "tempfile", "tinybox-agent37", - "tinybox-bus 0.2.5", + "tinybox-bus 0.2.6", "tinybox-core", "tinybox-docker", "tinybox-drivers", @@ -9414,17 +9415,17 @@ dependencies = [ [[package]] name = "tinybox-openshell" -version = "0.2.5" +version = "0.2.6" dependencies = [ "async-trait", "serde_json", - "sha2 0.10.9", + "sha2 0.11.1", "tinybox-core", ] [[package]] name = "tinybox-ssh" -version = "0.2.5" +version = "0.2.6" dependencies = [ "async-trait", "tinybox-core", diff --git a/crates/openhuman-app/Cargo.lock b/crates/openhuman-app/Cargo.lock index 057bd9cd1b9..3eed9fa6fd3 100644 --- a/crates/openhuman-app/Cargo.lock +++ b/crates/openhuman-app/Cargo.lock @@ -7821,7 +7821,7 @@ dependencies = [ [[package]] name = "tinybox-bus" -version = "0.2.5" +version = "0.2.6" dependencies = [ "schemars 1.2.3", "serde", diff --git a/crates/openhuman-app/src/gateway/provision.rs b/crates/openhuman-app/src/gateway/provision.rs index 6c2ce979d37..0ef97f74750 100644 --- a/crates/openhuman-app/src/gateway/provision.rs +++ b/crates/openhuman-app/src/gateway/provision.rs @@ -194,6 +194,7 @@ pub(super) fn create_request( resources: contract::ResourceLimits::default(), ports, env: env.clone(), + retention: None, } } diff --git a/crates/openhuman-core/src/artifacts/box_source.rs b/crates/openhuman-core/src/artifacts/box_source.rs index 08ddf36f677..240b2fcbbc4 100644 --- a/crates/openhuman-core/src/artifacts/box_source.rs +++ b/crates/openhuman-core/src/artifacts/box_source.rs @@ -1,13 +1,13 @@ //! `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 +//! With a backend that keeps one box per tenant (`openshell`, `agent37`; 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`]) and hands the bytes +//! caller's box ([`crate::sandbox::boxes::read_file`]) and hands the bytes //! to the crate's tool in memory ([`Content::Bytes`]), with the box file's name //! for its extension. Nothing is written to the host on the way. Everything //! after that is [`create_artifact`](tiny_artifacts::CreateArtifactTool) as @@ -25,20 +25,20 @@ use tiny_artifacts::{ArtifactKind, Artifacts, Content, CreateArtifactTool, Updat use tinytools::{PermissionLevel, Tool, ToolResult}; use crate::core::runtime::{DispatchCtx, NoTenant, Tenant}; -use crate::sandbox::openshell::BoxError; +use crate::sandbox::boxes::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. + /// The work folder of this call's box when its sandbox keeps a box per + /// tenant, so a file `path` names a file in it; `None` when it keeps none. /// /// # 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; + async fn work_folder(&self) -> Result, BoxError>; /// The file at `path` in `tenant`'s box. async fn read( @@ -62,12 +62,12 @@ impl SandboxBoxFiles { #[async_trait] impl BoxFiles for SandboxBoxFiles { - async fn keeps_boxes(&self) -> Result { + async fn work_folder(&self) -> Result, BoxError> { 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)) + Ok(crate::sandbox::ops::sandbox_box_workdir(&self.ctx, &config)) } async fn read( @@ -76,7 +76,7 @@ impl BoxFiles for SandboxBoxFiles { path: &str, max_bytes: u64, ) -> Result, BoxError> { - let tenant = crate::sandbox::openshell::tenant_for_box(tenant)?; + let tenant = crate::sandbox::boxes::tenant_for_box(tenant)?; let config = self.ctx.load_config().await.map_err(|error| { BoxError::Driver(format!("cannot read the configuration: {error}")) @@ -116,10 +116,9 @@ impl BytesTool for UpdateArtifactTool { } } -/// `path` as a name relative to the box's work folder: an agent in the box +/// `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; +fn box_path<'a>(path: &'a str, work_folder: &str) -> &'a str { path.strip_prefix(work_folder) .and_then(|rest| rest.strip_prefix('/')) .filter(|rest| !rest.is_empty()) @@ -230,9 +229,9 @@ impl BoxSourced { }; Ok(self .boxes - .keeps_boxes() + .work_folder() .await? - .then(|| box_path(path).to_owned())) + .map(|work_folder| box_path(path, work_folder).to_owned())) } } diff --git a/crates/openhuman-core/src/artifacts/box_source_tests.rs b/crates/openhuman-core/src/artifacts/box_source_tests.rs index 3f4f6ac741d..1e2a6b9c8e8 100644 --- a/crates/openhuman-core/src/artifacts/box_source_tests.rs +++ b/crates/openhuman-core/src/artifacts/box_source_tests.rs @@ -1,10 +1,9 @@ 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 crate::sandbox::boxes::scripted_driver::{Call, ExecStep, ScriptedDriver}; +use crate::sandbox::boxes::{read_file_in, BoxOutput, BoxRegistry, BoxSettings, RegistryLimits}; use base64::Engine as _; use serde_json::{json, Value}; use std::path::PathBuf; @@ -33,8 +32,9 @@ struct ScriptedBoxes { #[async_trait] impl BoxFiles for ScriptedBoxes { - async fn keeps_boxes(&self) -> Result { + async fn work_folder(&self) -> Result, BoxError> { self.keeps + .map(|keeps| keeps.then_some("/sandbox")) .ok_or_else(|| BoxError::Driver("cannot read the configuration: unreadable".into())) } @@ -47,7 +47,8 @@ impl BoxFiles for ScriptedBoxes { read_file_in( &self.registry, tenant, - &OpenShellRuntimeConfig::default(), + &BoxSettings::from_config(&crate::config::OpenShellRuntimeConfig::default()) + .expect("the default OpenShell settings are valid"), path, max_bytes, ) @@ -115,6 +116,7 @@ impl Fixture { RegistryLimits { idle_ttl: Duration::from_secs(900), max_live: 10, + retain: None, }, ); let service = Arc::new(service); @@ -378,10 +380,29 @@ async fn the_tool_keeps_the_artifact_tools_name_and_schema() { #[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"); + assert_eq!(box_path("report.pdf", "/sandbox"), "report.pdf"); + assert_eq!( + box_path("/sandbox/out/report.pdf", "/sandbox"), + "out/report.pdf" + ); + assert_eq!( + box_path("/sandboxed/report.pdf", "/sandbox"), + "/sandboxed/report.pdf" + ); + assert_eq!(box_path("/sandbox", "/sandbox"), "/sandbox"); +} + +#[test] +fn an_agent37_box_path_is_relative_to_its_home() { + assert_eq!( + box_path("/home/node/out/report.pdf", "/home/node"), + "out/report.pdf" + ); + // Another backend's work folder is just an absolute path here. + assert_eq!( + box_path("/sandbox/out/report.pdf", "/home/node"), + "/sandbox/out/report.pdf" + ); } #[tokio::test] diff --git a/crates/openhuman-core/src/config/schema/runtime_agent37.rs b/crates/openhuman-core/src/config/schema/runtime_agent37.rs index 641a4aee600..fce762b0b10 100644 --- a/crates/openhuman-core/src/config/schema/runtime_agent37.rs +++ b/crates/openhuman-core/src/config/schema/runtime_agent37.rs @@ -16,6 +16,17 @@ //! memory above 32 GiB gets the largest shape. These settings are therefore a //! request, not a hard ceiling or floor, which is why the sandbox reports them //! as best effort. The defaults ask for agent37's smallest shape. +//! +//! Each tenant keeps one box between commands, so the files it makes are +//! there for the next command, even after this process restarts. A box falls +//! asleep after `idle_sleep_secs` without a command (clamped to 300–86400, the +//! range agent37 accepts) and wakes on the next one; it is deleted once it has +//! slept for `delete_after_secs`. `max_live` caps the boxes this process holds +//! a handle on at once; letting go of a handle leaves the box asleep, not +//! gone. The sleep delay and the cap are read when the first box is needed, +//! so changing them takes effect on the next core start. Hosts sharing one +//! agent37 workspace should agree on `delete_after_secs`: expiry applies it to +//! every retained box the service lists. use schemars::JsonSchema; use serde::{Deserialize, Serialize}; @@ -41,6 +52,16 @@ pub const MAX_AGENT37_CPU_MILLIS: u32 = 4_000; /// Memory of agent37's largest instance shape, in mebibytes: 32 GiB. pub const MAX_AGENT37_MEMORY_MB: u64 = 32_768; +/// Default seconds a box may sit idle before it falls asleep: agent37's own +/// default of 15 minutes. +pub const DEFAULT_AGENT37_IDLE_SLEEP_SECS: u32 = 900; + +/// Default seconds a box may sleep before it is deleted: 30 days. +pub const DEFAULT_AGENT37_DELETE_AFTER_SECS: u64 = 30 * 24 * 60 * 60; + +/// Default most boxes this process holds a handle on at once. +pub const DEFAULT_AGENT37_MAX_LIVE: usize = 50; + /// `[runtime.agent37]`: what each agent37 box is created from and with. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] #[serde(default)] @@ -56,6 +77,15 @@ pub struct Agent37RuntimeConfig { /// and snaps the request up to the smallest that covers it, capping it at /// 32 GiB, so this is best effort. pub memory_mb: u64, + /// Seconds a box may sit idle before it falls asleep (it wakes on the next + /// command). Clamped to 300–86400, the range agent37 accepts. + pub idle_sleep_secs: u32, + /// Seconds a box may stay asleep before it is deleted, with its files. + /// Zero is raised to 1. + pub delete_after_secs: u64, + /// The most boxes this process holds a handle on at once. A box let go of + /// to make room is left asleep, not deleted. + pub max_live: usize, } impl Agent37RuntimeConfig { @@ -78,6 +108,9 @@ impl Default for Agent37RuntimeConfig { template: DEFAULT_AGENT37_TEMPLATE.to_owned(), cpu_millis: DEFAULT_AGENT37_CPU_MILLIS, memory_mb: DEFAULT_AGENT37_MEMORY_MB, + idle_sleep_secs: DEFAULT_AGENT37_IDLE_SLEEP_SECS, + delete_after_secs: DEFAULT_AGENT37_DELETE_AFTER_SECS, + max_live: DEFAULT_AGENT37_MAX_LIVE, } } } diff --git a/crates/openhuman-core/src/config/schema/runtime_agent37_tests.rs b/crates/openhuman-core/src/config/schema/runtime_agent37_tests.rs index fb917a12333..916b1629198 100644 --- a/crates/openhuman-core/src/config/schema/runtime_agent37_tests.rs +++ b/crates/openhuman-core/src/config/schema/runtime_agent37_tests.rs @@ -80,3 +80,23 @@ fn only_a_request_above_the_largest_shape_exceeds_it() { }; assert!(too_much_memory.exceeds_largest_shape()); } + +#[test] +fn boxes_sleep_after_fifteen_idle_minutes_and_go_after_thirty_days_asleep() { + let config = Agent37RuntimeConfig::default(); + assert_eq!(config.idle_sleep_secs, 900); + assert_eq!(config.delete_after_secs, 30 * 24 * 60 * 60); + assert_eq!(config.max_live, 50); +} + +#[test] +fn retention_settings_are_read_from_the_table() { + let config: Agent37RuntimeConfig = + toml::from_str("idle_sleep_secs = 600\ndelete_after_secs = 86400\nmax_live = 7") + .expect("parses"); + assert_eq!(config.idle_sleep_secs, 600); + assert_eq!(config.delete_after_secs, 86_400); + assert_eq!(config.max_live, 7); + // Unset fields keep their defaults. + assert_eq!(config.template, DEFAULT_AGENT37_TEMPLATE); +} diff --git a/crates/openhuman-core/src/config/schema/security.rs b/crates/openhuman-core/src/config/schema/security.rs index 7b960944b4f..b4f894b3bb3 100644 --- a/crates/openhuman-core/src/config/schema/security.rs +++ b/crates/openhuman-core/src/config/schema/security.rs @@ -47,8 +47,9 @@ pub enum SandboxBackend { /// the TinyBox module (`[runtime.openshell]`). #[serde(rename = "openshell")] OpenShell, - /// A box per command on the hosted agent37 HTTP sandbox service, through - /// the TinyBox module (`[runtime.agent37]`). + /// The tenant's retained box on the hosted agent37 HTTP sandbox service, + /// through the TinyBox module (`[runtime.agent37]`): it sleeps when idle + /// and keeps its files across commands and restarts. #[serde(rename = "agent37")] Agent37, None, diff --git a/crates/openhuman-core/src/modules/registry/records_extra.rs b/crates/openhuman-core/src/modules/registry/records_extra.rs index 189bd5e96cb..e044b800b3b 100644 --- a/crates/openhuman-core/src/modules/registry/records_extra.rs +++ b/crates/openhuman-core/src/modules/registry/records_extra.rs @@ -9,109 +9,109 @@ pub(crate) const TINYBOX: ModuleRecord = ModuleRecord { description: "Sandbox execution and lifecycle operations through TinyBox", bus_name: tinybox_bus::INTERFACE, object_path: tinybox_bus::OBJECT_PATH, - version: "0.2.5", - release_url: "https://github.com/tinyhumansai/tinybox/releases/tag/v0.2.5", + version: "0.2.6", + release_url: "https://github.com/tinyhumansai/tinybox/releases/tag/v0.2.6", assets: &[ PlatformAsset { host_key: "archlinux-arm64", - archive: "tinybox-0.2.5-archlinux-arm64.tar.gz", - sha256: "05fcd49d54ed41cebca618f3f9cdf785ee1095275ce1127154cc84c528d51665", + archive: "tinybox-0.2.6-archlinux-arm64.tar.gz", + sha256: "284cda47d58de498a02f9643243746deb858d8f71c8f54ccac7275f0965e3be1", library_sha256: None, }, PlatformAsset { host_key: "archlinux-x86_64", - archive: "tinybox-0.2.5-archlinux-x86_64.tar.gz", - sha256: "5767fb8efccac06826487affd7085e761caebca665b076051da5b7d4effc7ea0", + archive: "tinybox-0.2.6-archlinux-x86_64.tar.gz", + sha256: "55f4ecda62225df11f6e546c13851c9a1a78ed3037f99394b955816f79ffce6b", library_sha256: None, }, PlatformAsset { host_key: "fedora-43-arm64", - archive: "tinybox-0.2.5-fedora-43-arm64.tar.gz", - sha256: "4bbd52705e19fe55ab3784d5509ede2569de41a9ca0f64ffcc6fdb8741eab235", + archive: "tinybox-0.2.6-fedora-43-arm64.tar.gz", + sha256: "2e4d134f8dbdef9b41fba43036e5803babebb3d0f24bdfff341c8f29d25ae0d8", library_sha256: None, }, PlatformAsset { host_key: "fedora-43-x86_64", - archive: "tinybox-0.2.5-fedora-43-x86_64.tar.gz", - sha256: "645374ff97a0ebf645771fd0c7fd5c7ab11da80dac1b329a9417f14ec0d97a87", + archive: "tinybox-0.2.6-fedora-43-x86_64.tar.gz", + sha256: "57a259f7297f5a7e20e9f9b8cb47c57d70a4edbaf6f6ea0d4c33f5f6321a66dc", library_sha256: None, }, PlatformAsset { host_key: "fedora-44-arm64", - archive: "tinybox-0.2.5-fedora-44-arm64.tar.gz", - sha256: "61e277e5814cdbfb1e5f4aefcae4bffa011d8dd4d991ad102498b0fad1c440df", + archive: "tinybox-0.2.6-fedora-44-arm64.tar.gz", + sha256: "3ab57d75c478091384e23019e8fe7807ffddaaeb436b52b8d9604ac0336d9ceb", library_sha256: None, }, PlatformAsset { host_key: "fedora-44-x86_64", - archive: "tinybox-0.2.5-fedora-44-x86_64.tar.gz", - sha256: "c0120866b20b05fb31d11bcf8124786b38097c14fde80b5110914fb44c02fdda", + archive: "tinybox-0.2.6-fedora-44-x86_64.tar.gz", + sha256: "6b9f65d8501ff0a32ee60f13c22e6501696d9722fd2951f73fbe5a796bb21eb9", library_sha256: None, }, PlatformAsset { host_key: "macos-15-arm64", - archive: "tinybox-0.2.5-macos-15-arm64.tar.gz", - sha256: "642a6f7776acdd8483da49fbd1157663e19ee681cd85e69c90d7eae5c0cafbd5", + archive: "tinybox-0.2.6-macos-15-arm64.tar.gz", + sha256: "8d62d2e86c41a2220ca6c4d989fb116fb5e09664b6ead2b0cdccb984db50b068", library_sha256: None, }, PlatformAsset { host_key: "macos-15-x86_64", - archive: "tinybox-0.2.5-macos-15-x86_64.tar.gz", - sha256: "0fc96965cbe8cd8dd21e59988cc638d04983eed98a92ef6ad48645eea962de4e", + archive: "tinybox-0.2.6-macos-15-x86_64.tar.gz", + sha256: "8e4f2ebde00a6f8a06445b310df7417de5877c8bdb7d6fbe7ae5653d003f7afa", library_sha256: None, }, PlatformAsset { host_key: "macos-26-arm64", - archive: "tinybox-0.2.5-macos-26-arm64.tar.gz", - sha256: "e6832b67ab5ebdeb82bc77168556cd1da79d64d44a6979c2a0dcd6f594f6163c", + archive: "tinybox-0.2.6-macos-26-arm64.tar.gz", + sha256: "a9c14971de977c02202197a57329de9c73275e09b13cdaa4b2726472b711f718", library_sha256: None, }, PlatformAsset { host_key: "macos-26-x86_64", - archive: "tinybox-0.2.5-macos-26-x86_64.tar.gz", - sha256: "d3b6c7a5c1d08baf8fd1c2350eadd2410490f5b05ce4fd4df6050961b45266cd", + archive: "tinybox-0.2.6-macos-26-x86_64.tar.gz", + sha256: "c63f858405bdbe38f6635b77cb79cc45b11fbe186e69ca03b5d88cb2a7df7696", library_sha256: None, }, PlatformAsset { host_key: "ubuntu-22.04-arm64", - archive: "tinybox-0.2.5-ubuntu-22.04-arm64.tar.gz", - sha256: "595b8f9dbce5459429d2f3b5bb65f28114990e8a2c2ae36e77b1852772d0ff84", + archive: "tinybox-0.2.6-ubuntu-22.04-arm64.tar.gz", + sha256: "a8b79919554b603022b1acf028cc75594b999569b242f12630ec0f1c13ce7a8b", library_sha256: None, }, PlatformAsset { host_key: "ubuntu-22.04-x86_64", - archive: "tinybox-0.2.5-ubuntu-22.04-x86_64.tar.gz", - sha256: "2ed696818a50df69fb8e823ad07497e505727798d828335f52828332ef9b0f9b", + archive: "tinybox-0.2.6-ubuntu-22.04-x86_64.tar.gz", + sha256: "9df93f7112ce5f05285446c75891d886dfe9228c7f2b42620f8d9ec68ec9e0a1", library_sha256: None, }, PlatformAsset { host_key: "ubuntu-24.04-arm64", - archive: "tinybox-0.2.5-ubuntu-24.04-arm64.tar.gz", - sha256: "26b31a46ca0a24d213de63afe21214f2f44d74b14837bf8e6c8b4c9e18f26271", + archive: "tinybox-0.2.6-ubuntu-24.04-arm64.tar.gz", + sha256: "422bec85c4e45953fc830aab4d7f9774e91df46c533b53028db6eb51b7a982f8", library_sha256: None, }, PlatformAsset { host_key: "ubuntu-24.04-x86_64", - archive: "tinybox-0.2.5-ubuntu-24.04-x86_64.tar.gz", - sha256: "a369579d000ca74ef2967681634330c96221305ead5c1f433d072f367898a161", + archive: "tinybox-0.2.6-ubuntu-24.04-x86_64.tar.gz", + sha256: "576c03733c70bba869647ab1fc137b6b941aee977c322494df0e72e4194705ee", library_sha256: None, }, PlatformAsset { host_key: "windows-11-arm64", - archive: "tinybox-0.2.5-windows-11-arm64.zip", - sha256: "69c79ca7f7dc9215353e329b20748f0c72ad278aa6bc1d55a2340f9d37a9b9fe", + archive: "tinybox-0.2.6-windows-11-arm64.zip", + sha256: "7400205c377b2803ba89a8be5e78cb06307da113d452582be8cfe04afd7c877c", library_sha256: None, }, PlatformAsset { host_key: "windows-2022-x86_64", - archive: "tinybox-0.2.5-windows-2022-x86_64.zip", - sha256: "c6b322e2caf40273cd0c4ad6dc766d832e32c80dd88c1ab795f9cac566f5295b", + archive: "tinybox-0.2.6-windows-2022-x86_64.zip", + sha256: "4cad9cad7f79502757583d46134ee25bf80d0d9745d889f91e3e68b98bc1cd0a", library_sha256: None, }, PlatformAsset { host_key: "windows-2025-x86_64", - archive: "tinybox-0.2.5-windows-2025-x86_64.zip", - sha256: "c49fe369511c4f0ed6dfc47f7cedff439a50b6a64b4b5fda7c40b722c9fdec55", + archive: "tinybox-0.2.6-windows-2025-x86_64.zip", + sha256: "a21e2d12a1ad844abad51f584c9ffb6fa5a8bb9c5900f8713a4f89e5bd70dfaf", library_sha256: None, }, ], diff --git a/crates/openhuman-core/src/modules/registry_tests.rs b/crates/openhuman-core/src/modules/registry_tests.rs index 34a7dc5adf2..6923c156c5e 100644 --- a/crates/openhuman-core/src/modules/registry_tests.rs +++ b/crates/openhuman-core/src/modules/registry_tests.rs @@ -118,13 +118,13 @@ fn tinywallet_registry_matches_the_verified_v0290_release_manifest() { } #[test] -fn tinybox_registry_matches_the_published_v025_release_manifest() { +fn tinybox_registry_matches_the_published_v026_release_manifest() { let record = find("tinybox").expect("compiled TinyBox module"); - assert_eq!(record.version, "0.2.5"); - assert_eq!(tinybox_bus::CONTRACT_VERSION, (2, 3)); + assert_eq!(record.version, "0.2.6"); + assert_eq!(tinybox_bus::CONTRACT_VERSION, (2, 4)); assert_eq!( record.release_url, - "https://github.com/tinyhumansai/tinybox/releases/tag/v0.2.5" + "https://github.com/tinyhumansai/tinybox/releases/tag/v0.2.6" ); let actual = record @@ -135,88 +135,88 @@ fn tinybox_registry_matches_the_published_v025_release_manifest() { let published = [ ( "archlinux-arm64", - "tinybox-0.2.5-archlinux-arm64.tar.gz", - "05fcd49d54ed41cebca618f3f9cdf785ee1095275ce1127154cc84c528d51665", + "tinybox-0.2.6-archlinux-arm64.tar.gz", + "284cda47d58de498a02f9643243746deb858d8f71c8f54ccac7275f0965e3be1", ), ( "archlinux-x86_64", - "tinybox-0.2.5-archlinux-x86_64.tar.gz", - "5767fb8efccac06826487affd7085e761caebca665b076051da5b7d4effc7ea0", + "tinybox-0.2.6-archlinux-x86_64.tar.gz", + "55f4ecda62225df11f6e546c13851c9a1a78ed3037f99394b955816f79ffce6b", ), ( "fedora-43-arm64", - "tinybox-0.2.5-fedora-43-arm64.tar.gz", - "4bbd52705e19fe55ab3784d5509ede2569de41a9ca0f64ffcc6fdb8741eab235", + "tinybox-0.2.6-fedora-43-arm64.tar.gz", + "2e4d134f8dbdef9b41fba43036e5803babebb3d0f24bdfff341c8f29d25ae0d8", ), ( "fedora-43-x86_64", - "tinybox-0.2.5-fedora-43-x86_64.tar.gz", - "645374ff97a0ebf645771fd0c7fd5c7ab11da80dac1b329a9417f14ec0d97a87", + "tinybox-0.2.6-fedora-43-x86_64.tar.gz", + "57a259f7297f5a7e20e9f9b8cb47c57d70a4edbaf6f6ea0d4c33f5f6321a66dc", ), ( "fedora-44-arm64", - "tinybox-0.2.5-fedora-44-arm64.tar.gz", - "61e277e5814cdbfb1e5f4aefcae4bffa011d8dd4d991ad102498b0fad1c440df", + "tinybox-0.2.6-fedora-44-arm64.tar.gz", + "3ab57d75c478091384e23019e8fe7807ffddaaeb436b52b8d9604ac0336d9ceb", ), ( "fedora-44-x86_64", - "tinybox-0.2.5-fedora-44-x86_64.tar.gz", - "c0120866b20b05fb31d11bcf8124786b38097c14fde80b5110914fb44c02fdda", + "tinybox-0.2.6-fedora-44-x86_64.tar.gz", + "6b9f65d8501ff0a32ee60f13c22e6501696d9722fd2951f73fbe5a796bb21eb9", ), ( "macos-15-arm64", - "tinybox-0.2.5-macos-15-arm64.tar.gz", - "642a6f7776acdd8483da49fbd1157663e19ee681cd85e69c90d7eae5c0cafbd5", + "tinybox-0.2.6-macos-15-arm64.tar.gz", + "8d62d2e86c41a2220ca6c4d989fb116fb5e09664b6ead2b0cdccb984db50b068", ), ( "macos-15-x86_64", - "tinybox-0.2.5-macos-15-x86_64.tar.gz", - "0fc96965cbe8cd8dd21e59988cc638d04983eed98a92ef6ad48645eea962de4e", + "tinybox-0.2.6-macos-15-x86_64.tar.gz", + "8e4f2ebde00a6f8a06445b310df7417de5877c8bdb7d6fbe7ae5653d003f7afa", ), ( "macos-26-arm64", - "tinybox-0.2.5-macos-26-arm64.tar.gz", - "e6832b67ab5ebdeb82bc77168556cd1da79d64d44a6979c2a0dcd6f594f6163c", + "tinybox-0.2.6-macos-26-arm64.tar.gz", + "a9c14971de977c02202197a57329de9c73275e09b13cdaa4b2726472b711f718", ), ( "macos-26-x86_64", - "tinybox-0.2.5-macos-26-x86_64.tar.gz", - "d3b6c7a5c1d08baf8fd1c2350eadd2410490f5b05ce4fd4df6050961b45266cd", + "tinybox-0.2.6-macos-26-x86_64.tar.gz", + "c63f858405bdbe38f6635b77cb79cc45b11fbe186e69ca03b5d88cb2a7df7696", ), ( "ubuntu-22.04-arm64", - "tinybox-0.2.5-ubuntu-22.04-arm64.tar.gz", - "595b8f9dbce5459429d2f3b5bb65f28114990e8a2c2ae36e77b1852772d0ff84", + "tinybox-0.2.6-ubuntu-22.04-arm64.tar.gz", + "a8b79919554b603022b1acf028cc75594b999569b242f12630ec0f1c13ce7a8b", ), ( "ubuntu-22.04-x86_64", - "tinybox-0.2.5-ubuntu-22.04-x86_64.tar.gz", - "2ed696818a50df69fb8e823ad07497e505727798d828335f52828332ef9b0f9b", + "tinybox-0.2.6-ubuntu-22.04-x86_64.tar.gz", + "9df93f7112ce5f05285446c75891d886dfe9228c7f2b42620f8d9ec68ec9e0a1", ), ( "ubuntu-24.04-arm64", - "tinybox-0.2.5-ubuntu-24.04-arm64.tar.gz", - "26b31a46ca0a24d213de63afe21214f2f44d74b14837bf8e6c8b4c9e18f26271", + "tinybox-0.2.6-ubuntu-24.04-arm64.tar.gz", + "422bec85c4e45953fc830aab4d7f9774e91df46c533b53028db6eb51b7a982f8", ), ( "ubuntu-24.04-x86_64", - "tinybox-0.2.5-ubuntu-24.04-x86_64.tar.gz", - "a369579d000ca74ef2967681634330c96221305ead5c1f433d072f367898a161", + "tinybox-0.2.6-ubuntu-24.04-x86_64.tar.gz", + "576c03733c70bba869647ab1fc137b6b941aee977c322494df0e72e4194705ee", ), ( "windows-11-arm64", - "tinybox-0.2.5-windows-11-arm64.zip", - "69c79ca7f7dc9215353e329b20748f0c72ad278aa6bc1d55a2340f9d37a9b9fe", + "tinybox-0.2.6-windows-11-arm64.zip", + "7400205c377b2803ba89a8be5e78cb06307da113d452582be8cfe04afd7c877c", ), ( "windows-2022-x86_64", - "tinybox-0.2.5-windows-2022-x86_64.zip", - "c6b322e2caf40273cd0c4ad6dc766d832e32c80dd88c1ab795f9cac566f5295b", + "tinybox-0.2.6-windows-2022-x86_64.zip", + "4cad9cad7f79502757583d46134ee25bf80d0d9745d889f91e3e68b98bc1cd0a", ), ( "windows-2025-x86_64", - "tinybox-0.2.5-windows-2025-x86_64.zip", - "c49fe369511c4f0ed6dfc47f7cedff439a50b6a64b4b5fda7c40b722c9fdec55", + "tinybox-0.2.6-windows-2025-x86_64.zip", + "a21e2d12a1ad844abad51f584c9ffb6fa5a8bb9c5900f8713a4f89e5bd70dfaf", ), ]; diff --git a/crates/openhuman-core/src/sandbox/README.md b/crates/openhuman-core/src/sandbox/README.md index 400c9f323a2..f9492c22c4d 100644 --- a/crates/openhuman-core/src/sandbox/README.md +++ b/crates/openhuman-core/src/sandbox/README.md @@ -8,7 +8,7 @@ The host builds a plan request from trusted command, environment, runtime and caller facts, asks TinySecurity for a plan, then passes the admitted artifact to the selected TinyBox executor. A missing module, refused plan or failed consumption denies execution. OpenHuman maps the module results to the existing -`None`, `Local`, `Docker` or `OpenShell` routing and status contracts; it does +`None`, `Local`, `Docker`, `OpenShell` or `Agent37` routing and status contracts; it does not duplicate the protected-path or credential-root policy. `[security.sandbox] backend = "openshell"` routes a command to the tenant's own @@ -20,18 +20,36 @@ 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. +`[security.sandbox] backend = "agent37"` goes through the same registry +([`boxes/`](./boxes/mod.rs), `BoxBackend::Agent37`) on agent37's hosted +service, declared as the `tinybox-agent37` container executor and refused +under `[privacy] mode = "local_only"`. Its boxes are *retained* (box contract +2.4): each is created with `Retention { key, idle_sleep_secs, +delete_after_secs }`, where `key` is `boxes::owner_key`, `oh-` plus the +SHA-256 of the whole tenant (stable, opaque, never a raw id). The service +sleeps a box after `[runtime.agent37] idle_sleep_secs` (default 900, clamped +to 300–86400), wakes it on the next command, and deletes it after +`delete_after_secs` asleep (default 30 days). The registry never deletes a +retained box: reaping, `release`, `shutdown`, a box that stopped answering and +a full registry (which lets go of its least recently used idle box) all only +forget it (`BoxDriver::forget`, the module's `Close`, which keeps a retained +instance). The next create with the same key adopts it, files included, even +after a restart. OpenShell boxes are not retained and are closed as before; +TinyBox refuses retention on every backend without `Capability::Retention`. + ## 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` / +agent makes in it is not on the host. `boxes::write_file` and +`boxes::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 +- Paths are relative to the box work folder (`BoxBackend::workdir`: `/sandbox` + on OpenShell, `/home/node` on agent37). The process-level calls use the + configured backend and refuse one that keeps no boxes (`NoBoxBackend`). 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) @@ -52,7 +70,7 @@ driver supports them and no box contract grows. The generic forms - 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` +(`SandboxBackendKind::keeps_boxes`: `openshell` and `agent37`): `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. diff --git a/crates/openhuman-core/src/sandbox/agent37.rs b/crates/openhuman-core/src/sandbox/agent37.rs index 58dd97e5394..ee6e93561c6 100644 --- a/crates/openhuman-core/src/sandbox/agent37.rs +++ b/crates/openhuman-core/src/sandbox/agent37.rs @@ -1,247 +1,61 @@ -//! The agent37 sandbox backend: a box per command on the hosted agent37 service. +//! The agent37 sandbox backend: the tenant's retained box on the hosted +//! agent37 service. //! //! With `[security.sandbox] backend = "agent37"`, a sandboxed shell command -//! runs in a box the TinyBox module creates on agent37's hosted HTTP service, -//! through the module's *generic* resource lifecycle (`Reserve` → `Create` with -//! backend `"agent37"` → `Exec` → `Close`) — the same contract the Docker and -//! OpenShell backends use. The agent37 module backend (`tinybox-agent37`) owns -//! the HTTP transport and its credential (`AGENT37_API_KEY`, with the hosts -//! fixed and overridable via `AGENT37_API_BASE` / `AGENT37_SANDBOX_BASE`); -//! OpenHuman only maps policy onto the create request and runs the command. +//! runs in a box the TinyBox module keeps for the calling tenant on agent37's +//! hosted HTTP service, through the shared box registry in +//! [`boxes`](super::boxes) — the same per-tenant registry the OpenShell +//! backend uses. The agent37 module backend (`tinybox-agent37`) owns the HTTP +//! transport and its credential (`AGENT37_API_KEY`, with the hosts fixed and +//! overridable via `AGENT37_API_BASE` / `AGENT37_SANDBOX_BASE`); OpenHuman +//! maps policy onto the create request and runs the command. //! -//! Unlike OpenShell, which keeps one long-lived box per tenant, this backend -//! currently creates a box per command and closes it afterwards. The box -//! template, CPU and memory come from `[runtime.agent37]` (the service snaps -//! CPU and memory up to a fixed instance shape, so they are best effort); -//! network is always `Denied`, since widening egress is the service's -//! decision, not this host's. The command is wrapped in `timeout` so the box -//! stops it itself, exactly as the OpenShell backend does. +//! Each box is created with box contract 2.4 retention, keyed on an opaque +//! hash of the tenant ([`boxes::owner_key`](super::boxes::owner_key)): it +//! sleeps after `[runtime.agent37] idle_sleep_secs` without a command, wakes +//! on the next one, and is deleted only after `delete_after_secs` asleep. The +//! host never deletes it: going idle, a release and process shutdown only +//! forget it, so the tenant's files survive across commands and restarts. +//! Commands run in `/home/node`, wrapped in `timeout` so the box stops them +//! itself. Template, CPU and memory come from `[runtime.agent37]` (the +//! service snaps CPU and memory up to a fixed instance shape, so they are best +//! effort); network is always `Denied`. +//! +//! Under `[privacy] mode = "local_only"` nothing is sent: the command, its +//! environment and any file would leave the device. -use std::collections::BTreeMap; +use std::collections::HashMap; use std::ffi::OsString; use std::time::Duration; +use super::boxes::BoxBackend; use super::types::SandboxExecResult; use crate::config::Config; use crate::core::runtime::DispatchCtx; -/// The TinyBox backend name for agent37 boxes. -pub(crate) const BACKEND: &str = "agent37"; - -/// `timeout` reports this exit code when it stops a command (coreutils). -const TIMED_OUT_EXIT: i32 = 124; - -/// Grace added to the command deadline for the bus round-trip, so the box's own -/// `timeout` fires before the bus call gives up. -const BUS_REPLY_GRACE: Duration = Duration::from_secs(10); - -/// Run `command` in a fresh agent37 box and return its result. +/// Run `command` in the calling tenant's agent37 box and return its result. /// /// # Errors /// -/// Returns an error when the TinyBox module cannot create the box or run the -/// command (for example, no `AGENT37_API_KEY`), or when module support is -/// compiled out. +/// Returns an error under local-only privacy, for a call with no tenant, or +/// when the TinyBox module cannot create the box or run the command (for +/// example, no `AGENT37_API_KEY`), or when module support is compiled out. pub(crate) async fn execute( - _ctx: &DispatchCtx, - config: &Config, - command: &str, - extra_env: &std::collections::HashMap, - timeout: Duration, -) -> anyhow::Result { - // agent37 runs the command — and its environment — on a hosted service off - // this device. Under local-only privacy that egress is not permitted, so - // refuse before anything leaves the host. This holds independently of the - // security module, so it is enforced even when security is disabled. - if local_only_forbids_agent37(config) { - anyhow::bail!( - "agent37 sandbox execution is unavailable under [privacy] mode = \"local_only\": \ - it would send the command and its environment to a hosted service" - ); - } - #[cfg(feature = "modules")] - { - tracing::debug!( - timeout_secs = timeout.as_secs(), - "[sandbox:agent37] running a command" - ); - run_command(config, command, extra_env, timeout).await - } - #[cfg(not(feature = "modules"))] - { - let _ = (config, command, extra_env, timeout); - anyhow::bail!( - "TinyBox module support is disabled; agent37 sandbox execution is unavailable" - ) - } -} - -/// Whether `[privacy] mode = "local_only"` forbids agent37 execution. agent37 -/// sends the command and its environment to a hosted service, which local-only -/// privacy does not permit; every other mode allows it. -fn local_only_forbids_agent37(config: &Config) -> bool { - config.privacy.mode == crate::config::PrivacyMode::LocalOnly -} - -/// Owns an agent37 reservation between create and close so a cancelled turn -/// still tears the hosted box down. While armed (`resource` is `Some`), dropping -/// the guard — which is what a cancelled future does to its locals — closes the -/// box on a detached task, since `Drop` cannot await. The happy path disarms it -/// with [`BoxGuard::disarm`] and closes the box itself. -#[cfg(feature = "modules")] -struct BoxGuard { - config: Config, - resource: Option, -} - -#[cfg(feature = "modules")] -impl BoxGuard { - fn disarm(&mut self) -> Option { - self.resource.take() - } -} - -#[cfg(feature = "modules")] -impl Drop for BoxGuard { - fn drop(&mut self) { - let Some(resource) = self.resource.take() else { - return; - }; - let config = self.config.clone(); - // Cancelled between create and close. Drop cannot await, so close the box - // on a detached task rather than leak it until the service's idle reaper - // takes it. - if let Ok(handle) = tokio::runtime::Handle::try_current() { - handle.spawn(async move { - if let Err(error) = crate::modules::tinybox::close(&config, resource).await { - tracing::warn!(%error, "[sandbox:agent37] cancelled-box cleanup failed"); - } - }); - } - } -} - -/// The limits a box is created with, from `[runtime.agent37]` rather than -/// `[runtime.docker]`. The service snaps them up to a fixed instance shape, so -/// they are a request, not a ceiling. CPU above 4 vCPU is capped before a shape -/// is chosen, and memory above 32 GiB gets the largest shape (logged, since the -/// box then gets less than was configured). A memory size too large to express -/// in bytes asks for the service's maximum. -#[cfg(feature = "modules")] -fn box_resources(config: &Config) -> crate::modules::tinybox::contract::ResourceLimits { - let agent37 = &config.runtime.agent37; - if agent37.exceeds_largest_shape() { - tracing::warn!( - cpu_millis = agent37.cpu_millis, - memory_mb = agent37.memory_mb, - "[sandbox:agent37] request exceeds the largest instance shape and will be capped" - ); - } - crate::modules::tinybox::contract::ResourceLimits { - cpu_millis: agent37.cpu_millis, - memory_bytes: agent37.memory_bytes().unwrap_or(u64::MAX), - ..Default::default() - } -} - -#[cfg(feature = "modules")] -async fn run_command( + ctx: &DispatchCtx, config: &Config, command: &str, - extra_env: &std::collections::HashMap, + extra_env: &HashMap, timeout: Duration, ) -> anyhow::Result { - use crate::modules::tinybox::{self, contract}; - - let resource = tinybox::reserve(config, contract::ReserveRequest::Resource) - .await - .map_err(|error| anyhow::anyhow!("agent37 reserve failed: {error}"))?; - - // From here the box must be closed on every path, cancellation included. - let mut guard = BoxGuard { - config: config.clone(), - resource: Some(resource.clone()), - }; - - if let Err(error) = tinybox::create( + super::boxes::execute( + ctx, config, - contract::CreateRequest { - resource: resource.clone(), - backend: BACKEND.to_owned(), - host: contract::HostConfig::Local, - // agent37 starts a box from a registered template name, not an OCI - // image; forwarding the Docker image slot is rejected with HTTP 400. - workspace: contract::Workspace::Image(config.runtime.agent37.template.clone()), - network: contract::NetworkPolicy::Denied, - resources: box_resources(config), - ports: Vec::new(), - env: BTreeMap::new(), - }, + BoxBackend::Agent37, + command, + extra_env, + timeout, ) .await - { - // No box to close: the backend tears a half-created instance down - // itself, so disarm rather than close an id the service never kept. - guard.disarm(); - return Err(anyhow::anyhow!("agent37 create failed: {error}")); - } - - let secs = whole_seconds(timeout); - let outcome = tinybox::exec_within( - config, - contract::ExecRequest { - resource: resource.clone(), - argv: timeout_argv(secs, command), - cwd: None, - env: utf8_env(extra_env), - stdin: None, - }, - timeout.saturating_add(BUS_REPLY_GRACE), - ) - .await; - - // Close the box ourselves, but keep the guard armed across the await: a turn - // cancelled during this close drops the future, and the still-armed guard - // then closes the box on its detached task. Disarm only once close has - // returned, so the reservation is never closed twice. - if let Some(resource) = guard.resource.clone() { - let _ = tinybox::close(config, resource).await; - guard.disarm(); - } - - match outcome { - Ok(output) => Ok(SandboxExecResult { - exit_code: output.exit_code, - stdout: String::from_utf8_lossy(&output.stdout).into_owned(), - stderr: String::from_utf8_lossy(&output.stderr).into_owned(), - timed_out: output.exit_code == TIMED_OUT_EXIT, - }), - Err(error) => Err(anyhow::anyhow!("agent37 execution failed: {error}")), - } -} - -/// `timeout -k 5 sh -c `: the box stops the command itself. -#[cfg(feature = "modules")] -fn timeout_argv(secs: u64, command: &str) -> Vec { - ["timeout", "-k", "5", &secs.to_string(), "sh", "-c", command] - .map(str::to_owned) - .to_vec() -} - -/// `timeout` counts whole seconds: round up, and never ask for none. -#[cfg(feature = "modules")] -fn whole_seconds(timeout: Duration) -> u64 { - (timeout.as_secs() + u64::from(timeout.subsec_nanos() > 0)).max(1) -} - -/// The per-command environment as UTF-8 string pairs, dropping any entry whose -/// name or value is not UTF-8 (the module contract carries strings). -#[cfg(feature = "modules")] -fn utf8_env(extra_env: &std::collections::HashMap) -> BTreeMap { - extra_env - .iter() - .filter_map(|(name, value)| Some((name.to_str()?.to_owned(), value.to_str()?.to_owned()))) - .collect() } #[cfg(test)] diff --git a/crates/openhuman-core/src/sandbox/agent37_tests.rs b/crates/openhuman-core/src/sandbox/agent37_tests.rs index bd13d505041..8c14ba1f32e 100644 --- a/crates/openhuman-core/src/sandbox/agent37_tests.rs +++ b/crates/openhuman-core/src/sandbox/agent37_tests.rs @@ -1,76 +1,143 @@ -//! Pure helpers for the agent37 backend: the `timeout` wrapping, whole-second -//! rounding, the box limits, and the UTF-8 environment projection. The command path itself goes -//! through the TinyBox module and is exercised by integration tests, not here. -#![cfg(feature = "modules")] +//! The agent37 backend: what it refuses before anything leaves the host, and +//! how `[runtime.agent37]` becomes its boxes' settings and retention. The box +//! lifecycle itself is the shared registry's, tested in `boxes`. use super::*; -use std::collections::HashMap; -use std::ffi::OsString; -use std::time::Duration; +use crate::sandbox::boxes::{BoxError, BoxSettings, RegistryLimits, RetainPolicy, AGENT37_WORKDIR}; -#[test] -fn timeout_argv_wraps_the_command_for_the_box_to_stop() { - assert_eq!( - timeout_argv(30, "echo hi"), - vec![ - "timeout".to_owned(), - "-k".to_owned(), - "5".to_owned(), - "30".to_owned(), - "sh".to_owned(), - "-c".to_owned(), - "echo hi".to_owned(), - ] - ); +fn local_only() -> Config { + let mut config = Config::default(); + config.privacy.mode = crate::config::PrivacyMode::LocalOnly; + config } -#[test] -fn whole_seconds_rounds_up_and_never_asks_for_none() { - assert_eq!(whole_seconds(Duration::from_secs(0)), 1); - assert_eq!(whole_seconds(Duration::from_millis(1)), 1); - assert_eq!(whole_seconds(Duration::from_millis(1500)), 2); - assert_eq!(whole_seconds(Duration::from_secs(5)), 5); -} +#[tokio::test] +async fn local_only_privacy_refuses_a_command_before_it_leaves_the_host() { + let error = execute( + &DispatchCtx::unbound(), + &local_only(), + "id", + &HashMap::new(), + Duration::from_secs(1), + ) + .await + .unwrap_err(); -#[test] -fn utf8_env_keeps_utf8_pairs_and_drops_the_rest() { - let mut env = HashMap::new(); - env.insert(OsString::from("KEY"), OsString::from("value")); - let out = utf8_env(&env); - assert_eq!(out.get("KEY").map(String::as_str), Some("value")); - assert_eq!(out.len(), 1); + assert_eq!( + error.downcast_ref::(), + Some(&BoxError::LocalOnly), + "{error}" + ); + assert!(error.to_string().contains("local_only")); } #[test] -fn local_only_privacy_forbids_agent37() { +fn only_local_only_privacy_forbids_agent37() { let mut config = Config::default(); // Standard (the default) allows agent37's off-device execution. - assert!(!local_only_forbids_agent37(&config)); - config.privacy.mode = crate::config::PrivacyMode::LocalOnly; - assert!(local_only_forbids_agent37(&config)); + assert_eq!(BoxBackend::Agent37.check_allowed(&config), Ok(())); // Sensitive is not local-only, so it still allows agent37. config.privacy.mode = crate::config::PrivacyMode::Sensitive; - assert!(!local_only_forbids_agent37(&config)); + assert_eq!(BoxBackend::Agent37.check_allowed(&config), Ok(())); + // OpenShell runs on the operator's own gateway. + assert_eq!(BoxBackend::OpenShell.check_allowed(&local_only()), Ok(())); } #[test] -fn box_resources_come_from_the_agent37_runtime_config() { +fn box_settings_come_from_the_agent37_runtime_config() { let mut config = Config::default(); config.runtime.docker.cpu_limit = Some(8.0); config.runtime.docker.memory_limit_mb = Some(1); + config.runtime.agent37.template = "team-sandbox".into(); config.runtime.agent37.cpu_millis = 4_000; config.runtime.agent37.memory_mb = 16_384; - let resources = box_resources(&config); + let settings = BoxBackend::Agent37.settings(&config).unwrap(); - assert_eq!(resources.cpu_millis, 4_000); - assert_eq!(resources.memory_bytes, 16_384 * 1024 * 1024); + assert_eq!( + settings, + BoxSettings { + image: "team-sandbox".into(), + cpu_millis: 4_000, + memory_bytes: 16_384 * 1024 * 1024, + workdir: AGENT37_WORKDIR.into(), + } + ); + assert_eq!(BoxBackend::Agent37.workdir(), "/home/node"); } #[test] -fn box_resources_ask_for_the_maximum_when_memory_overflows() { +fn box_settings_ask_for_the_maximum_when_memory_overflows() { let mut config = Config::default(); config.runtime.agent37.memory_mb = u64::MAX; - assert_eq!(box_resources(&config).memory_bytes, u64::MAX); + let settings = BoxBackend::Agent37.settings(&config).unwrap(); + assert_eq!(settings.memory_bytes, u64::MAX); +} + +#[test] +fn a_blank_template_is_refused_with_a_config_error() { + let mut config = Config::default(); + config.runtime.agent37.template = " ".into(); + + let refused = BoxBackend::Agent37.settings(&config).unwrap_err(); + assert!(matches!(refused, BoxError::InvalidConfig(_)), "{refused:?}"); + assert!(refused.to_string().contains("[runtime.agent37]")); +} + +#[test] +fn boxes_are_retained_with_the_configured_sleep_and_expiry() { + let mut config = Config::default(); + config.runtime.agent37.idle_sleep_secs = 1_200; + config.runtime.agent37.delete_after_secs = 86_400; + config.runtime.agent37.max_live = 7; + + assert_eq!( + BoxBackend::Agent37.limits(&config), + RegistryLimits { + idle_ttl: Duration::from_secs(1_200), + max_live: 7, + retain: Some(RetainPolicy { + idle_sleep_secs: 1_200, + delete_after_secs: 86_400, + }), + } + ); +} + +#[test] +fn the_sleep_delay_is_clamped_to_what_agent37_accepts() { + let mut config = Config::default(); + for (configured, used) in [ + (0, 300), + (299, 300), + (300, 300), + (86_400, 86_400), + (u32::MAX, 86_400), + ] { + config.runtime.agent37.idle_sleep_secs = configured; + let limits = BoxBackend::Agent37.limits(&config); + assert_eq!(limits.retain.unwrap().idle_sleep_secs, used, "{configured}"); + assert_eq!(limits.idle_ttl, Duration::from_secs(u64::from(used))); + } +} + +#[test] +fn zero_expiry_and_zero_capacity_are_raised_to_one() { + let mut config = Config::default(); + config.runtime.agent37.delete_after_secs = 0; + config.runtime.agent37.max_live = 0; + + let limits = BoxBackend::Agent37.limits(&config); + assert_eq!(limits.retain.unwrap().delete_after_secs, 1); + assert_eq!(limits.max_live, 1); +} + +#[test] +fn openshell_boxes_are_never_retained() { + assert_eq!( + BoxBackend::OpenShell.limits(&Config::default()).retain, + None + ); + assert_eq!(BoxBackend::OpenShell.workdir(), "/sandbox"); } diff --git a/crates/openhuman-core/src/sandbox/openshell/bus_driver.rs b/crates/openhuman-core/src/sandbox/boxes/bus_driver.rs similarity index 63% rename from crates/openhuman-core/src/sandbox/openshell/bus_driver.rs rename to crates/openhuman-core/src/sandbox/boxes/bus_driver.rs index c63a25178ac..9febaccbece 100644 --- a/crates/openhuman-core/src/sandbox/openshell/bus_driver.rs +++ b/crates/openhuman-core/src/sandbox/boxes/bus_driver.rs @@ -1,4 +1,14 @@ -//! [`BusBoxDriver`]: boxes through the TinyBox module's `openshell` backend. +//! [`BusBoxDriver`]: boxes through the TinyBox module's `openshell` or +//! `agent37` backend. +//! +//! A retained box (agent37) is created with the contract 2.4 +//! [`contract::Retention`]: the module adopts the box it already keeps under +//! the owner's key, or creates one that sleeps when idle. A module older than +//! 2.4 never sees the request: every call first requires a compatible +//! contract, and this host is built against 2.4. Forgetting a retained box is +//! the module's `Close`, which for a retained box drops only the module's +//! handle and leaves the instance, so the module's resource slots are freed +//! without deleting anything. //! //! Each step is one bus call (`Reserve` + `Create`, `Exec`, `Close`). The //! module's error names do not cross the bus client (it reports only @@ -10,12 +20,23 @@ use std::time::Duration; use async_trait::async_trait; -use super::{BoxDriver, BoxError, BoxExec, BoxOutput, BoxSettings}; +use super::{BoxBackend, BoxDriver, BoxError, BoxExec, BoxOutput, BoxRetention, BoxSettings}; use crate::config::Config; use crate::modules::tinybox::{self, contract}; /// The TinyBox backend name for OpenShell boxes. -pub(crate) const BACKEND: &str = "openshell"; +pub(crate) const OPENSHELL_BACKEND: &str = "openshell"; + +/// The TinyBox backend name for agent37 boxes. +pub(crate) const AGENT37_BACKEND: &str = "agent37"; + +/// The TinyBox backend name `backend` creates its boxes with. +pub(crate) fn module_backend(backend: BoxBackend) -> &'static str { + match backend { + BoxBackend::OpenShell => OPENSHELL_BACKEND, + BoxBackend::Agent37 => AGENT37_BACKEND, + } +} /// How long past the registry's own deadline the bus waits for an exec reply, /// so the registry's backstop always decides first. @@ -25,25 +46,32 @@ pub(crate) const BUS_REPLY_GRACE: Duration = Duration::from_secs(5); const LIVE_STATES: &[&str] = &["ready", "running"]; /// A [`BoxDriver`] over the TinyBox module, using the module configuration it -/// was built with. +/// was built with, for one backend. pub struct BusBoxDriver { config: Config, + backend: BoxBackend, } impl BusBoxDriver { - /// A driver that reaches the module with `config`'s module settings. - pub fn new(config: Config) -> Self { - Self { config } + /// A driver that reaches the module with `config`'s module settings and + /// creates `backend`'s boxes. + pub fn new(config: Config, backend: BoxBackend) -> Self { + Self { config, backend } } } #[async_trait] impl BoxDriver for BusBoxDriver { - async fn create(&self, settings: &BoxSettings) -> Result { + async fn create( + &self, + settings: &BoxSettings, + retention: Option<&BoxRetention>, + ) -> Result { let resource = tinybox::reserve(&self.config, contract::ReserveRequest::Resource) .await .map_err(BoxError::Driver)?; - let info = tinybox::create(&self.config, create_request(resource, settings)) + let request = create_request(resource, self.backend, settings, retention); + let info = tinybox::create(&self.config, request) .await .map_err(BoxError::Driver)?; Ok(info.resource.0) @@ -71,17 +99,26 @@ impl BoxDriver for BusBoxDriver { .await .map_err(BoxError::Driver) } + + async fn forget(&self, resource: &str) -> Result<(), BoxError> { + // The module's Close on a retained box drops its handle and keeps the + // instance (contract 2.4); see the module docs above. + self.close(resource).await + } } -/// An OpenShell box: the image, no network, no published ports, and no -/// environment from the host. +/// A box on `backend`: the image (a template name on agent37), no network, +/// no published ports, no environment from the host, and the retention a +/// retaining registry asked for. pub(crate) fn create_request( resource: contract::ResourceId, + backend: BoxBackend, settings: &BoxSettings, + retention: Option<&BoxRetention>, ) -> contract::CreateRequest { contract::CreateRequest { resource, - backend: BACKEND.to_owned(), + backend: module_backend(backend).to_owned(), host: contract::HostConfig::Local, workspace: contract::Workspace::Image(settings.image.clone()), network: contract::NetworkPolicy::Denied, @@ -92,6 +129,11 @@ pub(crate) fn create_request( }, ports: Vec::new(), env: std::collections::BTreeMap::new(), + retention: retention.map(|retention| contract::Retention { + key: retention.key.clone(), + idle_sleep_secs: retention.idle_sleep_secs, + delete_after_secs: retention.delete_after_secs, + }), } } diff --git a/crates/openhuman-core/src/sandbox/openshell/bus_driver_tests.rs b/crates/openhuman-core/src/sandbox/boxes/bus_driver_tests.rs similarity index 69% rename from crates/openhuman-core/src/sandbox/openshell/bus_driver_tests.rs rename to crates/openhuman-core/src/sandbox/boxes/bus_driver_tests.rs index 54b08e41d38..2239bb56f49 100644 --- a/crates/openhuman-core/src/sandbox/openshell/bus_driver_tests.rs +++ b/crates/openhuman-core/src/sandbox/boxes/bus_driver_tests.rs @@ -6,13 +6,14 @@ fn settings() -> BoxSettings { image: "registry.example/agent:1".into(), cpu_millis: 750, memory_bytes: 256 * 1024 * 1024, + workdir: "/sandbox".into(), } } fn info(state: &str) -> contract::ResourceInfo { contract::ResourceInfo { resource: contract::ResourceId("r-1".into()), - backend: BACKEND.into(), + backend: OPENSHELL_BACKEND.into(), state: state.into(), published_ports: Vec::new(), } @@ -20,7 +21,12 @@ fn info(state: &str) -> contract::ResourceInfo { #[test] fn a_box_is_an_openshell_image_with_no_network_no_ports_and_no_host_env() { - let request = create_request(contract::ResourceId("r-1".into()), &settings()); + let request = create_request( + contract::ResourceId("r-1".into()), + BoxBackend::OpenShell, + &settings(), + None, + ); assert_eq!(request.resource, contract::ResourceId("r-1".into())); assert_eq!(request.backend, "openshell"); @@ -44,6 +50,52 @@ fn a_box_is_an_openshell_image_with_no_network_no_ports_and_no_host_env() { ); } +#[test] +fn an_openshell_box_is_never_retained() { + let request = create_request( + contract::ResourceId("r-1".into()), + BoxBackend::OpenShell, + &settings(), + None, + ); + assert_eq!(request.retention, None); +} + +#[test] +fn an_agent37_box_starts_from_its_template_and_carries_its_owners_retention() { + let settings = BoxSettings::from_agent37(&crate::config::Agent37RuntimeConfig::default()) + .expect("the default agent37 settings are valid"); + let retention = BoxRetention { + key: "oh-abc".into(), + idle_sleep_secs: 900, + delete_after_secs: 2_592_000, + }; + + let request = create_request( + contract::ResourceId("r-1".into()), + BoxBackend::Agent37, + &settings, + Some(&retention), + ); + + assert_eq!(request.backend, "agent37"); + assert_eq!( + request.workspace, + contract::Workspace::Image("agent37-base".into()) + ); + assert_eq!(request.network, contract::NetworkPolicy::Denied); + assert_eq!(request.resources.cpu_millis, 2_000); + assert_eq!(request.resources.memory_bytes, 4 * 1024 * 1024 * 1024); + assert_eq!( + request.retention, + Some(contract::Retention { + key: "oh-abc".into(), + idle_sleep_secs: 900, + delete_after_secs: 2_592_000, + }) + ); +} + #[test] fn an_exec_carries_argv_workdir_and_only_the_given_env() { let mut env = BTreeMap::new(); diff --git a/crates/openhuman-core/src/sandbox/openshell/files.rs b/crates/openhuman-core/src/sandbox/boxes/files.rs similarity index 95% rename from crates/openhuman-core/src/sandbox/openshell/files.rs rename to crates/openhuman-core/src/sandbox/boxes/files.rs index 5294e93c9f5..750bea234b5 100644 --- a/crates/openhuman-core/src/sandbox/openshell/files.rs +++ b/crates/openhuman-core/src/sandbox/boxes/files.rs @@ -3,8 +3,8 @@ //! 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 +//! ([`BoxSettings::workdir`], the directory every command runs in: `/sandbox` +//! on OpenShell, `/home/node` on agent37), 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 @@ -38,7 +38,6 @@ 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; @@ -83,11 +82,11 @@ const DETAIL_MAX_CHARS: usize = 200; /// [`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. +/// removed); otherwise the registry errors. pub async fn write_file_in( registry: &BoxRegistry, tenant: Result, - openshell: &OpenShellRuntimeConfig, + settings: &BoxSettings, path: &str, bytes: &[u8], ) -> Result<(), BoxError> { @@ -100,11 +99,10 @@ pub async fn write_file_in( limit: MAX_FILE_BYTES, }); } - let settings = BoxSettings::from_config(openshell)?; let target = Target { registry, tenant: &tenant, - settings: &settings, + settings, path, }; @@ -141,21 +139,20 @@ pub async fn write_file_in( /// 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. +/// command fails; otherwise the registry errors. pub async fn read_file_in( registry: &BoxRegistry, tenant: Result, - openshell: &OpenShellRuntimeConfig, + settings: &BoxSettings, 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, + settings, path, }; @@ -228,7 +225,7 @@ impl Target<'_, D> { async fn run(&self, command: &str) -> Result { tracing::debug!( path_len = self.path.len(), - "[sandbox:openshell] running a file transfer command" + "[sandbox:box] running a file transfer command" ); let request = BoxRequest { command: command.to_owned(), diff --git a/crates/openhuman-core/src/sandbox/openshell/files_shell_tests.rs b/crates/openhuman-core/src/sandbox/boxes/files_shell_tests.rs similarity index 99% rename from crates/openhuman-core/src/sandbox/openshell/files_shell_tests.rs rename to crates/openhuman-core/src/sandbox/boxes/files_shell_tests.rs index 1bca78e48aa..6324e8e1f2f 100644 --- a/crates/openhuman-core/src/sandbox/openshell/files_shell_tests.rs +++ b/crates/openhuman-core/src/sandbox/boxes/files_shell_tests.rs @@ -4,8 +4,8 @@ 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 crate::sandbox::boxes::scripted_driver::{ExecStep, ScriptedDriver}; +use crate::sandbox::boxes::{BoxOutput, RegistryLimits}; use std::sync::Arc; use std::time::Duration; diff --git a/crates/openhuman-core/src/sandbox/openshell/files_tests.rs b/crates/openhuman-core/src/sandbox/boxes/files_tests.rs similarity index 96% rename from crates/openhuman-core/src/sandbox/openshell/files_tests.rs rename to crates/openhuman-core/src/sandbox/boxes/files_tests.rs index 6e2ad5caf18..a3cd963acd7 100644 --- a/crates/openhuman-core/src/sandbox/openshell/files_tests.rs +++ b/crates/openhuman-core/src/sandbox/boxes/files_tests.rs @@ -1,7 +1,7 @@ use super::*; use crate::core::runtime::NoTenant; -use crate::sandbox::openshell::scripted_driver::{Call, ExecStep, ScriptedDriver}; -use crate::sandbox::openshell::{BoxOutput, RegistryLimits}; +use crate::sandbox::boxes::scripted_driver::{Call, ExecStep, ScriptedDriver}; +use crate::sandbox::boxes::{BoxOutput, RegistryLimits}; use std::sync::Arc; use std::time::Duration; @@ -18,12 +18,15 @@ pub(super) fn registry(driver: &Arc) -> Arc OpenShellRuntimeConfig { - OpenShellRuntimeConfig::default() +/// The settings of an OpenShell box with the default `[runtime.openshell]`. +pub(super) fn config() -> BoxSettings { + BoxSettings::from_config(&crate::config::OpenShellRuntimeConfig::default()) + .expect("the default OpenShell settings are valid") } /// Every byte value, so NUL and bytes that are not UTF-8 are in the file. diff --git a/crates/openhuman-core/src/sandbox/boxes/mod.rs b/crates/openhuman-core/src/sandbox/boxes/mod.rs new file mode 100644 index 00000000000..20ab8abfaff --- /dev/null +++ b/crates/openhuman-core/src/sandbox/boxes/mod.rs @@ -0,0 +1,388 @@ +//! Boxes kept per tenant: the OpenShell and agent37 sandbox backends. +//! +//! With `[security.sandbox] backend = "openshell"` or `"agent37"`, a +//! sandboxed shell command runs in a box the TinyBox module creates, on an +//! NVIDIA OpenShell gateway (`[runtime.openshell]`) or on the hosted agent37 +//! service (`[runtime.agent37]`). Unlike the Docker backend, which starts a +//! container per command, a box outlives the command: [`BoxRegistry`] keeps +//! one per [`Tenant`], so files a command writes are there for the next one. +//! [`BoxBackend`] names the two and what differs between them. +//! +//! - **Keyed on the whole tenant.** An embedded host runs one agent per end +//! user with no profile, so keying on the profile alone would put every user +//! in one box. A call with no tenant ([`NoTenant`]) is refused, never sent +//! to a shared box. +//! - **Created once, reused, let go of.** Concurrent first commands make one +//! box. A box idle for the registry's TTL is let go of by a background +//! reaper, and `max_live` caps the boxes held at once. +//! - **OpenShell closes, agent37 retains.** An OpenShell box let go of is +//! closed and its files are gone. An agent37 box is created with the +//! tenant's [`owner_key`] and a [`RetainPolicy`] (box contract 2.4): letting +//! go only forgets it, the service sleeps it when idle, and the next command +//! (from this process or after a restart) finds the same box, files +//! included, until it has slept for `delete_after_secs`. +//! - **The box enforces the deadline.** Commands run as +//! `timeout -k 5 sh -c ` in the backend's work folder +//! ([`BoxBackend::workdir`]), with only the variables the request carries. +//! A box that does not answer shortly after the deadline is let go of 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, on whichever backend is configured. +//! +//! [`BoxDriver`] is the seam: [`BusBoxDriver`] reaches the TinyBox module +//! (behind the `modules` feature); tests use a scripted stand-in. The process +//! holds one registry per backend, built from the config of the first call +//! that needs it, so the TTL, `max_live` and retention changes take effect on +//! restart. + +#[cfg(feature = "modules")] +mod bus_driver; +mod files; +mod registry; +mod types; + +use std::collections::{BTreeMap, HashMap}; +use std::ffi::OsString; +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::{owner_key, BoxRegistry}; +pub use types::{ + BoxDriver, BoxError, BoxExec, BoxOutput, BoxRequest, BoxRetention, BoxSettings, RegistryLimits, + RetainPolicy, AGENT37_WORKDIR, MAX_IDLE_SLEEP_SECS, MIN_IDLE_SLEEP_SECS, OPENSHELL_WORKDIR, +}; + +use super::types::{SandboxBackendKind, SandboxExecResult}; +use crate::config::Config; +use crate::core::runtime::{DispatchCtx, NoTenant, Tenant}; + +/// A sandbox backend that keeps a box per tenant. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum BoxBackend { + /// An NVIDIA OpenShell gateway; boxes are closed when let go of. + OpenShell, + /// The hosted agent37 service; boxes are retained for their tenant. + Agent37, +} + +impl BoxBackend { + /// The box-keeping backend `kind` names, if it is one. + pub fn of(kind: SandboxBackendKind) -> Option { + match kind { + SandboxBackendKind::OpenShell => Some(Self::OpenShell), + SandboxBackendKind::Agent37 => Some(Self::Agent37), + SandboxBackendKind::None | SandboxBackendKind::Local | SandboxBackendKind::Docker => { + None + } + } + } + + /// The box-keeping backend `config` names, unless the config turns the + /// sandbox off. + pub fn configured(config: &Config) -> Option { + if crate::sandbox::ops::config_disables_sandbox(config) { + return None; + } + Self::of(crate::sandbox::policy::named_backend( + &config.sandbox, + &config.runtime, + false, + )) + } + + /// The folder commands run in and file paths are relative to. + pub fn workdir(self) -> &'static str { + match self { + Self::OpenShell => OPENSHELL_WORKDIR, + Self::Agent37 => AGENT37_WORKDIR, + } + } + + /// What a new box is created with, from the backend's runtime table. + /// + /// # Errors + /// + /// [`BoxError::InvalidConfig`] and [`BoxError::InvalidMemory`] for an + /// unusable table. + pub fn settings(self, config: &Config) -> Result { + match self { + Self::OpenShell => BoxSettings::from_config(&config.runtime.openshell), + Self::Agent37 => BoxSettings::from_agent37(&config.runtime.agent37), + } + } + + /// The registry bounds, and retention, from the backend's runtime table. + pub fn limits(self, config: &Config) -> RegistryLimits { + match self { + Self::OpenShell => RegistryLimits::from_config(&config.runtime.openshell), + Self::Agent37 => RegistryLimits::from_agent37(&config.runtime.agent37), + } + } + + /// Refuse a backend the config does not allow: agent37 sends commands, + /// their environment and files to a hosted service, which + /// `[privacy] mode = "local_only"` forbids. This holds whether or not + /// the security module is on. + /// + /// # Errors + /// + /// [`BoxError::LocalOnly`] for agent37 under local-only privacy. + pub fn check_allowed(self, config: &Config) -> Result<(), BoxError> { + if self == Self::Agent37 && config.privacy.mode == crate::config::PrivacyMode::LocalOnly { + tracing::warn!("[sandbox:box] refusing agent37 under local-only privacy"); + return Err(BoxError::LocalOnly); + } + Ok(()) + } + + fn label(self) -> &'static str { + match self { + Self::OpenShell => "OpenShell", + Self::Agent37 => "agent37", + } + } +} + +/// The tenant a box is kept for: the call's whole tenant, or a refusal. +/// +/// # Errors +/// +/// [`BoxError::NoTenant`] when the call carries no tenant. +pub fn tenant_for_box(tenant: Result) -> Result { + tenant.map_err(|NoTenant| { + tracing::warn!("[sandbox:box] refusing a box call with no tenant scope"); + BoxError::NoTenant + }) +} + +/// The command's variables as UTF-8, refusing any that are not. +/// +/// # Errors +/// +/// [`BoxError::NonUtf8Env`] when a name or value is not UTF-8. +pub fn box_env( + extra_env: &HashMap, +) -> Result, BoxError> { + extra_env + .iter() + .map(|(name, value)| match (name.to_str(), value.to_str()) { + (Some(name), Some(value)) => Ok((name.to_owned(), value.to_owned())), + _ => Err(BoxError::NonUtf8Env), + }) + .collect() +} + +/// Run `command` in the box of the tenant `tenant` resolves to. +/// +/// # Errors +/// +/// [`BoxError::NoTenant`] before any box is touched when there is no tenant; +/// otherwise the environment and registry errors. +pub async fn run_command( + registry: &BoxRegistry, + tenant: Result, + settings: &BoxSettings, + command: &str, + extra_env: &HashMap, + timeout: Duration, +) -> Result { + let tenant = tenant_for_box(tenant)?; + let request = BoxRequest { + command: command.to_owned(), + env: box_env(extra_env)?, + timeout, + }; + registry.exec(&tenant, settings, &request).await +} + +#[cfg(feature = "modules")] +type ProcessRegistry = std::sync::Arc>; + +#[cfg(feature = "modules")] +static OPENSHELL_REGISTRY: std::sync::OnceLock = std::sync::OnceLock::new(); + +#[cfg(feature = "modules")] +static AGENT37_REGISTRY: std::sync::OnceLock = std::sync::OnceLock::new(); + +#[cfg(feature = "modules")] +fn registry_cell(backend: BoxBackend) -> &'static std::sync::OnceLock { + match backend { + BoxBackend::OpenShell => &OPENSHELL_REGISTRY, + BoxBackend::Agent37 => &AGENT37_REGISTRY, + } +} + +/// The process's registry for `backend`, built (and its reaper started) on +/// first use. +#[cfg(feature = "modules")] +fn registry(backend: BoxBackend, config: &Config) -> &'static ProcessRegistry { + let registry = registry_cell(backend).get_or_init(|| { + BoxRegistry::new( + std::sync::Arc::new(BusBoxDriver::new(config.clone(), backend)), + backend.limits(config), + ) + }); + registry.start_reaper(); + registry +} + +/// Run a sandboxed shell command in the calling tenant's box on `backend`. +/// +/// # Errors +/// +/// Every [`BoxError`], and a refusal when this build has no module support. +pub(crate) async fn execute( + ctx: &DispatchCtx, + config: &Config, + backend: BoxBackend, + command: &str, + extra_env: &HashMap, + timeout: Duration, +) -> anyhow::Result { + backend.check_allowed(config)?; + #[cfg(feature = "modules")] + { + tracing::debug!( + backend = backend.label(), + timeout_secs = timeout.as_secs(), + "[sandbox:box] running a command" + ); + let tenant = tenant_for_box(ctx.tenant())?; + let settings = backend.settings(config)?; + run_command( + registry(backend, config), + Ok(tenant), + &settings, + command, + extra_env, + timeout, + ) + .await + .map_err(anyhow::Error::from) + } + #[cfg(not(feature = "modules"))] + { + let _ = (ctx, command, extra_env, timeout); + anyhow::bail!( + "TinyBox module support is disabled; {} sandbox execution is unavailable", + backend.label() + ) + } +} + +/// The box-keeping backend for a file call: the configured one, if it keeps +/// boxes and is allowed. +fn file_backend(config: &Config) -> Result { + let backend = BoxBackend::configured(config).ok_or(BoxError::NoBoxBackend)?; + backend.check_allowed(config)?; + Ok(backend) +} + +/// 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 is +/// on the backend `config` names and comes from the process's registry for +/// it, built from `config` on first use. +/// +/// # Errors +/// +/// [`BoxError::NoTenant`] first; [`BoxError::NoBoxBackend`] when the +/// configured backend keeps no boxes; [`BoxError::LocalOnly`] for agent37 +/// under local-only privacy; 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: Result = Ok(tenant_for_box(tenant)?); + let backend = file_backend(config)?; + #[cfg(feature = "modules")] + { + let settings = backend.settings(config)?; + write_file_in(registry(backend, config), tenant, &settings, path, bytes).await + } + #[cfg(not(feature = "modules"))] + { + let _ = (tenant, backend, 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 is on the backend `config` names +/// and comes from the process's registry for it, built from `config` on +/// first use. +/// +/// # Errors +/// +/// As [`write_file`], with [`read_file_in`]'s errors. +pub async fn read_file( + tenant: Result, + config: &Config, + path: &str, + max_bytes: u64, +) -> Result, BoxError> { + let tenant: Result = Ok(tenant_for_box(tenant)?); + let backend = file_backend(config)?; + #[cfg(feature = "modules")] + { + let settings = backend.settings(config)?; + read_file_in( + registry(backend, config), + tenant, + &settings, + path, + max_bytes, + ) + .await + } + #[cfg(not(feature = "modules"))] + { + let _ = (tenant, backend, path, max_bytes); + Err(modules_disabled()) + } +} + +#[cfg(not(feature = "modules"))] +fn modules_disabled() -> BoxError { + BoxError::Driver( + "TinyBox module support is disabled; sandbox box files are unavailable".to_owned(), + ) +} + +/// Let go of `tenant`'s boxes, on every backend the process holds boxes on: +/// an OpenShell box is closed, an agent37 box only forgotten (it sleeps). +pub async fn release(tenant: &Tenant) { + #[cfg(feature = "modules")] + for cell in [&OPENSHELL_REGISTRY, &AGENT37_REGISTRY] { + if let Some(registry) = cell.get() { + registry.release(tenant).await; + } + } + #[cfg(not(feature = "modules"))] + let _ = tenant; +} + +/// Let go of every box the process holds: OpenShell boxes are closed, agent37 +/// boxes only forgotten, so they are still there after a restart. +pub async fn shutdown() { + #[cfg(feature = "modules")] + for cell in [&OPENSHELL_REGISTRY, &AGENT37_REGISTRY] { + if let Some(registry) = cell.get() { + registry.shutdown().await; + } + } +} + +#[cfg(test)] +#[path = "scripted_driver_fixture.rs"] +pub(crate) mod scripted_driver; + +#[cfg(test)] +#[path = "mod_tests.rs"] +mod tests; diff --git a/crates/openhuman-core/src/sandbox/openshell/mod_tests.rs b/crates/openhuman-core/src/sandbox/boxes/mod_tests.rs similarity index 68% rename from crates/openhuman-core/src/sandbox/openshell/mod_tests.rs rename to crates/openhuman-core/src/sandbox/boxes/mod_tests.rs index ade45b4e8f2..2ab003500c1 100644 --- a/crates/openhuman-core/src/sandbox/openshell/mod_tests.rs +++ b/crates/openhuman-core/src/sandbox/boxes/mod_tests.rs @@ -19,7 +19,7 @@ fn a_call_without_a_tenant_is_refused() { assert_eq!(refused, BoxError::NoTenant); assert_eq!( refused.to_string(), - "no tenant scope; refusing to run a command in a shared sandbox" + "no tenant scope; refusing to use a shared sandbox" ); } @@ -44,6 +44,7 @@ fn settings_come_from_the_runtime_table() { image: "registry.example/agent:3".into(), cpu_millis: 250, memory_bytes: 64 * 1024 * 1024, + workdir: "/sandbox".into(), }) ); assert_eq!( @@ -51,6 +52,7 @@ fn settings_come_from_the_runtime_table() { RegistryLimits { idle_ttl: Duration::from_secs(120), max_live: 4, + retain: None, } ); } @@ -106,6 +108,7 @@ fn zero_registry_limits_are_raised_to_one() { RegistryLimits { idle_ttl: Duration::from_secs(1), max_live: 1, + retain: None, } ); } @@ -142,7 +145,7 @@ async fn an_unscoped_command_creates_no_box() { let refused = run_command( &boxes, Err(NoTenant), - &OpenShellRuntimeConfig::default(), + &BoxSettings::from_config(&OpenShellRuntimeConfig::default()).unwrap(), "id", &HashMap::new(), Duration::from_secs(10), @@ -163,7 +166,7 @@ async fn a_scoped_command_runs_in_its_tenants_box() { let result = run_command( &boxes, Ok(embedded("u1")), - &config, + &BoxSettings::from_config(&config).unwrap(), "id", &HashMap::new(), Duration::from_secs(10), @@ -174,7 +177,7 @@ async fn a_scoped_command_runs_in_its_tenants_box() { assert_eq!(result.stdout, "ok"); assert_eq!( driver.calls()[0], - scripted_driver::Call::Create(BoxSettings::from_config(&config).unwrap()) + scripted_driver::Call::Create(BoxSettings::from_config(&config).unwrap(), None) ); let exec = driver.last_exec().unwrap(); assert_eq!(exec.argv[3], "10"); @@ -213,3 +216,72 @@ async fn files_are_refused_without_a_tenant() { assert_eq!(wrote, Err(BoxError::NoTenant)); assert_eq!(read, Err(BoxError::NoTenant)); } + +fn config_with_backend(backend: crate::config::SandboxBackend) -> Config { + let mut config = Config::default(); + config.sandbox.backend = backend; + config +} + +#[test] +fn the_configured_backend_picks_the_box_backend() { + use crate::config::SandboxBackend; + assert_eq!( + BoxBackend::configured(&config_with_backend(SandboxBackend::OpenShell)), + Some(BoxBackend::OpenShell) + ); + assert_eq!( + BoxBackend::configured(&config_with_backend(SandboxBackend::Agent37)), + Some(BoxBackend::Agent37) + ); + for backend in [ + SandboxBackend::Docker, + SandboxBackend::None, + SandboxBackend::Landlock, + ] { + assert_eq!( + BoxBackend::configured(&config_with_backend(backend.clone())), + None, + "{backend:?}" + ); + } + let mut off = config_with_backend(SandboxBackend::Agent37); + off.sandbox.enabled = Some(false); + assert_eq!(BoxBackend::configured(&off), None); +} + +#[tokio::test] +async fn files_are_refused_when_the_configured_backend_keeps_no_boxes() { + let config = config_with_backend(crate::config::SandboxBackend::Docker); + + let wrote = write_file(Ok(embedded("u1")), &config, "a.txt", b"x").await; + let read = read_file(Ok(embedded("u1")), &config, "a.txt", 10).await; + + assert_eq!(wrote, Err(BoxError::NoBoxBackend)); + assert_eq!(read, Err(BoxError::NoBoxBackend)); + assert_eq!( + BoxError::NoBoxBackend.to_string(), + "the configured sandbox backend keeps no per-tenant box" + ); +} + +#[tokio::test] +async fn agent37_files_are_refused_under_local_only_privacy() { + let mut config = config_with_backend(crate::config::SandboxBackend::Agent37); + config.privacy.mode = crate::config::PrivacyMode::LocalOnly; + + let wrote = write_file(Ok(embedded("u1")), &config, "a.txt", b"x").await; + let read = read_file(Ok(embedded("u1")), &config, "a.txt", 10).await; + + assert_eq!(wrote, Err(BoxError::LocalOnly)); + assert_eq!(read, Err(BoxError::LocalOnly)); +} + +#[tokio::test] +async fn a_missing_tenant_is_refused_before_the_backend_is_considered() { + let config = config_with_backend(crate::config::SandboxBackend::Docker); + assert_eq!( + write_file(Err(NoTenant), &config, "a.txt", b"x").await, + Err(BoxError::NoTenant) + ); +} diff --git a/crates/openhuman-core/src/sandbox/openshell/registry.rs b/crates/openhuman-core/src/sandbox/boxes/registry.rs similarity index 67% rename from crates/openhuman-core/src/sandbox/openshell/registry.rs rename to crates/openhuman-core/src/sandbox/boxes/registry.rs index 6b87824c465..488aae21586 100644 --- a/crates/openhuman-core/src/sandbox/openshell/registry.rs +++ b/crates/openhuman-core/src/sandbox/boxes/registry.rs @@ -1,5 +1,13 @@ //! [`BoxRegistry`]: one live box per tenant, created on first use, reused, -//! and closed when idle, released, or no longer answering. +//! and let go of when idle, released, or no longer answering. +//! +//! A registry over a backend that keeps boxes for their owners +//! ([`RegistryLimits::retain`], agent37) creates each box with its tenant's +//! [`owner_key`], and letting go of a box only forgets it +//! ([`BoxDriver::forget`]): the backend sleeps it, and the next command finds +//! the same box again under the same key. Because forgetting costs nothing, a +//! full retaining registry also forgets its least recently used idle box to +//! make room. Every other registry (OpenShell) closes boxes it lets go of. //! //! State lives in one map behind a `std` mutex that is never held across an //! `.await`. Each tenant's entry counts the commands in flight on it and when @@ -14,12 +22,20 @@ use std::time::Duration; use tokio::time::Instant; -use super::{BoxDriver, BoxError, BoxExec, BoxOutput, BoxRequest, BoxSettings, RegistryLimits}; +use sha2::{Digest, Sha256}; + +use super::{ + BoxDriver, BoxError, BoxExec, BoxOutput, BoxRequest, BoxRetention, BoxSettings, RegistryLimits, +}; use crate::core::runtime::Tenant; use crate::sandbox::types::SandboxExecResult; -/// The working directory commands run in: the box's own workspace. -pub(crate) const BOX_WORKDIR: &str = "/sandbox"; +/// Prefix of every [`owner_key`], naming who chose the key. +const OWNER_KEY_PREFIX: &str = "oh-"; + +/// Domain separation for the [`owner_key`] hash, versioned so a change to the +/// derivation can never collide with keys already in use. +const OWNER_KEY_DOMAIN: &[u8] = b"openhuman.sandbox.box-owner.v1\0"; /// Seconds `timeout` waits after its signal before it kills the command. const KILL_AFTER_SECS: &str = "5"; @@ -155,27 +171,30 @@ impl BoxRegistry { let lease = self.check_out(tenant).await?; let mut replaced = false; loop { - let resource = self.resource_for(&lease.slot, settings).await?; - match self.run(&resource, request).await { + let resource = self + .resource_for(&lease.tenant, &lease.slot, settings) + .await?; + match self.run(&resource, settings, request).await { Ok(Run::Finished(output)) => return Ok(finished(output)), Ok(Run::BackstopFired) => { tracing::warn!( timeout_secs = whole_seconds(request.timeout), - "[sandbox:openshell] box did not answer by the deadline; closing it" + "[sandbox:box] box did not answer by the deadline; letting it go" ); lease.slot.forget(&resource); - self.close_quietly(&resource).await; + self.let_go(&resource).await; return Ok(backstop_timed_out(request.timeout)); } Err(BoxError::UnknownResource) => { // "Gone" is inferred after a failed exec, so the box may - // still exist on the gateway: close it rather than leak it. + // still exist on the gateway: let go of it rather than + // leak it (a retained box is only forgotten). lease.slot.forget(&resource); - self.close_quietly(&resource).await; + self.let_go(&resource).await; if replaced { return Err(BoxError::UnknownResource); } - tracing::warn!("[sandbox:openshell] box is gone; retrying in a new box"); + tracing::warn!("[sandbox:box] box is gone; retrying in a new box"); replaced = true; } Err(error) => return Err(error), @@ -183,33 +202,39 @@ impl BoxRegistry { } } - /// Close every box idle since `now - idle_ttl` or earlier with no command - /// in flight; returns how many were closed. + /// Let go of every box idle since `now - idle_ttl` or earlier with no + /// command in flight (closed, or forgotten when retained); returns how + /// many. pub async fn reap(&self, now: Instant) -> usize { let idle = self.take_idle(&mut self.entries(), now); - let closed = idle.len(); + let reaped = idle.len(); for resource in idle { - self.close_quietly(&resource).await; + self.let_go(&resource).await; } - if closed > 0 { - tracing::debug!(closed, "[sandbox:openshell] reaped idle boxes"); + if reaped > 0 { + tracing::debug!( + reaped, + retained = self.limits.retain.is_some(), + "[sandbox:box] reaped idle boxes" + ); } - closed + reaped } - /// Close `tenant`'s box, if it has one. A command still running in it - /// fails rather than starting another box. + /// Let go of `tenant`'s box, if it has one (closed, or forgotten when + /// retained). A command still running in it fails rather than starting + /// another box. pub async fn release(&self, tenant: &Tenant) { let resource = self .entries() .remove(tenant) .and_then(|entry| entry.slot.retire()); if let Some(resource) = resource { - self.close_quietly(&resource).await; + self.let_go(&resource).await; } } - /// Close every box. + /// Let go of every box: closed, or forgotten when retained. pub async fn shutdown(&self) { let resources: Vec = self .entries() @@ -217,7 +242,7 @@ impl BoxRegistry { .filter_map(|(_, entry)| entry.slot.retire()) .collect(); for resource in resources { - self.close_quietly(&resource).await; + self.let_go(&resource).await; } } @@ -250,12 +275,12 @@ impl BoxRegistry { async fn check_out(&self, tenant: &Tenant) -> Result, BoxError> { let (held, reaped) = self.hold(tenant, Instant::now()); for resource in reaped { - self.close_quietly(&resource).await; + self.let_go(&resource).await; } let Some(slot) = held else { tracing::warn!( max_live = self.limits.max_live, - "[sandbox:openshell] refusing a new box: at capacity" + "[sandbox:box] refusing a new box: at capacity" ); return Err(BoxError::AtCapacity); }; @@ -274,6 +299,9 @@ impl BoxRegistry { let mut reaped = Vec::new(); if !entries.contains_key(tenant) && entries.len() >= self.limits.max_live { reaped = self.take_idle(&mut entries, now); + if entries.len() >= self.limits.max_live && self.limits.retain.is_some() { + reaped.extend(take_least_recently_used(&mut entries)); + } if entries.len() >= self.limits.max_live { return (None, reaped); } @@ -319,8 +347,16 @@ impl BoxRegistry { resources } - /// The slot's box, created now if it has none. - async fn resource_for(&self, slot: &Slot, settings: &BoxSettings) -> Result { + /// The slot's box, created now if it has none. A retaining registry + /// creates it with `tenant`'s retention, so the backend hands back the box + /// it already keeps for the tenant; a refusal is returned as it is, never + /// retried as a disposable box. + async fn resource_for( + &self, + tenant: &Tenant, + slot: &Slot, + settings: &BoxSettings, + ) -> Result { if let Some(resource) = slot.current()? { return Ok(resource); } @@ -328,22 +364,35 @@ impl BoxRegistry { if let Some(resource) = slot.current()? { return Ok(resource); } - tracing::debug!(image = %settings.image, "[sandbox:openshell] creating a box"); - let resource = self.driver.create(settings).await?; + let retention: Option = self + .limits + .retain + .map(|policy| policy.for_owner(owner_key(tenant))); + tracing::debug!( + image = %settings.image, + retained = retention.is_some(), + "[sandbox:box] creating a box" + ); + let resource = self.driver.create(settings, retention.as_ref()).await?; if !slot.store(&resource) { - self.close_quietly(&resource).await; + self.let_go(&resource).await; return Err(BoxError::Released); } - tracing::debug!(resource = %resource, "[sandbox:openshell] box ready"); + tracing::debug!(resource = %resource, "[sandbox:box] box ready"); Ok(resource) } - async fn run(&self, resource: &str, request: &BoxRequest) -> Result { + async fn run( + &self, + resource: &str, + settings: &BoxSettings, + request: &BoxRequest, + ) -> Result { let secs = whole_seconds(request.timeout); let deadline = Duration::from_secs(secs).saturating_add(BACKSTOP_MARGIN); let exec = BoxExec { argv: timeout_argv(secs, &request.command), - cwd: BOX_WORKDIR.to_owned(), + cwd: settings.workdir.clone(), env: request.env.clone(), deadline, }; @@ -353,12 +402,21 @@ impl BoxRegistry { } } - async fn close_quietly(&self, resource: &str) { - if let Err(error) = self.driver.close(resource).await { + /// Let go of a box this registry no longer tracks: forget a retained one + /// (its backend keeps it, asleep), close any other. A failure is logged. + async fn let_go(&self, resource: &str) { + let retained = self.limits.retain.is_some(); + let outcome = if retained { + self.driver.forget(resource).await + } else { + self.driver.close(resource).await + }; + if let Err(error) = outcome { tracing::warn!( resource = %resource, + retained, error = %error, - "[sandbox:openshell] closing a box failed" + "[sandbox:box] letting go of a box failed" ); } } @@ -414,6 +472,45 @@ fn backstop_timed_out(timeout: Duration) -> SandboxExecResult { } } +/// Remove the least recently used entry with no command in flight and +/// return its box to let go of. Only a retaining registry does this: its box +/// is forgotten, not deleted, so the tenant finds it again next time. +fn take_least_recently_used(entries: &mut HashMap) -> Option { + let tenant = entries + .iter() + .filter(|(_, entry)| entry.in_flight == 0) + .min_by_key(|(_, entry)| entry.last_used) + .map(|(tenant, _)| tenant.clone())?; + entries + .remove(&tenant) + .and_then(|entry| entry.slot.retire()) +} + +/// The opaque key a retaining backend keeps `tenant`'s box under: `oh-` +/// and the hex SHA-256 of the whole tenant (profile and agent, each +/// length-prefixed and marked present or absent), so it is stable across +/// restarts, distinct per tenant, never a raw id, and within the backend's +/// key alphabet (`[A-Za-z0-9_-]`, 67 characters). +pub fn owner_key(tenant: &Tenant) -> String { + let mut hash = Sha256::new(); + hash.update(OWNER_KEY_DOMAIN); + for part in [&tenant.profile, &tenant.agent] { + match part { + None => hash.update([0u8]), + Some(value) => { + hash.update([1u8]); + hash.update((value.len() as u64).to_le_bytes()); + hash.update(value.as_bytes()); + } + } + } + format!("{OWNER_KEY_PREFIX}{}", hex::encode(hash.finalize())) +} + #[cfg(test)] #[path = "registry_tests.rs"] mod tests; + +#[cfg(test)] +#[path = "registry_retain_tests.rs"] +mod retain_tests; diff --git a/crates/openhuman-core/src/sandbox/boxes/registry_retain_tests.rs b/crates/openhuman-core/src/sandbox/boxes/registry_retain_tests.rs new file mode 100644 index 00000000000..170448a3adf --- /dev/null +++ b/crates/openhuman-core/src/sandbox/boxes/registry_retain_tests.rs @@ -0,0 +1,261 @@ +//! A retaining registry (agent37): boxes are created with their owner's key, +//! and every path that lets go of one forgets it, never closes it. + +use super::*; +use crate::sandbox::boxes::scripted_driver::{ExecStep, ScriptedDriver}; +use crate::sandbox::boxes::{BoxRetention, RetainPolicy}; +use std::collections::BTreeMap; + +const TTL: Duration = Duration::from_secs(900); +const THIRTY_DAYS: u64 = 30 * 24 * 60 * 60; + +fn policy() -> RetainPolicy { + RetainPolicy { + idle_sleep_secs: 900, + delete_after_secs: THIRTY_DAYS, + } +} + +fn retaining(driver: &Arc, max_live: usize) -> Arc> { + BoxRegistry::new( + Arc::clone(driver), + RegistryLimits { + idle_ttl: TTL, + max_live, + retain: Some(policy()), + }, + ) +} + +fn settings() -> BoxSettings { + BoxSettings { + image: "agent37-base".into(), + cpu_millis: 2_000, + memory_bytes: 4 * 1024 * 1024 * 1024, + workdir: "/home/node".into(), + } +} + +fn request(command: &str) -> BoxRequest { + BoxRequest { + command: command.into(), + env: BTreeMap::new(), + timeout: Duration::from_secs(30), + } +} + +fn user(id: &str) -> Tenant { + Tenant { + profile: None, + agent: Some(id.into()), + } +} + +fn kept_for(id: &str) -> Option { + Some(policy().for_owner(owner_key(&user(id)))) +} + +#[test] +fn the_owner_key_is_stable_opaque_and_valid_for_the_backend() { + let key = owner_key(&user("+15551234567")); + assert_eq!(key, owner_key(&user("+15551234567"))); + assert!(!key.contains("15551234567"), "{key}"); + assert!((1..=128).contains(&key.len()), "{key}"); + assert!( + key.bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-'), + "{key}" + ); +} + +#[test] +fn every_part_of_the_tenant_changes_the_owner_key() { + let tenants = [ + Tenant { + profile: None, + agent: None, + }, + Tenant { + profile: Some(String::new()), + agent: None, + }, + Tenant { + profile: None, + agent: Some(String::new()), + }, + Tenant { + profile: Some("a".into()), + agent: Some("b".into()), + }, + Tenant { + profile: Some("ab".into()), + agent: None, + }, + Tenant { + profile: None, + agent: Some("ab".into()), + }, + user("u1"), + user("u2"), + ]; + let keys: std::collections::HashSet = tenants.iter().map(owner_key).collect(); + assert_eq!(keys.len(), tenants.len()); +} + +#[tokio::test(start_paused = true)] +async fn each_box_is_created_with_its_owners_key_and_policy() { + let driver = ScriptedDriver::new(); + let boxes = retaining(&driver, 10); + + boxes + .exec(&user("u1"), &settings(), &request("pwd")) + .await + .unwrap(); + boxes + .exec(&user("u2"), &settings(), &request("pwd")) + .await + .unwrap(); + + assert_eq!(driver.retentions(), vec![kept_for("u1"), kept_for("u2")]); + let exec = driver.last_exec().unwrap(); + assert_eq!(exec.cwd, "/home/node"); +} + +#[tokio::test(start_paused = true)] +async fn reaping_forgets_an_idle_box_and_the_next_command_finds_it_again() { + let driver = ScriptedDriver::new(); + let boxes = retaining(&driver, 10); + boxes + .exec(&user("u1"), &settings(), &request("touch a")) + .await + .unwrap(); + + assert_eq!(boxes.reap(Instant::now() + TTL).await, 1); + assert_eq!(driver.forgotten(), vec!["box-0"]); + assert!(driver.closed().is_empty()); + + boxes + .exec(&user("u1"), &settings(), &request("ls")) + .await + .unwrap(); + assert_eq!(driver.exec_resources(), vec!["box-0", "box-0"]); + assert_eq!(driver.retentions(), vec![kept_for("u1"), kept_for("u1")]); +} + +#[tokio::test(start_paused = true)] +async fn release_and_shutdown_forget_retained_boxes() { + let driver = ScriptedDriver::new(); + let boxes = retaining(&driver, 10); + for id in ["u1", "u2", "u3"] { + boxes + .exec(&user(id), &settings(), &request("pwd")) + .await + .unwrap(); + } + + boxes.release(&user("u1")).await; + boxes.shutdown().await; + + let mut forgotten = driver.forgotten(); + forgotten.sort(); + assert_eq!(forgotten, vec!["box-0", "box-1", "box-2"]); + assert!(driver.closed().is_empty()); + assert_eq!(boxes.live(), 0); +} + +#[tokio::test(start_paused = true)] +async fn a_box_reported_gone_is_forgotten_not_closed() { + let driver = ScriptedDriver::new(); + let boxes = retaining(&driver, 10); + driver.then(ExecStep::Fail(BoxError::UnknownResource)); + + boxes + .exec(&user("u1"), &settings(), &request("pwd")) + .await + .unwrap(); + + assert_eq!(driver.forgotten(), vec!["box-0"]); + assert!(driver.closed().is_empty()); +} + +#[tokio::test(start_paused = true)] +async fn a_box_that_misses_the_deadline_is_forgotten_not_closed() { + let driver = ScriptedDriver::new(); + let boxes = retaining(&driver, 10); + driver.then(ExecStep::Hang); + + let result = boxes + .exec(&user("u1"), &settings(), &request("sleep 999")) + .await + .unwrap(); + + assert!(result.timed_out); + assert_eq!(driver.forgotten(), vec!["box-0"]); + assert!(driver.closed().is_empty()); +} + +#[tokio::test(start_paused = true)] +async fn a_full_registry_lets_go_of_its_least_recently_used_idle_box() { + let driver = ScriptedDriver::new(); + let boxes = retaining(&driver, 2); + boxes + .exec(&user("u1"), &settings(), &request("pwd")) + .await + .unwrap(); + tokio::time::advance(Duration::from_secs(5)).await; + boxes + .exec(&user("u2"), &settings(), &request("pwd")) + .await + .unwrap(); + tokio::time::advance(Duration::from_secs(5)).await; + + // Neither box has been idle for the TTL, but a retained box let go of + // is only asleep, so a new tenant takes the oldest one's place. + boxes + .exec(&user("u3"), &settings(), &request("pwd")) + .await + .unwrap(); + + assert_eq!(driver.forgotten(), vec!["box-0"]); + assert!(driver.closed().is_empty()); + assert_eq!(boxes.live(), 2); +} + +#[tokio::test(start_paused = true)] +async fn a_full_registry_never_lets_go_of_a_box_with_a_command_in_flight() { + let driver = ScriptedDriver::new(); + let boxes = retaining(&driver, 1); + let gate = Arc::new(tokio::sync::Notify::new()); + driver.then(ExecStep::WaitThenReply(Arc::clone(&gate))); + let running = { + let boxes = Arc::clone(&boxes); + tokio::spawn(async move { boxes.exec(&user("u1"), &settings(), &request("make")).await }) + }; + tokio::task::yield_now().await; + tokio::task::yield_now().await; + + let refused = boxes + .exec(&user("u2"), &settings(), &request("pwd")) + .await + .unwrap_err(); + + assert_eq!(refused, BoxError::AtCapacity); + assert!(driver.forgotten().is_empty()); + gate.notify_one(); + running.await.unwrap().unwrap(); +} + +#[tokio::test(start_paused = true)] +async fn a_refused_retained_create_is_never_retried_as_a_disposable_box() { + let driver = ScriptedDriver::new(); + let boxes = retaining(&driver, 10); + driver.fail_next_creates(1); + + let refused = boxes + .exec(&user("u1"), &settings(), &request("pwd")) + .await + .unwrap_err(); + + assert!(matches!(refused, BoxError::Driver(_)), "{refused:?}"); + assert_eq!(driver.retentions(), vec![kept_for("u1")]); +} diff --git a/crates/openhuman-core/src/sandbox/openshell/registry_tests.rs b/crates/openhuman-core/src/sandbox/boxes/registry_tests.rs similarity index 98% rename from crates/openhuman-core/src/sandbox/openshell/registry_tests.rs rename to crates/openhuman-core/src/sandbox/boxes/registry_tests.rs index d29923c880d..bf60e7052aa 100644 --- a/crates/openhuman-core/src/sandbox/openshell/registry_tests.rs +++ b/crates/openhuman-core/src/sandbox/boxes/registry_tests.rs @@ -1,5 +1,5 @@ use super::*; -use crate::sandbox::openshell::scripted_driver::{ok_output, Call, ExecStep, ScriptedDriver}; +use crate::sandbox::boxes::scripted_driver::{ok_output, Call, ExecStep, ScriptedDriver}; use std::collections::BTreeMap; use tokio::sync::Notify; @@ -9,6 +9,7 @@ fn limits(max_live: usize) -> RegistryLimits { RegistryLimits { idle_ttl: TTL, max_live, + retain: None, } } @@ -17,6 +18,7 @@ fn settings() -> BoxSettings { image: "registry.example/agent:1".into(), cpu_millis: 1_000, memory_bytes: 256 * 1024 * 1024, + workdir: "/sandbox".into(), } } @@ -82,7 +84,7 @@ async fn the_box_enforces_the_deadline_from_its_own_workspace() { assert_eq!(exec.cwd, "/sandbox"); assert_eq!(exec.env, request.env); assert_eq!(exec.deadline, Duration::from_secs(30) + BACKSTOP_MARGIN); - assert_eq!(driver.calls()[0], Call::Create(settings())); + assert_eq!(driver.calls()[0], Call::Create(settings(), None)); } #[test] @@ -253,7 +255,7 @@ async fn reaping_an_idle_box_makes_room_for_a_new_tenant() { .unwrap(); let created = calls .iter() - .rposition(|call| matches!(call, Call::Create(_))) + .rposition(|call| matches!(call, Call::Create(..))) .unwrap(); assert!(closed < created); assert_eq!(boxes.live(), 1); diff --git a/crates/openhuman-core/src/sandbox/openshell/scripted_driver_fixture.rs b/crates/openhuman-core/src/sandbox/boxes/scripted_driver_fixture.rs similarity index 76% rename from crates/openhuman-core/src/sandbox/openshell/scripted_driver_fixture.rs rename to crates/openhuman-core/src/sandbox/boxes/scripted_driver_fixture.rs index 8af3159df32..775e55fa353 100644 --- a/crates/openhuman-core/src/sandbox/openshell/scripted_driver_fixture.rs +++ b/crates/openhuman-core/src/sandbox/boxes/scripted_driver_fixture.rs @@ -6,7 +6,7 @@ //! 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::collections::{HashMap, VecDeque}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; @@ -15,14 +15,15 @@ use std::time::Duration; use async_trait::async_trait; use tokio::sync::Notify; -use super::{BoxDriver, BoxError, BoxExec, BoxOutput, BoxSettings}; +use super::{BoxDriver, BoxError, BoxExec, BoxOutput, BoxRetention, BoxSettings}; /// One call the registry made. #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) enum Call { - Create(BoxSettings), + Create(BoxSettings, Option), Exec { resource: String, exec: BoxExec }, Close(String), + Forget(String), } /// How the next exec answers. @@ -50,6 +51,8 @@ pub(crate) struct ScriptedDriver { create_failures: AtomicUsize, close_fails: AtomicBool, box_root: Mutex>, + /// Retained boxes by owner key, as a retaining backend keeps them. + kept: Mutex>, } impl ScriptedDriver { @@ -95,7 +98,7 @@ impl ScriptedDriver { pub(crate) fn created(&self) -> usize { self.calls() .iter() - .filter(|call| matches!(call, Call::Create(_))) + .filter(|call| matches!(call, Call::Create(..))) .count() } @@ -109,6 +112,27 @@ impl ScriptedDriver { .collect() } + pub(crate) fn forgotten(&self) -> Vec { + self.calls() + .into_iter() + .filter_map(|call| match call { + Call::Forget(resource) => Some(resource), + _ => None, + }) + .collect() + } + + /// The retention each create asked for, in order. + pub(crate) fn retentions(&self) -> Vec> { + self.calls() + .into_iter() + .filter_map(|call| match call { + Call::Create(_, retention) => Some(retention), + _ => None, + }) + .collect() + } + pub(crate) fn exec_resources(&self) -> Vec { self.calls() .into_iter() @@ -141,8 +165,12 @@ pub(crate) fn ok_output() -> BoxOutput { #[async_trait] impl BoxDriver for ScriptedDriver { - async fn create(&self, settings: &BoxSettings) -> Result { - self.record(Call::Create(settings.clone())); + async fn create( + &self, + settings: &BoxSettings, + retention: Option<&BoxRetention>, + ) -> Result { + self.record(Call::Create(settings.clone(), retention.cloned())); let delay = *self.create_delay.lock().unwrap(); tokio::time::sleep(delay).await; let failures = self.create_failures.load(Ordering::SeqCst); @@ -150,7 +178,19 @@ impl BoxDriver for ScriptedDriver { self.create_failures.store(failures - 1, Ordering::SeqCst); return Err(BoxError::Driver("create refused".into())); } + // A retaining backend hands back the box it already keeps for the key. + if let Some(retention) = retention { + if let Some(kept) = self.kept.lock().unwrap().get(&retention.key) { + return Ok(kept.clone()); + } + } let resource = format!("box-{}", self.next_id.fetch_add(1, Ordering::SeqCst)); + if let Some(retention) = retention { + self.kept + .lock() + .unwrap() + .insert(retention.key.clone(), resource.clone()); + } if let Some(dir) = self.box_dir(&resource) { std::fs::create_dir_all(dir).expect("create a box directory"); } @@ -189,6 +229,14 @@ impl BoxDriver for ScriptedDriver { } Ok(()) } + + async fn forget(&self, resource: &str) -> Result<(), BoxError> { + self.record(Call::Forget(resource.to_owned())); + if self.close_fails.load(Ordering::SeqCst) { + return Err(BoxError::Driver("forget refused".into())); + } + Ok(()) + } } /// Run `exec` in `dir`, standing in for the box's work folder. diff --git a/crates/openhuman-core/src/sandbox/boxes/types.rs b/crates/openhuman-core/src/sandbox/boxes/types.rs new file mode 100644 index 00000000000..411bbace3b5 --- /dev/null +++ b/crates/openhuman-core/src/sandbox/boxes/types.rs @@ -0,0 +1,322 @@ +//! The box registry's vocabulary: what a box is created with, how long it is +//! kept for its owner, the command it runs, what comes back, how it fails, +//! and the [`BoxDriver`] seam that creates, runs, closes and forgets boxes. + +use std::collections::BTreeMap; +use std::time::Duration; + +use async_trait::async_trait; + +use crate::config::{Agent37RuntimeConfig, OpenShellRuntimeConfig}; + +/// The work folder of an OpenShell box: the base image's `/sandbox` workspace. +pub const OPENSHELL_WORKDIR: &str = "/sandbox"; + +/// The work folder of an agent37 box: its user's home. +pub const AGENT37_WORKDIR: &str = "/home/node"; + +/// The fewest seconds agent37 lets a box sit idle before it sleeps. +pub const MIN_IDLE_SLEEP_SECS: u32 = 300; + +/// The most seconds agent37 lets a box sit idle before it sleeps. +pub const MAX_IDLE_SLEEP_SECS: u32 = 86_400; + +/// What a new box is created with. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct BoxSettings { + /// OCI image reference the box starts from. + pub image: String, + /// CPU allowance in thousandths of a core. + pub cpu_millis: u32, + /// Memory limit in bytes, always a whole number of mebibytes. + pub memory_bytes: u64, + /// The folder commands run in and file paths are relative to. + pub workdir: String, +} + +impl BoxSettings { + /// The settings `[runtime.openshell]` gives every new box. + /// + /// # Errors + /// + /// [`BoxError::InvalidConfig`] when `image` is blank or `cpu_millis` or + /// `memory_mb` is zero; [`BoxError::InvalidMemory`] when `memory_mb` does + /// not fit in bytes. + pub fn from_config(config: &OpenShellRuntimeConfig) -> Result { + if config.image.trim().is_empty() { + return Err(BoxError::InvalidConfig( + "[runtime.openshell] image must not be blank", + )); + } + if config.cpu_millis == 0 || config.memory_mb == 0 { + return Err(BoxError::InvalidConfig( + "[runtime.openshell] cpu_millis and memory_mb must be positive", + )); + } + let memory_bytes = config.memory_bytes().ok_or(BoxError::InvalidMemory { + memory_mb: config.memory_mb, + })?; + Ok(Self { + image: config.image.clone(), + cpu_millis: config.cpu_millis, + memory_bytes, + workdir: OPENSHELL_WORKDIR.to_owned(), + }) + } + + /// The settings `[runtime.agent37]` gives every new box. `image` carries + /// the template name (agent37 starts a box from a registered template, + /// not an OCI image). The service snaps CPU and memory up to a fixed + /// instance shape, so they are a request: a request over the largest + /// shape is logged, and a memory size too large to express in bytes asks + /// for the service's maximum. + /// + /// # Errors + /// + /// [`BoxError::InvalidConfig`] when `template` is blank. + pub fn from_agent37(config: &Agent37RuntimeConfig) -> Result { + if config.template.trim().is_empty() { + return Err(BoxError::InvalidConfig( + "[runtime.agent37] template must not be blank", + )); + } + if config.exceeds_largest_shape() { + tracing::warn!( + cpu_millis = config.cpu_millis, + memory_mb = config.memory_mb, + "[sandbox:box] agent37 request exceeds the largest instance shape and will be capped" + ); + } + Ok(Self { + image: config.template.clone(), + cpu_millis: config.cpu_millis, + memory_bytes: config.memory_bytes().unwrap_or(u64::MAX), + workdir: AGENT37_WORKDIR.to_owned(), + }) + } +} + +/// How long a retaining backend keeps a tenant's box: it sleeps after +/// `idle_sleep_secs` without a command and is deleted after +/// `delete_after_secs` asleep. The same for every tenant of a registry. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct RetainPolicy { + /// Seconds without a command before the box falls asleep. + pub idle_sleep_secs: u32, + /// Seconds a box may sleep before the backend deletes it. + pub delete_after_secs: u64, +} + +impl RetainPolicy { + /// The policy `[runtime.agent37]` sets: `idle_sleep_secs` clamped to the + /// range agent37 accepts (300 to 86400), and a zero `delete_after_secs` + /// (which would delete a box as soon as it sleeps) raised to 1. + pub fn from_agent37(config: &Agent37RuntimeConfig) -> Self { + Self { + idle_sleep_secs: config + .idle_sleep_secs + .clamp(MIN_IDLE_SLEEP_SECS, MAX_IDLE_SLEEP_SECS), + delete_after_secs: config.delete_after_secs.max(1), + } + } + + /// This policy for the box of the owner `key` names. + pub fn for_owner(self, key: String) -> BoxRetention { + BoxRetention { + key, + idle_sleep_secs: self.idle_sleep_secs, + delete_after_secs: self.delete_after_secs, + } + } +} + +/// What a retained box is created with: its owner's key and how long it is +/// kept. A later create with the same key finds the same box again. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct BoxRetention { + /// An opaque, stable key for the box's owner, derived from the tenant + /// (never a raw id): `[A-Za-z0-9_-]`, at most 128 characters. + pub key: String, + /// Seconds without a command before the box falls asleep. + pub idle_sleep_secs: u32, + /// Seconds a box may sleep before the backend deletes it. + pub delete_after_secs: u64, +} + +/// Registry-wide bounds, fixed when the registry is built. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct RegistryLimits { + /// How long a box may sit idle before it is closed. + pub idle_ttl: Duration, + /// The most boxes alive at once. + pub max_live: usize, + /// `Some` for a backend that keeps each tenant's box for it: boxes are + /// created with the tenant's [`BoxRetention`], and the registry only + /// ever forgets them ([`BoxDriver::forget`]), never closes them. + pub retain: Option, +} + +impl RegistryLimits { + /// The bounds `[runtime.openshell]` sets. A zero `max_live` would refuse + /// every command and a zero `idle_ttl_secs` would reap every box at once, + /// so each is raised to 1. + pub fn from_config(config: &OpenShellRuntimeConfig) -> Self { + Self { + idle_ttl: Duration::from_secs(config.idle_ttl_secs.max(1)), + max_live: config.max_live.max(1), + retain: None, + } + } + + /// The bounds `[runtime.agent37]` sets. A box is kept for its tenant + /// ([`RetainPolicy::from_agent37`]); the registry lets go of its handle + /// once the box has been idle as long as it takes to fall asleep, and a + /// zero `max_live` is raised to 1. + pub fn from_agent37(config: &Agent37RuntimeConfig) -> Self { + let retain = RetainPolicy::from_agent37(config); + Self { + idle_ttl: Duration::from_secs(u64::from(retain.idle_sleep_secs)), + max_live: config.max_live.max(1), + retain: Some(retain), + } + } +} + +/// One shell command for a tenant's box. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct BoxRequest { + /// The command line, run with `sh -c`. + pub command: String, + /// The only variables set for the command; nothing from the host. + pub env: BTreeMap, + /// How long the command may run. + pub timeout: Duration, +} + +/// What a driver runs inside a box: the program, already wrapped in the +/// box-side deadline. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct BoxExec { + /// Unshelled program and arguments. + pub argv: Vec, + /// Working directory inside the box. + pub cwd: String, + /// Variables set for the program. + pub env: BTreeMap, + /// When the registry gives up on the reply; a driver's own transport + /// deadline must not fire before it. + pub deadline: Duration, +} + +/// What a command left behind. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct BoxOutput { + /// The program's exit status. + pub exit_code: i32, + /// Standard output, unmodified. + pub stdout: Vec, + /// Standard error, unmodified. + pub stderr: Vec, +} + +/// Why a command could not run in a box. The messages are written to read +/// well as a tool result. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum BoxError { + /// Every box is in use and none has been idle long enough to reap. + #[error("the sandbox service is at capacity; try again shortly")] + AtCapacity, + /// The box is gone: closed, lost, or no longer able to run commands. + #[error("the sandbox box is no longer available")] + UnknownResource, + /// The box was released or shut down while the command was waiting on it. + #[error("the sandbox was released while the command was running")] + Released, + /// The call carries no tenant, so it has no box of its own. + #[error("no tenant scope; refusing to use a shared sandbox")] + NoTenant, + /// The configured sandbox backend keeps no box per tenant, so there is no + /// box to run in or move files to. + #[error("the configured sandbox backend keeps no per-tenant box")] + NoBoxBackend, + /// The box runs on a hosted service, which local-only privacy forbids. + #[error( + "the sandbox runs on a hosted service, which [privacy] mode = \"local_only\" does not permit" + )] + LocalOnly, + /// `[runtime.openshell] memory_mb` is too large to express in bytes. + #[error("sandbox memory of {memory_mb} MiB is too large")] + InvalidMemory { + /// The configured value. + memory_mb: u64, + }, + /// A `[runtime.openshell]` or `[runtime.agent37]` value is out of range; + /// the message names the table. + #[error("invalid sandbox setting: {0}")] + InvalidConfig(&'static str), + /// 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), +} + +/// Creates, runs, closes and forgets boxes. The registry owns their +/// lifecycle; a driver only performs each step. +#[async_trait] +pub trait BoxDriver: Send + Sync + 'static { + /// Create a box and return its resource id. With `retention`, the box is + /// kept for its owner: a backend that already keeps one under the same + /// key hands that one back, and a backend that cannot retain boxes + /// refuses rather than create a disposable one. + async fn create( + &self, + settings: &BoxSettings, + retention: Option<&BoxRetention>, + ) -> Result; + + /// Run one program in the box and collect its output. A box that is gone + /// fails with [`BoxError::UnknownResource`]. + async fn exec(&self, resource: &str, exec: &BoxExec) -> Result; + + /// Close the box and release what it holds. + async fn close(&self, resource: &str) -> Result<(), BoxError>; + + /// Let go of a retained box: drop this host's handle on it and leave the + /// box, and its files, to its backend, which sleeps it when idle and + /// deletes it only once it has slept past its retention. + async fn forget(&self, resource: &str) -> Result<(), BoxError>; +} diff --git a/crates/openhuman-core/src/sandbox/mod.rs b/crates/openhuman-core/src/sandbox/mod.rs index 309c1881ffd..5fae756a33d 100644 --- a/crates/openhuman-core/src/sandbox/mod.rs +++ b/crates/openhuman-core/src/sandbox/mod.rs @@ -10,10 +10,10 @@ //! explicit elevated escape paths. pub mod agent37; +pub mod boxes; pub mod docker; pub(crate) mod local_grants; pub(crate) mod native_jail; -pub mod openshell; pub(crate) mod operator; pub mod ops; #[cfg(feature = "security-module")] @@ -28,7 +28,7 @@ pub(crate) mod shell_progress; pub(crate) mod spawn_plan; pub mod types; -pub use openshell::{ +pub use boxes::{ read_file as read_box_file, write_file as write_box_file, BoxError, MAX_FILE_BYTES as MAX_BOX_FILE_BYTES, }; diff --git a/crates/openhuman-core/src/sandbox/openshell/mod.rs b/crates/openhuman-core/src/sandbox/openshell/mod.rs deleted file mode 100644 index b461f0ed2ab..00000000000 --- a/crates/openhuman-core/src/sandbox/openshell/mod.rs +++ /dev/null @@ -1,257 +0,0 @@ -//! The OpenShell sandbox backend: one long-lived box per tenant. -//! -//! With `[security.sandbox] backend = "openshell"`, a sandboxed shell command -//! runs in a box the TinyBox module creates on an NVIDIA OpenShell gateway -//! (`[runtime.openshell]`). Unlike the Docker backend, which starts a -//! container per command, a box outlives the command: [`BoxRegistry`] keeps -//! one per [`Tenant`], so files a command writes are there for the next one. -//! -//! - **Keyed on the whole tenant.** An embedded host runs one agent per end -//! user with no profile, so keying on the profile alone would put every user -//! in one box. A call with no tenant ([`NoTenant`]) is refused, never sent -//! to a shared box. -//! - **Created once, reused, reaped.** Concurrent first commands make one box. -//! A box idle for `idle_ttl_secs` is closed by a background reaper, and -//! `max_live` caps the boxes alive at once. -//! - **The box enforces the deadline.** Commands run as -//! `timeout -k 5 sh -c ` in `/sandbox`, with only the -//! 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 -//! it, so `idle_ttl_secs` and `max_live` changes take effect on restart. - -#[cfg(feature = "modules")] -mod bus_driver; -mod files; -mod registry; -mod types; - -use std::collections::{BTreeMap, HashMap}; -use std::ffi::OsString; -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; -use crate::config::{Config, OpenShellRuntimeConfig}; -use crate::core::runtime::{DispatchCtx, NoTenant, Tenant}; - -/// The tenant a box is kept for: the call's whole tenant, or a refusal. -/// -/// # Errors -/// -/// [`BoxError::NoTenant`] when the call carries no tenant. -pub fn tenant_for_box(tenant: Result) -> Result { - tenant.map_err(|NoTenant| { - tracing::warn!("[sandbox:openshell] refusing a command with no tenant scope"); - BoxError::NoTenant - }) -} - -/// The command's variables as UTF-8, refusing any that are not. -/// -/// # Errors -/// -/// [`BoxError::NonUtf8Env`] when a name or value is not UTF-8. -pub fn box_env( - extra_env: &HashMap, -) -> Result, BoxError> { - extra_env - .iter() - .map(|(name, value)| match (name.to_str(), value.to_str()) { - (Some(name), Some(value)) => Ok((name.to_owned(), value.to_owned())), - _ => Err(BoxError::NonUtf8Env), - }) - .collect() -} - -/// Run `command` in the box of the tenant `tenant` resolves to. -/// -/// # Errors -/// -/// [`BoxError::NoTenant`] before any box is touched when there is no tenant; -/// otherwise the settings, environment and registry errors. -pub async fn run_command( - registry: &BoxRegistry, - tenant: Result, - openshell: &OpenShellRuntimeConfig, - command: &str, - extra_env: &HashMap, - timeout: Duration, -) -> Result { - let tenant = tenant_for_box(tenant)?; - let settings = BoxSettings::from_config(openshell)?; - let request = BoxRequest { - command: command.to_owned(), - env: box_env(extra_env)?, - timeout, - }; - registry.exec(&tenant, &settings, &request).await -} - -#[cfg(feature = "modules")] -static REGISTRY: std::sync::OnceLock>> = - std::sync::OnceLock::new(); - -/// The process's registry, built (and its reaper started) on first use. -#[cfg(feature = "modules")] -fn registry(config: &Config) -> &'static std::sync::Arc> { - let registry = REGISTRY.get_or_init(|| { - BoxRegistry::new( - std::sync::Arc::new(BusBoxDriver::new(config.clone())), - RegistryLimits::from_config(&config.runtime.openshell), - ) - }); - registry.start_reaper(); - registry -} - -/// Run a sandboxed shell command in the calling tenant's OpenShell box. -/// -/// # Errors -/// -/// Every [`BoxError`], and a refusal when this build has no module support. -pub(crate) async fn execute( - ctx: &DispatchCtx, - config: &Config, - command: &str, - extra_env: &HashMap, - timeout: Duration, -) -> anyhow::Result { - #[cfg(feature = "modules")] - { - tracing::debug!( - timeout_secs = timeout.as_secs(), - "[sandbox:openshell] running a command" - ); - run_command( - registry(config), - ctx.tenant(), - &config.runtime.openshell, - command, - extra_env, - timeout, - ) - .await - .map_err(anyhow::Error::from) - } - #[cfg(not(feature = "modules"))] - { - let _ = (ctx, config, command, extra_env, timeout); - anyhow::bail!( - "TinyBox module support is disabled; OpenShell sandbox execution is unavailable" - ) - } -} - -/// 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: Result = 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: Result = 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")] - if let Some(registry) = REGISTRY.get() { - registry.release(tenant).await; - } - #[cfg(not(feature = "modules"))] - let _ = tenant; -} - -/// Close every box the process holds. -pub async fn shutdown() { - #[cfg(feature = "modules")] - if let Some(registry) = REGISTRY.get() { - registry.shutdown().await; - } -} - -#[cfg(test)] -#[path = "scripted_driver_fixture.rs"] -pub(crate) mod scripted_driver; - -#[cfg(test)] -#[path = "mod_tests.rs"] -mod tests; diff --git a/crates/openhuman-core/src/sandbox/openshell/types.rs b/crates/openhuman-core/src/sandbox/openshell/types.rs deleted file mode 100644 index c2a88cfee26..00000000000 --- a/crates/openhuman-core/src/sandbox/openshell/types.rs +++ /dev/null @@ -1,187 +0,0 @@ -//! The box registry's vocabulary: what a box is created with, the command it -//! runs, what comes back, how it fails, and the [`BoxDriver`] seam that -//! creates, runs and closes boxes. - -use std::collections::BTreeMap; -use std::time::Duration; - -use async_trait::async_trait; - -use crate::config::OpenShellRuntimeConfig; - -/// What a new box is created with. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct BoxSettings { - /// OCI image reference the box starts from. - pub image: String, - /// CPU allowance in thousandths of a core. - pub cpu_millis: u32, - /// Memory limit in bytes, always a whole number of mebibytes. - pub memory_bytes: u64, -} - -impl BoxSettings { - /// The settings `[runtime.openshell]` gives every new box. - /// - /// # Errors - /// - /// [`BoxError::InvalidConfig`] when `image` is blank or `cpu_millis` or - /// `memory_mb` is zero; [`BoxError::InvalidMemory`] when `memory_mb` does - /// not fit in bytes. - pub fn from_config(config: &OpenShellRuntimeConfig) -> Result { - if config.image.trim().is_empty() { - return Err(BoxError::InvalidConfig("image must not be blank")); - } - if config.cpu_millis == 0 || config.memory_mb == 0 { - return Err(BoxError::InvalidConfig( - "cpu_millis and memory_mb must be positive", - )); - } - let memory_bytes = config.memory_bytes().ok_or(BoxError::InvalidMemory { - memory_mb: config.memory_mb, - })?; - Ok(Self { - image: config.image.clone(), - cpu_millis: config.cpu_millis, - memory_bytes, - }) - } -} - -/// Registry-wide bounds, fixed when the registry is built. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct RegistryLimits { - /// How long a box may sit idle before it is closed. - pub idle_ttl: Duration, - /// The most boxes alive at once. - pub max_live: usize, -} - -impl RegistryLimits { - /// The bounds `[runtime.openshell]` sets. A zero `max_live` would refuse - /// every command and a zero `idle_ttl_secs` would reap every box at once, - /// so each is raised to 1. - pub fn from_config(config: &OpenShellRuntimeConfig) -> Self { - Self { - idle_ttl: Duration::from_secs(config.idle_ttl_secs.max(1)), - max_live: config.max_live.max(1), - } - } -} - -/// One shell command for a tenant's box. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct BoxRequest { - /// The command line, run with `sh -c`. - pub command: String, - /// The only variables set for the command; nothing from the host. - pub env: BTreeMap, - /// How long the command may run. - pub timeout: Duration, -} - -/// What a driver runs inside a box: the program, already wrapped in the -/// box-side deadline. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct BoxExec { - /// Unshelled program and arguments. - pub argv: Vec, - /// Working directory inside the box. - pub cwd: String, - /// Variables set for the program. - pub env: BTreeMap, - /// When the registry gives up on the reply; a driver's own transport - /// deadline must not fire before it. - pub deadline: Duration, -} - -/// What a command left behind. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct BoxOutput { - /// The program's exit status. - pub exit_code: i32, - /// Standard output, unmodified. - pub stdout: Vec, - /// Standard error, unmodified. - pub stderr: Vec, -} - -/// Why a command could not run in a box. The messages are written to read -/// well as a tool result. -#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] -pub enum BoxError { - /// Every box is in use and none has been idle long enough to reap. - #[error("the sandbox service is at capacity; try again shortly")] - AtCapacity, - /// The box is gone: closed, lost, or no longer able to run commands. - #[error("the sandbox box is no longer available")] - UnknownResource, - /// The box was released or shut down while the command was waiting on it. - #[error("the sandbox was released while the command was running")] - Released, - /// The call carries no tenant, so it has no box of its own. - #[error("no tenant scope; refusing to run a command in a shared sandbox")] - NoTenant, - /// `[runtime.openshell] memory_mb` is too large to express in bytes. - #[error("sandbox memory of {memory_mb} MiB is too large")] - InvalidMemory { - /// The configured value. - memory_mb: u64, - }, - /// A `[runtime.openshell]` value is out of range. - #[error("invalid [runtime.openshell] setting: {0}")] - InvalidConfig(&'static str), - /// 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), -} - -/// Creates, runs and closes boxes. The registry owns their lifecycle; a -/// driver only performs each step. -#[async_trait] -pub trait BoxDriver: Send + Sync + 'static { - /// Create a box and return its resource id. - async fn create(&self, settings: &BoxSettings) -> Result; - - /// Run one program in the box and collect its output. A box that is gone - /// fails with [`BoxError::UnknownResource`]. - async fn exec(&self, resource: &str, exec: &BoxExec) -> Result; - - /// Close the box and release what it holds. - async fn close(&self, resource: &str) -> Result<(), BoxError>; -} diff --git a/crates/openhuman-core/src/sandbox/ops.rs b/crates/openhuman-core/src/sandbox/ops.rs index 79d2906f212..5a22a5ed8ae 100644 --- a/crates/openhuman-core/src/sandbox/ops.rs +++ b/crates/openhuman-core/src/sandbox/ops.rs @@ -9,14 +9,13 @@ pub(crate) use exec::execute_unsandboxed; 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, config_keeps_boxes, sandbox_disabled_by_host, sandbox_off_value, + config_disables_sandbox, create_sandbox_backend_with_config, sandbox_box_workdir, + sandbox_component_off, }; +#[cfg(test)] +pub(crate) use policy::{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, sandbox_keeps_boxes, -}; #[cfg(test)] #[path = "ops_tests.rs"] diff --git a/crates/openhuman-core/src/sandbox/ops/exec.rs b/crates/openhuman-core/src/sandbox/ops/exec.rs index 63f5b4a5e28..96c9b8a1ddd 100644 --- a/crates/openhuman-core/src/sandbox/ops/exec.rs +++ b/crates/openhuman-core/src/sandbox/ops/exec.rs @@ -324,7 +324,7 @@ pub(crate) async fn execute_resolved( .await .map(ShellRunOutcome::Finished) } - // The box has its own workspace (`/sandbox`); no host path or host + // The box has its own workspace (its work folder); no host path or host // variable is sent, only the request's own environment. A box cannot // hand back a running command, so the caller bounded `timeout`. SandboxBackendKind::OpenShell => { @@ -333,9 +333,16 @@ pub(crate) async fn execute_resolved( .map_err(|error| { anyhow::anyhow!("Sandbox plan could not be consumed: {error}") })?; - crate::sandbox::openshell::execute(ctx, &config, command, &extra_env, timeout) - .await - .map(ShellRunOutcome::Finished) + crate::sandbox::boxes::execute( + ctx, + &config, + crate::sandbox::boxes::BoxBackend::OpenShell, + command, + &extra_env, + timeout, + ) + .await + .map(ShellRunOutcome::Finished) } SandboxBackendKind::Agent37 => { crate::sandbox::spawn_plan::consume(&planned) @@ -381,11 +388,16 @@ async fn execute_unchecked( .await .map(ShellRunOutcome::Finished) } - SandboxBackendKind::OpenShell => { - crate::sandbox::openshell::execute(ctx, &config, command, &extra_env, timeout) - .await - .map(ShellRunOutcome::Finished) - } + SandboxBackendKind::OpenShell => crate::sandbox::boxes::execute( + ctx, + &config, + crate::sandbox::boxes::BoxBackend::OpenShell, + command, + &extra_env, + timeout, + ) + .await + .map(ShellRunOutcome::Finished), SandboxBackendKind::Agent37 => { crate::sandbox::agent37::execute(ctx, &config, command, &extra_env, timeout) .await diff --git a/crates/openhuman-core/src/sandbox/ops/policy.rs b/crates/openhuman-core/src/sandbox/ops/policy.rs index f3c6adddb50..f8d2b24a139 100644 --- a/crates/openhuman-core/src/sandbox/ops/policy.rs +++ b/crates/openhuman-core/src/sandbox/ops/policy.rs @@ -55,6 +55,18 @@ pub(crate) fn sandbox_keeps_boxes(ctx: &DispatchCtx, config: &crate::config::Con !crate::core::runtime::is_saas() && !sandbox_disabled_by_host(ctx) && config_keeps_boxes(config) } +/// The work folder of the box a command on this call runs in, when +/// [`sandbox_keeps_boxes`]: `/sandbox` on OpenShell, `/home/node` on agent37. +pub(crate) fn sandbox_box_workdir( + ctx: &DispatchCtx, + config: &crate::config::Config, +) -> Option<&'static str> { + if !sandbox_keeps_boxes(ctx, config) { + return None; + } + crate::sandbox::boxes::BoxBackend::configured(config).map(|backend| backend.workdir()) +} + /// [`sandbox_keeps_boxes`] for what the config alone says. pub(crate) fn config_keeps_boxes(config: &crate::config::Config) -> bool { !config_disables_sandbox(config) diff --git a/crates/openhuman-core/src/sandbox/ops_tests.rs b/crates/openhuman-core/src/sandbox/ops_tests.rs index 95c24bb3739..2367b16f7ea 100644 --- a/crates/openhuman-core/src/sandbox/ops_tests.rs +++ b/crates/openhuman-core/src/sandbox/ops_tests.rs @@ -483,17 +483,19 @@ fn config_with_backend(backend: crate::config::SandboxBackend) -> crate::config: } #[test] -fn a_config_naming_the_openshell_backend_keeps_boxes() { +fn a_config_naming_a_box_keeping_backend_keeps_boxes() { use crate::config::SandboxBackend; - assert!(config_keeps_boxes(&config_with_backend( - SandboxBackend::OpenShell - ))); + for backend in [SandboxBackend::OpenShell, SandboxBackend::Agent37] { + assert!( + config_keeps_boxes(&config_with_backend(backend.clone())), + "{backend:?}" + ); + } for backend in [ SandboxBackend::Auto, SandboxBackend::None, SandboxBackend::Docker, SandboxBackend::Landlock, - SandboxBackend::Agent37, ] { assert!(!config_keeps_boxes(&config_with_backend(backend))); } diff --git a/crates/openhuman-core/src/sandbox/plan.rs b/crates/openhuman-core/src/sandbox/plan.rs index 4129f1f04ec..5f08c92de93 100644 --- a/crates/openhuman-core/src/sandbox/plan.rs +++ b/crates/openhuman-core/src/sandbox/plan.rs @@ -31,8 +31,8 @@ pub enum PlannedExecutor { Docker, /// The tenant's long-lived OpenShell box: no host mounts, no egress. OpenShell, - /// A box per command on the hosted agent37 service: no host mounts, no - /// egress, reached over HTTP through the TinyBox module. + /// The tenant's retained box on the hosted agent37 service: no host + /// mounts, no egress, reached over HTTP through the TinyBox module. Agent37, /// No jail: the operator disabled the sandbox and the module planned a run on the /// host. Only a `host_run` artifact maps here. diff --git a/crates/openhuman-core/src/sandbox/shell_exec.rs b/crates/openhuman-core/src/sandbox/shell_exec.rs index 6ee899946e8..661ae9875d0 100644 --- a/crates/openhuman-core/src/sandbox/shell_exec.rs +++ b/crates/openhuman-core/src/sandbox/shell_exec.rs @@ -195,6 +195,7 @@ async fn run_owned( resources: contract::ResourceLimits::default(), ports: Vec::new(), env: BTreeMap::new(), + retention: None, }, shell: shell_exec_request( contract::ResourceId(String::new()), diff --git a/crates/openhuman-core/src/sandbox/spawn_plan/executors.rs b/crates/openhuman-core/src/sandbox/spawn_plan/executors.rs index ce60b10f158..19a9bbb64e4 100644 --- a/crates/openhuman-core/src/sandbox/spawn_plan/executors.rs +++ b/crates/openhuman-core/src/sandbox/spawn_plan/executors.rs @@ -123,8 +123,8 @@ pub(crate) fn openshell() -> SandboxExecutor2 { } } -/// A box per command on the hosted agent37 service: a container with its own -/// workspace and egress denied. Filesystem and network are enforced, but the +/// The tenant's retained box on the hosted agent37 service: a container with +/// its own workspace and egress denied. Filesystem and network are enforced, but the /// service snaps CPU and memory up to fixed instance shapes, so those are /// best effort — a requested bound is a floor the service rounds up, never a /// ceiling it holds the box to. Reporting them as enforced would feed diff --git a/crates/openhuman-core/src/sandbox/types.rs b/crates/openhuman-core/src/sandbox/types.rs index 774422496bd..919599f7ae0 100644 --- a/crates/openhuman-core/src/sandbox/types.rs +++ b/crates/openhuman-core/src/sandbox/types.rs @@ -15,10 +15,11 @@ pub enum SandboxBackendKind { Local, /// Docker container isolation. Docker, - /// The tenant's long-lived OpenShell box (`sandbox::openshell`). + /// The tenant's long-lived OpenShell box (`sandbox::boxes`). #[serde(rename = "openshell")] OpenShell, - /// A box per command on the hosted agent37 service (`sandbox::agent37`). + /// The tenant's retained box on the hosted agent37 service + /// (`sandbox::agent37`, over `sandbox::boxes`). #[serde(rename = "agent37")] Agent37, } @@ -26,10 +27,11 @@ pub enum SandboxBackendKind { 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. + /// [`Self::OpenShell`] and [`Self::Agent37`] do; 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) + matches!(self, Self::OpenShell | Self::Agent37) } } diff --git a/crates/openhuman-core/src/sandbox/types_tests.rs b/crates/openhuman-core/src/sandbox/types_tests.rs index f4b256a28ed..b3f56c1aff4 100644 --- a/crates/openhuman-core/src/sandbox/types_tests.rs +++ b/crates/openhuman-core/src/sandbox/types_tests.rs @@ -73,13 +73,13 @@ fn the_openshell_kind_is_named_openshell_on_the_wire() { } #[test] -fn only_the_openshell_backend_keeps_a_box_between_commands() { +fn the_openshell_and_agent37_backends_keep_a_box_between_commands() { assert!(SandboxBackendKind::OpenShell.keeps_boxes()); + assert!(SandboxBackendKind::Agent37.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/sandbox.rs b/crates/openhuman-embed/src/sandbox.rs index a15823213b6..cd1399ee784 100644 --- a/crates/openhuman-embed/src/sandbox.rs +++ b/crates/openhuman-embed/src/sandbox.rs @@ -1,5 +1,7 @@ //! Files in and out of a tenant's sandbox box, for hosts whose sandbox keeps -//! one box per tenant (`[security.sandbox] backend = "openshell"`). +//! one box per tenant (`[security.sandbox] backend = "openshell"` or +//! `"agent37"`; on any other backend both calls fail with +//! [`BoxError::NoBoxBackend`]). //! //! 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, @@ -10,7 +12,8 @@ //! - [`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 +//! Paths are relative to the box's work folder (`/sandbox` on OpenShell, +//! `/home/node` on agent37). 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 @@ -19,8 +22,11 @@ //! 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. +//! it is for a shell command, so `[runtime.openshell]` or `[runtime.agent37]` +//! settings apply from then on. An agent37 box is retained for its tenant, so +//! a file written there is still there after the box sleeps or this process +//! restarts, until the box expires. +//! [`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, diff --git a/vendor/tinybox b/vendor/tinybox index 8febf22a75b..b498faf7796 160000 --- a/vendor/tinybox +++ b/vendor/tinybox @@ -1 +1 @@ -Subproject commit 8febf22a75b470bd6cb3f2849a01a9606773c6a2 +Subproject commit b498faf77968e840c70b9927f87c85a385e2e438