diff --git a/crates/openhuman-core/src/config/mod.rs b/crates/openhuman-core/src/config/mod.rs index 141bc7164dc..1a4be0cb2ca 100644 --- a/crates/openhuman-core/src/config/mod.rs +++ b/crates/openhuman-core/src/config/mod.rs @@ -57,16 +57,17 @@ pub use schema::{ LegacySearchInputs, LinqConfig, LocalAiConfig, LocalJailConfig, MatrixConfig, McpAuthConfig, McpClientConfig, McpClientIdentityConfig, McpServerConfig, McpToolExposure, MemoryConfig, MemoryLayoutMode, ModelRouteConfig, MultimodalConfig, MultimodalFileConfig, - ObservabilityConfig, OrchestratorModelConfig, PresentationMode, PrivacyConfig, PrivacyMode, - ProviderRoute, ProxyConfig, ProxyScope, ReliabilityConfig, ResourceLimitsConfig, RuntimeConfig, - SandboxBackend, SandboxConfig, SchedulerConfig, SchedulerGateConfig, SchedulerGateMode, - SearchConfig, SearchEngineCredentials, SearchHostCredential, SearchProviderSettings, - SearxngConfig, SecretsConfig, SecurityConfig, ShellConfig, SlackConfig, StreamMode, SttEngine, - TeamModelConfig, TelegramConfig, TokenjuiceConfig, UnknownKeyedSearchProvider, UpdateConfig, - UpdateRestartStrategy, VoiceServerConfig, WebSearchConfig, WebhookConfig, YuanbaoConfig, - MANAGED_SEARCH_PROVIDERS, SEARCH_ENGINE_BRAVE, SEARCH_ENGINE_DISABLED, SEARCH_ENGINE_EXA, - SEARCH_ENGINE_MANAGED, SEARCH_ENGINE_PARALLEL, SEARCH_ENGINE_QUERIT, SEARCH_ENGINE_TAVILY, - SEARCH_PROVIDERS, SEARCH_ROLES, SEARCH_ROLE_ANSWER, SEARCH_ROLE_CONTENTS, SEARCH_ROLE_SEARCH, + ObservabilityConfig, OpenShellRuntimeConfig, OrchestratorModelConfig, PresentationMode, + PrivacyConfig, PrivacyMode, ProviderRoute, ProxyConfig, ProxyScope, ReliabilityConfig, + ResourceLimitsConfig, RuntimeConfig, SandboxBackend, SandboxConfig, SchedulerConfig, + SchedulerGateConfig, SchedulerGateMode, SearchConfig, SearchEngineCredentials, + SearchHostCredential, SearchProviderSettings, SearxngConfig, SecretsConfig, SecurityConfig, + ShellConfig, SlackConfig, StreamMode, SttEngine, TeamModelConfig, TelegramConfig, + TokenjuiceConfig, UnknownKeyedSearchProvider, UpdateConfig, UpdateRestartStrategy, + VoiceServerConfig, WebSearchConfig, WebhookConfig, YuanbaoConfig, MANAGED_SEARCH_PROVIDERS, + SEARCH_ENGINE_BRAVE, SEARCH_ENGINE_DISABLED, SEARCH_ENGINE_EXA, SEARCH_ENGINE_MANAGED, + SEARCH_ENGINE_PARALLEL, SEARCH_ENGINE_QUERIT, SEARCH_ENGINE_TAVILY, SEARCH_PROVIDERS, + SEARCH_ROLES, SEARCH_ROLE_ANSWER, SEARCH_ROLE_CONTENTS, SEARCH_ROLE_SEARCH, }; // Kept as a separate re-export (issue #4117) so the large alphabetized group // above stays byte-identical and rustfmt-stable. diff --git a/crates/openhuman-core/src/config/ops/sandbox.rs b/crates/openhuman-core/src/config/ops/sandbox.rs index 5971aeb7542..1612d1ef21c 100644 --- a/crates/openhuman-core/src/config/ops/sandbox.rs +++ b/crates/openhuman-core/src/config/ops/sandbox.rs @@ -31,14 +31,7 @@ pub async fn get_sandbox_settings(ctx: &DispatchCtx) -> Result "auto", - crate::config::SandboxBackend::Landlock => "landlock", - crate::config::SandboxBackend::Firejail => "firejail", - crate::config::SandboxBackend::Bubblewrap => "bubblewrap", - crate::config::SandboxBackend::Docker => "docker", - crate::config::SandboxBackend::None => "none", - }; + let backend_str = backend_name(&sandbox.backend); let detected_backend = crate::sandbox::native_jail::status(&config) .await @@ -62,6 +55,45 @@ pub async fn get_sandbox_settings(ctx: &DispatchCtx) -> Result &'static str { + use crate::config::SandboxBackend; + match backend { + SandboxBackend::Auto => "auto", + SandboxBackend::Landlock => "landlock", + SandboxBackend::Firejail => "firejail", + SandboxBackend::Bubblewrap => "bubblewrap", + SandboxBackend::Docker => "docker", + SandboxBackend::OpenShell => "openshell", + SandboxBackend::None => "none", + } +} + +/// The backend a settings name selects. `firejail` and `bubblewrap` stay +/// readable in saved settings but cannot be chosen: TinyBox does the native +/// sandboxing in this build. +fn parse_backend(name: &str) -> Result { + use crate::config::SandboxBackend; + Ok(match name { + "auto" => SandboxBackend::Auto, + "landlock" => SandboxBackend::Landlock, + "firejail" | "bubblewrap" => { + return Err(format!( + "unsupported sandbox backend '{name}': this build uses TinyBox for native sandboxing; valid: auto, landlock, docker, openshell, none" + )); + } + "docker" => SandboxBackend::Docker, + "openshell" => SandboxBackend::OpenShell, + "none" => SandboxBackend::None, + other => { + log::warn!("[config][sandbox] rejected unknown backend: {other}"); + return Err(format!( + "unknown sandbox backend '{other}'; valid: auto, landlock, docker, openshell, none" + )); + } + }) +} + pub async fn apply_sandbox_settings( config: &mut Config, update: SandboxSettingsPatch, @@ -73,23 +105,7 @@ pub async fn apply_sandbox_settings( ); } if let Some(ref backend) = update.backend { - config.sandbox.backend = match backend.as_str() { - "auto" => crate::config::SandboxBackend::Auto, - "landlock" => crate::config::SandboxBackend::Landlock, - "firejail" | "bubblewrap" => { - return Err(format!( - "unsupported sandbox backend '{backend}': this build uses TinyBox for native sandboxing; valid: auto, landlock, docker, none" - )); - } - "docker" => crate::config::SandboxBackend::Docker, - "none" => crate::config::SandboxBackend::None, - other => { - log::warn!("[config][sandbox] rejected unknown backend: {other}"); - return Err(format!( - "unknown sandbox backend '{other}'; valid: auto, landlock, docker, none" - )); - } - }; + config.sandbox.backend = parse_backend(backend)?; } if let Some(enabled) = update.enabled { config.sandbox.enabled = Some(enabled); @@ -133,3 +149,7 @@ pub async fn load_and_apply_sandbox_settings( let mut config = ctx.load_config().await?; apply_sandbox_settings(&mut config, update).await } + +#[cfg(test)] +#[path = "sandbox_tests.rs"] +mod tests; diff --git a/crates/openhuman-core/src/config/ops/sandbox_tests.rs b/crates/openhuman-core/src/config/ops/sandbox_tests.rs new file mode 100644 index 00000000000..52126d63798 --- /dev/null +++ b/crates/openhuman-core/src/config/ops/sandbox_tests.rs @@ -0,0 +1,35 @@ +use super::*; +use crate::config::SandboxBackend; + +#[test] +fn every_backend_name_parses_back_to_itself() { + for backend in [ + SandboxBackend::Auto, + SandboxBackend::Landlock, + SandboxBackend::Docker, + SandboxBackend::OpenShell, + SandboxBackend::None, + ] { + let name = backend_name(&backend); + assert_eq!( + serde_json::to_value(&backend).unwrap(), + serde_json::json!(name) + ); + assert_eq!(backend_name(&parse_backend(name).unwrap()), name); + } +} + +#[test] +fn an_unknown_backend_names_the_valid_ones() { + let refused = parse_backend("vm").unwrap_err(); + assert!(refused.contains("unknown sandbox backend 'vm'")); + assert!(refused.contains("openshell")); +} + +#[test] +fn the_legacy_jail_names_are_refused_as_unsupported() { + for name in ["firejail", "bubblewrap"] { + let refused = parse_backend(name).unwrap_err(); + assert!(refused.contains("unsupported sandbox backend"), "{refused}"); + } +} diff --git a/crates/openhuman-core/src/config/schema/README.md b/crates/openhuman-core/src/config/schema/README.md index d17e9fa7d39..ae3a4c89f6d 100644 --- a/crates/openhuman-core/src/config/schema/README.md +++ b/crates/openhuman-core/src/config/schema/README.md @@ -41,6 +41,7 @@ is mounted as a submodule of [`load/dirs.rs`](./load/dirs.rs) via `#[path]`. | `[[model_routes]]`, `[[embedding_routes]]` | [`routes.rs`](./routes.rs) | `ModelRouteConfig`, `EmbeddingRouteConfig` | | `[runtime]` (+ `[runtime.docker]`), `[shell]`, `[reliability]`, `[scheduler]` | [`runtime.rs`](./runtime.rs) | `RuntimeConfig`, `DockerRuntimeConfig`, `ShellConfig`, `ReliabilityConfig`, `SchedulerConfig` | | `[runtime.local_jail]` | [`runtime_local_jail.rs`](./runtime_local_jail.rs) | `LocalJailConfig`: filesystem grants for the local OS jail | +| `[runtime.openshell]` | [`runtime_openshell.rs`](./runtime_openshell.rs) | `OpenShellRuntimeConfig`: image, CPU, memory (whole MiB), idle TTL and `max_live` for the OpenShell sandbox backend | | `[scheduler_gate]` | [`scheduler_gate.rs`](./scheduler_gate.rs) | `SchedulerGateConfig`, `SchedulerGateMode` | | `[memory]` (engine, `engines.`, `conversations`, `context`, `sources`, embedding settings) | [`memory.rs`](./memory.rs) | `MemoryConfig`, `MemoryEngineSettings`, `MemoryConversationsConfig`, `MemoryContextConfig`, `MemorySourceConfig` (see [`docs/specs/memory-v2.md`](../../../../../docs/specs/memory-v2.md)) | | `[task_sources]` | [`task_sources.rs`](./task_sources.rs) | `TaskSourcesConfig` | diff --git a/crates/openhuman-core/src/config/schema/mod.rs b/crates/openhuman-core/src/config/schema/mod.rs index be2a91274d2..0c69eab7db1 100644 --- a/crates/openhuman-core/src/config/schema/mod.rs +++ b/crates/openhuman-core/src/config/schema/mod.rs @@ -104,6 +104,7 @@ mod proxy; mod routes; mod runtime; mod runtime_local_jail; +mod runtime_openshell; mod scheduler_gate; mod task_sources; mod tokenjuice; @@ -149,6 +150,7 @@ pub use runtime::{ DockerRuntimeConfig, ReliabilityConfig, RuntimeConfig, SchedulerConfig, ShellConfig, }; pub use runtime_local_jail::LocalJailConfig; +pub use runtime_openshell::{OpenShellRuntimeConfig, DEFAULT_OPENSHELL_IMAGE}; pub use scheduler_gate::{PauseReason, Policy, SchedulerGateConfig, SchedulerGateMode}; pub use security::{ AuditConfig, ResourceLimitsConfig, SandboxBackend, SandboxConfig, SecurityConfig, diff --git a/crates/openhuman-core/src/config/schema/runtime.rs b/crates/openhuman-core/src/config/schema/runtime.rs index 527e3ad77a4..dfb09271d27 100644 --- a/crates/openhuman-core/src/config/schema/runtime.rs +++ b/crates/openhuman-core/src/config/schema/runtime.rs @@ -15,6 +15,9 @@ pub struct RuntimeConfig { /// Filesystem grants for the local OS jail (`[runtime.local_jail]`). #[serde(default)] pub local_jail: super::LocalJailConfig, + /// Boxes for the OpenShell sandbox backend (`[runtime.openshell]`). + #[serde(default)] + pub openshell: super::OpenShellRuntimeConfig, #[serde(default)] pub reasoning_enabled: Option, /// Reasoning ("thinking") effort for agent turns: `none`, `minimal`, @@ -107,6 +110,7 @@ impl Default for RuntimeConfig { kind: default_runtime_kind(), docker: DockerRuntimeConfig::default(), local_jail: super::LocalJailConfig::default(), + openshell: super::OpenShellRuntimeConfig::default(), reasoning_enabled: None, reasoning_effort: None, reasoning_effort_by_model: BTreeMap::new(), diff --git a/crates/openhuman-core/src/config/schema/runtime_openshell.rs b/crates/openhuman-core/src/config/schema/runtime_openshell.rs new file mode 100644 index 00000000000..16ff7a8412d --- /dev/null +++ b/crates/openhuman-core/src/config/schema/runtime_openshell.rs @@ -0,0 +1,63 @@ +//! `[runtime.openshell]` — the boxes the OpenShell sandbox backend creates. +//! +//! With `[security.sandbox] backend = "openshell"`, every sandboxed shell +//! command runs in a box the TinyBox module creates on an NVIDIA OpenShell +//! gateway. Each tenant (profile and agent) gets one box, created on its first +//! command, reused after that, and closed once it has been idle for +//! `idle_ttl_secs`. `max_live` caps the boxes alive at once across the +//! process. The idle TTL and the cap are read when the first box is needed, so +//! changing them takes effect on the next core start; the image and limits +//! apply to every box created after a change. + +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +/// The image a box starts from when none is configured: the OpenShell +/// community base sandbox, which carries the `/sandbox` workspace, `sh` and +/// `timeout` the backend relies on. +pub const DEFAULT_OPENSHELL_IMAGE: &str = + "ghcr.io/nvidia/openshell-community/sandboxes/base:latest"; + +const MEBIBYTE: u64 = 1024 * 1024; + +/// `[runtime.openshell]`: what each OpenShell box is created with, and how +/// many may live at once. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(default)] +pub struct OpenShellRuntimeConfig { + /// OCI image reference every new box starts from. + pub image: String, + /// CPU allowance per box, in thousandths of a core. + pub cpu_millis: u32, + /// Memory per box, in mebibytes. OpenShell only accepts whole mebibytes, + /// which is why the setting is not in bytes. + pub memory_mb: u64, + /// Seconds a box may sit idle before it is closed. + pub idle_ttl_secs: u64, + /// The most boxes alive at once in this process. + pub max_live: usize, +} + +impl OpenShellRuntimeConfig { + /// [`Self::memory_mb`] in bytes, always a whole number of mebibytes, or + /// `None` when that many bytes does not fit in a `u64`. + pub fn memory_bytes(&self) -> Option { + self.memory_mb.checked_mul(MEBIBYTE) + } +} + +impl Default for OpenShellRuntimeConfig { + fn default() -> Self { + Self { + image: DEFAULT_OPENSHELL_IMAGE.to_owned(), + cpu_millis: 1_000, + memory_mb: 256, + idle_ttl_secs: 900, + max_live: 50, + } + } +} + +#[cfg(test)] +#[path = "runtime_openshell_tests.rs"] +mod tests; diff --git a/crates/openhuman-core/src/config/schema/runtime_openshell_tests.rs b/crates/openhuman-core/src/config/schema/runtime_openshell_tests.rs new file mode 100644 index 00000000000..66521a52e57 --- /dev/null +++ b/crates/openhuman-core/src/config/schema/runtime_openshell_tests.rs @@ -0,0 +1,76 @@ +use super::*; + +#[test] +fn defaults_give_one_core_256_mib_and_a_fifteen_minute_idle_ttl() { + let config = OpenShellRuntimeConfig::default(); + assert_eq!(config.image, DEFAULT_OPENSHELL_IMAGE); + assert_eq!(config.cpu_millis, 1_000); + assert_eq!(config.memory_mb, 256); + assert_eq!(config.idle_ttl_secs, 900); + assert_eq!(config.max_live, 50); +} + +#[test] +fn an_empty_table_keeps_every_default() { + let config: OpenShellRuntimeConfig = toml::from_str("").unwrap(); + assert_eq!(config, OpenShellRuntimeConfig::default()); +} + +#[test] +fn the_serde_form_pins_its_field_names() { + let config = OpenShellRuntimeConfig { + image: "registry.example/agent:1".into(), + cpu_millis: 500, + memory_mb: 128, + idle_ttl_secs: 60, + max_live: 3, + }; + let value = serde_json::to_value(&config).unwrap(); + assert_eq!( + value, + serde_json::json!({ + "image": "registry.example/agent:1", + "cpu_millis": 500, + "memory_mb": 128, + "idle_ttl_secs": 60, + "max_live": 3, + }) + ); + let back: OpenShellRuntimeConfig = serde_json::from_value(value).unwrap(); + assert_eq!(back, config); +} + +#[test] +fn memory_converts_to_whole_mebibytes() { + let config = OpenShellRuntimeConfig::default(); + assert_eq!(config.memory_bytes(), Some(256 * 1024 * 1024)); + assert_eq!(config.memory_bytes().unwrap() % (1024 * 1024), 0); +} + +#[test] +fn memory_that_overflows_bytes_has_no_byte_count() { + let config = OpenShellRuntimeConfig { + memory_mb: u64::MAX, + ..OpenShellRuntimeConfig::default() + }; + assert_eq!(config.memory_bytes(), None); +} + +#[test] +fn the_runtime_table_reads_its_openshell_section() { + let runtime: super::super::RuntimeConfig = toml::from_str( + r#" + [openshell] + image = "registry.example/agent:2" + max_live = 7 + "#, + ) + .unwrap(); + assert_eq!(runtime.openshell.image, "registry.example/agent:2"); + assert_eq!(runtime.openshell.max_live, 7); + assert_eq!(runtime.openshell.idle_ttl_secs, 900); + assert_eq!( + super::super::RuntimeConfig::default().openshell, + OpenShellRuntimeConfig::default() + ); +} diff --git a/crates/openhuman-core/src/config/schema/security.rs b/crates/openhuman-core/src/config/schema/security.rs index eb9faaf49f6..ef2e1bb4bde 100644 --- a/crates/openhuman-core/src/config/schema/security.rs +++ b/crates/openhuman-core/src/config/schema/security.rs @@ -43,6 +43,10 @@ pub enum SandboxBackend { Firejail, Bubblewrap, Docker, + /// One long-lived box per tenant on an NVIDIA OpenShell gateway, through + /// the TinyBox module (`[runtime.openshell]`). + #[serde(rename = "openshell")] + OpenShell, None, } diff --git a/crates/openhuman-core/src/config/schema/security_tests.rs b/crates/openhuman-core/src/config/schema/security_tests.rs index 04c27f37742..1b059b204a9 100644 --- a/crates/openhuman-core/src/config/schema/security_tests.rs +++ b/crates/openhuman-core/src/config/schema/security_tests.rs @@ -8,6 +8,16 @@ fn security_config_defaults() { assert_eq!(sec.audit.max_size_mb, 100); } +#[test] +fn the_openshell_backend_is_named_openshell_on_the_wire() { + assert_eq!( + serde_json::to_value(SandboxBackend::OpenShell).unwrap(), + serde_json::json!("openshell") + ); + let config: SandboxConfig = toml::from_str("backend = \"openshell\"").unwrap(); + assert!(matches!(config.backend, SandboxBackend::OpenShell)); +} + #[test] fn sandbox_config_default() { let sb = SandboxConfig::default(); diff --git a/crates/openhuman-core/src/doctor/checks/sandbox.rs b/crates/openhuman-core/src/doctor/checks/sandbox.rs index 68fcb258940..6c6da9484f2 100644 --- a/crates/openhuman-core/src/doctor/checks/sandbox.rs +++ b/crates/openhuman-core/src/doctor/checks/sandbox.rs @@ -149,6 +149,11 @@ impl SandboxBackendCheck { "Review the sandbox runtime and rerun doctor.", ), }, + SandboxBackend::OpenShell => Finding::skipped( + "sandbox/backend", + "The OpenShell backend is configured; its gateway is reached when a tenant's first box is created.", + "Run a sandboxed command to confirm the OpenShell gateway accepts new boxes.", + ), SandboxBackend::Firejail | SandboxBackend::Bubblewrap => Finding::error( "sandbox/backend", "The configured sandbox backend is not supported by this build.", diff --git a/crates/openhuman-core/src/doctor/checks/sandbox_tests.rs b/crates/openhuman-core/src/doctor/checks/sandbox_tests.rs index 9e523ed77d6..ce03d99bbb9 100644 --- a/crates/openhuman-core/src/doctor/checks/sandbox_tests.rs +++ b/crates/openhuman-core/src/doctor/checks/sandbox_tests.rs @@ -185,3 +185,19 @@ async fn missing_tinybox_status_does_not_start_the_module_runtime() { crate::modules::types::ModuleState::Available ); } + +#[tokio::test] +async fn a_configured_openshell_backend_is_checked_when_its_first_box_is_created() { + let scratch = tempfile::tempdir().expect("create isolated config fixture"); + let check = SandboxBackendCheck::with_probe(Arc::new(DockerAvailability(false))); + let finding = check + .detect(&DoctorCtx::from_config(config( + scratch.path(), + SandboxBackend::OpenShell, + ))) + .await + .remove(0); + + assert_eq!(finding.severity, FindingSeverity::Skipped); + assert!(finding.message.contains("OpenShell")); +} diff --git a/crates/openhuman-core/src/modules/tinybox/operations.rs b/crates/openhuman-core/src/modules/tinybox/operations.rs index 9775cda4cf4..9cd629433cd 100644 --- a/crates/openhuman-core/src/modules/tinybox/operations.rs +++ b/crates/openhuman-core/src/modules/tinybox/operations.rs @@ -124,6 +124,17 @@ pub async fn exec( call(config, EXEC, (request,), true).await } +/// [`exec`] that waits up to `deadline` for the reply instead of the module +/// call default, for a long command whose caller enforces its own deadline. +pub async fn exec_within( + config: &Config, + request: contract::ExecRequest, + deadline: Duration, +) -> Result { + let client = crate::modules::client(config.clone()).with_timeout(deadline); + call_with_client(&client, EXEC, (request,), true).await +} + /// Inspect a module-owned resource. pub async fn inspect( config: &Config, diff --git a/crates/openhuman-core/src/sandbox/README.md b/crates/openhuman-core/src/sandbox/README.md index a2e0e7ee845..1fc824d9bf7 100644 --- a/crates/openhuman-core/src/sandbox/README.md +++ b/crates/openhuman-core/src/sandbox/README.md @@ -8,8 +8,17 @@ 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` or `Docker` routing and status contracts; it does not duplicate -the protected-path or credential-root policy. +`None`, `Local`, `Docker` or `OpenShell` 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 +long-lived box on an NVIDIA OpenShell gateway ([`openshell/`](./openshell/mod.rs)), +declared to TinySecurity as the `tinybox-openshell` container executor. Nothing +on the host is mounted, egress is denied, and the box comes from +`[runtime.openshell]`. `BoxRegistry` keys boxes on the whole `Tenant` (profile +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. The host keeps the `SANDBOX_ENV_PASSTHROUGH` allowlist, configuration switches, status RPC, and executor lifecycle. The sandbox cannot be disabled for SaaS. diff --git a/crates/openhuman-core/src/sandbox/mod.rs b/crates/openhuman-core/src/sandbox/mod.rs index fcfe04d594e..483172e4a0e 100644 --- a/crates/openhuman-core/src/sandbox/mod.rs +++ b/crates/openhuman-core/src/sandbox/mod.rs @@ -12,6 +12,7 @@ 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")] diff --git a/crates/openhuman-core/src/sandbox/openshell/bus_driver.rs b/crates/openhuman-core/src/sandbox/openshell/bus_driver.rs new file mode 100644 index 00000000000..c63a25178ac --- /dev/null +++ b/crates/openhuman-core/src/sandbox/openshell/bus_driver.rs @@ -0,0 +1,141 @@ +//! [`BusBoxDriver`]: boxes through the TinyBox module's `openshell` backend. +//! +//! Each step is one bus call (`Reserve` + `Create`, `Exec`, `Close`). The +//! module's error names do not cross the bus client (it reports only +//! sanitized categories), so a failed exec is followed by an `Inspect`: a box +//! the module no longer knows, or one that can no longer take commands, is +//! [`BoxError::UnknownResource`], which the registry answers with a new box. + +use std::time::Duration; + +use async_trait::async_trait; + +use super::{BoxDriver, BoxError, BoxExec, BoxOutput, BoxSettings}; +use crate::config::Config; +use crate::modules::tinybox::{self, contract}; + +/// The TinyBox backend name for OpenShell boxes. +pub(crate) const BACKEND: &str = "openshell"; + +/// How long past the registry's own deadline the bus waits for an exec reply, +/// so the registry's backstop always decides first. +pub(crate) const BUS_REPLY_GRACE: Duration = Duration::from_secs(5); + +/// Box states that still take commands. +const LIVE_STATES: &[&str] = &["ready", "running"]; + +/// A [`BoxDriver`] over the TinyBox module, using the module configuration it +/// was built with. +pub struct BusBoxDriver { + config: Config, +} + +impl BusBoxDriver { + /// A driver that reaches the module with `config`'s module settings. + pub fn new(config: Config) -> Self { + Self { config } + } +} + +#[async_trait] +impl BoxDriver for BusBoxDriver { + async fn create(&self, settings: &BoxSettings) -> 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)) + .await + .map_err(BoxError::Driver)?; + Ok(info.resource.0) + } + + async fn exec(&self, resource: &str, exec: &BoxExec) -> Result { + match tinybox::exec_within( + &self.config, + exec_request(resource, exec), + bus_deadline(exec.deadline), + ) + .await + { + Ok(output) => Ok(box_output(output)), + Err(error) => { + let probe = + tinybox::inspect(&self.config, contract::ResourceId(resource.to_owned())).await; + Err(exec_failure(error, probe)) + } + } + } + + async fn close(&self, resource: &str) -> Result<(), BoxError> { + tinybox::close(&self.config, contract::ResourceId(resource.to_owned())) + .await + .map_err(BoxError::Driver) + } +} + +/// An OpenShell box: the image, no network, no published ports, and no +/// environment from the host. +pub(crate) fn create_request( + resource: contract::ResourceId, + settings: &BoxSettings, +) -> contract::CreateRequest { + contract::CreateRequest { + resource, + backend: BACKEND.to_owned(), + host: contract::HostConfig::Local, + workspace: contract::Workspace::Image(settings.image.clone()), + network: contract::NetworkPolicy::Denied, + resources: contract::ResourceLimits { + cpu_millis: settings.cpu_millis, + memory_bytes: settings.memory_bytes, + ..contract::ResourceLimits::default() + }, + ports: Vec::new(), + env: std::collections::BTreeMap::new(), + } +} + +pub(crate) fn exec_request(resource: &str, exec: &BoxExec) -> contract::ExecRequest { + contract::ExecRequest { + resource: contract::ResourceId(resource.to_owned()), + argv: exec.argv.clone(), + cwd: Some(exec.cwd.clone()), + env: exec.env.clone(), + stdin: None, + } +} + +pub(crate) fn bus_deadline(registry_deadline: Duration) -> Duration { + registry_deadline.saturating_add(BUS_REPLY_GRACE) +} + +/// Classify a failed exec by what `Inspect` says about its box afterwards. +pub(crate) fn exec_failure( + exec_error: String, + probe: Result, +) -> BoxError { + let gone = match probe { + Ok(info) => !LIVE_STATES.contains(&info.state.as_str()), + // The module answered and refused: it holds no such box. + Err(probe_error) => { + probe_error == tinybus::module::ModuleCallError::ModuleFault.to_string() + } + }; + if gone { + BoxError::UnknownResource + } else { + BoxError::Driver(exec_error) + } +} + +pub(crate) fn box_output(output: contract::ExecOutput) -> BoxOutput { + BoxOutput { + exit_code: output.exit_code, + stdout: output.stdout, + stderr: output.stderr, + } +} + +#[cfg(test)] +#[path = "bus_driver_tests.rs"] +mod tests; diff --git a/crates/openhuman-core/src/sandbox/openshell/bus_driver_tests.rs b/crates/openhuman-core/src/sandbox/openshell/bus_driver_tests.rs new file mode 100644 index 00000000000..54b08e41d38 --- /dev/null +++ b/crates/openhuman-core/src/sandbox/openshell/bus_driver_tests.rs @@ -0,0 +1,128 @@ +use super::*; +use std::collections::BTreeMap; + +fn settings() -> BoxSettings { + BoxSettings { + image: "registry.example/agent:1".into(), + cpu_millis: 750, + memory_bytes: 256 * 1024 * 1024, + } +} + +fn info(state: &str) -> contract::ResourceInfo { + contract::ResourceInfo { + resource: contract::ResourceId("r-1".into()), + backend: BACKEND.into(), + state: state.into(), + published_ports: Vec::new(), + } +} + +#[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()); + + assert_eq!(request.resource, contract::ResourceId("r-1".into())); + assert_eq!(request.backend, "openshell"); + assert_eq!( + request.workspace, + contract::Workspace::Image("registry.example/agent:1".into()) + ); + assert_eq!(request.network, contract::NetworkPolicy::Denied); + assert_eq!(request.host, contract::HostConfig::Local); + assert!(request.ports.is_empty()); + assert!(request.env.is_empty()); + assert_eq!(request.resources.cpu_millis, 750); + assert_eq!(request.resources.memory_bytes, 256 * 1024 * 1024); + assert_eq!( + request.resources.pids_max, + contract::ResourceLimits::default().pids_max + ); + assert_eq!( + request.resources.disk_bytes, + contract::ResourceLimits::default().disk_bytes + ); +} + +#[test] +fn an_exec_carries_argv_workdir_and_only_the_given_env() { + let mut env = BTreeMap::new(); + env.insert("LANG".to_owned(), "C.UTF-8".to_owned()); + let exec = BoxExec { + argv: vec!["sh".into(), "-c".into(), "true".into()], + cwd: "/sandbox".into(), + env: env.clone(), + deadline: Duration::from_secs(40), + }; + + let request = exec_request("r-1", &exec); + + assert_eq!(request.resource, contract::ResourceId("r-1".into())); + assert_eq!(request.argv, exec.argv); + assert_eq!(request.cwd.as_deref(), Some("/sandbox")); + assert_eq!(request.env, env); + assert_eq!(request.stdin, None); +} + +#[test] +fn the_bus_waits_past_the_registry_backstop() { + assert_eq!( + bus_deadline(Duration::from_secs(40)), + Duration::from_secs(40) + BUS_REPLY_GRACE + ); +} + +#[test] +fn a_failed_exec_in_a_live_box_is_a_driver_error() { + for state in ["ready", "running"] { + assert_eq!( + exec_failure("exec broke".into(), Ok(info(state))), + BoxError::Driver("exec broke".into()) + ); + } +} + +#[test] +fn a_failed_exec_in_a_dead_box_is_an_unknown_resource() { + for state in ["failed", "stopped", "archived"] { + assert_eq!( + exec_failure("exec broke".into(), Ok(info(state))), + BoxError::UnknownResource + ); + } +} + +#[test] +fn a_box_the_module_refuses_to_inspect_is_an_unknown_resource() { + let refused = tinybus::module::ModuleCallError::ModuleFault.to_string(); + assert_eq!( + exec_failure("exec broke".into(), Err(refused)), + BoxError::UnknownResource + ); +} + +#[test] +fn an_unreachable_module_is_a_driver_error_not_a_lost_box() { + let unreachable = tinybus::module::ModuleCallError::Unavailable.to_string(); + assert_eq!( + exec_failure("exec broke".into(), Err(unreachable)), + BoxError::Driver("exec broke".into()) + ); +} + +#[test] +fn output_is_passed_through_unchanged() { + let output = box_output(contract::ExecOutput { + exit_code: 3, + stdout: b"out".to_vec(), + stderr: b"err".to_vec(), + }); + assert_eq!( + output, + BoxOutput { + exit_code: 3, + stdout: b"out".to_vec(), + stderr: b"err".to_vec(), + } + ); +} diff --git a/crates/openhuman-core/src/sandbox/openshell/mod.rs b/crates/openhuman-core/src/sandbox/openshell/mod.rs new file mode 100644 index 00000000000..c3f4d382a47 --- /dev/null +++ b/crates/openhuman-core/src/sandbox/openshell/mod.rs @@ -0,0 +1,176 @@ +//! 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. +//! +//! [`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 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 registry::BoxRegistry; +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" + ) + } +} + +/// 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/mod_tests.rs b/crates/openhuman-core/src/sandbox/openshell/mod_tests.rs new file mode 100644 index 00000000000..c5475ca0e7c --- /dev/null +++ b/crates/openhuman-core/src/sandbox/openshell/mod_tests.rs @@ -0,0 +1,203 @@ +use super::*; +use crate::config::OpenShellRuntimeConfig; +use crate::core::runtime::NoTenant; +use scripted_driver::ScriptedDriver; +use std::collections::HashMap; +use std::ffi::OsString; +use std::sync::Arc; + +fn embedded(id: &str) -> Tenant { + Tenant { + profile: None, + agent: Some(id.into()), + } +} + +#[test] +fn a_call_without_a_tenant_is_refused() { + let refused = tenant_for_box(Err(NoTenant)).unwrap_err(); + assert_eq!(refused, BoxError::NoTenant); + assert_eq!( + refused.to_string(), + "no tenant scope; refusing to run a command in a shared sandbox" + ); +} + +#[test] +fn the_whole_tenant_keys_the_box_not_just_its_profile() { + assert_eq!(tenant_for_box(Ok(embedded("u1"))), Ok(embedded("u1"))); +} + +#[test] +fn settings_come_from_the_runtime_table() { + let config = OpenShellRuntimeConfig { + image: "registry.example/agent:3".into(), + cpu_millis: 250, + memory_mb: 64, + idle_ttl_secs: 120, + max_live: 4, + }; + + assert_eq!( + BoxSettings::from_config(&config), + Ok(BoxSettings { + image: "registry.example/agent:3".into(), + cpu_millis: 250, + memory_bytes: 64 * 1024 * 1024, + }) + ); + assert_eq!( + RegistryLimits::from_config(&config), + RegistryLimits { + idle_ttl: Duration::from_secs(120), + max_live: 4, + } + ); +} + +#[test] +fn memory_too_large_for_bytes_is_refused() { + let config = OpenShellRuntimeConfig { + memory_mb: u64::MAX, + ..OpenShellRuntimeConfig::default() + }; + let refused = BoxSettings::from_config(&config).unwrap_err(); + assert_eq!( + refused, + BoxError::InvalidMemory { + memory_mb: u64::MAX + } + ); + assert!(refused.to_string().contains("too large")); +} + +#[test] +fn unusable_box_settings_are_refused_with_a_config_error() { + let defaults = OpenShellRuntimeConfig::default(); + for config in [ + OpenShellRuntimeConfig { + image: " ".into(), + ..defaults.clone() + }, + OpenShellRuntimeConfig { + cpu_millis: 0, + ..defaults.clone() + }, + OpenShellRuntimeConfig { + memory_mb: 0, + ..defaults.clone() + }, + ] { + let refused = BoxSettings::from_config(&config).unwrap_err(); + assert!(matches!(refused, BoxError::InvalidConfig(_)), "{refused:?}"); + assert!(refused.to_string().contains("[runtime.openshell]")); + } +} + +#[test] +fn zero_registry_limits_are_raised_to_one() { + let config = OpenShellRuntimeConfig { + idle_ttl_secs: 0, + max_live: 0, + ..OpenShellRuntimeConfig::default() + }; + assert_eq!( + RegistryLimits::from_config(&config), + RegistryLimits { + idle_ttl: Duration::from_secs(1), + max_live: 1, + } + ); +} + +#[test] +fn the_command_env_is_only_what_the_request_carries() { + let mut extra = HashMap::new(); + extra.insert(OsString::from("GIT_TERMINAL_PROMPT"), OsString::from("0")); + + let env = box_env(&extra).unwrap(); + + assert_eq!(env.len(), 1); + assert_eq!(env["GIT_TERMINAL_PROMPT"], "0"); +} + +#[cfg(unix)] +#[test] +fn a_non_utf8_env_is_refused_rather_than_altered() { + use std::os::unix::ffi::OsStringExt; + let mut extra = HashMap::new(); + extra.insert(OsString::from("BAD"), OsString::from_vec(vec![0xff])); + + assert_eq!(box_env(&extra).unwrap_err(), BoxError::NonUtf8Env); +} + +#[tokio::test(start_paused = true)] +async fn an_unscoped_command_creates_no_box() { + let driver = ScriptedDriver::new(); + let boxes = BoxRegistry::new( + Arc::clone(&driver), + RegistryLimits::from_config(&OpenShellRuntimeConfig::default()), + ); + + let refused = run_command( + &boxes, + Err(NoTenant), + &OpenShellRuntimeConfig::default(), + "id", + &HashMap::new(), + Duration::from_secs(10), + ) + .await + .unwrap_err(); + + assert_eq!(refused, BoxError::NoTenant); + assert!(driver.calls().is_empty()); +} + +#[tokio::test(start_paused = true)] +async fn a_scoped_command_runs_in_its_tenants_box() { + let driver = ScriptedDriver::new(); + let config = OpenShellRuntimeConfig::default(); + let boxes = BoxRegistry::new(Arc::clone(&driver), RegistryLimits::from_config(&config)); + + let result = run_command( + &boxes, + Ok(embedded("u1")), + &config, + "id", + &HashMap::new(), + Duration::from_secs(10), + ) + .await + .unwrap(); + + assert_eq!(result.stdout, "ok"); + assert_eq!( + driver.calls()[0], + scripted_driver::Call::Create(BoxSettings::from_config(&config).unwrap()) + ); + let exec = driver.last_exec().unwrap(); + assert_eq!(exec.argv[3], "10"); + assert!(exec.env.is_empty()); +} + +#[cfg(not(feature = "modules"))] +#[tokio::test] +async fn without_module_support_execution_is_refused() { + let error = execute( + &crate::core::runtime::DispatchCtx::unbound(), + &crate::config::Config::default(), + "id", + &HashMap::new(), + Duration::from_secs(1), + ) + .await + .unwrap_err(); + assert!(error.to_string().contains("module support is disabled")); +} + +#[tokio::test] +async fn release_and_shutdown_before_any_box_exists_are_no_ops() { + release(&embedded("u1")).await; + shutdown().await; +} diff --git a/crates/openhuman-core/src/sandbox/openshell/registry.rs b/crates/openhuman-core/src/sandbox/openshell/registry.rs new file mode 100644 index 00000000000..6b87824c465 --- /dev/null +++ b/crates/openhuman-core/src/sandbox/openshell/registry.rs @@ -0,0 +1,419 @@ +//! [`BoxRegistry`]: one live box per tenant, created on first use, reused, +//! and closed when idle, released, or no longer answering. +//! +//! 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 +//! it was last used; its [`Slot`] holds the box id and the gate that makes +//! creation single-flight. A slot taken out of the map (released, shut down, +//! reaped) is marked retired, so a command still running on it can never +//! create a box nobody tracks. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex, MutexGuard, Once, PoisonError, Weak}; +use std::time::Duration; + +use tokio::time::Instant; + +use super::{BoxDriver, BoxError, BoxExec, BoxOutput, BoxRequest, 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"; + +/// Seconds `timeout` waits after its signal before it kills the command. +const KILL_AFTER_SECS: &str = "5"; + +/// How long past the command's deadline the host waits for the box to answer +/// before it gives the box up. Covers the kill grace above plus the reply. +pub(crate) const BACKSTOP_MARGIN: Duration = Duration::from_secs(10); + +/// The exit status `timeout` reports for a command it stopped. +const TIMED_OUT_EXIT: i32 = 124; + +/// The longest the background reaper waits between passes. +pub(crate) const REAP_EVERY_AT_MOST: Duration = Duration::from_secs(30); + +/// One live box per [`Tenant`], over a [`BoxDriver`]. +pub struct BoxRegistry { + driver: Arc, + limits: RegistryLimits, + entries: Mutex>, + reaper: Once, +} + +struct Entry { + slot: Arc, + in_flight: usize, + last_used: Instant, +} + +#[derive(Default)] +struct Slot { + /// Held while the box is created, so concurrent first commands make one. + create_gate: tokio::sync::Mutex<()>, + state: Mutex, +} + +#[derive(Default)] +struct SlotState { + resource: Option, + retired: bool, +} + +impl Slot { + fn state(&self) -> MutexGuard<'_, SlotState> { + self.state.lock().unwrap_or_else(PoisonError::into_inner) + } + + fn current(&self) -> Result, BoxError> { + let state = self.state(); + if state.retired { + return Err(BoxError::Released); + } + Ok(state.resource.clone()) + } + + /// Record a new box; `false` when the slot was retired meanwhile. + fn store(&self, resource: &str) -> bool { + let mut state = self.state(); + if state.retired { + return false; + } + state.resource = Some(resource.to_owned()); + true + } + + /// Drop `resource` if it is still the slot's box. + fn forget(&self, resource: &str) { + let mut state = self.state(); + if state.resource.as_deref() == Some(resource) { + state.resource = None; + } + } + + /// Retire the slot and hand back its box to close. + fn retire(&self) -> Option { + let mut state = self.state(); + state.retired = true; + state.resource.take() + } +} + +/// A command's hold on its tenant's entry; dropping it (finished or +/// abandoned) ends the hold and touches the entry. +struct Lease<'a, D: BoxDriver> { + registry: &'a BoxRegistry, + tenant: Tenant, + slot: Arc, +} + +impl Drop for Lease<'_, D> { + fn drop(&mut self) { + self.registry.check_in(&self.tenant, &self.slot); + } +} + +enum Run { + Finished(BoxOutput), + BackstopFired, +} + +impl BoxRegistry { + /// A registry with no boxes yet. Call [`Self::start_reaper`] to close + /// idle boxes in the background. + pub fn new(driver: Arc, limits: RegistryLimits) -> Arc { + Arc::new(Self { + driver, + limits, + entries: Mutex::new(HashMap::new()), + reaper: Once::new(), + }) + } + + /// How many tenants hold a box (or are creating one). + pub fn live(&self) -> usize { + self.entries().len() + } + + /// Run `request` in `tenant`'s box, creating the box first if it has none. + /// + /// A box the driver reports gone is replaced once and the command retried. + /// A box that does not answer by the command's deadline plus + /// [`BACKSTOP_MARGIN`] is closed, and the command reported as timed out. + /// + /// # Errors + /// + /// [`BoxError::AtCapacity`] when a new box would exceed `max_live`, and + /// any creation or execution failure from the driver. + pub async fn exec( + &self, + tenant: &Tenant, + settings: &BoxSettings, + request: &BoxRequest, + ) -> Result { + 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 { + 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" + ); + lease.slot.forget(&resource); + self.close_quietly(&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. + lease.slot.forget(&resource); + self.close_quietly(&resource).await; + if replaced { + return Err(BoxError::UnknownResource); + } + tracing::warn!("[sandbox:openshell] box is gone; retrying in a new box"); + replaced = true; + } + Err(error) => return Err(error), + } + } + } + + /// Close every box idle since `now - idle_ttl` or earlier with no command + /// in flight; returns how many were closed. + pub async fn reap(&self, now: Instant) -> usize { + let idle = self.take_idle(&mut self.entries(), now); + let closed = idle.len(); + for resource in idle { + self.close_quietly(&resource).await; + } + if closed > 0 { + tracing::debug!(closed, "[sandbox:openshell] reaped idle boxes"); + } + closed + } + + /// Close `tenant`'s box, if it has one. 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; + } + } + + /// Close every box. + pub async fn shutdown(&self) { + let resources: Vec = self + .entries() + .drain() + .filter_map(|(_, entry)| entry.slot.retire()) + .collect(); + for resource in resources { + self.close_quietly(&resource).await; + } + } + + /// Start the background reaper, once; it stops when the registry drops. + pub fn start_reaper(self: &Arc) { + self.reaper.call_once(|| { + let registry: Weak = Arc::downgrade(self); + let every = reap_interval(self.limits.idle_ttl); + // A process-wide sweeper: it closes boxes by id and acts under no + // tenant's context, so it carries none. + tokio::spawn(async move { + let mut ticks = tokio::time::interval(every); + ticks.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); + loop { + ticks.tick().await; + let Some(registry) = registry.upgrade() else { + return; + }; + registry.reap(Instant::now()).await; + } + }); + }); + } + + fn entries(&self) -> MutexGuard<'_, HashMap> { + self.entries.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// Hold `tenant`'s entry, making one when it has none and there is room. + 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; + } + let Some(slot) = held else { + tracing::warn!( + max_live = self.limits.max_live, + "[sandbox:openshell] refusing a new box: at capacity" + ); + return Err(BoxError::AtCapacity); + }; + Ok(Lease { + registry: self, + tenant: tenant.clone(), + slot, + }) + } + + /// Count a command against `tenant`'s entry, making the entry when there + /// is room (after reaping idle boxes if there is not). Returns the slot, + /// or `None` at capacity, and the reaped boxes to close. + fn hold(&self, tenant: &Tenant, now: Instant) -> (Option>, Vec) { + let mut entries = self.entries(); + 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 { + return (None, reaped); + } + } + let entry = entries.entry(tenant.clone()).or_insert_with(|| Entry { + slot: Arc::new(Slot::default()), + in_flight: 0, + last_used: now, + }); + entry.in_flight += 1; + entry.last_used = now; + (Some(Arc::clone(&entry.slot)), reaped) + } + + /// End a command's hold; an entry left with no box and no command goes. + fn check_in(&self, tenant: &Tenant, slot: &Arc) { + let mut entries = self.entries(); + let Some(entry) = entries.get_mut(tenant) else { + return; + }; + if !Arc::ptr_eq(&entry.slot, slot) { + return; + } + entry.in_flight = entry.in_flight.saturating_sub(1); + entry.last_used = Instant::now(); + if entry.in_flight == 0 && entry.slot.state().resource.is_none() { + entries.remove(tenant); + } + } + + /// Remove idle entries and return their boxes to close. + fn take_idle(&self, entries: &mut HashMap, now: Instant) -> Vec { + let ttl = self.limits.idle_ttl; + let mut resources = Vec::new(); + entries.retain(|_, entry| { + let idle = + entry.in_flight == 0 && now.saturating_duration_since(entry.last_used) >= ttl; + if idle { + resources.extend(entry.slot.retire()); + } + !idle + }); + resources + } + + /// The slot's box, created now if it has none. + async fn resource_for(&self, slot: &Slot, settings: &BoxSettings) -> Result { + if let Some(resource) = slot.current()? { + return Ok(resource); + } + let _creating = slot.create_gate.lock().await; + 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?; + if !slot.store(&resource) { + self.close_quietly(&resource).await; + return Err(BoxError::Released); + } + tracing::debug!(resource = %resource, "[sandbox:openshell] box ready"); + Ok(resource) + } + + async fn run(&self, resource: &str, 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(), + env: request.env.clone(), + deadline, + }; + match tokio::time::timeout(deadline, self.driver.exec(resource, &exec)).await { + Ok(output) => output.map(Run::Finished), + Err(_) => Ok(Run::BackstopFired), + } + } + + async fn close_quietly(&self, resource: &str) { + if let Err(error) = self.driver.close(resource).await { + tracing::warn!( + resource = %resource, + error = %error, + "[sandbox:openshell] closing a box failed" + ); + } + } +} + +/// `timeout -k 5 sh -c `: the box stops the command itself. +fn timeout_argv(secs: u64, command: &str) -> Vec { + [ + "timeout", + "-k", + KILL_AFTER_SECS, + &secs.to_string(), + "sh", + "-c", + command, + ] + .map(str::to_owned) + .to_vec() +} + +/// `timeout` counts whole seconds: round up, and never ask for none. +pub(crate) fn whole_seconds(timeout: Duration) -> u64 { + let secs = timeout.as_secs() + u64::from(timeout.subsec_nanos() > 0); + secs.max(1) +} + +/// Half the TTL, at most [`REAP_EVERY_AT_MOST`], at least a second. +pub(crate) fn reap_interval(idle_ttl: Duration) -> Duration { + (idle_ttl / 2) + .min(REAP_EVERY_AT_MOST) + .max(Duration::from_secs(1)) +} + +/// A command's output as a sandbox result; exit 124 is `timeout` stopping it. +pub(crate) fn finished(output: BoxOutput) -> SandboxExecResult { + 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, + } +} + +fn backstop_timed_out(timeout: Duration) -> SandboxExecResult { + SandboxExecResult { + exit_code: TIMED_OUT_EXIT, + stdout: String::new(), + stderr: format!( + "the command did not finish within {}s and its sandbox was discarded", + whole_seconds(timeout) + ), + timed_out: true, + } +} + +#[cfg(test)] +#[path = "registry_tests.rs"] +mod tests; diff --git a/crates/openhuman-core/src/sandbox/openshell/registry_tests.rs b/crates/openhuman-core/src/sandbox/openshell/registry_tests.rs new file mode 100644 index 00000000000..d29923c880d --- /dev/null +++ b/crates/openhuman-core/src/sandbox/openshell/registry_tests.rs @@ -0,0 +1,511 @@ +use super::*; +use crate::sandbox::openshell::scripted_driver::{ok_output, Call, ExecStep, ScriptedDriver}; +use std::collections::BTreeMap; +use tokio::sync::Notify; + +const TTL: Duration = Duration::from_secs(900); + +fn limits(max_live: usize) -> RegistryLimits { + RegistryLimits { + idle_ttl: TTL, + max_live, + } +} + +fn settings() -> BoxSettings { + BoxSettings { + image: "registry.example/agent:1".into(), + cpu_millis: 1_000, + memory_bytes: 256 * 1024 * 1024, + } +} + +fn request(command: &str) -> BoxRequest { + BoxRequest { + command: command.into(), + env: BTreeMap::new(), + timeout: Duration::from_secs(30), + } +} + +/// An embedded user: no profile, the user's id as the agent. +fn user(id: &str) -> Tenant { + Tenant { + profile: None, + agent: Some(id.into()), + } +} + +fn registry(driver: &Arc, max_live: usize) -> Arc> { + BoxRegistry::new(Arc::clone(driver), limits(max_live)) +} + +#[tokio::test(start_paused = true)] +async fn one_tenant_reuses_its_box_across_commands() { + let driver = ScriptedDriver::new(); + let boxes = registry(&driver, 10); + + let first = boxes + .exec(&user("u1"), &settings(), &request("echo hi")) + .await + .unwrap(); + boxes + .exec(&user("u1"), &settings(), &request("pwd")) + .await + .unwrap(); + + assert_eq!(first.stdout, "ok"); + assert_eq!(first.exit_code, 0); + assert!(!first.timed_out); + assert_eq!(driver.created(), 1); + assert_eq!(driver.exec_resources(), vec!["box-0", "box-0"]); + assert_eq!(boxes.live(), 1); +} + +#[tokio::test(start_paused = true)] +async fn the_box_enforces_the_deadline_from_its_own_workspace() { + let driver = ScriptedDriver::new(); + let boxes = registry(&driver, 10); + let mut request = request("ls | wc -l"); + request.env.insert("LANG".into(), "C.UTF-8".into()); + + boxes + .exec(&user("u1"), &settings(), &request) + .await + .unwrap(); + + let exec = driver.last_exec().unwrap(); + assert_eq!( + exec.argv, + vec!["timeout", "-k", "5", "30", "sh", "-c", "ls | wc -l"] + ); + 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())); +} + +#[test] +fn deadlines_round_up_to_whole_seconds_of_at_least_one() { + assert_eq!(whole_seconds(Duration::from_millis(1_500)), 2); + assert_eq!(whole_seconds(Duration::from_secs(30)), 30); + assert_eq!(whole_seconds(Duration::ZERO), 1); +} + +#[tokio::test(start_paused = true)] +async fn embedded_users_of_one_host_get_separate_boxes() { + let driver = ScriptedDriver::new(); + let boxes = registry(&driver, 10); + + boxes + .exec(&user("alice"), &settings(), &request("id")) + .await + .unwrap(); + boxes + .exec(&user("bob"), &settings(), &request("id")) + .await + .unwrap(); + + assert_eq!(driver.created(), 2); + assert_eq!(driver.exec_resources(), vec!["box-0", "box-1"]); +} + +#[tokio::test(start_paused = true)] +async fn concurrent_first_commands_create_one_box() { + let driver = ScriptedDriver::new(); + driver.slow_create(Duration::from_secs(3)); + let boxes = registry(&driver, 10); + + let runs = (0..5).map(|n| { + let boxes = Arc::clone(&boxes); + tokio::spawn(async move { + boxes + .exec(&user("u1"), &settings(), &request(&format!("echo {n}"))) + .await + }) + }); + for run in futures::future::join_all(runs).await { + run.unwrap().unwrap(); + } + + assert_eq!(driver.created(), 1); + assert!(driver.exec_resources().iter().all(|id| id == "box-0")); +} + +#[tokio::test(start_paused = true)] +async fn reap_closes_a_box_once_it_has_been_idle_for_the_ttl() { + let driver = ScriptedDriver::new(); + let boxes = registry(&driver, 10); + boxes + .exec(&user("u1"), &settings(), &request("true")) + .await + .unwrap(); + let finished = Instant::now(); + + assert_eq!(boxes.reap(finished + TTL - Duration::from_secs(1)).await, 0); + assert!(driver.closed().is_empty()); + assert_eq!(boxes.reap(finished + TTL).await, 1); + assert_eq!(driver.closed(), vec!["box-0"]); + assert_eq!(boxes.live(), 0); + + boxes + .exec(&user("u1"), &settings(), &request("true")) + .await + .unwrap(); + assert_eq!(driver.created(), 2); +} + +#[tokio::test(start_paused = true)] +async fn reap_never_closes_a_box_with_a_command_in_flight() { + let driver = ScriptedDriver::new(); + let gate = Arc::new(Notify::new()); + driver.then(ExecStep::WaitThenReply(Arc::clone(&gate))); + let boxes = registry(&driver, 10); + let running = { + let boxes = Arc::clone(&boxes); + tokio::spawn(async move { + boxes + .exec(&user("u1"), &settings(), &request("sleep 3600")) + .await + }) + }; + tokio::task::yield_now().await; + while driver.exec_resources().is_empty() { + tokio::task::yield_now().await; + } + + assert_eq!(boxes.reap(Instant::now() + TTL * 4).await, 0); + assert!(driver.closed().is_empty()); + + gate.notify_one(); + running.await.unwrap().unwrap(); + assert_eq!(boxes.reap(Instant::now() + TTL).await, 1); +} + +#[tokio::test(start_paused = true)] +async fn the_background_reaper_closes_idle_boxes() { + let driver = ScriptedDriver::new(); + let boxes = registry(&driver, 10); + boxes.start_reaper(); + boxes.start_reaper(); + boxes + .exec(&user("u1"), &settings(), &request("true")) + .await + .unwrap(); + + tokio::time::sleep(TTL + REAP_EVERY_AT_MOST * 2).await; + + assert_eq!(driver.closed(), vec!["box-0"]); +} + +#[test] +fn the_reaper_ticks_at_half_the_ttl_capped_and_never_zero() { + assert_eq!(reap_interval(TTL), REAP_EVERY_AT_MOST); + assert_eq!( + reap_interval(Duration::from_secs(20)), + Duration::from_secs(10) + ); + assert_eq!(reap_interval(Duration::ZERO), Duration::from_secs(1)); +} + +#[tokio::test(start_paused = true)] +async fn a_new_tenant_is_refused_when_no_idle_box_can_be_reaped() { + let driver = ScriptedDriver::new(); + let boxes = registry(&driver, 1); + boxes + .exec(&user("alice"), &settings(), &request("true")) + .await + .unwrap(); + + let refused = boxes + .exec(&user("bob"), &settings(), &request("true")) + .await + .unwrap_err(); + + assert_eq!(refused, BoxError::AtCapacity); + assert_eq!( + refused.to_string(), + "the sandbox service is at capacity; try again shortly" + ); + assert_eq!(driver.created(), 1); + assert!(driver.closed().is_empty()); +} + +#[tokio::test(start_paused = true)] +async fn reaping_an_idle_box_makes_room_for_a_new_tenant() { + let driver = ScriptedDriver::new(); + let boxes = registry(&driver, 1); + boxes + .exec(&user("alice"), &settings(), &request("true")) + .await + .unwrap(); + tokio::time::advance(TTL).await; + + boxes + .exec(&user("bob"), &settings(), &request("true")) + .await + .unwrap(); + + let calls = driver.calls(); + let closed = calls + .iter() + .position(|call| *call == Call::Close("box-0".into())) + .unwrap(); + let created = calls + .iter() + .rposition(|call| matches!(call, Call::Create(_))) + .unwrap(); + assert!(closed < created); + assert_eq!(boxes.live(), 1); +} + +#[tokio::test(start_paused = true)] +async fn a_failed_create_does_not_hold_a_slot() { + let driver = ScriptedDriver::new(); + driver.fail_next_creates(1); + let boxes = registry(&driver, 1); + + let failed = boxes + .exec(&user("alice"), &settings(), &request("true")) + .await + .unwrap_err(); + assert_eq!(failed, BoxError::Driver("create refused".into())); + assert_eq!(boxes.live(), 0); + + boxes + .exec(&user("bob"), &settings(), &request("true")) + .await + .unwrap(); +} + +#[tokio::test(start_paused = true)] +async fn an_unknown_box_is_replaced_once_and_the_command_retried() { + let driver = ScriptedDriver::new(); + driver.then(ExecStep::Fail(BoxError::UnknownResource)); + let boxes = registry(&driver, 10); + + let result = boxes + .exec(&user("u1"), &settings(), &request("true")) + .await + .unwrap(); + + assert_eq!(result.stdout, "ok"); + assert_eq!(driver.created(), 2); + assert_eq!(driver.exec_resources(), vec!["box-0", "box-1"]); +} + +#[tokio::test(start_paused = true)] +async fn a_box_reported_gone_is_still_closed_before_it_is_replaced() { + // "Gone" is inferred from a probe after a failed exec, so the box may + // still exist; dropping it without a close would leak it on the gateway. + let driver = ScriptedDriver::new(); + driver.then(ExecStep::Fail(BoxError::UnknownResource)); + let boxes = registry(&driver, 10); + + boxes + .exec(&user("u1"), &settings(), &request("true")) + .await + .unwrap(); + + assert_eq!(driver.closed(), vec!["box-0"]); +} + +#[tokio::test(start_paused = true)] +async fn a_second_unknown_box_fails_the_command() { + let driver = ScriptedDriver::new(); + driver.then(ExecStep::Fail(BoxError::UnknownResource)); + driver.then(ExecStep::Fail(BoxError::UnknownResource)); + let boxes = registry(&driver, 10); + + let failed = boxes + .exec(&user("u1"), &settings(), &request("true")) + .await + .unwrap_err(); + + assert_eq!(failed, BoxError::UnknownResource); + assert_eq!(driver.created(), 2); + assert_eq!(boxes.live(), 0); +} + +#[tokio::test(start_paused = true)] +async fn other_exec_failures_keep_the_box() { + let driver = ScriptedDriver::new(); + driver.then(ExecStep::Fail(BoxError::Driver("bus down".into()))); + let boxes = registry(&driver, 10); + + let failed = boxes + .exec(&user("u1"), &settings(), &request("true")) + .await + .unwrap_err(); + boxes + .exec(&user("u1"), &settings(), &request("true")) + .await + .unwrap(); + + assert_eq!(failed, BoxError::Driver("bus down".into())); + assert_eq!(driver.created(), 1); +} + +#[tokio::test(start_paused = true)] +async fn an_exit_of_124_is_the_box_timing_the_command_out() { + let driver = ScriptedDriver::new(); + driver.then(ExecStep::Reply(BoxOutput { + exit_code: 124, + stdout: b"partial".to_vec(), + stderr: Vec::new(), + })); + let boxes = registry(&driver, 10); + + let result = boxes + .exec(&user("u1"), &settings(), &request("sleep 99")) + .await + .unwrap(); + + assert!(result.timed_out); + assert_eq!(result.stdout, "partial"); + assert!(driver.closed().is_empty()); +} + +#[tokio::test(start_paused = true)] +async fn the_backstop_discards_a_box_that_does_not_answer() { + let driver = ScriptedDriver::new(); + driver.then(ExecStep::Hang); + let boxes = registry(&driver, 10); + let started = Instant::now(); + + let result = boxes + .exec(&user("u1"), &settings(), &request("sleep 99")) + .await + .unwrap(); + + assert_eq!(started.elapsed(), Duration::from_secs(30) + BACKSTOP_MARGIN); + assert!(result.timed_out); + assert_eq!(result.exit_code, 124); + assert_eq!(driver.closed(), vec!["box-0"]); + boxes + .exec(&user("u1"), &settings(), &request("true")) + .await + .unwrap(); + assert_eq!(driver.created(), 2); +} + +#[tokio::test(start_paused = true)] +async fn release_closes_the_tenants_box_only() { + let driver = ScriptedDriver::new(); + let boxes = registry(&driver, 10); + for id in ["alice", "bob"] { + boxes + .exec(&user(id), &settings(), &request("true")) + .await + .unwrap(); + } + + boxes.release(&user("alice")).await; + boxes.release(&user("nobody")).await; + + assert_eq!(driver.closed(), vec!["box-0"]); + assert_eq!(boxes.live(), 1); +} + +#[tokio::test(start_paused = true)] +async fn a_released_box_is_not_recreated_by_a_command_still_running() { + let driver = ScriptedDriver::new(); + let gate = Arc::new(Notify::new()); + driver.then(ExecStep::WaitThenFail( + Arc::clone(&gate), + BoxError::UnknownResource, + )); + let boxes = registry(&driver, 10); + let running = { + let boxes = Arc::clone(&boxes); + tokio::spawn(async move { + boxes + .exec(&user("u1"), &settings(), &request("sleep 3600")) + .await + }) + }; + while driver.exec_resources().is_empty() { + tokio::task::yield_now().await; + } + + boxes.release(&user("u1")).await; + gate.notify_one(); + + assert_eq!(running.await.unwrap().unwrap_err(), BoxError::Released); + assert_eq!(driver.created(), 1); + assert_eq!(boxes.live(), 0); +} + +#[tokio::test(start_paused = true)] +async fn shutdown_closes_every_box() { + let driver = ScriptedDriver::new(); + let boxes = registry(&driver, 10); + for id in ["alice", "bob"] { + boxes + .exec(&user(id), &settings(), &request("true")) + .await + .unwrap(); + } + + boxes.shutdown().await; + + let mut closed = driver.closed(); + closed.sort(); + assert_eq!(closed, vec!["box-0", "box-1"]); + assert_eq!(boxes.live(), 0); +} + +#[tokio::test(start_paused = true)] +async fn a_failed_close_is_logged_not_raised() { + let driver = ScriptedDriver::new(); + driver.fail_closes(); + let boxes = registry(&driver, 10); + boxes + .exec(&user("u1"), &settings(), &request("true")) + .await + .unwrap(); + + boxes.release(&user("u1")).await; + boxes.shutdown().await; + + assert_eq!(driver.closed(), vec!["box-0"]); + assert_eq!(boxes.live(), 0); +} + +#[tokio::test(start_paused = true)] +async fn an_abandoned_command_stops_holding_its_box() { + let driver = ScriptedDriver::new(); + driver.then(ExecStep::Hang); + let boxes = registry(&driver, 10); + let running = { + let boxes = Arc::clone(&boxes); + tokio::spawn(async move { + boxes + .exec(&user("u1"), &settings(), &request("sleep 3600")) + .await + }) + }; + while driver.exec_resources().is_empty() { + tokio::task::yield_now().await; + } + + running.abort(); + assert!(running.await.unwrap_err().is_cancelled()); + + assert_eq!(boxes.reap(Instant::now() + TTL).await, 1); + assert_eq!(driver.closed(), vec!["box-0"]); +} + +#[test] +fn output_bytes_become_lossy_text() { + let result = finished(BoxOutput { + exit_code: 2, + stdout: vec![b'a', 0xff], + stderr: b"oops".to_vec(), + }); + assert_eq!(result.exit_code, 2); + assert_eq!(result.stdout, "a\u{fffd}"); + assert_eq!(result.stderr, "oops"); + assert!(!result.timed_out); + assert_eq!(finished(ok_output()).stdout, "ok"); +} diff --git a/crates/openhuman-core/src/sandbox/openshell/scripted_driver_fixture.rs b/crates/openhuman-core/src/sandbox/openshell/scripted_driver_fixture.rs new file mode 100644 index 00000000000..90017a1a0c2 --- /dev/null +++ b/crates/openhuman-core/src/sandbox/openshell/scripted_driver_fixture.rs @@ -0,0 +1,166 @@ +//! Test-only [`BoxDriver`] stand-in: records every call and answers execs from +//! a script, so the registry's lifecycle is testable without a TinyBox module. + +use std::collections::VecDeque; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use async_trait::async_trait; +use tokio::sync::Notify; + +use super::{BoxDriver, BoxError, BoxExec, BoxOutput, BoxSettings}; + +/// One call the registry made. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum Call { + Create(BoxSettings), + Exec { resource: String, exec: BoxExec }, + Close(String), +} + +/// How the next exec answers. +pub(crate) enum ExecStep { + /// Reply with this output. + Reply(BoxOutput), + /// Fail with this error. + Fail(BoxError), + /// Never answer. + Hang, + /// Wait for the notification, then reply `ok`. + WaitThenReply(Arc), + /// Wait for the notification, then fail. + WaitThenFail(Arc, BoxError), +} + +/// A driver that mints `box-` ids and follows its exec script; an exec past +/// the end of the script replies `ok` with exit code 0. +#[derive(Default)] +pub(crate) struct ScriptedDriver { + calls: Mutex>, + next_id: AtomicUsize, + script: Mutex>, + create_delay: Mutex, + create_failures: AtomicUsize, + close_fails: AtomicBool, +} + +impl ScriptedDriver { + pub(crate) fn new() -> Arc { + Arc::new(Self::default()) + } + + pub(crate) fn then(&self, step: ExecStep) { + self.script.lock().unwrap().push_back(step); + } + + pub(crate) fn slow_create(&self, delay: Duration) { + *self.create_delay.lock().unwrap() = delay; + } + + pub(crate) fn fail_next_creates(&self, count: usize) { + self.create_failures.store(count, Ordering::SeqCst); + } + + pub(crate) fn fail_closes(&self) { + self.close_fails.store(true, Ordering::SeqCst); + } + + pub(crate) fn calls(&self) -> Vec { + self.calls.lock().unwrap().clone() + } + + pub(crate) fn created(&self) -> usize { + self.calls() + .iter() + .filter(|call| matches!(call, Call::Create(_))) + .count() + } + + pub(crate) fn closed(&self) -> Vec { + self.calls() + .into_iter() + .filter_map(|call| match call { + Call::Close(resource) => Some(resource), + _ => None, + }) + .collect() + } + + pub(crate) fn exec_resources(&self) -> Vec { + self.calls() + .into_iter() + .filter_map(|call| match call { + Call::Exec { resource, .. } => Some(resource), + _ => None, + }) + .collect() + } + + pub(crate) fn last_exec(&self) -> Option { + self.calls().into_iter().rev().find_map(|call| match call { + Call::Exec { exec, .. } => Some(exec), + _ => None, + }) + } + + fn record(&self, call: Call) { + self.calls.lock().unwrap().push(call); + } +} + +pub(crate) fn ok_output() -> BoxOutput { + BoxOutput { + exit_code: 0, + stdout: b"ok".to_vec(), + stderr: Vec::new(), + } +} + +#[async_trait] +impl BoxDriver for ScriptedDriver { + async fn create(&self, settings: &BoxSettings) -> Result { + self.record(Call::Create(settings.clone())); + let delay = *self.create_delay.lock().unwrap(); + tokio::time::sleep(delay).await; + let failures = self.create_failures.load(Ordering::SeqCst); + if failures > 0 { + self.create_failures.store(failures - 1, Ordering::SeqCst); + return Err(BoxError::Driver("create refused".into())); + } + Ok(format!( + "box-{}", + self.next_id.fetch_add(1, Ordering::SeqCst) + )) + } + + async fn exec(&self, resource: &str, exec: &BoxExec) -> Result { + self.record(Call::Exec { + resource: resource.to_owned(), + exec: exec.clone(), + }); + let step = self.script.lock().unwrap().pop_front(); + match step { + None => Ok(ok_output()), + Some(ExecStep::Reply(output)) => Ok(output), + Some(ExecStep::Fail(error)) => Err(error), + Some(ExecStep::Hang) => std::future::pending().await, + Some(ExecStep::WaitThenReply(gate)) => { + gate.notified().await; + Ok(ok_output()) + } + Some(ExecStep::WaitThenFail(gate, error)) => { + gate.notified().await; + Err(error) + } + } + } + + async fn close(&self, resource: &str) -> Result<(), BoxError> { + self.record(Call::Close(resource.to_owned())); + if self.close_fails.load(Ordering::SeqCst) { + return Err(BoxError::Driver("close refused".into())); + } + Ok(()) + } +} diff --git a/crates/openhuman-core/src/sandbox/openshell/types.rs b/crates/openhuman-core/src/sandbox/openshell/types.rs new file mode 100644 index 00000000000..1908a514e9d --- /dev/null +++ b/crates/openhuman-core/src/sandbox/openshell/types.rs @@ -0,0 +1,155 @@ +//! 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, + /// 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/exec.rs b/crates/openhuman-core/src/sandbox/ops/exec.rs index a84a16fe107..57e3e030bac 100644 --- a/crates/openhuman-core/src/sandbox/ops/exec.rs +++ b/crates/openhuman-core/src/sandbox/ops/exec.rs @@ -186,6 +186,22 @@ pub(crate) async fn execute_in_sandbox_yielding( .await .map(ShellRunOutcome::Finished) } + // The box has its own workspace (`/sandbox`); no host path or host + // variable is sent, only the request's own environment. A box cannot + // hand back a running command, so the come-back time is a deadline. + SandboxBackendKind::OpenShell => { + let timeout = come_back + .deadline_instead + .map_or(timeout, |deadline| timeout.min(deadline)); + crate::sandbox::spawn_plan::consume(&planned) + .await + .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) + } } } #[cfg(not(feature = "security-module"))] diff --git a/crates/openhuman-core/src/sandbox/ops/policy.rs b/crates/openhuman-core/src/sandbox/ops/policy.rs index 9e6c4eadf10..e927fef19c5 100644 --- a/crates/openhuman-core/src/sandbox/ops/policy.rs +++ b/crates/openhuman-core/src/sandbox/ops/policy.rs @@ -130,6 +130,14 @@ pub async fn create_sandbox_backend_with_config( }) } SandboxBackendKind::Docker => docker::docker_backend_handle(config).await, + // A box is created on a tenant's first command, so there is nothing + // to probe or name yet; the gateway's availability shows on that call. + SandboxBackendKind::OpenShell => Ok(SandboxBackendHandle { + kind: SandboxBackendKind::OpenShell, + status: SandboxStatus::Ready, + backend_id: None, + isolation: None, + }), } } diff --git a/crates/openhuman-core/src/sandbox/ops_tests.rs b/crates/openhuman-core/src/sandbox/ops_tests.rs index c7348ef63ab..fedfbe64440 100644 --- a/crates/openhuman-core/src/sandbox/ops_tests.rs +++ b/crates/openhuman-core/src/sandbox/ops_tests.rs @@ -399,3 +399,20 @@ fn config_disables_sandbox_for_legacy_flag_or_component() { config.components.sandbox = false; assert!(config_disables_sandbox(&config)); } + +#[tokio::test] +async fn the_openshell_handle_is_ready_without_pretending_to_be_a_container() { + let policy = SandboxPolicy { + backend: SandboxBackendKind::OpenShell, + ..unsandboxed_policy(Path::new("/tmp/action"), Path::new("/tmp/state")) + }; + + let handle = create_sandbox_backend_with_config(&policy, &crate::config::Config::default()) + .await + .unwrap(); + + assert_eq!(handle.kind, SandboxBackendKind::OpenShell); + assert_eq!(handle.status, SandboxStatus::Ready); + assert_eq!(handle.backend_id, None); + assert_eq!(handle.isolation, None); +} diff --git a/crates/openhuman-core/src/sandbox/plan.rs b/crates/openhuman-core/src/sandbox/plan.rs index dcda52a43d7..5e43a7ded21 100644 --- a/crates/openhuman-core/src/sandbox/plan.rs +++ b/crates/openhuman-core/src/sandbox/plan.rs @@ -29,6 +29,8 @@ pub enum PlannedExecutor { NativeJail, /// A one-shot container. Docker, + /// The tenant's long-lived OpenShell box: no host mounts, no egress. + OpenShell, /// No jail: the operator disabled the sandbox and the module planned a run on the /// host. Only a `host_run` artifact maps here. Host, @@ -73,6 +75,8 @@ pub enum PlanMappingError { HostResourceLimitUnenforceable, /// A grant path is not valid UTF-8 text for the bus. InvalidGrant, + /// A network reach for an OpenShell box, whose egress the gateway denies. + OpenShellNetworkUnenforceable, /// A plan marked as a run on the host that also claims a jail, grants or constraints. MalformedHostRun, } @@ -103,6 +107,9 @@ impl std::fmt::Display for PlanMappingError { "the host sandbox executor cannot enforce resource limits" } Self::InvalidGrant => "the sandbox plan carries a grant that is not valid text", + Self::OpenShellNetworkUnenforceable => { + "the sandbox plan grants network to an OpenShell box, which has none" + } Self::MalformedHostRun => "the sandbox plan for a run on the host claims a jail", }) } @@ -122,6 +129,11 @@ impl BoxPlan { } let executor = match &artifact.backend { SandboxBackend::Jail => PlannedExecutor::NativeJail, + SandboxBackend::Docker + if artifact.executor_id == super::spawn_plan::OPENSHELL_EXECUTOR => + { + PlannedExecutor::OpenShell + } SandboxBackend::Docker => PlannedExecutor::Docker, SandboxBackend::Noop => return Err(PlanMappingError::NoopBackend), SandboxBackend::Namespace | SandboxBackend::MicroVm => { @@ -133,6 +145,9 @@ impl BoxPlan { PlannedNetwork::Host => NetworkPolicy::Open, PlannedNetwork::EgressProxy => return Err(PlanMappingError::EgressProxyUnavailable), }; + if executor == PlannedExecutor::OpenShell && network != NetworkPolicy::Denied { + return Err(PlanMappingError::OpenShellNetworkUnenforceable); + } validate_resources(artifact, executor)?; let mut read_only = Vec::new(); diff --git a/crates/openhuman-core/src/sandbox/plan_tests.rs b/crates/openhuman-core/src/sandbox/plan_tests.rs index 295b3e878ff..a346d743bca 100644 --- a/crates/openhuman-core/src/sandbox/plan_tests.rs +++ b/crates/openhuman-core/src/sandbox/plan_tests.rs @@ -278,3 +278,28 @@ fn a_plan_with_no_workspace_grant_does_not_mount_one() { artifact.no_workspace = true; assert!(!BoxPlan::from_artifact(&artifact, None).unwrap().workspace); } + +#[test] +fn a_container_plan_on_the_openshell_executor_maps_to_the_tenant_box() { + let mut planned = artifact(SandboxBackend::Docker); + planned.executor_id = crate::sandbox::spawn_plan::OPENSHELL_EXECUTOR.into(); + let plan = BoxPlan::from_artifact(&planned, None).unwrap(); + assert_eq!(plan.executor, PlannedExecutor::OpenShell); + assert_eq!(plan.network, NetworkPolicy::Denied); + assert!(!plan.jail.allow_net); +} + +#[test] +fn an_openshell_plan_that_reaches_the_network_is_refused() { + let mut planned = artifact(SandboxBackend::Docker); + planned.executor_id = crate::sandbox::spawn_plan::OPENSHELL_EXECUTOR.into(); + planned.network = PlannedNetwork::Host; + assert_eq!( + BoxPlan::from_artifact(&planned, None), + Err(PlanMappingError::OpenShellNetworkUnenforceable) + ); + assert_eq!( + PlanMappingError::OpenShellNetworkUnenforceable.to_string(), + "the sandbox plan grants network to an OpenShell box, which has none" + ); +} diff --git a/crates/openhuman-core/src/sandbox/policy.rs b/crates/openhuman-core/src/sandbox/policy.rs index 25698a7ad33..85728421569 100644 --- a/crates/openhuman-core/src/sandbox/policy.rs +++ b/crates/openhuman-core/src/sandbox/policy.rs @@ -25,6 +25,7 @@ fn named_backend( SandboxBackendKind::Local } SandboxBackend::Docker => SandboxBackendKind::Docker, + SandboxBackend::OpenShell => SandboxBackendKind::OpenShell, SandboxBackend::Auto | SandboxBackend::None => { // `[runtime] kind = "docker"` is the legacy spelling of an operator-required // container. @@ -59,6 +60,9 @@ pub fn route_for_mode( SandboxMode::Sandboxed => SandboxBackendKind::Local, }; let docker = &runtime.docker; + // A tenant's OpenShell box has its own workspace and no egress: nothing on + // the host is mounted into it and no container settings apply. + let remote_box = backend == SandboxBackendKind::OpenShell; tracing::debug!( backend = ?backend, remote, @@ -71,14 +75,14 @@ pub fn route_for_mode( state_dir: state_dir.to_path_buf(), read_only_mounts: Vec::new(), read_write_mounts: Vec::new(), - allow_network: !matches!(mode, SandboxMode::Sandboxed) || !remote, - mount_workspace: docker.mount_workspace || runtime.kind != "docker", + allow_network: !remote_box && (!matches!(mode, SandboxMode::Sandboxed) || !remote), + mount_workspace: !remote_box && (docker.mount_workspace || runtime.kind != "docker"), env_passthrough: SANDBOX_ENV_PASSTHROUGH .iter() .map(|s| s.to_string()) .collect(), // Carried whichever executor the module picks; only a container reads it. - docker_overrides: Some(DockerOverrides { + docker_overrides: (!remote_box).then(|| DockerOverrides { image: Some(docker.image.clone()), network: Some(docker.network.clone()), memory_limit_mb: docker.memory_limit_mb, @@ -123,13 +127,20 @@ pub(crate) async fn should_plan_command( return Ok(true); } let config = ctx.load_config().await?; - Ok(matches!( - config.sandbox.backend, + Ok(backend_requires_sandbox(&config.sandbox.backend)) +} + +/// Whether the operator's backend selection is an explicit isolation +/// requirement, rather than leaving the choice to the agent's mode. +pub(crate) fn backend_requires_sandbox(backend: &SandboxBackend) -> bool { + matches!( + backend, SandboxBackend::Landlock | SandboxBackend::Firejail | SandboxBackend::Bubblewrap | SandboxBackend::Docker - )) + | SandboxBackend::OpenShell + ) } #[cfg(test)] diff --git a/crates/openhuman-core/src/sandbox/policy_tests.rs b/crates/openhuman-core/src/sandbox/policy_tests.rs index cbcb5622a3d..ccafd563e08 100644 --- a/crates/openhuman-core/src/sandbox/policy_tests.rs +++ b/crates/openhuman-core/src/sandbox/policy_tests.rs @@ -182,3 +182,38 @@ fn the_configured_docker_runtime_carries_its_workspace_setting() { assert_eq!(filled.backend, SandboxBackendKind::Docker); assert!(!filled.mount_workspace); } + +#[test] +fn an_openshell_selection_routes_to_openshell_without_docker_network_or_host_mounts() { + let sandbox = SandboxConfig { + backend: SandboxBackend::OpenShell, + ..SandboxConfig::default() + }; + for (mode, runtime, remote) in [ + (SandboxMode::Sandboxed, docker_runtime(), false), + (SandboxMode::Sandboxed, RuntimeConfig::default(), true), + (SandboxMode::None, RuntimeConfig::default(), false), + ] { + let routed = policy(mode, &sandbox, &runtime, remote); + assert_eq!(routed.backend, SandboxBackendKind::OpenShell); + assert!(routed.docker_overrides.is_none()); + assert!(!routed.allow_network); + assert!(!routed.mount_workspace); + assert!(routed.read_only_mounts.is_empty() && routed.read_write_mounts.is_empty()); + } +} + +#[test] +fn an_explicit_backend_selection_requires_the_sandbox() { + for backend in [ + SandboxBackend::Landlock, + SandboxBackend::Firejail, + SandboxBackend::Bubblewrap, + SandboxBackend::Docker, + SandboxBackend::OpenShell, + ] { + assert!(backend_requires_sandbox(&backend), "{backend:?}"); + } + assert!(!backend_requires_sandbox(&SandboxBackend::Auto)); + assert!(!backend_requires_sandbox(&SandboxBackend::None)); +} diff --git a/crates/openhuman-core/src/sandbox/spawn_plan/executors.rs b/crates/openhuman-core/src/sandbox/spawn_plan/executors.rs index 4572d5de9be..d3134694912 100644 --- a/crates/openhuman-core/src/sandbox/spawn_plan/executors.rs +++ b/crates/openhuman-core/src/sandbox/spawn_plan/executors.rs @@ -17,6 +17,9 @@ use crate::modules::tinybox::contract::JailStatus; pub(crate) const JAIL_EXECUTOR: &str = "tinybox-jail"; /// The Docker executor's identity on the bus. pub(crate) const DOCKER_EXECUTOR: &str = "tinybox-docker"; +/// The OpenShell executor's identity on the bus. It is declared as a container +/// backend, so a plan that selects it names it by this id. +pub(crate) const OPENSHELL_EXECUTOR: &str = "tinybox-openshell"; fn enforcement(reported: &str) -> ConstraintEnforcement2 { match reported.trim() { @@ -96,6 +99,27 @@ pub(crate) fn docker(available: bool) -> SandboxExecutor2 { } } +/// A tenant's long-lived OpenShell box: a container on the gateway, with its own +/// workspace and egress denied, bounded by `[runtime.openshell]`'s CPU and memory. +/// Nothing on the host is mounted into it. Whether the gateway accepts boxes +/// shows when the tenant's first box is created, so it is declared available. +pub(crate) fn openshell() -> SandboxExecutor2 { + let enforced = ConstraintEnforcement2::Enforced; + SandboxExecutor2 { + executor_id: OPENSHELL_EXECUTOR.into(), + capability_id: "tinybox-openshell|box|fs:own|net:denied|mem|cpu".into(), + backend: SandboxBackend::Docker, + available: true, + isolation: IsolationLevel2::Kernel, + constraints: vec![ + support(SandboxConstraint2::Filesystem, enforced), + support(SandboxConstraint2::Network, enforced), + support(SandboxConstraint2::Memory, enforced), + support(SandboxConstraint2::CpuMillicores, enforced), + ], + } +} + /// The native jail when TinyBox could not report on it: declared unavailable, so the /// module never plans onto it. pub(crate) fn jail_unavailable() -> SandboxExecutor2 { diff --git a/crates/openhuman-core/src/sandbox/spawn_plan/executors_tests.rs b/crates/openhuman-core/src/sandbox/spawn_plan/executors_tests.rs index 1bd6428d921..9f72fa84a87 100644 --- a/crates/openhuman-core/src/sandbox/spawn_plan/executors_tests.rs +++ b/crates/openhuman-core/src/sandbox/spawn_plan/executors_tests.rs @@ -151,3 +151,24 @@ fn a_jail_that_could_not_be_verified_is_declared_unavailable() { assert_eq!(executor.isolation, IsolationLevel2::None); assert!(executor.constraints.is_empty()); } + +#[test] +fn openshell_is_a_container_executor_with_its_own_identity() { + let executor = openshell(); + assert_eq!(executor.executor_id, OPENSHELL_EXECUTOR); + assert_ne!(executor.executor_id, DOCKER_EXECUTOR); + assert_eq!(executor.backend, SandboxBackend::Docker); + assert_eq!(executor.isolation, IsolationLevel2::Kernel); + assert!(executor.available); + for constraint in [ + SandboxConstraint2::Filesystem, + SandboxConstraint2::Network, + SandboxConstraint2::Memory, + SandboxConstraint2::CpuMillicores, + ] { + assert_eq!( + enforcement_of(&executor, constraint), + Some(ConstraintEnforcement2::Enforced) + ); + } +} diff --git a/crates/openhuman-core/src/sandbox/spawn_plan/facts.rs b/crates/openhuman-core/src/sandbox/spawn_plan/facts.rs index 3ee7a670222..fb588b00000 100644 --- a/crates/openhuman-core/src/sandbox/spawn_plan/facts.rs +++ b/crates/openhuman-core/src/sandbox/spawn_plan/facts.rs @@ -161,7 +161,7 @@ pub(crate) fn operator_host_network(policy: &SandboxPolicy) -> bool { fn configured(config: &Config) -> bool { matches!( config.sandbox.backend, - SandboxBackend::Landlock | SandboxBackend::Docker + SandboxBackend::Landlock | SandboxBackend::Docker | SandboxBackend::OpenShell ) } diff --git a/crates/openhuman-core/src/sandbox/spawn_plan/mod.rs b/crates/openhuman-core/src/sandbox/spawn_plan/mod.rs index 2cc47f6b1d7..4e3c03ab392 100644 --- a/crates/openhuman-core/src/sandbox/spawn_plan/mod.rs +++ b/crates/openhuman-core/src/sandbox/spawn_plan/mod.rs @@ -35,6 +35,7 @@ use tinysecurity_bus::{ SubjectScope, Verdict, }; +pub(crate) use executors::OPENSHELL_EXECUTOR; pub(crate) use facts::SpawnSource; pub(crate) use operation::SpawnOperation; @@ -200,7 +201,10 @@ fn options(policy: &SandboxPolicy, host_run: bool) -> SandboxPlanOptions2 { preferred_backend: match policy.backend { SandboxBackendKind::None => None, SandboxBackendKind::Local => Some(SandboxBackend::Jail), - SandboxBackendKind::Docker => Some(SandboxBackend::Docker), + // OpenShell is the only container executor declared for it. + SandboxBackendKind::Docker | SandboxBackendKind::OpenShell => { + Some(SandboxBackend::Docker) + } }, require_preferred_backend: policy.backend != SandboxBackendKind::None, no_workspace: !policy.mount_workspace, @@ -228,6 +232,8 @@ async fn probe( .map_err(|error| format!("docker status: {error}")) }; let (jail, docker) = match policy.backend { + // A box is created on the tenant's first command; there is nothing to probe. + SandboxBackendKind::OpenShell => return Ok(vec![executors::openshell()]), SandboxBackendKind::Local => (Some(jail().await), None), SandboxBackendKind::Docker => (None, Some(docker().await)), SandboxBackendKind::None => { @@ -463,6 +469,7 @@ impl PlannedSpawn { super::plan::PlannedExecutor::NativeJail => SandboxBackendKind::Local, super::plan::PlannedExecutor::Docker => SandboxBackendKind::Docker, super::plan::PlannedExecutor::Host => SandboxBackendKind::None, + super::plan::PlannedExecutor::OpenShell => SandboxBackendKind::OpenShell, }; let workspace = policy.workspace_root.to_str(); let paths = |list: &[String]| -> Vec { diff --git a/crates/openhuman-core/src/sandbox/spawn_plan/mod_tests.rs b/crates/openhuman-core/src/sandbox/spawn_plan/mod_tests.rs index 06517c703e1..22061175c55 100644 --- a/crates/openhuman-core/src/sandbox/spawn_plan/mod_tests.rs +++ b/crates/openhuman-core/src/sandbox/spawn_plan/mod_tests.rs @@ -169,3 +169,22 @@ fn plan_request_carries_openhuman_owned_credential_paths_to_tinysecurity() { .any(|path| path.ends_with("auth-profiles/secrets.enc"))); assert!(denied.iter().any(|path| path.ends_with("secrets.enc"))); } + +#[test] +fn an_openshell_spawn_requires_the_container_backend_and_asks_for_no_bounds() { + let openshell = options(&policy(SandboxBackendKind::OpenShell), false); + assert_eq!(openshell.preferred_backend, Some(SandboxBackend::Docker)); + assert!(openshell.require_preferred_backend); + let mut bounded = with_overrides(Some(2.0), Some(256)); + bounded.backend = SandboxBackendKind::OpenShell; + assert_eq!(limits(&bounded), ResourceLimits2::default()); +} + +#[tokio::test] +async fn an_openshell_spawn_declares_only_the_openshell_executor() { + let declared = probe(&Config::default(), &policy(SandboxBackendKind::OpenShell)) + .await + .unwrap(); + assert_eq!(declared.len(), 1); + assert_eq!(declared[0].executor_id, OPENSHELL_EXECUTOR); +} diff --git a/crates/openhuman-core/src/sandbox/types.rs b/crates/openhuman-core/src/sandbox/types.rs index a96e8f42f37..e7a3302b719 100644 --- a/crates/openhuman-core/src/sandbox/types.rs +++ b/crates/openhuman-core/src/sandbox/types.rs @@ -15,6 +15,9 @@ pub enum SandboxBackendKind { Local, /// Docker container isolation. Docker, + /// The tenant's long-lived OpenShell box (`sandbox::openshell`). + #[serde(rename = "openshell")] + OpenShell, } /// Per-session sandbox policy resolved from agent definition, session diff --git a/crates/openhuman-core/src/sandbox/types_tests.rs b/crates/openhuman-core/src/sandbox/types_tests.rs index 1733ebce0c7..6a4cabf4544 100644 --- a/crates/openhuman-core/src/sandbox/types_tests.rs +++ b/crates/openhuman-core/src/sandbox/types_tests.rs @@ -61,3 +61,13 @@ fn sandbox_status_variants() { assert_ne!(SandboxStatus::Ready, SandboxStatus::Busy); assert_ne!(SandboxStatus::Busy, SandboxStatus::Error); } + +#[test] +fn the_openshell_kind_is_named_openshell_on_the_wire() { + assert_eq!( + serde_json::to_value(SandboxBackendKind::OpenShell).unwrap(), + serde_json::json!("openshell") + ); + let back: SandboxBackendKind = serde_json::from_value(serde_json::json!("openshell")).unwrap(); + assert_eq!(back, SandboxBackendKind::OpenShell); +} diff --git a/scripts/ci/process-statics.json b/scripts/ci/process-statics.json index f223f01b7ac..d322f219db1 100644 --- a/scripts/ci/process-statics.json +++ b/scripts/ci/process-statics.json @@ -668,5 +668,15 @@ "category": "A", "reason": "One-shot guard that subscribes the proactive web subscriber to the process-wide bus once; it stores no tenant identifiers, and per-event tenant scope arrives on each event.", "verification": "web_chat/event_bus_tests.rs: egress_surface_bridges_pending_with_chat_context" + }, + { + "file": "crates/openhuman-core/src/sandbox/openshell/mod.rs", + "scope": "", + "name": "REGISTRY", + "type": "std::sync::OnceLock>>", + "count": 1, + "category": "B", + "reason": "The process's OpenShell box registry holds one box per tenant, keyed on the whole authenticated Tenant (profile and agent), never the profile alone; a call with no tenant is refused before the registry is touched, so no two tenants can share a box.", + "verification": "sandbox/openshell/registry_tests.rs: embedded_users_of_one_host_get_separate_boxes; sandbox/openshell/mod_tests.rs: an_unscoped_command_creates_no_box" } ] diff --git a/scripts/ci/saas-ambient-baseline.json b/scripts/ci/saas-ambient-baseline.json index e8188c8f6a8..997bccb51a6 100644 --- a/scripts/ci/saas-ambient-baseline.json +++ b/scripts/ci/saas-ambient-baseline.json @@ -650,6 +650,13 @@ "text": "tokio::spawn(async move {", "occurrence": 1 }, + { + "rule": "bare-spawn", + "path": "crates/openhuman-core/src/sandbox/openshell/registry.rs", + "line": 231, + "text": "tokio::spawn(async move {", + "occurrence": 1 + }, { "rule": "home-dir", "path": "crates/openhuman-core/src/security/policy/native_commands.rs",