From f313cf2d405cad43e27cc862ebe67ae429c285f3 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 4 Nov 2026 08:35:43 +0000 Subject: [PATCH 01/21] test(embed): register security_second_runtime integration test Add a Cargo test target for a new integration test that exercises a second embedded runtime reaching the TinySecurity module admitted by a released first one. The target requires the security-module feature and is ignored by default since it needs the module's release. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-embed/Cargo.toml | 6 ++ .../tests/security_second_runtime.rs | 70 +++++++++++++++++++ 2 files changed, 76 insertions(+) create mode 100644 crates/openhuman-embed/tests/security_second_runtime.rs diff --git a/crates/openhuman-embed/Cargo.toml b/crates/openhuman-embed/Cargo.toml index 7c19223192a..8ff77d2bed3 100644 --- a/crates/openhuman-embed/Cargo.toml +++ b/crates/openhuman-embed/Cargo.toml @@ -201,3 +201,9 @@ required-features = ["profiles"] [[test]] name = "mcp_module" required-features = ["mcp", "modules", "skills", "storage-sqlite"] + +# A second embedded runtime reaches the TinySecurity module admitted by a +# released first one. Ignored by default: it needs the module's release. +[[test]] +name = "security_second_runtime" +required-features = ["security-module"] 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..dac8a675cad --- /dev/null +++ b/crates/openhuman-embed/tests/security_second_runtime.rs @@ -0,0 +1,70 @@ +//! 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: its prompts are screened and pass, rather than being held for +//! security review because the module "belongs" to a runtime that is gone. +//! +//! 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 common::{chat_requests, offline_config, provider, runtime, stub_backend}; +use openhuman_embed::{AgentSpec, Provider, Runtime, Workspace}; + +/// A plain request the prompt screen lets through. +const BENIGN: &str = "What is the capital of France?"; + +/// Build a runtime with the prompt screen enforced, send one benign turn and +/// release the runtime. Returns the turn's reply, or the error it failed with. +async fn screened_turn(name: &str) -> Result { + let backend = stub_backend().await; + let model = provider("Paris").await; + let runtime = Runtime::builder() + .config(offline_config()) + .workspace(Workspace::Ephemeral) + .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( + Provider::openai_compatible(format!("{}/v1", model.uri()), "fixture") + .model("fixture"), + ), + ) + .map_err(|error| format!("{name} agent: {error}"))?; + let outcome = agent.turn(BENIGN).send().await; + let requests = chat_requests(&model).await.len(); + runtime.remove_agent(name).await.expect("remove agent"); + drop(agent); + drop(runtime); + let outcome = outcome.map_err(|error| format!("{name} turn: {error:?}"))?; + if requests != 1 { + return Err(format!( + "{name} turn never reached the model ({requests} requests): {}", + outcome.reply + )); + } + Ok(outcome.reply) +} + +#[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 { + assert_eq!(screened_turn("first").await.as_deref(), Ok("Paris")); + assert_eq!(screened_turn("second").await.as_deref(), Ok("Paris")); + }) + .await + .expect("test task"); + }); +} From d8137186d82e328e7fe133bb77ccddb023a5ba44 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 4 Nov 2026 08:40:00 +0000 Subject: [PATCH 02/21] test(embed): add diagnostics to second runtime screening test The test now loops over both runtime names and prints each outcome before asserting, so a failure reports which runtime misbehaved instead of only the assertion mismatch. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-embed/tests/security_second_runtime.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/openhuman-embed/tests/security_second_runtime.rs b/crates/openhuman-embed/tests/security_second_runtime.rs index dac8a675cad..d970dd8a2ec 100644 --- a/crates/openhuman-embed/tests/security_second_runtime.rs +++ b/crates/openhuman-embed/tests/security_second_runtime.rs @@ -61,8 +61,11 @@ async fn screened_turn(name: &str) -> Result { fn a_runtime_built_after_another_is_released_still_screens_its_prompts() { runtime().block_on(async { tokio::spawn(async { - assert_eq!(screened_turn("first").await.as_deref(), Ok("Paris")); - assert_eq!(screened_turn("second").await.as_deref(), Ok("Paris")); + for name in ["first", "second"] { + let outcome = screened_turn(name).await; + eprintln!("{name} runtime: {outcome:?}"); + assert_eq!(outcome.as_deref(), Ok("Paris"), "{name} runtime"); + } }) .await .expect("test task"); From e51c35280990a5fdacaac6dc9620b1c1b8a7e02f Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 4 Nov 2026 08:40:19 +0000 Subject: [PATCH 03/21] test(embed): add temporary logger init to second runtime security test Adds a temporary env_logger initialization to the ignored second-runtime security test so its output can be inspected when run against the TinySecurity fixture. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-embed/tests/security_second_runtime.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/openhuman-embed/tests/security_second_runtime.rs b/crates/openhuman-embed/tests/security_second_runtime.rs index d970dd8a2ec..347d8cd4c65 100644 --- a/crates/openhuman-embed/tests/security_second_runtime.rs +++ b/crates/openhuman-embed/tests/security_second_runtime.rs @@ -59,6 +59,7 @@ async fn screened_turn(name: &str) -> Result { #[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() { + let _ = env_logger::builder().is_test(true).try_init(); // TEMPDEBUG runtime().block_on(async { tokio::spawn(async { for name in ["first", "second"] { From 0af6ab4c6c227e5d0855d8c3700b95bfbc46babb Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 4 Nov 2026 08:40:35 +0000 Subject: [PATCH 04/21] test(security): add tracing subscriber init to second runtime test Initialise a tracing subscriber in the second-runtime screening test so its logs are captured during the ignored fixture run. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-embed/tests/security_second_runtime.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/openhuman-embed/tests/security_second_runtime.rs b/crates/openhuman-embed/tests/security_second_runtime.rs index 347d8cd4c65..d8e774482af 100644 --- a/crates/openhuman-embed/tests/security_second_runtime.rs +++ b/crates/openhuman-embed/tests/security_second_runtime.rs @@ -60,6 +60,7 @@ async fn screened_turn(name: &str) -> Result { #[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() { let _ = env_logger::builder().is_test(true).try_init(); // TEMPDEBUG + let _ = tracing_subscriber::fmt().with_env_filter(tracing_subscriber::EnvFilter::from_default_env()).try_init(); // TEMPDEBUG runtime().block_on(async { tokio::spawn(async { for name in ["first", "second"] { From de134f9ad8fcd5933b9b1252af6abfdaeca95bcc Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 4 Nov 2026 08:40:57 +0000 Subject: [PATCH 05/21] test(embed): use stateless workspace with in-memory session store The second-runtime security test now builds its runtime on a stateless workspace backed by an in-memory session store instead of an ephemeral workspace, so the test exercises the session-store path without touching persistent state. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-embed/tests/security_second_runtime.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/openhuman-embed/tests/security_second_runtime.rs b/crates/openhuman-embed/tests/security_second_runtime.rs index d8e774482af..c11133e667d 100644 --- a/crates/openhuman-embed/tests/security_second_runtime.rs +++ b/crates/openhuman-embed/tests/security_second_runtime.rs @@ -12,7 +12,10 @@ mod common; use common::{chat_requests, offline_config, provider, runtime, stub_backend}; +use std::sync::Arc; + use openhuman_embed::{AgentSpec, Provider, Runtime, Workspace}; +use tinyagents_session::testkit::InMemorySessionStores; /// A plain request the prompt screen lets through. const BENIGN: &str = "What is the capital of France?"; @@ -24,7 +27,8 @@ async fn screened_turn(name: &str) -> Result { let model = provider("Paris").await; let runtime = Runtime::builder() .config(offline_config()) - .workspace(Workspace::Ephemeral) + .workspace(Workspace::Stateless) + .session_store(Arc::new(InMemorySessionStores::new())) .backend_url(backend.uri()) .build() .await From 46ad028d5e00d991701fedd862543959ebe093c4 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 4 Nov 2026 08:41:07 +0000 Subject: [PATCH 06/21] test(security): update InMemorySessionStores import path Point the second-runtime security test at the session stores type's new home in the port module, keeping the test compiling after the type moved out of testkit. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-embed/tests/security_second_runtime.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/openhuman-embed/tests/security_second_runtime.rs b/crates/openhuman-embed/tests/security_second_runtime.rs index c11133e667d..d57295ebe33 100644 --- a/crates/openhuman-embed/tests/security_second_runtime.rs +++ b/crates/openhuman-embed/tests/security_second_runtime.rs @@ -15,7 +15,7 @@ use common::{chat_requests, offline_config, provider, runtime, stub_backend}; use std::sync::Arc; use openhuman_embed::{AgentSpec, Provider, Runtime, Workspace}; -use tinyagents_session::testkit::InMemorySessionStores; +use tinyagents_session::port::InMemorySessionStores; /// A plain request the prompt screen lets through. const BENIGN: &str = "What is the capital of France?"; From a7a88824772aeb8706f6294d05665d87924461f0 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 4 Nov 2026 08:41:58 +0000 Subject: [PATCH 07/21] feat(security): allow secret scope takeover after owner release Admitted modules now track which secret scope currently owns them, so a different scope is still refused while the original owner is live but can take the module over once that owner has been released. This lets a host reuse a loaded module after its scope is dropped instead of failing every later call. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/modules/security/host_callbacks.rs | 80 ++++++++++++++++++- 1 file changed, 77 insertions(+), 3 deletions(-) diff --git a/crates/openhuman-core/src/modules/security/host_callbacks.rs b/crates/openhuman-core/src/modules/security/host_callbacks.rs index 3b7c234b6ae..0b5a178fb41 100644 --- a/crates/openhuman-core/src/modules/security/host_callbacks.rs +++ b/crates/openhuman-core/src/modules/security/host_callbacks.rs @@ -25,6 +25,70 @@ type SecurityCallbackLoads = static SECURITY_CALLBACK_LOADS: std::sync::LazyLock = std::sync::LazyLock::new(|| tokio::sync::Mutex::new(std::collections::HashMap::new())); +/// The secret scope (its `.secret_key` path) currently using each admitted +/// module, or no entry once that scope's owner has been released. +/// +/// 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, and may take the module over only after +/// [`release_scope_owner`] says the current one is gone. +/// +/// A plain mutex, not the async one guarding [`SECURITY_CALLBACK_LOADS`], so a +/// host can release its scope from a synchronous `Drop`. +static SECURITY_SCOPE_OWNERS: std::sync::LazyLock< + std::sync::Mutex>, +> = std::sync::LazyLock::new(Default::default); + +/// Whether the secret scope at `requested` may use a module whose current +/// owner is `owner` (`None`: released). A released module is taken over by +/// the requesting scope. +fn claim_scope(owner: Option<&Path>, requested: &Path) -> Result { + match owner { + Some(owner) if owner == requested => Ok(ScopeClaim::Held), + Some(_) => Err("security secret scope changed after module admission".into()), + None => Ok(ScopeClaim::TakenOver), + } +} + +/// 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, +} + +fn scope_owner(id: &str) -> Option { + SECURITY_SCOPE_OWNERS + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .get(id) + .cloned() +} + +fn set_scope_owner(id: &str, key_path: PathBuf) { + SECURITY_SCOPE_OWNERS + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .insert(id.to_owned(), key_path); +} + +/// Mark the scope using module `id` as released. See +/// [`super::release_secret_scope`]. +pub(in crate::modules) fn release_scope_owner(id: &str) { + let released = SECURITY_SCOPE_OWNERS + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .remove(id) + .is_some(); + if released { + log::debug!("[security] secret scope owner released module={id}"); + } +} + impl SecurityCallbackState { fn module_config(&self, config: &Config) -> Result { let trusted_host = self.binding.unique_name().to_string(); @@ -190,15 +254,20 @@ pub(in crate::modules) async fn ensure_loaded( .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 claim = claim_scope(scope_owner(id).as_deref(), &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?; + if claim == ScopeClaim::TakenOver { + // The loads lock is held, so no other caller claims it meanwhile. + log::info!( + "[security] secret scope taken over after its owner was released module={id}" + ); + set_scope_owner(id, key_path); + } return Ok(()); } @@ -323,6 +392,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)); + set_scope_owner(id, state.key_path.clone()); register_scope(config, &state).await?; Ok(()) @@ -362,3 +432,7 @@ async fn register_scope(config: &Config, state: &SecurityCallbackState) -> Resul } Ok(()) } + +#[cfg(test)] +#[path = "host_callbacks_tests.rs"] +mod tests; From 621de5eff443d7927b8ec82fedc227abb0b1adf0 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 4 Nov 2026 08:42:12 +0000 Subject: [PATCH 08/21] feat(security): add release_secret_scope for host core handover Add a public function that releases the secret scope held by the admitted TinySecurity module so a host that drops its core and builds a new one in the same process can hand the module over instead of having every security call refused. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../modules/security/host_callbacks_tests.rs | 52 +++++++++++++++++++ .../src/modules/security/mod.rs | 16 ++++++ 2 files changed, 68 insertions(+) create mode 100644 crates/openhuman-core/src/modules/security/host_callbacks_tests.rs 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..4eec3f3a695 --- /dev/null +++ b/crates/openhuman-core/src/modules/security/host_callbacks_tests.rs @@ -0,0 +1,52 @@ +//! Which secret scope may use the admitted TinySecurity module. + +use super::*; + +#[test] +fn the_admitting_scope_keeps_its_module() { + let path = Path::new("/home/a/.openhuman/.secret_key"); + assert_eq!(claim_scope(Some(path), path), Ok(ScopeClaim::Held)); +} + +#[test] +fn a_different_scope_is_refused_while_the_owner_is_live() { + let owner = Path::new("/home/a/.openhuman/.secret_key"); + let other = Path::new("/home/b/.openhuman/.secret_key"); + assert_eq!( + claim_scope(Some(owner), other), + Err("security secret scope changed after module admission".to_owned()) + ); +} + +#[test] +fn a_scope_takes_over_a_module_whose_owner_was_released() { + let other = Path::new("/tmp/openhuman-scratch-second/.secret_key"); + assert_eq!(claim_scope(None, other), Ok(ScopeClaim::TakenOver)); +} + +#[test] +fn releasing_the_owner_lets_the_next_scope_claim_and_then_hold_the_module() { + let id = "tinysecurity-claim-test"; + let first = PathBuf::from("/tmp/openhuman-scratch-first/.secret_key"); + let second = PathBuf::from("/tmp/openhuman-scratch-second/.secret_key"); + set_scope_owner(id, first.clone()); + assert!(claim_scope(scope_owner(id).as_deref(), &second).is_err()); + + release_scope_owner(id); + assert_eq!(scope_owner(id), None); + assert_eq!( + claim_scope(scope_owner(id).as_deref(), &second), + Ok(ScopeClaim::TakenOver) + ); + set_scope_owner(id, second.clone()); + + assert_eq!( + claim_scope(scope_owner(id).as_deref(), &second), + Ok(ScopeClaim::Held) + ); + assert!( + claim_scope(scope_owner(id).as_deref(), &first).is_err(), + "the released scope cannot return while the new owner is live" + ); + release_scope_owner(id); +} diff --git a/crates/openhuman-core/src/modules/security/mod.rs b/crates/openhuman-core/src/modules/security/mod.rs index e49e174e336..4370e351dab 100644 --- a/crates/openhuman-core/src/modules/security/mod.rs +++ b/crates/openhuman-core/src/modules/security/mod.rs @@ -591,6 +591,22 @@ pub(crate) async fn validate_host_path( Err("TinySecurity is not built into this host".into()) } +/// Release the secret scope using the admitted TinySecurity module, for a host +/// whose core is gone. +/// +/// TinySecurity keeps the secret scope it was admitted with (the approval +/// subject, audit stream and master-key registration derived from the admitting +/// config) for as long as the module is loaded, which is the life of the +/// process. A later core whose config derives a different scope is refused the +/// module while the admitting core is live, 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: the next core then takes +/// the admitted module over instead of being refused every security call. +pub fn release_secret_scope() { + host_callbacks::release_scope_owner(MODULE_ID); +} + /// 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. From 9b993160bedd9a63a81c2e57aa68735365c47e94 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 4 Nov 2026 08:42:23 +0000 Subject: [PATCH 09/21] fix(embed): release security secret scope when runtime slot is freed Runtime teardown now goes through a shared release_process_slot helper that also drops the secret scope the security module was admitted with, so a subsequent runtime built in its own directory can take the module over instead of having every security call refused. The build-time slot claim uses the same helper so both paths release consistently. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-embed/src/runtime/build.rs | 2 +- crates/openhuman-embed/src/runtime/mod.rs | 15 ++++++++++++++- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/crates/openhuman-embed/src/runtime/build.rs b/crates/openhuman-embed/src/runtime/build.rs index 5de0ef82c69..dc215ac909e 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"); } } diff --git a/crates/openhuman-embed/src/runtime/mod.rs b/crates/openhuman-embed/src/runtime/mod.rs index 71a0d2d03c4..7f36b2bdb96 100644 --- a/crates/openhuman-embed/src/runtime/mod.rs +++ b/crates/openhuman-embed/src/runtime/mod.rs @@ -111,6 +111,19 @@ 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 directory, takes the module over instead of being refused every +/// security call. +pub(crate) fn release_process_slot() { + #[cfg(feature = "security-module")] + openhuman_core::modules::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 +276,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"); } } From 98be9be259e055f392f32cd041d63b82e05d02e8 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 4 Nov 2026 08:43:53 +0000 Subject: [PATCH 10/21] test(security): remove temporary debug logging from second runtime test Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-embed/tests/security_second_runtime.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/crates/openhuman-embed/tests/security_second_runtime.rs b/crates/openhuman-embed/tests/security_second_runtime.rs index d57295ebe33..d7957f661a8 100644 --- a/crates/openhuman-embed/tests/security_second_runtime.rs +++ b/crates/openhuman-embed/tests/security_second_runtime.rs @@ -63,8 +63,6 @@ async fn screened_turn(name: &str) -> Result { #[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() { - let _ = env_logger::builder().is_test(true).try_init(); // TEMPDEBUG - let _ = tracing_subscriber::fmt().with_env_filter(tracing_subscriber::EnvFilter::from_default_env()).try_init(); // TEMPDEBUG runtime().block_on(async { tokio::spawn(async { for name in ["first", "second"] { From 429bf4d15855d06542ecb3e1ea5e40a56fb718bf Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 4 Nov 2026 08:44:24 +0000 Subject: [PATCH 11/21] test(embed): register security_live_scope integration test target Adds a Cargo test target for the new security_live_scope integration test, gated behind the security-module feature. The test is ignored by default since it requires the module's release build. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-embed/Cargo.toml | 6 ++ .../tests/security_live_scope.rs | 75 +++++++++++++++++++ 2 files changed, 81 insertions(+) create mode 100644 crates/openhuman-embed/tests/security_live_scope.rs diff --git a/crates/openhuman-embed/Cargo.toml b/crates/openhuman-embed/Cargo.toml index 8ff77d2bed3..f0409c9d929 100644 --- a/crates/openhuman-embed/Cargo.toml +++ b/crates/openhuman-embed/Cargo.toml @@ -207,3 +207,9 @@ required-features = ["mcp", "modules", "skills", "storage-sqlite"] [[test]] name = "security_second_runtime" required-features = ["security-module"] + +# While the runtime that admitted TinySecurity is live, another secret scope is +# refused the module. Ignored by default: it needs the module's release. +[[test]] +name = "security_live_scope" +required-features = ["security-module"] 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"); + }); +} From 4ff7a0ec9d9a7e3ea5629cc02675dcb057e1402c Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 4 Nov 2026 08:44:44 +0000 Subject: [PATCH 12/21] ci(security-native): run embed runtime security tests in native workflow The native security workflow now triggers on the embed runtime sources and its two security test files, and the fixture script runs the new second-runtime and live-scope tests. The runtime README documents that releasing the process slot also releases the TinySecurity secret scope so a later runtime can take the module over. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .github/workflows/security-native.yml | 3 +++ crates/openhuman-embed/src/runtime/README.md | 5 ++++- scripts/ci/security-native-fixture.sh | 15 +++++++++++++++ 3 files changed, 22 insertions(+), 1 deletion(-) 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-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/scripts/ci/security-native-fixture.sh b/scripts/ci/security-native-fixture.sh index 83c503e6870..1aa4bcd5245 100644 --- a/scripts/ci/security-native-fixture.sh +++ b/scripts/ci/security-native-fixture.sh @@ -106,3 +106,18 @@ 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. +bash scripts/ci-cancel-aware.sh cargo test --manifest-path Cargo.toml -p openhuman-embed \ + --test security_second_runtime --no-default-features \ + --features "$core_features,security-module" \ + 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 From f0c5217f17891a7ce547b146d12fc4676f488134 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 4 Nov 2026 08:51:34 +0000 Subject: [PATCH 13/21] test(embed): reformat agent spec construction in security test Reformatted the provider setup in the second-runtime security test to a more compact layout without changing any behaviour. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-embed/tests/security_second_runtime.rs | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/crates/openhuman-embed/tests/security_second_runtime.rs b/crates/openhuman-embed/tests/security_second_runtime.rs index d7957f661a8..75dd42555a0 100644 --- a/crates/openhuman-embed/tests/security_second_runtime.rs +++ b/crates/openhuman-embed/tests/security_second_runtime.rs @@ -38,12 +38,9 @@ async fn screened_turn(name: &str) -> Result { "{name} runtime enforces security" ); let agent = runtime - .agent( - AgentSpec::new(name).provider( - Provider::openai_compatible(format!("{}/v1", model.uri()), "fixture") - .model("fixture"), - ), - ) + .agent(AgentSpec::new(name).provider( + Provider::openai_compatible(format!("{}/v1", model.uri()), "fixture").model("fixture"), + )) .map_err(|error| format!("{name} agent: {error}"))?; let outcome = agent.turn(BENIGN).send().await; let requests = chat_requests(&model).await.len(); From 4e4a6c576b11f3bd39c4398d4a0ffb11c171953f Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 4 Nov 2026 09:04:59 +0000 Subject: [PATCH 14/21] fix(security): prevent stale scope ownership after release Module loads now capture the release epoch before being scheduled and only publish their scope as owner if no release happened in between, so a detached load finishing after its runtime was dropped can no longer claim ownership. Released modules may only be taken over by the admitting scope or a scope declared transient, keeping durable scopes from encrypting state under another scope's master key. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-core/src/modules/ops.rs | 6 +- .../src/modules/security/host_callbacks.rs | 145 ++++++++++++------ .../src/modules/security/mod.rs | 16 -- 3 files changed, 101 insertions(+), 66 deletions(-) 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 0b5a178fb41..ea1d01c96bc 100644 --- a/crates/openhuman-core/src/modules/security/host_callbacks.rs +++ b/crates/openhuman-core/src/modules/security/host_callbacks.rs @@ -25,31 +25,38 @@ type SecurityCallbackLoads = static SECURITY_CALLBACK_LOADS: std::sync::LazyLock = std::sync::LazyLock::new(|| tokio::sync::Mutex::new(std::collections::HashMap::new())); -/// The secret scope (its `.secret_key` path) currently using each admitted -/// module, or no entry once that scope's owner has been released. +/// 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, and may take the module over only after -/// [`release_scope_owner`] says the current one is gone. +/// 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`. -static SECURITY_SCOPE_OWNERS: std::sync::LazyLock< - std::sync::Mutex>, -> = std::sync::LazyLock::new(Default::default); - -/// Whether the secret scope at `requested` may use a module whose current -/// owner is `owner` (`None`: released). A released module is taken over by -/// the requesting scope. -fn claim_scope(owner: Option<&Path>, requested: &Path) -> Result { - match owner { - Some(owner) if owner == requested => Ok(ScopeClaim::Held), - Some(_) => Err("security secret scope changed after module admission".into()), - None => Ok(ScopeClaim::TakenOver), - } +#[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. @@ -61,32 +68,73 @@ enum ScopeClaim { TakenOver, } -fn scope_owner(id: &str) -> Option { - SECURITY_SCOPE_OWNERS - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .get(id) - .cloned() +/// 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()), + } } -fn set_scope_owner(id: &str, key_path: PathBuf) { - SECURITY_SCOPE_OWNERS - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .insert(id.to_owned(), key_path); +/// The current release epoch, captured before a load is scheduled. +pub(in crate::modules) fn scope_epoch() -> u64 { + ownership().epoch } -/// Mark the scope using module `id` as released. See -/// [`super::release_secret_scope`]. -pub(in crate::modules) fn release_scope_owner(id: &str) { - let released = SECURITY_SCOPE_OWNERS - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .remove(id) - .is_some(); - if released { - log::debug!("[security] secret scope owner released module={id}"); +/// 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 { @@ -242,31 +290,30 @@ 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"); - let claim = claim_scope(scope_owner(id).as_deref(), &key_path)?; + 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?; - if claim == ScopeClaim::TakenOver { - // The loads lock is held, so no other caller claims it meanwhile. + // 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}" ); - set_scope_owner(id, key_path); } return Ok(()); } @@ -276,7 +323,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 { @@ -392,7 +439,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)); - set_scope_owner(id, state.key_path.clone()); + publish_owner(id, state.key_path.clone(), epoch); register_scope(config, &state).await?; Ok(()) diff --git a/crates/openhuman-core/src/modules/security/mod.rs b/crates/openhuman-core/src/modules/security/mod.rs index 4370e351dab..e49e174e336 100644 --- a/crates/openhuman-core/src/modules/security/mod.rs +++ b/crates/openhuman-core/src/modules/security/mod.rs @@ -591,22 +591,6 @@ pub(crate) async fn validate_host_path( Err("TinySecurity is not built into this host".into()) } -/// Release the secret scope using the admitted TinySecurity module, for a host -/// whose core is gone. -/// -/// TinySecurity keeps the secret scope it was admitted with (the approval -/// subject, audit stream and master-key registration derived from the admitting -/// config) for as long as the module is loaded, which is the life of the -/// process. A later core whose config derives a different scope is refused the -/// module while the admitting core is live, 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: the next core then takes -/// the admitted module over instead of being refused every security call. -pub fn release_secret_scope() { - host_callbacks::release_scope_owner(MODULE_ID); -} - /// 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. From 82ddefb2bf14415ab24e8185a80c1bbcb3c0b958 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 4 Nov 2026 09:05:17 +0000 Subject: [PATCH 15/21] fix(security): allow a new core to take over the admitted module Replace the one-shot config cell in the TinySecurity text adapter with a replaceable one so a later runtime can re-arm the module with its own scope instead of being stuck with the first config. Add public helpers to release the admitted secret scope and to declare a transient scope, letting an embedder that drops its core and builds a new one in the same process hand the module over without exposing secrets encrypted under another scope's master key. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/modules/security/mod.rs | 10 ++++++ .../src/modules/security/text.rs | 35 +++++++++++-------- crates/openhuman-core/src/security/mod.rs | 35 +++++++++++++++++++ 3 files changed, 65 insertions(+), 15 deletions(-) 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(); +} From 221c0e89f73cd21627143dfd72b207a9a58533c8 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 4 Nov 2026 09:06:04 +0000 Subject: [PATCH 16/21] refactor(security): thread transient flag through scope claim checks The scope claim logic now takes the admitting scope and a transient flag so a durable scope is refused a module whose owner was released while a transient one may take it over. Tests were reworked around a shared admitted path and a single lifecycle test to cover release, declaration, and stale-epoch publishing. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/modules/security/host_callbacks.rs | 11 ++- .../modules/security/host_callbacks_tests.rs | 93 +++++++++++++------ 2 files changed, 71 insertions(+), 33 deletions(-) diff --git a/crates/openhuman-core/src/modules/security/host_callbacks.rs b/crates/openhuman-core/src/modules/security/host_callbacks.rs index ea1d01c96bc..bcd2bf196ca 100644 --- a/crates/openhuman-core/src/modules/security/host_callbacks.rs +++ b/crates/openhuman-core/src/modules/security/host_callbacks.rs @@ -122,9 +122,7 @@ fn secret_key_path(config_dir: &Path) -> PathBuf { /// 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)); + ownership().transient.insert(secret_key_path(config_dir)); } /// Release every module's live owner and forget the declared transient @@ -301,7 +299,12 @@ pub(in crate::modules) async fn ensure_loaded( ) -> Result<(), String> { let mut loads = SECURITY_CALLBACK_LOADS.lock().await; if let Some(state) = loads.get(id) { - let key_path = secret_key_path(config.config_path.parent().unwrap_or_else(|| Path::new("."))); + 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 diff --git a/crates/openhuman-core/src/modules/security/host_callbacks_tests.rs b/crates/openhuman-core/src/modules/security/host_callbacks_tests.rs index 4eec3f3a695..ddd3882a9f4 100644 --- a/crates/openhuman-core/src/modules/security/host_callbacks_tests.rs +++ b/crates/openhuman-core/src/modules/security/host_callbacks_tests.rs @@ -2,51 +2,86 @@ use super::*; -#[test] -fn the_admitting_scope_keeps_its_module() { - let path = Path::new("/home/a/.openhuman/.secret_key"); - assert_eq!(claim_scope(Some(path), path), Ok(ScopeClaim::Held)); +const CHANGED: &str = "security secret scope changed after module admission"; + +fn admitted() -> &'static Path { + Path::new("/tmp/openhuman-scratch-first/.secret_key") } #[test] -fn a_different_scope_is_refused_while_the_owner_is_live() { - let owner = Path::new("/home/a/.openhuman/.secret_key"); - let other = Path::new("/home/b/.openhuman/.secret_key"); +fn the_owning_scope_keeps_its_module() { assert_eq!( - claim_scope(Some(owner), other), - Err("security secret scope changed after module admission".to_owned()) + claim_scope(Some(admitted()), admitted(), admitted(), false), + Ok(ScopeClaim::Held) ); } #[test] -fn a_scope_takes_over_a_module_whose_owner_was_released() { +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(None, other), Ok(ScopeClaim::TakenOver)); + 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 releasing_the_owner_lets_the_next_scope_claim_and_then_hold_the_module() { - let id = "tinysecurity-claim-test"; - let first = PathBuf::from("/tmp/openhuman-scratch-first/.secret_key"); - let second = PathBuf::from("/tmp/openhuman-scratch-second/.secret_key"); - set_scope_owner(id, first.clone()); - assert!(claim_scope(scope_owner(id).as_deref(), &second).is_err()); - - release_scope_owner(id); - assert_eq!(scope_owner(id), None); +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(scope_owner(id).as_deref(), &second), + claim_scope(None, admitted(), other, true), Ok(ScopeClaim::TakenOver) ); - set_scope_owner(id, second.clone()); +} +#[test] +fn the_admitting_scope_takes_its_module_back_after_a_release() { assert_eq!( - claim_scope(scope_owner(id).as_deref(), &second), - Ok(ScopeClaim::Held) - ); - assert!( - claim_scope(scope_owner(id).as_deref(), &first).is_err(), - "the released scope cannot return while the new owner is live" + claim_scope(None, admitted(), admitted(), false), + Ok(ScopeClaim::TakenOver) ); - release_scope_owner(id); +} + +#[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(); } From d3160b57336f21a68c28a91abc5d0a205b48c3d6 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 4 Nov 2026 09:06:33 +0000 Subject: [PATCH 17/21] fix(embed): declare transient secret scope for scratch runtimes Scratch-directory runtimes now declare their config directory as a transient secret scope so they can take over the TinySecurity module left admitted by a released runtime, while durable directories are excluded to avoid keeping secrets under another scope's master key. The release path also calls the core's release unconditionally, since the core builds TinySecurity in by default regardless of this crate's feature flag. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-embed/src/runtime/build.rs | 10 ++++++++++ crates/openhuman-embed/src/runtime/mod.rs | 9 +++++---- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/crates/openhuman-embed/src/runtime/build.rs b/crates/openhuman-embed/src/runtime/build.rs index dc215ac909e..b92fbd6e571 100644 --- a/crates/openhuman-embed/src/runtime/build.rs +++ b/crates/openhuman-embed/src/runtime/build.rs @@ -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 7f36b2bdb96..5620e3a2f47 100644 --- a/crates/openhuman-embed/src/runtime/mod.rs +++ b/crates/openhuman-embed/src/runtime/mod.rs @@ -116,11 +116,12 @@ pub(crate) static RUNTIME_LIVE: AtomicBool = AtomicBool::new(false); /// 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 directory, takes the module over instead of being refused every -/// security call. +/// 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() { - #[cfg(feature = "security-module")] - openhuman_core::modules::security::release_secret_scope(); + openhuman_core::security::release_secret_scope(); RUNTIME_LIVE.store(false, std::sync::atomic::Ordering::Release); } From 68031ec71ad6e589ad9305430b58cf9423dd73b4 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 4 Nov 2026 09:07:03 +0000 Subject: [PATCH 18/21] test(security): cover tool results across successive runtimes The second-runtime security test now drives a host tool call as well as a plain prompt, so it checks that a runtime built after another is released still delivers its tool result to the model scrubbed rather than replaced by the redaction placeholder. The turn helper was reworked to script a lookup call and return what the model actually saw. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../tests/security_second_runtime.rs | 86 +++++++++++++++---- 1 file changed, 71 insertions(+), 15 deletions(-) diff --git a/crates/openhuman-embed/tests/security_second_runtime.rs b/crates/openhuman-embed/tests/security_second_runtime.rs index 75dd42555a0..59a9aa9e511 100644 --- a/crates/openhuman-embed/tests/security_second_runtime.rs +++ b/crates/openhuman-embed/tests/security_second_runtime.rs @@ -2,8 +2,13 @@ //! 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: its prompts are screened and pass, rather than being held for -//! security review because the module "belongs" to a runtime that is gone. +//! 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 @@ -11,20 +16,56 @@ mod common; -use common::{chat_requests, offline_config, provider, runtime, stub_backend}; use std::sync::Arc; -use openhuman_embed::{AgentSpec, Provider, Runtime, Workspace}; +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?"; -/// Build a runtime with the prompt screen enforced, send one benign turn and -/// release the runtime. Returns the turn's reply, or the error it failed with. +/// 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 = provider("Paris").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) @@ -38,23 +79,33 @@ async fn screened_turn(name: &str) -> Result { "{name} runtime enforces security" ); let agent = runtime - .agent(AgentSpec::new(name).provider( - Provider::openai_compatible(format!("{}/v1", model.uri()), "fixture").model("fixture"), - )) + .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.len(); + 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 != 1 { + if requests.len() < 2 { return Err(format!( - "{name} turn never reached the model ({requests} requests): {}", + "{name} turn never returned a tool result to the model ({} requests): {}", + requests.len(), outcome.reply )); } - Ok(outcome.reply) + Ok(tool_results(&requests[1])) } #[test] @@ -65,7 +116,12 @@ fn a_runtime_built_after_another_is_released_still_screens_its_prompts() { for name in ["first", "second"] { let outcome = screened_turn(name).await; eprintln!("{name} runtime: {outcome:?}"); - assert_eq!(outcome.as_deref(), Ok("Paris"), "{name} runtime"); + 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 From 256dc03f3be4a7bdc4b52387e5a0ebf2d31fe689 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 4 Nov 2026 09:07:12 +0000 Subject: [PATCH 19/21] chore(embed): drop test targets for removed security tests Remove the Cargo test target entries for security_second_runtime and security_live_scope, since those test files no longer exist and the targets would fail to build. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-embed/Cargo.toml | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/crates/openhuman-embed/Cargo.toml b/crates/openhuman-embed/Cargo.toml index f0409c9d929..7c19223192a 100644 --- a/crates/openhuman-embed/Cargo.toml +++ b/crates/openhuman-embed/Cargo.toml @@ -201,15 +201,3 @@ required-features = ["profiles"] [[test]] name = "mcp_module" required-features = ["mcp", "modules", "skills", "storage-sqlite"] - -# A second embedded runtime reaches the TinySecurity module admitted by a -# released first one. Ignored by default: it needs the module's release. -[[test]] -name = "security_second_runtime" -required-features = ["security-module"] - -# While the runtime that admitted TinySecurity is live, another secret scope is -# refused the module. Ignored by default: it needs the module's release. -[[test]] -name = "security_live_scope" -required-features = ["security-module"] From 0798b80d87ac57cc8c2d7dfa4e93a02a40511a0b Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 4 Nov 2026 09:07:24 +0000 Subject: [PATCH 20/21] test(embed): register security_live_scope test and simplify fixture features Adds a security_live_scope integration test target gated on the security-module feature, and drops the explicit feature selection from the native fixture script so the second-runtime test runs with the facade's default features instead. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-embed/Cargo.toml | 7 +++++++ scripts/ci/security-native-fixture.sh | 5 +++-- 2 files changed, 10 insertions(+), 2 deletions(-) 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/scripts/ci/security-native-fixture.sh b/scripts/ci/security-native-fixture.sh index 1aa4bcd5245..6c242e78336 100644 --- a/scripts/ci/security-native-fixture.sh +++ b/scripts/ci/security-native-fixture.sh @@ -110,9 +110,10 @@ bash scripts/ci-cancel-aware.sh cargo test --manifest-path Cargo.toml -p openhum # 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 --no-default-features \ - --features "$core_features,security-module" \ + --test security_second_runtime \ a_runtime_built_after_another_is_released_still_screens_its_prompts \ -- --ignored --exact --nocapture From af24aaa88fe54eed34c7a23bfec019644b2294d3 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 4 Nov 2026 09:10:42 +0000 Subject: [PATCH 21/21] test(embed): reformat second runtime security test Reformatted the test's tool-call setup and tool registration closure to satisfy rustfmt, with no change to the behaviour being exercised. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-embed/tests/security_second_runtime.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/crates/openhuman-embed/tests/security_second_runtime.rs b/crates/openhuman-embed/tests/security_second_runtime.rs index 59a9aa9e511..993cd8cd179 100644 --- a/crates/openhuman-embed/tests/security_second_runtime.rs +++ b/crates/openhuman-embed/tests/security_second_runtime.rs @@ -62,7 +62,10 @@ impl Tool for Lookup { async fn screened_turn(name: &str) -> Result { let backend = stub_backend().await; let model = scripted_provider( - vec![tool_call_completion("lookup", "{}"), chat_completion("Paris")], + vec![ + tool_call_completion("lookup", "{}"), + chat_completion("Paris"), + ], "Paris", ) .await; @@ -87,9 +90,7 @@ async fn screened_turn(name: &str) -> Result { .bare_prompt("Use lookup then answer") .tools(ToolScopeSpec::HostOnly), ) - .tools(|_| { - Box::pin(async { HostTurnTools::advertised(vec![Box::new(Lookup)]) }) - }), + .tools(|_| Box::pin(async { HostTurnTools::advertised(vec![Box::new(Lookup)]) })), ) .map_err(|error| format!("{name} agent: {error}"))?; let outcome = agent.turn(BENIGN).send().await;