diff --git a/.github/workflows/security-native.yml b/.github/workflows/security-native.yml index a9c6076c87c..a84b45d7770 100644 --- a/.github/workflows/security-native.yml +++ b/.github/workflows/security-native.yml @@ -10,6 +10,9 @@ on: - vendor/tinysecurity - crates/openhuman-core/Cargo.toml - crates/openhuman-embed/Cargo.toml + - crates/openhuman-embed/src/runtime/** + - crates/openhuman-embed/tests/security_live_scope.rs + - crates/openhuman-embed/tests/security_second_runtime.rs - crates/openhuman-tinyhumans/Cargo.toml - crates/openhuman-rpc/Cargo.toml - crates/openhuman-cli/Cargo.toml diff --git a/crates/openhuman-core/src/modules/ops.rs b/crates/openhuman-core/src/modules/ops.rs index 1b2e3053149..982f016c91e 100644 --- a/crates/openhuman-core/src/modules/ops.rs +++ b/crates/openhuman-core/src/modules/ops.rs @@ -324,8 +324,12 @@ async fn ensure_loaded_with_security_callback( id: &str, ) -> Result<(), String> { let (task_resolver, config, id) = (resolver.clone(), config.clone(), id.to_owned()); + // Captured before the load is scheduled: if the caller's runtime is + // released while the detached load runs, the load must not record that + // runtime's scope as the module's owner. + let epoch = super::security::host_callbacks::scope_epoch(); callback_load::detached(resolver, async move { - super::security::host_callbacks::ensure_loaded(&task_resolver, &config, &id).await + super::security::host_callbacks::ensure_loaded(&task_resolver, &config, &id, epoch).await }) .await } diff --git a/crates/openhuman-core/src/modules/security/host_callbacks.rs b/crates/openhuman-core/src/modules/security/host_callbacks.rs index 3b7c234b6ae..bcd2bf196ca 100644 --- a/crates/openhuman-core/src/modules/security/host_callbacks.rs +++ b/crates/openhuman-core/src/modules/security/host_callbacks.rs @@ -25,6 +25,116 @@ type SecurityCallbackLoads = static SECURITY_CALLBACK_LOADS: std::sync::LazyLock = std::sync::LazyLock::new(|| tokio::sync::Mutex::new(std::collections::HashMap::new())); +/// Which secret scope (its `.secret_key` path) is using each admitted module. +/// +/// TinySecurity keeps the secret scope it was admitted with for the life of +/// the module: its secret registration and audit stream cannot be replaced by +/// reinitialization, and a loaded module is never unloaded. So a module is +/// handed to one scope at a time. Another scope is refused while the current +/// one is live. Once the host releases the current one ([`release_scopes`]), +/// the module may be taken over, but only by the admitting scope itself or by +/// a scope the host declared transient ([`declare_transient_scope`]): a +/// durable scope must never encrypt state it keeps under a master key that +/// belongs to a different scope. +/// +/// A plain mutex, not the async one guarding [`SECURITY_CALLBACK_LOADS`], so a +/// host can release its scope from a synchronous `Drop`. +#[derive(Default)] +struct ScopeOwnership { + /// The live owner of each admitted module; no entry once released. + owners: std::collections::HashMap, + /// Scopes whose secret state does not outlive their runtime. + transient: std::collections::HashSet, + /// Bumped by every release. A load that started before a release must + /// not publish its scope as the owner when it finishes after it. + epoch: u64, +} + +static SECURITY_SCOPE_OWNERSHIP: std::sync::LazyLock> = + std::sync::LazyLock::new(Default::default); + +fn ownership() -> std::sync::MutexGuard<'static, ScopeOwnership> { + SECURITY_SCOPE_OWNERSHIP + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) +} + +/// How a later caller came to use an admitted module's secret scope. +#[derive(Debug, PartialEq, Eq)] +enum ScopeClaim { + /// The caller's scope is the one already using the module. + Held, + /// The previous owner was released; the caller's scope now uses it. + TakenOver, +} + +/// Whether the secret scope at `requested` may use a module admitted with +/// `admitted`, whose live owner is `owner` (`None`: released). +fn claim_scope( + owner: Option<&Path>, + admitted: &Path, + requested: &Path, + transient: bool, +) -> Result { + match owner { + Some(owner) if owner == requested => Ok(ScopeClaim::Held), + Some(_) => Err("security secret scope changed after module admission".into()), + None if requested == admitted || transient => Ok(ScopeClaim::TakenOver), + None => Err("security secret scope changed after module admission; \ + a durable scope cannot take over a released one" + .into()), + } +} + +/// The current release epoch, captured before a load is scheduled. +pub(in crate::modules) fn scope_epoch() -> u64 { + ownership().epoch +} + +/// Claim module `id` for `requested`, given the scope it was admitted with. +fn claim(id: &str, admitted: &Path, requested: &Path) -> Result { + let ownership = ownership(); + claim_scope( + ownership.owners.get(id).map(PathBuf::as_path), + admitted, + requested, + ownership.transient.contains(requested), + ) +} + +/// Record `key_path` as the live owner of module `id`, unless a release +/// happened since `epoch` was captured: the load that started before it +/// belongs to a released runtime. Returns whether the owner was recorded. +fn publish_owner(id: &str, key_path: PathBuf, epoch: u64) -> bool { + let mut ownership = ownership(); + if ownership.epoch != epoch { + log::debug!("[security] scope released during load; owner not recorded module={id}"); + return false; + } + ownership.owners.insert(id.to_owned(), key_path); + true +} + +fn secret_key_path(config_dir: &Path) -> PathBuf { + config_dir.join(".secret_key") +} + +/// Declare the config directory `config_dir` transient. See +/// [`crate::security::declare_transient_secret_scope`]. +pub(crate) fn declare_transient_scope(config_dir: &Path) { + ownership().transient.insert(secret_key_path(config_dir)); +} + +/// Release every module's live owner and forget the declared transient +/// scopes. See [`crate::security::release_secret_scope`]. +pub(crate) fn release_scopes() { + let mut ownership = ownership(); + ownership.epoch = ownership.epoch.wrapping_add(1); + ownership.transient.clear(); + let released = ownership.owners.drain().count(); + log::debug!("[security] secret scope owners released count={released}"); +} + impl SecurityCallbackState { fn module_config(&self, config: &Config) -> Result { let trusted_host = self.binding.unique_name().to_string(); @@ -178,27 +288,36 @@ fn opaque_id(label: &str, path: &Path, suffix: &str) -> String { format!("{:x}", hasher.finalize())[..32].to_owned() } +/// Admit module `id` for `config`'s secret scope, or confirm the admitted one +/// may serve it. `epoch` is [`scope_epoch`] captured when the caller asked, +/// before the load was scheduled. pub(in crate::modules) async fn ensure_loaded( resolver: &Resolver, config: &Config, id: &str, + epoch: u64, ) -> Result<(), String> { let mut loads = SECURITY_CALLBACK_LOADS.lock().await; if let Some(state) = loads.get(id) { - let key_path = config - .config_path - .parent() - .unwrap_or_else(|| Path::new(".")) - .join(".secret_key"); - if state.key_path != key_path { - return Err("security secret scope changed after module admission".into()); - } + let key_path = secret_key_path( + config + .config_path + .parent() + .unwrap_or_else(|| Path::new(".")), + ); + let claim = claim(id, &state.key_path, &key_path)?; // Confirm the admitted module still retains this binding. Re-presenting // it would be refused (a binding is spent once a module takes it), and // the single-binding path accepts only a local-file source, so it // failed every later call on a host served from the release. super::super::ops::callback_load::confirm(resolver, id, &state.binding).await?; register_scope(config, state).await?; + // The loads lock is held, so no other caller claims it meanwhile. + if claim == ScopeClaim::TakenOver && publish_owner(id, key_path, epoch) { + log::info!( + "[security] secret scope taken over after its owner was released module={id}" + ); + } return Ok(()); } @@ -207,7 +326,7 @@ pub(in crate::modules) async fn ensure_loaded( .parent() .unwrap_or_else(|| Path::new(".")) .to_path_buf(); - let key_path = key_dir.join(".secret_key"); + let key_path = secret_key_path(&key_dir); let user_id = crate::security::secret_storage::encrypted_store::keyring_user_id_from_dir(&key_dir); let subject = tinysecurity_bus::SubjectScope { @@ -323,6 +442,7 @@ pub(in crate::modules) async fn ensure_loaded( .ok_or_else(|| "admitted security callback state unavailable".to_owned())?; candidates.clear(); loads.insert(id.to_owned(), std::sync::Arc::clone(&state)); + publish_owner(id, state.key_path.clone(), epoch); register_scope(config, &state).await?; Ok(()) @@ -362,3 +482,7 @@ async fn register_scope(config: &Config, state: &SecurityCallbackState) -> Resul } Ok(()) } + +#[cfg(test)] +#[path = "host_callbacks_tests.rs"] +mod tests; diff --git a/crates/openhuman-core/src/modules/security/host_callbacks_tests.rs b/crates/openhuman-core/src/modules/security/host_callbacks_tests.rs new file mode 100644 index 00000000000..ddd3882a9f4 --- /dev/null +++ b/crates/openhuman-core/src/modules/security/host_callbacks_tests.rs @@ -0,0 +1,87 @@ +//! Which secret scope may use the admitted TinySecurity module. + +use super::*; + +const CHANGED: &str = "security secret scope changed after module admission"; + +fn admitted() -> &'static Path { + Path::new("/tmp/openhuman-scratch-first/.secret_key") +} + +#[test] +fn the_owning_scope_keeps_its_module() { + assert_eq!( + claim_scope(Some(admitted()), admitted(), admitted(), false), + Ok(ScopeClaim::Held) + ); +} + +#[test] +fn a_different_scope_is_refused_while_the_owner_is_live() { + let other = Path::new("/tmp/openhuman-scratch-second/.secret_key"); + assert_eq!( + claim_scope(Some(admitted()), admitted(), other, true), + Err(CHANGED.to_owned()), + "even a transient scope waits for the owner's release" + ); +} + +#[test] +fn a_transient_scope_takes_over_a_module_whose_owner_was_released() { + let other = Path::new("/tmp/openhuman-scratch-second/.secret_key"); + assert_eq!( + claim_scope(None, admitted(), other, true), + Ok(ScopeClaim::TakenOver) + ); +} + +#[test] +fn the_admitting_scope_takes_its_module_back_after_a_release() { + assert_eq!( + claim_scope(None, admitted(), admitted(), false), + Ok(ScopeClaim::TakenOver) + ); +} + +#[test] +fn a_durable_scope_is_refused_a_module_whose_owner_was_released() { + let durable = Path::new("/home/someone/.openhuman/.secret_key"); + let refused = claim_scope(None, admitted(), durable, false).expect_err("durable refused"); + assert!(refused.starts_with(CHANGED), "{refused}"); + assert!(refused.contains("durable"), "{refused}"); +} + +/// The ownership table is process-wide, so its lifecycle is one test. +#[test] +fn release_declare_and_claim_follow_the_hosts_lifecycle() { + let id = "tinysecurity-ownership-test"; + let first_dir = Path::new("/tmp/openhuman-scratch-first"); + let second_dir = Path::new("/tmp/openhuman-scratch-second"); + let first = secret_key_path(first_dir); + let second = secret_key_path(second_dir); + + // The first runtime admits the module. + assert!(publish_owner(id, first.clone(), scope_epoch())); + assert_eq!(claim(id, &first, &first), Ok(ScopeClaim::Held)); + + // A second runtime is refused while the first is live, declared or not. + declare_transient_scope(second_dir); + assert_eq!(claim(id, &first, &second), Err(CHANGED.to_owned())); + + // A load the first runtime started before its release finishes after it: + // it must not record the released scope as the owner. + let stale_epoch = scope_epoch(); + release_scopes(); + assert!(!publish_owner(id, first.clone(), stale_epoch)); + + // The release also forgot the second's declaration: it must declare again. + assert!(claim(id, &first, &second).is_err()); + declare_transient_scope(second_dir); + assert_eq!(claim(id, &first, &second), Ok(ScopeClaim::TakenOver)); + assert!(publish_owner(id, second.clone(), scope_epoch())); + + // Now the second owns it, and the released first is refused. + assert_eq!(claim(id, &first, &second), Ok(ScopeClaim::Held)); + assert_eq!(claim(id, &first, &first), Err(CHANGED.to_owned())); + release_scopes(); +} diff --git a/crates/openhuman-core/src/modules/security/mod.rs b/crates/openhuman-core/src/modules/security/mod.rs index e49e174e336..318a889ae71 100644 --- a/crates/openhuman-core/src/modules/security/mod.rs +++ b/crates/openhuman-core/src/modules/security/mod.rs @@ -591,6 +591,16 @@ pub(crate) async fn validate_host_path( Err("TinySecurity is not built into this host".into()) } +/// See [`crate::security::release_secret_scope`]. +pub(crate) fn release_secret_scope() { + host_callbacks::release_scopes(); +} + +/// See [`crate::security::declare_transient_secret_scope`]. +pub(crate) fn declare_transient_secret_scope(config_dir: &std::path::Path) { + host_callbacks::declare_transient_scope(config_dir); +} + /// Replace the running module configuration through the loader control plane. /// Any reinitialization failure is returned to the caller; policy consumers must /// keep denying while the configuration is uncertain. diff --git a/crates/openhuman-core/src/modules/security/text.rs b/crates/openhuman-core/src/modules/security/text.rs index 8a6bbeaf8da..53535d5615e 100644 --- a/crates/openhuman-core/src/modules/security/text.rs +++ b/crates/openhuman-core/src/modules/security/text.rs @@ -1,20 +1,26 @@ //! TinySecurity redaction operations and the single sync adapter for host seams. -use std::sync::OnceLock; +use std::sync::RwLock; use std::time::Duration; pub(crate) use tinysecurity_bus::RedactMode; use crate::config::Config; -static CONFIG: OnceLock = OnceLock::new(); +/// The config the synchronous adapters reach the module with: the latest one +/// admitted. Replaced on every arm, so after a later runtime takes the module +/// over (see `host_callbacks`) these adapters present its scope, not that of +/// the released runtime that armed them first. +static CONFIG: RwLock> = RwLock::new(None); const SYNC_TIMEOUT: Duration = Duration::from_secs(2); pub(crate) fn arm(config: &Config) { if !super::sync_seam::arm_current() { return; } - let _ = CONFIG.set(config.clone()); + *CONFIG + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(config.clone()); crate::core::log_redaction::install_module_scrubber(scrub_log); } @@ -55,10 +61,7 @@ pub(crate) fn redact_blocking( text: &str, timeout: Duration, ) -> Result { - let config = CONFIG - .get() - .cloned() - .ok_or_else(|| "TinySecurity text adapter is not armed".to_owned())?; + let config = armed_config()?; let text = text.to_owned(); super::sync_seam::run(timeout, async move { redact(&config, mode, &text).await }) } @@ -70,10 +73,7 @@ pub(crate) fn privacy_check_blocking( request: tinysecurity_bus::PrivacyCheckRequest2, timeout: Duration, ) -> Result { - let config = CONFIG - .get() - .cloned() - .ok_or_else(|| "TinySecurity text adapter is not armed".to_owned())?; + let config = armed_config()?; super::sync_seam::run(timeout, async move { super::gap::privacy_check_with_config(&config, request).await }) @@ -83,15 +83,20 @@ pub(crate) fn classify_provider_host_blocking( host: String, timeout: Duration, ) -> Result { - let config = CONFIG - .get() - .cloned() - .ok_or_else(|| "TinySecurity text adapter is not armed".to_owned())?; + let config = armed_config()?; super::sync_seam::run(timeout, async move { super::gap::classify_provider_host_with_config(&config, host).await }) } +fn armed_config() -> Result { + CONFIG + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + .ok_or_else(|| "TinySecurity text adapter is not armed".to_owned()) +} + fn scrub_log(text: &str) -> Option { redact_blocking(RedactMode::CredentialsOnly, text, SYNC_TIMEOUT).ok() } diff --git a/crates/openhuman-core/src/security/mod.rs b/crates/openhuman-core/src/security/mod.rs index a760804ae82..72b365eea2a 100644 --- a/crates/openhuman-core/src/security/mod.rs +++ b/crates/openhuman-core/src/security/mod.rs @@ -51,3 +51,38 @@ pub use schemas::{ all_controller_schemas as all_security_controller_schemas, all_registered_controllers as all_security_registered_controllers, }; + +/// Declare that the secret state of the config directory `config_dir` does not +/// outlive the runtime using it (an embedder's scratch directory). +/// +/// TinySecurity keeps the secret scope it was admitted with (approval subject, +/// audit stream and master-key registration, all derived from the admitting +/// config) for as long as the module is loaded, which is the life of the +/// process. After [`release_secret_scope`], a later config may take that scope +/// over only if it is the admitting config itself or declared here: a durable +/// config would otherwise keep secrets encrypted under another scope's master +/// key. Declarations last until the next release. A no-op in a build without +/// the `security-module` feature. +pub fn declare_transient_secret_scope(config_dir: &std::path::Path) { + #[cfg(feature = "security-module")] + crate::modules::security::declare_transient_secret_scope(config_dir); + #[cfg(not(feature = "security-module"))] + let _ = config_dir; +} + +/// Release the secret scope using the admitted TinySecurity module, for a host +/// whose core is gone. +/// +/// While the core that admitted TinySecurity is live, a config that derives a +/// different secret scope is refused the module, so one live scope is never +/// handed another's master key. A host that releases its core and builds a +/// new one in the same process (an embedder's `Runtime`, each in its own +/// scratch directory) calls this once the old core is dropped, so the next +/// core can take the admitted module over (see +/// [`declare_transient_secret_scope`]) instead of being refused every security +/// call. A load still in flight for the released core does not reclaim it. A +/// no-op in a build without the `security-module` feature. +pub fn release_secret_scope() { + #[cfg(feature = "security-module")] + crate::modules::security::release_secret_scope(); +} diff --git a/crates/openhuman-embed/Cargo.toml b/crates/openhuman-embed/Cargo.toml index 7c19223192a..89872035e3f 100644 --- a/crates/openhuman-embed/Cargo.toml +++ b/crates/openhuman-embed/Cargo.toml @@ -201,3 +201,10 @@ required-features = ["profiles"] [[test]] name = "mcp_module" required-features = ["mcp", "modules", "skills", "storage-sqlite"] + +# While the runtime that admitted TinySecurity is live, another secret scope is +# refused the module. Calls the core's security module directly, so it needs +# the feature by name. Ignored by default: it needs the module's release. +[[test]] +name = "security_live_scope" +required-features = ["security-module"] diff --git a/crates/openhuman-embed/src/runtime/README.md b/crates/openhuman-embed/src/runtime/README.md index 2f0d1b3ea9a..fbaf64c3d58 100644 --- a/crates/openhuman-embed/src/runtime/README.md +++ b/crates/openhuman-embed/src/runtime/README.md @@ -55,7 +55,10 @@ an ephemeral one), and the installed session store. Both `Runtime` and every agent or in-flight turn exists, even after the host drops its `Runtime`. When the last owner drops, the guard drops the core while the process slot is still claimed, restores the previous session store if it still owns the -slot, drops its handle on an ephemeral workspace, and releases `RUNTIME_LIVE`. +slot, drops its handle on an ephemeral workspace, and releases `RUNTIME_LIVE` +together with the TinySecurity secret scope (`release_process_slot`): the +module stays loaded with the scope it was admitted with, and the next runtime +takes it over instead of being refused every security call. The ephemeral root (`EphemeralRoot`) is removed with a short retry loop (background writers can recreate subdirectories just after a turn returns) when its last holder drops. A dropped agent's deferred MCP cleanup retains the diff --git a/crates/openhuman-embed/src/runtime/build.rs b/crates/openhuman-embed/src/runtime/build.rs index 5de0ef82c69..b92fbd6e571 100644 --- a/crates/openhuman-embed/src/runtime/build.rs +++ b/crates/openhuman-embed/src/runtime/build.rs @@ -41,7 +41,7 @@ struct SlotClaim { impl Drop for SlotClaim { fn drop(&mut self) { if self.armed { - RUNTIME_LIVE.store(false, std::sync::atomic::Ordering::Release); + super::release_process_slot(); log::debug!("[embed][runtime] build did not complete; process slot released"); } } @@ -176,6 +176,16 @@ impl RuntimeBuilder { let inherit = self.workspace.is_operator_owned(); let resolved = ResolvedWorkspace::resolve(&self.workspace, self.action_dir.as_deref()) .map_err(map_ws)?; + // A scratch directory's secrets go with it, so this runtime may take + // over the TinySecurity module a released runtime left admitted (it is + // loaded once per process and keeps its first secret scope). A durable + // directory may not: its secrets would be kept under another scope's + // master key. + if resolved._temp.is_some() { + if let Some(config_dir) = resolved.config_path.parent() { + openhuman_core::security::declare_transient_secret_scope(config_dir); + } + } // Discovered: the core loads its own config during boot; nothing to // assemble here. Resolved: `Inherit` starts from the operator's own diff --git a/crates/openhuman-embed/src/runtime/mod.rs b/crates/openhuman-embed/src/runtime/mod.rs index 71a0d2d03c4..5620e3a2f47 100644 --- a/crates/openhuman-embed/src/runtime/mod.rs +++ b/crates/openhuman-embed/src/runtime/mod.rs @@ -111,6 +111,20 @@ use crate::{Core, CoreError}; /// Guards the process-scoped core state described in the module docs. pub(crate) static RUNTIME_LIVE: AtomicBool = AtomicBool::new(false); +/// Give up the process slot once this runtime's core is gone. +/// +/// Also releases the secret scope the TinySecurity module was admitted with. +/// The module stays loaded for the process and keeps that scope, but the scope +/// belonged to the released runtime's config; the next runtime, built in its +/// own scratch directory, takes the module over instead of being refused +/// every security call. Unconditional: the core decides whether TinySecurity +/// is built in (its default features include it even when this crate's own +/// `security-module` feature is off). +pub(crate) fn release_process_slot() { + openhuman_core::security::release_secret_scope(); + RUNTIME_LIVE.store(false, std::sync::atomic::Ordering::Release); +} + /// Error from building a [`Runtime`]. #[derive(Debug, thiserror::Error)] pub enum RuntimeError { @@ -263,7 +277,7 @@ impl Drop for CoreGuard { } } drop(self.workspace._temp.take()); - RUNTIME_LIVE.store(false, std::sync::atomic::Ordering::Release); + release_process_slot(); log::debug!("[embed][runtime] released"); } } diff --git a/crates/openhuman-embed/tests/security_live_scope.rs b/crates/openhuman-embed/tests/security_live_scope.rs new file mode 100644 index 00000000000..5a3d01ece89 --- /dev/null +++ b/crates/openhuman-embed/tests/security_live_scope.rs @@ -0,0 +1,75 @@ +//! TinySecurity is admitted with one secret scope per process. While the +//! runtime that admitted it is live, a config that derives a different secret +//! scope (another config directory) is refused the module, so one live scope +//! is never handed another's master key, and the refusal leaves the live +//! runtime's own screening working. +//! +//! Needs the TinySecurity release on `OPENHUMAN_MODULE_PATH` (or in the module +//! release cache), so it is ignored by default and run by +//! `scripts/ci/security-native-fixture.sh`. + +mod common; + +use std::sync::Arc; + +use common::{chat_requests, offline_config, provider, runtime, stub_backend}; +use openhuman_embed::{AgentSpec, Provider, Runtime, Workspace}; +use tinyagents_session::port::InMemorySessionStores; + +/// A plain request the prompt screen lets through. +const BENIGN: &str = "What is the capital of France?"; + +#[test] +#[ignore = "needs the TinySecurity release; run by scripts/ci/security-native-fixture.sh"] +fn a_different_secret_scope_is_refused_while_the_admitting_runtime_is_live() { + runtime().block_on(async { + tokio::spawn(async { + let backend = stub_backend().await; + let model = provider("Paris").await; + let runtime = Runtime::builder() + .config(offline_config()) + .workspace(Workspace::Stateless) + .session_store(Arc::new(InMemorySessionStores::new())) + .backend_url(backend.uri()) + .build() + .await + .expect("runtime"); + let agent = runtime + .agent( + AgentSpec::new("live").provider( + Provider::openai_compatible(format!("{}/v1", model.uri()), "fixture") + .model("fixture"), + ), + ) + .expect("agent"); + let first = agent.turn(BENIGN).send().await.expect("screened turn"); + assert_eq!(first.reply, "Paris"); + + let elsewhere = tempfile::tempdir().expect("other config directory"); + let mut other = offline_config(); + other.config_path = elsewhere.path().join("config.toml"); + other.workspace_dir = elsewhere.path().join("workspace"); + let refused = openhuman_core::modules::security::ensure_loaded(&other) + .await + .expect_err("another secret scope is refused the admitted module"); + assert!( + refused + .to_string() + .contains("security secret scope changed after module admission"), + "{refused}" + ); + + let second = agent + .turn(BENIGN) + .send() + .await + .expect("the live runtime still screens"); + assert_eq!(second.reply, "Paris"); + assert_eq!(chat_requests(&model).await.len(), 2); + runtime.remove_agent("live").await.expect("remove agent"); + drop(agent); + }) + .await + .expect("test task"); + }); +} diff --git a/crates/openhuman-embed/tests/security_second_runtime.rs b/crates/openhuman-embed/tests/security_second_runtime.rs new file mode 100644 index 00000000000..993cd8cd179 --- /dev/null +++ b/crates/openhuman-embed/tests/security_second_runtime.rs @@ -0,0 +1,131 @@ +//! TinySecurity is admitted once per process and keeps the secret scope it was +//! admitted with. An embedded [`Runtime`] owns a fresh scratch config directory, +//! so a runtime built after an earlier one has been released derives a +//! different scope from its own config. It must still reach the admitted +//! module, through both of its paths: +//! +//! - the async client: its prompt is screened and passes, rather than being +//! held for security review because the module "belongs" to a runtime that +//! is gone; +//! - the synchronous adapters: its tool result is scrubbed and reaches the +//! model, rather than being replaced by the redaction placeholder. +//! +//! Needs the TinySecurity release on `OPENHUMAN_MODULE_PATH` (or in the module +//! release cache), so it is ignored by default and run by +//! `scripts/ci/security-native-fixture.sh`. + +mod common; + +use std::sync::Arc; + +use common::{ + chat_completion, chat_requests, offline_config, route, runtime, scripted_provider, + stub_backend, tool_call_completion, tool_results, +}; +use openhuman_embed::{ + AgentDefinitionSpec, AgentSpec, HostTurnTools, Runtime, Tool, ToolScopeSpec, Workspace, +}; +use serde_json::{json, Value}; +use tinyagents_session::port::InMemorySessionStores; + +/// A plain request the prompt screen lets through. +const BENIGN: &str = "What is the capital of France?"; + +/// What the lookup tool returns; nothing in it is a credential. +const LOOKUP: &str = "capital of France: Paris"; + +/// A read-only host tool with a fixed answer. +struct Lookup; + +#[async_trait::async_trait] +impl Tool for Lookup { + fn name(&self) -> &str { + "lookup" + } + fn description(&self) -> &str { + "Look up a fact" + } + fn parameters_schema(&self) -> Value { + json!({"type": "object", "properties": {}}) + } + fn permission_level(&self) -> tinytools::PermissionLevel { + tinytools::PermissionLevel::ReadOnly + } + async fn execute(&self, _: Value) -> anyhow::Result { + Ok(tinytools::ToolResult::success(LOOKUP)) + } +} + +/// Build a runtime with the prompt screen enforced, run one turn whose model +/// calls `lookup` and then answers, and release the runtime. Returns the tool +/// result the model saw, or why the turn failed. +async fn screened_turn(name: &str) -> Result { + let backend = stub_backend().await; + let model = scripted_provider( + vec![ + tool_call_completion("lookup", "{}"), + chat_completion("Paris"), + ], + "Paris", + ) + .await; + let runtime = Runtime::builder() + .config(offline_config()) + .workspace(Workspace::Stateless) + .session_store(Arc::new(InMemorySessionStores::new())) + .backend_url(backend.uri()) + .build() + .await + .map_err(|error| format!("{name} runtime: {error}"))?; + assert!( + runtime.capabilities().configuration.security_enforced, + "{name} runtime enforces security" + ); + let agent = runtime + .agent( + AgentSpec::new(name) + .provider(route(&model, "fixture")) + .definition( + AgentDefinitionSpec::new() + .bare_prompt("Use lookup then answer") + .tools(ToolScopeSpec::HostOnly), + ) + .tools(|_| Box::pin(async { HostTurnTools::advertised(vec![Box::new(Lookup)]) })), + ) + .map_err(|error| format!("{name} agent: {error}"))?; + let outcome = agent.turn(BENIGN).send().await; + let requests = chat_requests(&model).await; + runtime.remove_agent(name).await.expect("remove agent"); + drop(agent); + drop(runtime); + let outcome = outcome.map_err(|error| format!("{name} turn: {error:?}"))?; + if requests.len() < 2 { + return Err(format!( + "{name} turn never returned a tool result to the model ({} requests): {}", + requests.len(), + outcome.reply + )); + } + Ok(tool_results(&requests[1])) +} + +#[test] +#[ignore = "needs the TinySecurity release; run by scripts/ci/security-native-fixture.sh"] +fn a_runtime_built_after_another_is_released_still_screens_its_prompts() { + runtime().block_on(async { + tokio::spawn(async { + for name in ["first", "second"] { + let outcome = screened_turn(name).await; + eprintln!("{name} runtime: {outcome:?}"); + let tool_result = outcome.unwrap_or_else(|error| panic!("{error}")); + assert!( + tool_result.contains(LOOKUP), + "{name} runtime's tool result reached the model scrubbed, not \ + replaced: {tool_result}" + ); + } + }) + .await + .expect("test task"); + }); +} diff --git a/scripts/ci/security-native-fixture.sh b/scripts/ci/security-native-fixture.sh index 83c503e6870..6c242e78336 100644 --- a/scripts/ci/security-native-fixture.sh +++ b/scripts/ci/security-native-fixture.sh @@ -106,3 +106,19 @@ bash scripts/ci-cancel-aware.sh cargo test --manifest-path Cargo.toml -p openhum --features "$core_features,security-module" \ native_fixture_denies_an_approval_when_the_audit_write_fails \ -- --ignored --exact --nocapture + +# TinySecurity keeps the secret scope it was admitted with for the process. An +# embedded runtime built after an earlier one was released takes the module +# over; another scope is refused while the admitting runtime is live. +# The facade's default features on purpose: they reach TinySecurity through +# the core's defaults without naming the facade's own `security-module`. +bash scripts/ci-cancel-aware.sh cargo test --manifest-path Cargo.toml -p openhuman-embed \ + --test security_second_runtime \ + a_runtime_built_after_another_is_released_still_screens_its_prompts \ + -- --ignored --exact --nocapture + +bash scripts/ci-cancel-aware.sh cargo test --manifest-path Cargo.toml -p openhuman-embed \ + --test security_live_scope --no-default-features \ + --features "$core_features,security-module" \ + a_different_secret_scope_is_refused_while_the_admitting_runtime_is_live \ + -- --ignored --exact --nocapture