diff --git a/.github/workflows/ci-lanes.yml b/.github/workflows/ci-lanes.yml index b70035a42d4..76a0706aad4 100644 --- a/.github/workflows/ci-lanes.yml +++ b/.github/workflows/ci-lanes.yml @@ -176,11 +176,10 @@ jobs: - name: Install jq and unzip for release-script tests # stage-modules.mjs unpacks module archives with unzip, which the - # image does not carry. + # image does not carry. The script falls back to another Ubuntu mirror + # when the runner cannot resolve archive.ubuntu.com. if: matrix.container != '' && needs.plan.outputs.scripts == 'true' - run: | - apt-get update - apt-get install -y --no-install-recommends jq python3-tomli unzip + run: bash scripts/ci/install-ci-packages.sh - name: Install bubblewrap for the sandbox jail # The image's bubblewrap 0.6.1 lacks --disable-userns, so TinyBox finds diff --git a/app/src/features/conversations/tools/__fixtures__/coreToolNames.json b/app/src/features/conversations/tools/__fixtures__/coreToolNames.json index 1aaf8200842..a0121314ca8 100644 --- a/app/src/features/conversations/tools/__fixtures__/coreToolNames.json +++ b/app/src/features/conversations/tools/__fixtures__/coreToolNames.json @@ -164,7 +164,9 @@ "update_check", "use_skill", "validate_workflow", + "wallet_balances", "wallet_chain_status", + "wallet_execute_prepared", "wallet_lookup_tx", "wallet_prepare_transfer", "wallet_status", diff --git a/crates/openhuman-app/Cargo.lock b/crates/openhuman-app/Cargo.lock index 3eed9fa6fd3..cb04bce083a 100644 --- a/crates/openhuman-app/Cargo.lock +++ b/crates/openhuman-app/Cargo.lock @@ -8254,7 +8254,7 @@ dependencies = [ [[package]] name = "tinysecurity-bus" -version = "0.20.0" +version = "0.21.0" dependencies = [ "serde", "thiserror 2.0.21", diff --git a/crates/openhuman-core/src/agent/session_host/runtime_adapter_trace_tests.rs b/crates/openhuman-core/src/agent/session_host/runtime_adapter_trace_tests.rs index c626fc53593..6d0a8952c27 100644 --- a/crates/openhuman-core/src/agent/session_host/runtime_adapter_trace_tests.rs +++ b/crates/openhuman-core/src/agent/session_host/runtime_adapter_trace_tests.rs @@ -124,8 +124,12 @@ async fn cancellation_during_required_output_repair_finalizes_native_run() { Arc::clone(&core), async move { host.run_single_with_origin(&input, Some(origin)).await }, )); + // A hang guard on the repair signal, not a speed budget: before the first + // model call the turn resolves TinyBox's local jail grants for each MCP + // sandbox seed (about 0.85 s each, three times, on an idle machine), so a + // loaded test process spent all of a 5 s bound before the model was asked. tokio::time::timeout( - std::time::Duration::from_secs(5), + std::time::Duration::from_secs(60), model.repair_started.notified(), ) .await diff --git a/crates/openhuman-core/src/artifacts/box_source.rs b/crates/openhuman-core/src/artifacts/box_source.rs index 240b2fcbbc4..a084e3e6557 100644 --- a/crates/openhuman-core/src/artifacts/box_source.rs +++ b/crates/openhuman-core/src/artifacts/box_source.rs @@ -51,23 +51,37 @@ pub(crate) trait BoxFiles: Send + Sync { /// The process's own boxes, for the call running under `ctx`. pub(crate) struct SandboxBoxFiles { - ctx: DispatchCtx, + /// Weak: `PerCallTool` also builds a prototype of the tool when the belt + /// is assembled, under the building request's context, and that prototype + /// lives as long as the belt. A cached chat session keeps its belt in its + /// tenant's own state slots, so a strong context would keep the tenant in + /// use (`CoreContext::tenant_in_use`) and its profile slot never frees. + core: Option>, } impl SandboxBoxFiles { pub(crate) fn new(ctx: DispatchCtx) -> Self { - Self { ctx } + Self { + core: ctx.downgrade(), + } + } + + /// The context the call runs under: the one this was built for while it + /// lives, else the calling task's own. + fn ctx(&self) -> DispatchCtx { + DispatchCtx::from_weak(self.core.as_ref()) } } #[async_trait] impl BoxFiles for SandboxBoxFiles { async fn work_folder(&self) -> Result, BoxError> { - let config = - self.ctx.load_config().await.map_err(|error| { - BoxError::Driver(format!("cannot read the configuration: {error}")) - })?; - Ok(crate::sandbox::ops::sandbox_box_workdir(&self.ctx, &config)) + let ctx = self.ctx(); + let config = ctx + .load_config() + .await + .map_err(|error| BoxError::Driver(format!("cannot read the configuration: {error}")))?; + Ok(crate::sandbox::ops::sandbox_box_workdir(&ctx, &config)) } async fn read( @@ -78,7 +92,7 @@ impl BoxFiles for SandboxBoxFiles { ) -> Result, BoxError> { let tenant = crate::sandbox::boxes::tenant_for_box(tenant)?; let config = - self.ctx.load_config().await.map_err(|error| { + self.ctx().load_config().await.map_err(|error| { BoxError::Driver(format!("cannot read the configuration: {error}")) })?; crate::sandbox::read_box_file(Ok(tenant), &config, path, max_bytes).await diff --git a/crates/openhuman-core/src/artifacts/tiny_store_tests.rs b/crates/openhuman-core/src/artifacts/tiny_store_tests.rs index 9973e303f18..bcdf5571716 100644 --- a/crates/openhuman-core/src/artifacts/tiny_store_tests.rs +++ b/crates/openhuman-core/src/artifacts/tiny_store_tests.rs @@ -661,3 +661,32 @@ fn share_artifact_is_offered_only_with_a_publisher() { let with = names(true); assert!(with.contains(&"share_artifact".to_string()), "{with:?}"); } + +/// A cached chat session keeps its tool belt in its tenant's own state +/// slots (`web_chat::ops::thread_sessions`), so an artifact tool that held +/// the context it was built under strongly would keep that tenant in use +/// (`CoreContext::tenant_in_use`) forever, and its SaaS profile slot would +/// never free. +#[tokio::test] +async fn artifact_tools_kept_past_their_turn_do_not_keep_the_tenant_in_use() { + use crate::core::runtime::{ContextOverlay, CoreContext, DomainSet}; + let root = CoreContext::for_test(DomainSet::full(), None); + let profile = root.derive_with( + ContextOverlay::new( + crate::config::Config::default(), + DomainSet::kernel(), + crate::tools::toolpacks::ToolGroups::none(), + ) + .profile("p1"), + ); + let (workspace, files) = temp_dirs(); + let tools = CoreContext::scope_with_turn_origin(std::sync::Arc::clone(&profile), None, async { + registered_tools(&workspace, FileRoots::new(&files), &workspace, None) + }) + .await; + assert!(tools.iter().any(|t| t.name() == "create_artifact")); + assert!( + !profile.tenant_in_use(), + "the kept artifact tools pin the tenant they were built under" + ); +} diff --git a/crates/openhuman-core/src/core/invoke.rs b/crates/openhuman-core/src/core/invoke.rs index 0d7d864adda..0ec68ba8920 100644 --- a/crates/openhuman-core/src/core/invoke.rs +++ b/crates/openhuman-core/src/core/invoke.rs @@ -13,6 +13,7 @@ use super::session_expiry::{is_session_expired_error, is_unconfirmed_unauthorize use crate::core::all; use crate::core::runtime::{CoreContext, DispatchCtx}; use crate::core::types::AppState; +use crate::core::StructuredRpcError; /// Invokes a JSON-RPC method by name. /// @@ -171,18 +172,16 @@ fn session_failure_outcome( current_token: Option<&str>, ) -> SessionFailureOutcome { if api_key { - return SessionFailureOutcome::Replace { - reason: "api_key_credential", - message: "Backend request failed while using an API-key credential".to_string(), - }; + return replace( + msg, + "api_key_credential", + "Backend request failed while using an API-key credential".to_string(), + ); } if let Some(message) = translate_local_session_error(msg, local) { // The RPC error is also observed by the renderer's auth classifier. // Keep the background hosted probe recoverable. - return SessionFailureOutcome::Replace { - reason: "local_offline_credential", - message, - }; + return replace(msg, "local_offline_credential", message); } if current_token.is_none() { // Nothing was stored or sendable (no session, no API key): this is a @@ -196,10 +195,61 @@ fn session_failure_outcome( } // Avoid returning an auth-expired marker that would let the renderer sign // out a token this request may not have used. - SessionFailureOutcome::Replace { - reason: "credential_provenance_unavailable", - message: "Backend request failed; credential provenance could not be verified".to_string(), - } + replace( + msg, + "credential_provenance_unavailable", + "Backend request failed; credential provenance could not be verified".to_string(), + ) +} + +/// A [`SessionFailureOutcome::Replace`] whose error says `message` and keeps +/// the original [`StructuredRpcError`] `data` unless it carries a sign-out +/// marker. Codes such as memory's `UNAUTHORIZED` drive specific UI and never +/// sign out, so dropping them would only cost the renderer its branch. +fn replace(original: &str, reason: &'static str, message: String) -> SessionFailureOutcome { + let kept = StructuredRpcError::decode(original).and_then(|envelope| { + let data = envelope + .data + .filter(|data| !carries_sign_out_marker(&data.to_string()))?; + Some((data, envelope.expected_user_state)) + }); + log::debug!( + "[invoke][session-failure] replacing auth-expired error reason={reason} structured_data={}", + if kept.is_some() { + "kept" + } else { + "dropped_or_absent" + } + ); + let message = match kept { + Some((data, expected_user_state)) => StructuredRpcError { + message, + data: Some(data), + expected_user_state, + } + .encode(), + None => message, + }; + SessionFailureOutcome::Replace { reason, message } +} + +/// Whether `text` holds anything that reads as "session expired, sign out": +/// [`is_session_expired_error`], or a marker the renderer's auth classifier +/// (`classifyRpcError` / `classifyAuthExpiredReason` in +/// `app/src/services/coreRpcClient.ts`) matches case-insensitively — +/// `Session expired`, `SESSION_EXPIRED`, `no backend session token`, +/// `session jwt required`. +fn carries_sign_out_marker(text: &str) -> bool { + let lower = text.to_ascii_lowercase(); + is_session_expired_error(text) + || [ + "session expired", + "session_expired", + "no backend session token", + "session jwt required", + ] + .iter() + .any(|marker| lower.contains(marker)) } fn request_session_failure_is_actionable( diff --git a/crates/openhuman-core/src/core/invoke_tests.rs b/crates/openhuman-core/src/core/invoke_tests.rs index c12e3901a68..6a8e6e31531 100644 --- a/crates/openhuman-core/src/core/invoke_tests.rs +++ b/crates/openhuman-core/src/core/invoke_tests.rs @@ -299,6 +299,104 @@ fn stored_credentials_keep_session_failure_rewrites() { ); } +/// A memory engine 401 as the memory controller encodes it: a structured +/// `UNAUTHORIZED` code the UI branches on, under a message the session-expiry +/// classifier matches. +fn structured_memory_unauthorized() -> String { + crate::core::StructuredRpcError { + message: "unauthorized: [UNAUTHORIZED] memory API memory/learn on api.tinyhumans.ai: \ + the session expired or the API key was rejected (HTTP 401 Unauthorized); \ + re-authenticate" + .to_string(), + data: Some(json!({ "kind": "UNAUTHORIZED", "code": "UNAUTHORIZED" })), + expected_user_state: true, + } + .encode() +} + +fn replaced_message(outcome: SessionFailureOutcome) -> String { + match outcome { + SessionFailureOutcome::Replace { message, .. } => message, + other => panic!("expected a replaced error, got {other:?}"), + } +} + +/// The rewrite drops the auth-expired message but keeps a structured code the +/// renderer does not read as sign-out, so `memoryErrorCode` still sees +/// `UNAUTHORIZED` instead of `data: null`. +#[test] +fn replaced_session_failure_keeps_non_signout_structured_code() { + let original = structured_memory_unauthorized(); + assert!(is_session_expired_error(&original)); + let cases = [ + ( + session_failure_outcome(&original, false, false, None, Some("header.payload.sig")), + "Backend request failed; credential provenance could not be verified", + ), + ( + session_failure_outcome(&original, false, true, None, None), + "Backend request failed while using an API-key credential", + ), + ( + session_failure_outcome(&original, true, false, None, Some("header.payload.local")), + crate::core::observability::BACKEND_UNAVAILABLE_PREFIX, + ), + ]; + for (outcome, expected_message) in cases { + let message = replaced_message(outcome); + assert!(!is_session_expired_error(&message), "{message}"); + let envelope = crate::core::StructuredRpcError::decode(&message) + .unwrap_or_else(|| panic!("structured envelope dropped: {message}")); + assert!( + envelope.message.starts_with(expected_message), + "{}", + envelope.message + ); + assert_eq!( + envelope.data, + Some(json!({ "kind": "UNAUTHORIZED", "code": "UNAUTHORIZED" })) + ); + assert!(envelope.expected_user_state); + } +} + +/// A structured error whose data itself carries a sign-out marker must not +/// reach the renderer through the rewrite, in any casing or field. +#[test] +fn replaced_session_failure_never_passes_through_a_signout_marker() { + for data in [ + json!({ "kind": "SESSION_EXPIRED", "code": "SESSION_EXPIRED" }), + json!({ "code": "session_expired" }), + json!({ "code": "ENGINE", "detail": "Session expired; sign in again" }), + json!({ "code": "ENGINE", "detail": "no backend session token" }), + json!({ "code": "ENGINE", "detail": "session JWT required" }), + ] { + let original = crate::core::StructuredRpcError { + message: "SESSION_EXPIRED: backend rejected session token".to_string(), + data: Some(data.clone()), + expected_user_state: false, + } + .encode(); + let message = replaced_message(session_failure_outcome( + &original, + false, + false, + None, + Some("header.payload.sig"), + )); + assert!(!is_session_expired_error(&message), "{message}"); + let lower = message.to_ascii_lowercase(); + assert!( + !lower.contains("session_expired") && !lower.contains("session expired"), + "{message}" + ); + assert!( + crate::core::StructuredRpcError::decode(&message).is_none_or(|e| e.data.is_none()), + "{data} leaked: {message}" + ); + } +} + /// #8081: a Memory tab on a plan without memory got `403 MEMORY_PLAN_REQUIRED` /// from the hosted engine, whose message said "the session expired", and the /// user was signed out. Neither that nor a plain memory 403 may publish diff --git a/crates/openhuman-core/src/core/runtime/context.rs b/crates/openhuman-core/src/core/runtime/context.rs index 50e415b9d5e..8067fa65003 100644 --- a/crates/openhuman-core/src/core/runtime/context.rs +++ b/crates/openhuman-core/src/core/runtime/context.rs @@ -113,6 +113,10 @@ pub struct CoreContext { extensions: crate::core::slots::Extensions, /// Explicit authority on this derived turn context. turn_origin: Option, + /// A library host's authorisation of its own runtime's secret master + /// grant, set only by [`CoreContext::scope_with_host_secret_grant`]; it + /// holds only on the host's own task while that scope runs. + host_secret_grant: Option>, /// Durable relay conversation carried by the immutable turn context. channel_thread: Option, /// The agent whose stores a host-installed session store @@ -301,6 +305,7 @@ impl CoreContext { user_skill_roots: overlay.user_skill_roots, extensions: self.extensions.clone(), turn_origin: self.turn_origin.clone(), + host_secret_grant: None, channel_thread: self.channel_thread.clone(), session_agent: overlay.session_agent.or_else(|| self.session_agent.clone()), profile: overlay.profile.or_else(|| self.profile.clone()), @@ -431,28 +436,36 @@ impl CoreContext { /// its own, scoped inside a turn that has one (an embedded agent's derived /// context replacing the caller's, say), keeps that turn's origin. Dropping /// it would turn a labelled turn into an unlabelled one the approval gate - /// refuses. + /// refuses. A host's secret grant survives it the same way. pub async fn scope(ctx: Arc, fut: F) -> F::Output { CURRENT_CONTEXT - .scope(Self::keeping_turn_origin(ctx), fut) + .scope(Self::keeping_turn_authority(ctx), fut) .await } /// [`scope`](Self::scope) for a synchronous closure. pub fn sync_scope(ctx: Arc, f: impl FnOnce() -> R) -> R { - CURRENT_CONTEXT.sync_scope(Self::keeping_turn_origin(ctx), f) + CURRENT_CONTEXT.sync_scope(Self::keeping_turn_authority(ctx), f) } - /// `ctx`, carrying the origin of the turn it is being scoped inside when it - /// has none of its own. - fn keeping_turn_origin(ctx: Arc) -> Arc { - if ctx.turn_origin.is_some() { + /// `ctx`, carrying the origin of the turn it is being scoped inside, and + /// that scope's host secret grant, where it has none of its own. + fn keeping_turn_authority(ctx: Arc) -> Arc { + let Some(outer) = Self::scoped_for_turn() else { + return ctx; + }; + let origin = outer + .turn_origin + .clone() + .filter(|_| ctx.turn_origin.is_none()); + let grant = outer + .host_secret_grant + .clone() + .filter(|_| ctx.host_secret_grant.is_none()); + if origin.is_none() && grant.is_none() { return ctx; } - match Self::scoped_for_turn().and_then(|outer| outer.turn_origin.clone()) { - Some(origin) => ctx.derive_channel_turn(None, Some(origin)), - None => ctx, - } + Arc::new(ctx.copy_with(None, origin, grant)) } /// Capture the current context now and carry it across a subsequently @@ -490,6 +503,9 @@ mod turn_origin_scope; #[path = "context_for_agent.rs"] mod for_agent_scope; +#[path = "context_host_grant.rs"] +mod host_grant_scope; + #[path = "context_agent.rs"] mod agent_parts; diff --git a/crates/openhuman-core/src/core/runtime/context_boot.rs b/crates/openhuman-core/src/core/runtime/context_boot.rs index 2e4f75a4854..5f2fe8139f9 100644 --- a/crates/openhuman-core/src/core/runtime/context_boot.rs +++ b/crates/openhuman-core/src/core/runtime/context_boot.rs @@ -231,6 +231,7 @@ impl CoreContext { user_skill_roots: true, extensions: Default::default(), turn_origin: None, + host_secret_grant: None, channel_thread: None, session_agent: None, profile: None, diff --git a/crates/openhuman-core/src/core/runtime/context_for_agent.rs b/crates/openhuman-core/src/core/runtime/context_for_agent.rs index 2230dd10122..637e6e3ee78 100644 --- a/crates/openhuman-core/src/core/runtime/context_for_agent.rs +++ b/crates/openhuman-core/src/core/runtime/context_for_agent.rs @@ -38,6 +38,7 @@ impl CoreContext { user_skill_roots: self.user_skill_roots, extensions: self.extensions.clone(), turn_origin: self.turn_origin.clone(), + host_secret_grant: self.host_secret_grant.clone(), channel_thread: self.channel_thread.clone(), session_agent: Some(agent.to_string()), profile: self.profile.clone(), diff --git a/crates/openhuman-core/src/core/runtime/context_host_grant.rs b/crates/openhuman-core/src/core/runtime/context_host_grant.rs new file mode 100644 index 00000000000..17fb0b68a4c --- /dev/null +++ b/crates/openhuman-core/src/core/runtime/context_host_grant.rs @@ -0,0 +1,33 @@ +//! Carrying a library host's secret grant on the context of the store it +//! authorises (`security::approval::gate::host_authorised_secret_grant`). + +use super::*; + +type HostSecretGrant = crate::security::approval::gate::HostSecretGrant; + +impl CoreContext { + /// The host secret grant on the context scoped onto this task, a + /// [`bare`](Self::bare) one included. Whether it holds here is the + /// grant's own check. + pub(crate) fn current_host_secret_grant() -> Option> { + Self::scoped_for_turn().and_then(|ctx| ctx.host_secret_grant.clone()) + } + + /// Run `fut` under this task's context carrying `grant`, or under a bare + /// context carrying only it where no context is scoped (a library runtime + /// storing its credential before its core boots). Every other reader + /// answers exactly as it does outside. + pub(crate) async fn scope_with_host_secret_grant( + grant: Arc, + fut: F, + ) -> F::Output { + let base = Self::scoped_for_turn().unwrap_or_else(Self::bare); + tracing::debug!( + bare = base.bare, + "[core-context] scoping a host secret grant onto the current context" + ); + CURRENT_CONTEXT + .scope(Arc::new(base.copy_with(None, None, Some(grant))), fut) + .await + } +} diff --git a/crates/openhuman-core/src/core/runtime/context_inspection.rs b/crates/openhuman-core/src/core/runtime/context_inspection.rs index 59ba1ccf6bc..b44c37c3422 100644 --- a/crates/openhuman-core/src/core/runtime/context_inspection.rs +++ b/crates/openhuman-core/src/core/runtime/context_inspection.rs @@ -54,6 +54,7 @@ impl CoreContext { user_skill_roots: true, extensions: Default::default(), turn_origin: None, + host_secret_grant: None, channel_thread: None, session_agent: None, profile: None, diff --git a/crates/openhuman-core/src/core/runtime/context_test_support.rs b/crates/openhuman-core/src/core/runtime/context_test_support.rs index 5bdf566de15..c0e2961e88d 100644 --- a/crates/openhuman-core/src/core/runtime/context_test_support.rs +++ b/crates/openhuman-core/src/core/runtime/context_test_support.rs @@ -91,6 +91,7 @@ impl CoreContext { user_skill_roots: true, extensions: Default::default(), turn_origin: None, + host_secret_grant: None, channel_thread: None, session_agent: None, profile: None, @@ -185,6 +186,7 @@ impl CoreContext { user_skill_roots: true, extensions: Default::default(), turn_origin: None, + host_secret_grant: None, channel_thread: None, session_agent: None, profile: None, diff --git a/crates/openhuman-core/src/core/runtime/context_tests.rs b/crates/openhuman-core/src/core/runtime/context_tests.rs index 1d24f70ab23..4a9a731715a 100644 --- a/crates/openhuman-core/src/core/runtime/context_tests.rs +++ b/crates/openhuman-core/src/core/runtime/context_tests.rs @@ -18,6 +18,7 @@ fn ctx(dir: &str) -> Arc { user_skill_roots: true, extensions: Default::default(), turn_origin: None, + host_secret_grant: None, channel_thread: None, session_agent: None, profile: None, @@ -453,6 +454,7 @@ fn degraded_context_rejects_workspace_bound_stores() { user_skill_roots: true, extensions: Default::default(), turn_origin: None, + host_secret_grant: None, channel_thread: None, session_agent: None, profile: None, diff --git a/crates/openhuman-core/src/core/runtime/context_turn_origin.rs b/crates/openhuman-core/src/core/runtime/context_turn_origin.rs index 4e077011055..9a8a391ac25 100644 --- a/crates/openhuman-core/src/core/runtime/context_turn_origin.rs +++ b/crates/openhuman-core/src/core/runtime/context_turn_origin.rs @@ -48,6 +48,7 @@ impl CoreContext { user_skill_roots: true, extensions: Default::default(), turn_origin: None, + host_secret_grant: None, channel_thread: None, session_agent: None, profile: None, @@ -97,8 +98,19 @@ impl CoreContext { thread: Option, origin: Option, ) -> Arc { + Arc::new(self.copy_with(thread, origin, None)) + } + + /// A copy of this context with `thread`, `origin` and `grant` replacing + /// its own where given. + pub(super) fn copy_with( + &self, + thread: Option, + origin: Option, + grant: Option>, + ) -> CoreContext { let ctx = self; - Arc::new(CoreContext { + CoreContext { host_kind: ctx.host_kind, workspace_binding: RwLock::new( ctx.workspace_binding @@ -116,12 +128,13 @@ impl CoreContext { user_skill_roots: ctx.user_skill_roots, extensions: ctx.extensions.clone(), turn_origin: origin.or_else(|| ctx.turn_origin.clone()), + host_secret_grant: grant.or_else(|| ctx.host_secret_grant.clone()), channel_thread: thread.or_else(|| ctx.channel_thread.clone()), session_agent: ctx.session_agent.clone(), profile: ctx.profile.clone(), profile_admission: Arc::clone(&ctx.profile_admission), agent: ctx.agent.clone(), bare: ctx.bare, - }) + } } } diff --git a/crates/openhuman-core/src/credentials/README.md b/crates/openhuman-core/src/credentials/README.md index e8f7a4e7359..bb1ffae1abf 100644 --- a/crates/openhuman-core/src/credentials/README.md +++ b/crates/openhuman-core/src/credentials/README.md @@ -83,7 +83,7 @@ refresh preserves the association; it cannot rebind the token. Legacy profiles without this field remain unbound because the original backend cannot be inferred. API-key precedence and local-session behavior are unchanged. -`AuthProfilesStore` (`profiles.rs`) writes the schema document to `auth-profiles/secrets.enc` in the config state directory (parent of `config.config_path`, user-scoped after activation). The document contains `schema_version` (current = 1), `updated_at`, `active_profiles` (provider → profile-id), and [`profiles`](./profiles) (id → profile). The old root-level `auth-profiles.json` is read only for one-time import. The `app-session` profile's metadata carries `user_id`, `user_json` (the host-supplied payload) and `session_expires_at` (the JWT `exp`, for the local expiry precheck). Secret handling: +`AuthProfilesStore` (`profiles.rs`) writes the schema document to `auth-profiles/secrets.enc` in the config state directory (parent of `config.config_path`, user-scoped after activation). The document contains `schema_version` (current = 1), `updated_at`, `active_profiles` (provider → profile-id), and [`profiles`](./profiles) (id → profile). The old root-level `auth-profiles.json` is read only for one-time import. A SaaS tenant's store (`/users//`, used under that tenant's context) with a storage backend installed keeps the same document as one encrypted secret (`auth-profiles`, `DocumentSecrets`) in the tenant's storage scope instead (`profiles/backend.rs`): no `auth-profiles/` directory or `auth-profiles.lock` is created beside the profile, and the lock is the backend's compare-and-swap on the secret's version plus an in-process lock per tenant. The first backend read adopts a document a profile-local store left (read-only). A tenant's store reached outside that tenant's scope is refused, and a missing master key or scope fails closed. Desktop, CLI, embed and the SaaS operator plane keep the profile-local file and lease, with or without a backend. The `app-session` profile's metadata carries `user_id`, `user_json` (the host-supplied payload) and `session_expires_at` (the JWT `exp`, for the local expiry precheck). Secret handling: - Config-backed profile secrets use TinySecurity `KeyringAccess2` over TSD `KeyringSecrets`, with fresh approval for each keyring read, write, and delete. No-Config bootstrap APIs keep secrets only in the encrypted profile document. - Each process keeps the profile secrets it has read or written in memory (`profiles/keychain.rs`, `READ_CACHE`), by keyring entry name, so later reads of that entry in the same process don't reach the keyring and ask again. The cache lives for the process only and is never persisted. diff --git a/crates/openhuman-core/src/credentials/api_key.rs b/crates/openhuman-core/src/credentials/api_key.rs index 10fa91d70a1..1d2ab7a5aee 100644 --- a/crates/openhuman-core/src/credentials/api_key.rs +++ b/crates/openhuman-core/src/credentials/api_key.rs @@ -96,8 +96,17 @@ pub async fn get_api_key_read_only( /// name, `"api-key"` included; without the marker check, such a profile /// would be accepted here as a TinyHumans runtime key and its bearer sent to /// the managed backend as one. -pub async fn get_api_key_in(state_dir: &Path, encrypt: bool) -> Result> { - get_api_key_with_service(&service_in(state_dir, encrypt)).await +/// +/// `config` is the runtime config the caller was built for (the managed model's +/// own); it binds the store only when it owns `state_dir` with the same +/// encryption setting, exactly as the session lookup does through +/// [`AuthService::for_state_dir`]. +pub async fn get_api_key_in( + state_dir: &Path, + encrypt: bool, + config: Option<&Config>, +) -> Result> { + get_api_key_with_service(&service_for(state_dir, encrypt, config)).await } async fn get_api_key_with_service(service: &AuthService) -> Result> { @@ -108,11 +117,22 @@ async fn get_api_key_with_service(service: &AuthService) -> Result AuthService { - match crate::core::runtime::CoreContext::current_embedder_config().filter(|config| { - super::core::state_dir_from_config(config) == state_dir && config.secrets.encrypt == encrypt - }) { + service_for(state_dir, encrypt, None) +} + +fn service_for(state_dir: &Path, encrypt: bool, config: Option<&Config>) -> AuthService { + if let Some(config) = + config.filter(|config| super::core::config_owns_state_dir(config, state_dir, encrypt)) + { + return AuthService::config_document(config); + } + match super::core::owning_embedder_config(state_dir, encrypt) { Some(config) => AuthService::config_document(&config), None => AuthService::new(state_dir, encrypt), } @@ -138,7 +158,7 @@ fn api_key_from_profile(profile: AuthProfile) -> Option { /// so a corrupt profile file degrades to the session path instead of /// panicking a hot path; the error is logged. pub async fn has_api_key_in(state_dir: &Path, encrypt: bool) -> bool { - match get_api_key_in(state_dir, encrypt).await { + match get_api_key_in(state_dir, encrypt, None).await { Ok(key) => key.is_some(), Err(e) => { log::debug!("[credentials][api-key] store read failed, treating as absent: {e:#}"); diff --git a/crates/openhuman-core/src/credentials/api_key_tests.rs b/crates/openhuman-core/src/credentials/api_key_tests.rs index b7bce2ed4e4..7501cb78c9c 100644 --- a/crates/openhuman-core/src/credentials/api_key_tests.rs +++ b/crates/openhuman-core/src/credentials/api_key_tests.rs @@ -139,3 +139,58 @@ async fn encrypted_api_key_retains_the_admitted_host_configuration() { }) .await; } + +/// Managed chat and embeddings look the key up by `(state_dir, encrypt)`. With +/// no ambient embedder config owning that directory, the model's own config +/// must bind the store, or a config-encrypted key reads as absent and an +/// API-key-only runtime cannot authenticate. +#[cfg(feature = "security-module")] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn an_encrypted_api_key_is_read_through_the_owning_config() { + let dir = tempfile::tempdir().expect("isolated credentials"); + let mut config = config_in(dir.path()); + config.secrets.encrypt = true; + let worker_config = config.clone(); + crate::credentials::test_support::with_native_cipher_approval(&config, async move { + assert!( + crate::core::runtime::CoreContext::current_embedder_config().is_none(), + "no ambient config owns the directory" + ); + store_api_key(&worker_config, "fixture-owned-api-key") + .await + .expect("store with admitted host configuration"); + let state_dir = crate::credentials::state_dir_from_config(&worker_config); + let read = get_api_key_in(&state_dir, true, Some(&worker_config)).await; + let cleared = clear_api_key(&worker_config).await; + assert_eq!( + read.expect("read through the owning config").as_deref(), + Some("fixture-owned-api-key") + ); + assert!(cleared.expect("remove encrypted key")); + }) + .await; +} + +/// A config for another credential directory never lends its authority: the +/// lookup stays bound to the directory it was asked about. +#[tokio::test] +async fn a_config_for_another_directory_does_not_supply_the_api_key() { + let owner = tempfile::tempdir().expect("owner credentials"); + let other = tempfile::tempdir().expect("other credentials"); + let config = config_in(owner.path()); + store_api_key(&config, "th_owner").await.expect("store"); + assert_eq!( + get_api_key_in(other.path(), false, Some(&config)) + .await + .expect("read"), + None + ); + let owner_dir = crate::credentials::state_dir_from_config(&config); + assert_eq!( + get_api_key_in(&owner_dir, false, Some(&config)) + .await + .expect("read") + .as_deref(), + Some("th_owner") + ); +} diff --git a/crates/openhuman-core/src/credentials/core.rs b/crates/openhuman-core/src/credentials/core.rs index 8dfdf03bb4b..57ed2fe2b2b 100644 --- a/crates/openhuman-core/src/credentials/core.rs +++ b/crates/openhuman-core/src/credentials/core.rs @@ -68,6 +68,35 @@ impl AuthService { } } + /// The profile store for a credential directory known by its path, bound + /// to the runtime config that owns that directory. + /// + /// Sign-in writes the app session through [`Self::from_config`], whose + /// store keeps secrets in the keyring under `security-module`; a plain + /// [`Self::new`] store over the same directory cannot see them. So a + /// caller holding only `(state_dir, encrypt)` reads through the owning + /// config's store: `config` when it owns the directory, else the current + /// dispatch's embedder config when that does. A config for another + /// directory, or with another encryption setting, never lends its + /// authority; with no owner the store is directory-only. + pub fn for_state_dir(state_dir: &Path, encrypt_secrets: bool, config: Option<&Config>) -> Self { + if let Some(config) = + config.filter(|config| config_owns_state_dir(config, state_dir, encrypt_secrets)) + { + return Self::from_config(config); + } + match owning_embedder_config(state_dir, encrypt_secrets) { + Some(config) => Self::from_config(&config), + None => { + log::debug!( + "[auth] no runtime config owns state_dir={}; using a directory-only store", + state_dir.display() + ); + Self::new(state_dir, encrypt_secrets) + } + } + } + pub async fn load_profiles(&self) -> Result { self.store.load().await } @@ -201,6 +230,21 @@ pub fn state_dir_from_config(config: &Config) -> PathBuf { .map_or_else(|| PathBuf::from("."), PathBuf::from) } +/// Whether `config` is the runtime config for the credential directory +/// `state_dir` stored with `encrypt` — the same directory and the same +/// encryption setting. +pub(super) fn config_owns_state_dir(config: &Config, state_dir: &Path, encrypt: bool) -> bool { + state_dir_from_config(config) == state_dir && config.secrets.encrypt == encrypt +} + +/// The current dispatch's embedder config, only when it owns the credential +/// directory `state_dir` stored with `encrypt`. A different ambient tenant +/// never supplies cipher or keyring authority for another directory. +pub(super) fn owning_embedder_config(state_dir: &Path, encrypt: bool) -> Option { + crate::core::runtime::CoreContext::current_embedder_config() + .filter(|config| config_owns_state_dir(config, state_dir, encrypt)) +} + /// The files holding OpenHuman's own credentials for `config`, at the paths /// their stores write: the encrypted keyring (`secrets.enc`), the auth /// profiles, the HTTP credentials and the account config. A path may not diff --git a/crates/openhuman-core/src/credentials/openai_oauth/openai_oauth_tests.rs b/crates/openhuman-core/src/credentials/openai_oauth/openai_oauth_tests.rs index 90a10c1863b..97e6c9f32af 100644 --- a/crates/openhuman-core/src/credentials/openai_oauth/openai_oauth_tests.rs +++ b/crates/openhuman-core/src/credentials/openai_oauth/openai_oauth_tests.rs @@ -113,7 +113,10 @@ async fn concurrent_refresh_persists_rotated_token_and_stable_metadata_once() { assert_eq!(second.unwrap().unwrap().access_token, "fresh-access"); assert_eq!(source.refresh_count.load(Ordering::SeqCst), 1); - let profile = profiles + // Read back through the config-bound store the refresh writes with: under + // `security-module` it keeps the rotated secrets in the keyring, and a + // document-only store never surfaces a keyring-owned profile. + let profile = AuthProfilesStore::new_with_config(tmp.path(), false, &config) .load() .await .unwrap() diff --git a/crates/openhuman-core/src/credentials/profiles.rs b/crates/openhuman-core/src/credentials/profiles.rs index a6262b7d5c8..fb11f81dedd 100644 --- a/crates/openhuman-core/src/credentials/profiles.rs +++ b/crates/openhuman-core/src/credentials/profiles.rs @@ -8,6 +8,7 @@ use std::fs; use std::path::{Path, PathBuf}; use std::time::Duration; +mod backend; mod keychain; #[cfg(test)] pub(crate) use keychain::namespaced_keyring_name; @@ -212,6 +213,8 @@ fn user_id_from_state_dir(state_dir: &Path) -> String { #[derive(Clone)] pub struct AuthProfilesStore { + /// The credential directory (`config_path`'s parent) this store serves. + state_dir: PathBuf, path: PathBuf, legacy_path: PathBuf, lock_path: PathBuf, diff --git a/crates/openhuman-core/src/credentials/profiles/backend.rs b/crates/openhuman-core/src/credentials/profiles/backend.rs new file mode 100644 index 00000000000..b5e8ed4d101 --- /dev/null +++ b/crates/openhuman-core/src/credentials/profiles/backend.rs @@ -0,0 +1,215 @@ +//! A SaaS tenant's auth-profile document on the configured storage backend. +//! +//! When a backend is installed and the store belongs to the tenant the call +//! serves (`/users//` under that profile's context), the +//! document is one encrypted secret in the tenant's storage scope +//! (`DocumentSecrets`, `enc2:`), not the profile-local file, and its lock is +//! the backend's compare-and-swap on that secret's version plus an in-process +//! serialisation, not a lease file. Nothing auth-related is created beside the +//! tenant's workspace. Every other store (desktop, CLI, embed, the operator +//! plane) keeps the profile-local file and lease. A tenant's store reached from +//! any other scope in SaaS is refused, never served from the local file. + +use std::collections::HashSet; +use std::path::Path; +use std::sync::{Arc, Condvar, Mutex}; + +use anyhow::{Context, Result}; +use tinystoragedrivers::secrets::{ + DocumentSecrets, SecretPrecondition, SecretStore as _, SecretVersion, +}; +use zeroize::Zeroizing; + +use super::PROFILE_DOCUMENT_SECRET_NAME; + +/// Where a store's document lives for the current call. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) enum Home { + /// The profile-local encrypted file and its lease. + Local, + /// The backend, in tenant `profile`'s scope. + Tenant(String), + /// A tenant's store reached outside that tenant's scope. + Refused, +} + +/// Decide [`Home`] from resolved facts. `users_dir` is the SaaS host's +/// `/users`, when a host runs in this process. +pub(super) fn decide( + backend_installed: bool, + ambient_profile: Option<&str>, + state_dir: &Path, + users_dir: Option<&Path>, +) -> Home { + if !backend_installed { + return Home::Local; + } + let parent = state_dir.parent(); + let name = state_dir.file_name().and_then(|name| name.to_str()); + let under_users = match users_dir { + Some(users) => parent == Some(users), + None => { + parent.and_then(Path::file_name) + == Some(crate::config::schema::profile_layout::USERS_DIR.as_ref()) + } + }; + match (ambient_profile.filter(|p| !p.is_empty()), name) { + (Some(profile), Some(name)) if name == profile && under_users => { + Home::Tenant(profile.to_owned()) + } + // Only a SaaS host makes `/users/` a tenant's store; the + // desktop's `users/` stays local. + _ if users_dir.is_some() && under_users => Home::Refused, + _ => Home::Local, + } +} + +/// The backend document for `state_dir` in the current call, or `None` when +/// the store keeps its local file. +/// +/// # Errors +/// +/// When the store is a tenant's reached outside that tenant's scope, or the +/// backend scope or master key cannot be resolved (fail closed). +pub(super) fn document_for(state_dir: &Path) -> Result> { + let backend = crate::storage::installed(); + let profile = crate::core::runtime::DispatchCtx::ambient() + .tenant() + .ok() + .and_then(|tenant| tenant.profile); + let users_dir = crate::profiles::host::host() + .map(|host| crate::config::schema::users_dir(&host.saas().root)); + let home = decide( + backend.is_some(), + profile.as_deref(), + state_dir, + users_dir.as_deref(), + ); + match (home, backend) { + (Home::Tenant(profile), Some(backend)) => { + let scope = crate::storage::scope_for_profile(&profile); + let scoped = backend + .for_scope(&scope.to_storage_scope()) + .context("auth profile storage scope")?; + let keys = crate::storage::secrets::keys().context("auth profile storage key")?; + log::debug!("[auth] tenant auth profiles served from the storage backend"); + Ok(Some(BackendDocument { + secrets: crate::storage::secrets::over(&scoped, scope, keys), + profile, + })) + } + (Home::Refused, _) => { + log::warn!("[auth] tenant auth profile store reached outside its tenant scope"); + anyhow::bail!("a tenant's auth profiles are reachable only under that tenant's scope") + } + _ => Ok(None), + } +} + +/// One tenant's auth-profile secret on the backend. +pub(super) struct BackendDocument { + secrets: DocumentSecrets, + profile: String, +} + +impl BackendDocument { + /// The document and its version, without a lock (read-only lookups). + pub(super) fn get(&self) -> Result>, SecretVersion)>> { + let secrets = self.secrets.clone(); + crate::storage::block_on(async move { + secrets.get_versioned(PROFILE_DOCUMENT_SECRET_NAME).await + }) + .context("Failed to read auth profiles from the storage backend") + } + + /// Take this tenant's in-process lock for a read-modify-write. + pub(super) fn lock(self) -> BackendLease { + let serial = Serial::acquire(&self.profile); + BackendLease { + document: self, + observed: Mutex::new(None), + _serial: serial, + } + } +} + +/// The backend counterpart of the local lease: in-process exclusion for one +/// tenant's document, and the version last read under it, which a write must +/// still match on the backend (compare-and-swap across processes). +pub(super) struct BackendLease { + document: BackendDocument, + observed: Mutex>, + _serial: Serial, +} + +impl BackendLease { + /// Read the document, remembering its version for the next write. + pub(super) fn read(&self) -> Result>>> { + let found = self.document.get()?; + let (value, condition) = match found { + Some((value, version)) => (Some(value), SecretPrecondition::Version(version)), + None => (None, SecretPrecondition::Absent), + }; + *self.observed.lock().unwrap_or_else(|e| e.into_inner()) = Some(condition); + Ok(value) + } + + /// Replace the document, only if it is still the version read under this + /// lease. + pub(super) fn write(&self, json: Vec) -> Result<()> { + let mut observed = self.observed.lock().unwrap_or_else(|e| e.into_inner()); + let condition = observed + .take() + .context("auth profile backend write without a read under its lease")?; + let secrets = self.document.secrets.clone(); + let json = Zeroizing::new(json); + let version = crate::storage::block_on(async move { + secrets + .set_if(PROFILE_DOCUMENT_SECRET_NAME, &json, condition) + .await + }) + .context("Failed to write auth profiles to the storage backend")?; + *observed = Some(SecretPrecondition::Version(version)); + Ok(()) + } +} + +/// Process-wide exclusion per tenant document, released on drop. +struct Serial { + key: String, + held: Arc<(Mutex>, Condvar)>, +} + +impl Serial { + fn acquire(key: &str) -> Self { + static HELD: std::sync::OnceLock>, Condvar)>> = + std::sync::OnceLock::new(); + let held = Arc::clone(HELD.get_or_init(Arc::default)); + { + let (set, ready) = &*held; + let mut set = set.lock().unwrap_or_else(|e| e.into_inner()); + while set.contains(key) { + set = ready.wait(set).unwrap_or_else(|e| e.into_inner()); + } + set.insert(key.to_owned()); + } + Self { + key: key.to_owned(), + held, + } + } +} + +impl Drop for Serial { + fn drop(&mut self) { + let (set, ready) = &*self.held; + set.lock() + .unwrap_or_else(|e| e.into_inner()) + .remove(&self.key); + ready.notify_all(); + } +} + +#[cfg(test)] +#[path = "backend_tests.rs"] +mod tests; diff --git a/crates/openhuman-core/src/credentials/profiles/backend_tests.rs b/crates/openhuman-core/src/credentials/profiles/backend_tests.rs new file mode 100644 index 00000000000..d5bc555ccc7 --- /dev/null +++ b/crates/openhuman-core/src/credentials/profiles/backend_tests.rs @@ -0,0 +1,70 @@ +use super::*; +use std::path::PathBuf; + +fn users() -> PathBuf { + PathBuf::from("/srv/saas/users") +} + +#[test] +fn without_a_backend_every_store_stays_local() { + let alice = users().join("alice"); + assert_eq!( + decide(false, Some("alice"), &alice, Some(&users())), + Home::Local + ); +} + +#[test] +fn a_tenant_store_under_its_own_scope_lives_on_the_backend() { + let alice = users().join("alice"); + assert_eq!( + decide(true, Some("alice"), &alice, Some(&users())), + Home::Tenant("alice".into()) + ); + // An in-process host without a registered SaaS root (embedding, tests) + // recognises the same `users/` shape. + assert_eq!( + decide(true, Some("alice"), &alice, None), + Home::Tenant("alice".into()) + ); +} + +#[test] +fn a_tenant_store_outside_its_own_scope_is_refused_in_saas() { + let alice = users().join("alice"); + assert_eq!( + decide(true, Some("bob"), &alice, Some(&users())), + Home::Refused, + "another tenant's scope" + ); + assert_eq!( + decide(true, None, &alice, Some(&users())), + Home::Refused, + "the operator plane or an unscoped task" + ); + // A same-named directory outside the SaaS root is not a tenant store. + assert_eq!( + decide( + true, + Some("alice"), + Path::new("/elsewhere/users/alice"), + Some(&users()) + ), + Home::Local + ); +} + +#[test] +fn desktop_and_operator_stores_keep_their_local_file() { + // The desktop's `users/` with its default storage backend: no tenant + // context and no SaaS host. + assert_eq!( + decide(true, None, Path::new("/home/u/.openhuman/users/abc"), None), + Home::Local + ); + // The SaaS operator plane's own store, outside `/users`. + assert_eq!( + decide(true, None, Path::new("/srv/saas/operator"), Some(&users())), + Home::Local + ); +} diff --git a/crates/openhuman-core/src/credentials/profiles/lock.rs b/crates/openhuman-core/src/credentials/profiles/lock.rs index 8ebf1b4ca5e..b140d4676de 100644 --- a/crates/openhuman-core/src/credentials/profiles/lock.rs +++ b/crates/openhuman-core/src/credentials/profiles/lock.rs @@ -1,21 +1,55 @@ -//! Auth-profile locking through the shared local lease implementation. +//! Auth-profile locking: the shared local lease for a profile-local document, +//! or, for a tenant document on a storage backend, the backend lease +//! (`backend.rs`). use anyhow::Result; use tinystoragedrivers_fence::{LocalLeaseGuard, LocalLeases}; +use super::backend::{self, BackendLease}; use super::AuthProfilesStore; -/// Owns one TSD local lease for the duration of an auth-profile operation. +/// Held for the duration of an auth-profile operation; reads and writes of +/// the document go through the store it was taken on. pub(super) struct AuthProfileLockGuard { - _lease: LocalLeaseGuard, + held: Held, +} + +enum Held { + /// A local lease, or `None` for the lock-free read-only snapshot. + Local(Option), + Backend(BackendLease), +} + +impl AuthProfileLockGuard { + /// No lease: the read-only snapshot of a full or read-only filesystem. + pub(super) fn lock_free() -> Self { + Self { + held: Held::Local(None), + } + } + + /// The backend lease, when the document lives on the storage backend. + pub(super) fn backend(&self) -> Option<&BackendLease> { + match &self.held { + Held::Backend(lease) => Some(lease), + Held::Local(_) => None, + } + } } impl AuthProfilesStore { /// Acquire an exclusive lease for a profile-store mutation. pub(super) fn acquire_lock(&self) -> Result { + if let Some(document) = backend::document_for(&self.state_dir)? { + return Ok(AuthProfileLockGuard { + held: Held::Backend(document.lock()), + }); + } LocalLeases::new(self.lock_path.clone()) .acquire() - .map(|lease| AuthProfileLockGuard { _lease: lease }) + .map(|lease| AuthProfileLockGuard { + held: Held::Local(Some(lease)), + }) .map_err(|error| anyhow::anyhow!("Failed to acquire auth profile lease: {error}")) } @@ -23,9 +57,18 @@ impl AuthProfilesStore { /// lock-free fallback when a full or read-only filesystem cannot create /// the lease file. pub(super) fn acquire_read_lock(&self) -> Result> { + if let Some(document) = backend::document_for(&self.state_dir)? { + return Ok(Some(AuthProfileLockGuard { + held: Held::Backend(document.lock()), + })); + } LocalLeases::new(self.lock_path.clone()) .acquire_for_read() - .map(|lease| lease.map(|lease| AuthProfileLockGuard { _lease: lease })) + .map(|lease| { + lease.map(|lease| AuthProfileLockGuard { + held: Held::Local(Some(lease)), + }) + }) .map_err(|error| anyhow::anyhow!("Failed to acquire auth profile read lease: {error}")) } } diff --git a/crates/openhuman-core/src/credentials/profiles/persistence.rs b/crates/openhuman-core/src/credentials/profiles/persistence.rs index 5f41978b394..443aa3b4152 100644 --- a/crates/openhuman-core/src/credentials/profiles/persistence.rs +++ b/crates/openhuman-core/src/credentials/profiles/persistence.rs @@ -1,5 +1,6 @@ //! Reading and writing the persisted auth-profile document through TSD's -//! encrypted local secret store. +//! encrypted local secret store, or, for a SaaS tenant with a storage backend, +//! through the backend lease taken for the operation (`backend.rs`). use anyhow::{Context, Result}; use chrono::{DateTime, Utc}; @@ -256,6 +257,42 @@ impl AuthProfilesStore { )) } + /// Read the document under `lock`: from the storage backend when the lock + /// is a backend lease, else from the profile-local file. + pub(super) fn read_persisted( + &self, + lock: &super::lock::AuthProfileLockGuard, + ) -> Result { + let Some(lease) = lock.backend() else { + return self.read_persisted_locked(); + }; + match lease.read()? { + Some(bytes) => parse_backend_document(&bytes), + // First use of the backend: adopt a document a profile-local + // store left, read-only. The next write publishes it to the + // backend; the local file is never written again. + None => match self.read_encrypted_file_locked()? { + Some(persisted) => Ok(persisted), + None => self.read_file_locked(), + }, + } + } + + /// Write the document under `lock`, to wherever [`Self::read_persisted`] + /// read it from. + pub(super) fn write_persisted( + &self, + lock: &super::lock::AuthProfileLockGuard, + persisted: &PersistedAuthProfiles, + ) -> Result<()> { + let Some(lease) = lock.backend() else { + return self.write_persisted_locked(persisted); + }; + let json = serde_json::to_vec(persisted).context("Failed to serialize auth profiles")?; + lease.write(json) + } + + /// The profile-local document (the caller holds the local lease). pub(super) fn read_persisted_locked(&self) -> Result { if let Some(persisted) = self.read_encrypted_file_locked()? { return Ok(persisted); @@ -384,6 +421,25 @@ impl AuthProfilesStore { } } +/// Parse the document read from the storage backend. No quarantine there: an +/// unparseable or newer record is an error, so a later write can never replace +/// profiles it could not read. +pub(super) fn parse_backend_document(bytes: &[u8]) -> Result { + let mut persisted: PersistedAuthProfiles = serde_json::from_slice(bytes) + .context("auth profile record on the storage backend is not valid JSON")?; + if persisted.schema_version == 0 { + persisted.schema_version = CURRENT_SCHEMA_VERSION; + } + if persisted.schema_version > CURRENT_SCHEMA_VERSION { + anyhow::bail!( + "Unsupported auth profile schema version {} (max supported: {})", + persisted.schema_version, + CURRENT_SCHEMA_VERSION + ); + } + Ok(persisted) +} + async fn encrypt_profile_field( store: &super::SecretStore, value: Option, diff --git a/crates/openhuman-core/src/credentials/profiles/readonly.rs b/crates/openhuman-core/src/credentials/profiles/readonly.rs index 987fc171238..5eb6ffa6b46 100644 --- a/crates/openhuman-core/src/credentials/profiles/readonly.rs +++ b/crates/openhuman-core/src/credentials/profiles/readonly.rs @@ -74,7 +74,19 @@ async fn load_profile_with_keyring( .config_path .parent() .ok_or(ReadOnlyAuthProfileError::Unavailable)?; - let bytes = { + // A SaaS tenant's document lives on the storage backend; a tenant's store + // outside its own scope is refused, not read from a local file. + let backend_bytes = match super::backend::document_for(state_dir) { + Ok(Some(document)) => document + .get() + .map_err(|_| ReadOnlyAuthProfileError::Unavailable)? + .map(|(value, _)| value.to_vec()), + Ok(None) => None, + Err(_) => return Err(ReadOnlyAuthProfileError::Unavailable), + }; + let bytes = if let Some(bytes) = backend_bytes { + bytes + } else { let path = super::profiles_file(state_dir); if path.exists() { let directory = path.parent().ok_or(ReadOnlyAuthProfileError::Unavailable)?; diff --git a/crates/openhuman-core/src/credentials/profiles/store_core.rs b/crates/openhuman-core/src/credentials/profiles/store_core.rs index c72a7135a9f..fec6f1106c7 100644 --- a/crates/openhuman-core/src/credentials/profiles/store_core.rs +++ b/crates/openhuman-core/src/credentials/profiles/store_core.rs @@ -67,6 +67,7 @@ impl AuthProfilesStore { |config| SecretStore::new_with_config(state_dir, encrypt_secrets, config), ); Self { + state_dir: state_dir.to_path_buf(), path: super::profiles_file(state_dir), legacy_path: super::legacy_profiles_file(state_dir), lock_path: state_dir.join(LOCK_FILENAME), @@ -86,13 +87,14 @@ impl AuthProfilesStore { /// are published atomically, so this snapshot stays internally consistent. pub async fn load(&self) -> Result { let (persisted, can_publish) = match self.acquire_read_lock()? { - Some(_lock) => (self.read_persisted_locked()?, true), + Some(lock) => (self.read_persisted(&lock)?, true), None => { log::warn!( "[auth] profile lease unavailable on a full or read-only filesystem; \ serving a lock-free read-only snapshot" ); - (self.read_persisted_locked()?, false) + let lock = super::lock::AuthProfileLockGuard::lock_free(); + (self.read_persisted(&lock)?, false) } }; let before = serde_json::to_vec(&persisted).context("serialize auth profile snapshot")?; @@ -112,10 +114,10 @@ impl AuthProfilesStore { ) -> Result<()> { let candidate = serde_json::to_vec(cleaned).context("serialize cleaned auth profiles")?; if candidate != expected { - let _lock = self.acquire_lock()?; - let current = self.read_persisted_locked()?; + let lock = self.acquire_lock()?; + let current = self.read_persisted(&lock)?; if serde_json::to_vec(¤t)? == expected { - self.write_persisted_locked(cleaned)?; + self.write_persisted(&lock, cleaned)?; } } Ok(()) @@ -123,8 +125,8 @@ impl AuthProfilesStore { async fn snapshot(&self) -> Result<(PersistedAuthProfiles, Vec)> { let persisted = { - let _lock = self.acquire_lock()?; - self.read_persisted_locked()? + let lock = self.acquire_lock()?; + self.read_persisted(&lock)? }; let version = serde_json::to_vec(&persisted).context("serialize auth profile snapshot")?; Ok((persisted, version)) @@ -139,14 +141,14 @@ impl AuthProfilesStore { // Cipher operations can ask the operator for consent. Prepare the // candidate document before reacquiring the non-Send local lease. let persisted = self.prepare_persisted(data, previous).await?; - let _lock = self.acquire_lock()?; - let current = self.read_persisted_locked()?; + let lock = self.acquire_lock()?; + let current = self.read_persisted(&lock)?; let current_version = serde_json::to_vec(¤t).context("serialize current auth profile snapshot")?; if current_version != expected_version { return Ok(false); } - self.write_persisted_locked(&persisted)?; + self.write_persisted(&lock, &persisted)?; Ok(true) } @@ -204,12 +206,12 @@ impl AuthProfilesStore { .retain(|_, active| active != profile_id); candidate.updated_at = Utc::now().to_rfc3339(); { - let _lock = self.acquire_lock()?; - let current = serde_json::to_vec(&self.read_persisted_locked()?)?; + let lock = self.acquire_lock()?; + let current = serde_json::to_vec(&self.read_persisted(&lock)?)?; if current != version { continue; } - self.write_persisted_locked(&candidate)?; + self.write_persisted(&lock, &candidate)?; } if keyring_owned { if let Err(error) = self.keychain_delete_secrets(profile_id).await { @@ -252,8 +254,8 @@ impl AuthProfilesStore { persisted_before: &PersistedAuthProfiles, delete_error: anyhow::Error, ) -> Result { - let _lock = self.acquire_lock()?; - let mut current = self.read_persisted_locked()?; + let lock = self.acquire_lock()?; + let mut current = self.read_persisted(&lock)?; if !current.profiles.contains_key(profile_id) { if let Some(profile) = persisted_before.profiles.get(profile_id) { current @@ -268,7 +270,7 @@ impl AuthProfilesStore { } } current.updated_at = Utc::now().to_rfc3339(); - self.write_persisted_locked(¤t)?; + self.write_persisted(&lock, ¤t)?; } } Err(delete_error.context("profile removal was not completed")) diff --git a/crates/openhuman-core/src/credentials/profiles_keychain_error_tests.rs b/crates/openhuman-core/src/credentials/profiles_keychain_error_tests.rs index ffe59a95d90..5acd7720f1a 100644 --- a/crates/openhuman-core/src/credentials/profiles_keychain_error_tests.rs +++ b/crates/openhuman-core/src/credentials/profiles_keychain_error_tests.rs @@ -77,7 +77,12 @@ async fn file_keyring_backend_stores_profile_secrets_without_asking_the_keyring( #[tokio::test] async fn unavailable_keyring_keeps_keyring_only_oauth_metadata_in_place() { let tmp = TempDir::new().unwrap(); - let config = crate::config::Config::default(); + // Make the keyring unavailable on every host: with modules disabled + // TinySecurity cannot load, a non-consent failure. Left to the host, a + // machine with a working session keyring answers a miss instead, and a + // miss rightly purges the record this test needs to keep. + let mut config = crate::config::Config::default(); + config.modules.enabled = false; let store = AuthProfilesStore::new_with_config(tmp.path(), true, &config); let profile = AuthProfile::new_oauth( "openai-codex", diff --git a/crates/openhuman-core/src/credentials/profiles_storage_tests.rs b/crates/openhuman-core/src/credentials/profiles_storage_tests.rs index 2fd9e24d07f..4da12ddaced 100644 --- a/crates/openhuman-core/src/credentials/profiles_storage_tests.rs +++ b/crates/openhuman-core/src/credentials/profiles_storage_tests.rs @@ -51,3 +51,90 @@ async fn configured_generic_storage_does_not_replace_the_profile_local_document( Some("local-secret") ); } + +/// A host key source holding one fixed key, so the storage master key is +/// never minted or read from the developer's keychain. +struct FixedStorageKey; +impl crate::security::secret_storage::MasterKeySource for FixedStorageKey { + fn load( + &self, + ) -> Result< + Option>, + crate::security::secret_storage::SecretStorageError, + > { + Ok(Some(zeroize::Zeroizing::new([0x42; 32]))) + } + fn store( + &self, + _: &[u8; 32], + ) -> Result<(), crate::security::secret_storage::SecretStorageError> { + Ok(()) + } +} + +/// A context serving SaaS tenant `profile`, as the profile host binds one. +fn tenant_context( + workspace: &Path, + profile: &str, +) -> std::sync::Arc { + use crate::core::runtime::{ContextOverlay, CoreContext, DomainSet}; + use crate::tools::toolpacks::ToolGroups; + let mut config = crate::config::Config::default(); + config.workspace_dir = workspace.to_path_buf(); + CoreContext::for_test_with_config(DomainSet::full(), config.clone()).derive_with( + ContextOverlay::new(config, DomainSet::full(), ToolGroups::none()).profile(profile), + ) +} + +// Current-thread runtime: the key source slot is thread-local in unit tests. +#[tokio::test(flavor = "current_thread")] +async fn a_tenant_store_keeps_its_document_and_lock_in_the_configured_backend() { + crate::security::secret_storage::install_master_key_source(std::sync::Arc::new( + FixedStorageKey, + )); + let backend = crate::storage::test_support::memory_backend(); + let _installed = + crate::storage::test_support::install_backend_for_test(std::sync::Arc::clone(&backend)); + let root = tempfile::TempDir::new().unwrap(); + let tenant_dir = root.path().join("users").join("alice"); + std::fs::create_dir_all(tenant_dir.join("workspace")).unwrap(); + + let ctx = tenant_context(&tenant_dir.join("workspace"), "alice"); + let loaded = crate::core::runtime::CoreContext::scope(ctx, async { + let store = AuthProfilesStore::new(&tenant_dir, false); + store + .upsert_profile( + AuthProfile::new_token("openai", "default", "tenant-secret".into()), + true, + ) + .await + .unwrap(); + store.load().await.unwrap() + }) + .await; + crate::security::secret_storage::clear_master_key_source(); + + assert_eq!( + loaded.profiles["openai:default"].token.as_deref(), + Some("tenant-secret") + ); + let beside: Vec = std::fs::read_dir(&tenant_dir) + .unwrap() + .flatten() + .map(|entry| entry.file_name().to_string_lossy().into_owned()) + .collect(); + assert!( + !beside.iter().any(|name| name.contains("auth")), + "the backend owns a tenant's auth profiles and their lock: {beside:?}" + ); + let scope = crate::storage::scope_for_profile("alice"); + let secrets = crate::storage::secrets::over( + &backend.for_scope(&scope.to_storage_scope()).unwrap(), + scope, + crate::storage::secrets::keys().unwrap(), + ); + let stored = crate::storage::secrets::get_blocking(&secrets, PROFILE_DOCUMENT_SECRET_NAME) + .unwrap() + .expect("the document lives in the tenant's scope on the backend"); + assert!(!String::from_utf8_lossy(&stored).is_empty()); +} diff --git a/crates/openhuman-core/src/doctor/README.md b/crates/openhuman-core/src/doctor/README.md index a479b63a19c..d038b3057b1 100644 --- a/crates/openhuman-core/src/doctor/README.md +++ b/crates/openhuman-core/src/doctor/README.md @@ -29,6 +29,13 @@ contain sensitive data. A passing check uses “No action required.” as its hi | `connect` | Static checks and bounded, read-only connectivity probes. This is the default. | 10 seconds per check. | | `live` | Static and connect checks plus probes that may incur inference cost or write disposable remote test data. | 60 seconds per check. | +The live chat and embedding probes build inspection-only models from the +selected profile's frozen, read-only credential and send one fixed probe +string. The doctor never loads TinySecurity, so these models carry no +TinySecurity egress guard; instead the host's local-only privacy check runs +before either probe is built, as it does for every other inference route. +Ordinary inference and embedding traffic keeps the TinySecurity guard. + The runner allows at most eight checks at once. Synchronous checks run on Tokio's blocking pool; async checks stay on the runtime. A timeout or failed worker becomes an error finding and does not stop sibling checks. Tier and diff --git a/crates/openhuman-core/src/doctor/checks/embeddings_live_tests.rs b/crates/openhuman-core/src/doctor/checks/embeddings_live_tests.rs index de20750b21b..e9cc1246bbe 100644 --- a/crates/openhuman-core/src/doctor/checks/embeddings_live_tests.rs +++ b/crates/openhuman-core/src/doctor/checks/embeddings_live_tests.rs @@ -123,3 +123,162 @@ async fn managed_inspection_does_not_fall_back_to_the_mutable_provider_factory() assert_eq!(calls.load(Ordering::SeqCst), 0); } + +/// The selected config routes embeddings to the managed cloud provider with a +/// two-wide model, so a loopback mock can answer the expected width. +fn managed_config_in(tmp: &TempDir) -> Config { + let mut config = config_in(tmp, String::new()); + config.local_ai.base_url = None; + config.memory.embedding_provider = "cloud".to_owned(); + config.memory.embedding_model = "managed-test-model".to_owned(); + config.memory.embedding_dimensions = 2; + config +} + +/// Registers, for one context only, the host's inspection-safe managed +/// embedder: a frozen bearer and no TinySecurity egress guard, which is the +/// shape `openhuman-tinyhumans` registers for the doctor. +fn inspection_embedder_at(base_url: String) -> Extensions { + let extensions = Extensions::new(); + crate::inference::registry::register_inspection_embedding_in( + &extensions, + PROVIDER_OPENHUMAN, + move |request| { + let base_url = format!("{base_url}/openai/v1"); + Box::pin(async move { + let bearer: tinyinference_embeddings::BearerResolver = + Arc::new(|| Box::pin(async { Ok("frozen-doctor-bearer".to_owned()) })); + Ok(Box::new(tinyinference_embeddings::CloudEmbeddingModel::new( + base_url, + request.model, + request.dimensions, + bearer, + )) + as Box) + }) + }, + ); + extensions +} + +async fn mock_managed_embeddings() -> (String, Arc) { + let calls = Arc::new(AtomicUsize::new(0)); + let app = Router::new() + .route( + "/openai/v1/embeddings", + post( + |State(calls): State>, Json(_body): Json| async move { + calls.fetch_add(1, Ordering::SeqCst); + Json(serde_json::json!({ + "object": "list", + "data": [{ "object": "embedding", "index": 0, "embedding": [0.5, 0.25] }], + "model": "managed-test-model", + })) + }, + ), + ) + .with_state(Arc::clone(&calls)); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind managed embedding mock"); + let endpoint = format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port()); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + (endpoint, calls) +} + +async fn detect_managed(base_url: String, tmp: &TempDir) -> Vec { + detect_managed_with(base_url, managed_config_in(tmp)).await +} + +async fn detect_managed_with(base_url: String, config: Config) -> Vec { + let ctx = DoctorCtx::from_config(config); + let context = CoreContext::for_test_with_extensions( + DomainSet::full(), + None, + inspection_embedder_at(base_url), + ); + CoreContext::scope(context, async { EmbeddingsLiveCheck.detect(&ctx).await }).await +} + +#[tokio::test] +async fn managed_probe_passes_without_loading_the_security_module() { + let tmp = TempDir::new().expect("temporary config and workspace"); + let (endpoint, calls) = mock_managed_embeddings().await; + + let findings = detect_managed(endpoint, &tmp).await; + + assert_eq!(calls.load(Ordering::SeqCst), 1, "one fixed probe request"); + assert_eq!(findings.len(), 1); + assert_eq!( + findings[0].severity, + FindingSeverity::Pass, + "{}", + findings[0].message + ); +} + +#[tokio::test] +async fn managed_probe_reports_an_unreachable_endpoint_as_an_error() { + let tmp = TempDir::new().expect("temporary config and workspace"); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("reserve a local port"); + let closed = format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port()); + drop(listener); + + let findings = detect_managed(closed, &tmp).await; + + assert_eq!(findings.len(), 1); + assert_eq!(findings[0].severity, FindingSeverity::Error); + assert!( + findings[0] + .message + .contains("could not complete the live probe"), + "{}", + findings[0].message + ); +} + +#[tokio::test] +async fn local_only_privacy_refuses_the_managed_probe_before_any_request() { + let _privacy = + crate::security::live_policy::test_privacy_scope(crate::config::PrivacyMode::LocalOnly); + let tmp = TempDir::new().expect("temporary config and workspace"); + let (endpoint, calls) = mock_managed_embeddings().await; + + let findings = detect_managed(endpoint, &tmp).await; + + assert_eq!( + calls.load(Ordering::SeqCst), + 0, + "local-only mode keeps the probe on this machine" + ); + assert_eq!(findings.len(), 1); + assert_eq!(findings[0].severity, FindingSeverity::Error); +} + +/// Inspection boot installs no live policy, so the live mode reads the +/// Standard fallback; the selected config's own `local_only` mode must still +/// keep the managed probe (and its credential) on this machine. +#[tokio::test] +async fn a_local_only_selected_config_refuses_the_managed_probe_without_a_live_policy() { + let tmp = TempDir::new().expect("temporary config and workspace"); + let (endpoint, calls) = mock_managed_embeddings().await; + let mut config = managed_config_in(&tmp); + config.privacy.mode = crate::config::PrivacyMode::LocalOnly; + assert_eq!( + crate::security::live_policy::current_privacy_mode(), + crate::config::PrivacyMode::Standard, + "no live policy is installed for an inspection" + ); + + let findings = detect_managed_with(endpoint, config).await; + + assert_eq!( + calls.load(Ordering::SeqCst), + 0, + "the selected local-only config keeps the probe on this machine" + ); + assert_eq!(findings.len(), 1); + assert_eq!(findings[0].severity, FindingSeverity::Error); +} diff --git a/crates/openhuman-core/src/inference/embedding_host/factory.rs b/crates/openhuman-core/src/inference/embedding_host/factory.rs index d0323bec8e1..9cdf38937b5 100644 --- a/crates/openhuman-core/src/inference/embedding_host/factory.rs +++ b/crates/openhuman-core/src/inference/embedding_host/factory.rs @@ -70,12 +70,24 @@ pub(super) fn managed_factory( }) } +/// The doctor's managed embedding factory. The host's inspection embedder +/// freezes a read-only credential and carries no TinySecurity egress guard (the +/// doctor never loads the module), exactly like the doctor's chat probe. Like +/// that probe, the host-side local-only check runs here first, so a local-only +/// privacy mode still keeps the probe on this machine. Inspection installs no +/// live policy, so the selected config's own mode is checked as well. fn inspection_managed_factory(config: &Config) -> ManagedModelFactory { let config = config.clone(); Arc::new(move |model, dimensions| { let model = model.to_owned(); let config = config.clone(); Box::pin(async move { + crate::inference::provider::factory::access_gates::enforce_local_only_inference_for( + &config, + "embeddings", + PROVIDER_OPENHUMAN, + ) + .map_err(|error| tinyinference_embeddings::Error::Validation(error.to_string()))?; let Some(registered) = crate::inference::registry::inspection_embedding(PROVIDER_OPENHUMAN) else { diff --git a/crates/openhuman-core/src/inference/provider/factory/access_gates.rs b/crates/openhuman-core/src/inference/provider/factory/access_gates.rs index dc324a96bb4..16cc6db9445 100644 --- a/crates/openhuman-core/src/inference/provider/factory/access_gates.rs +++ b/crates/openhuman-core/src/inference/provider/factory/access_gates.rs @@ -211,7 +211,7 @@ pub(super) fn enforce_local_only_endpoint(role: &str, endpoint: &str) -> anyhow: /// an external chat provider when the live policy is local-only. Reads the live /// privacy mode (defaults to `Standard`/allow when no session policy is /// installed). See [`local_only_violation`] for the pure decision. -pub(super) fn enforce_local_only_inference(role: &str, provider: &str) -> anyhow::Result<()> { +pub(crate) fn enforce_local_only_inference(role: &str, provider: &str) -> anyhow::Result<()> { let mode = crate::security::live_policy::current_privacy_mode(); match local_only_violation(mode, provider) { None => { @@ -230,14 +230,40 @@ pub(super) fn enforce_local_only_inference(role: &str, provider: &str) -> anyhow provider.trim(), label ); - anyhow::bail!( - "Local-only privacy mode is active: this action needs external provider {label}. \ - Switch to a local model (Ollama/LM Studio/etc.) or change privacy mode in Settings." - ) + Err(local_only_refusal(&label)) } } } +/// [`enforce_local_only_inference`] for a model built from a selected config +/// that may have no live policy behind it (the doctor's inspection boot +/// installs none, so the live mode reads its `Standard` fallback). The selected +/// config's own privacy mode refuses as well, and the live policy still does, +/// so a hot-swapped `LocalOnly` blocks a config saved as `Standard`. +pub(crate) fn enforce_local_only_inference_for( + config: &crate::config::Config, + role: &str, + provider: &str, +) -> anyhow::Result<()> { + if let Some(label) = local_only_violation(config.privacy.mode, provider) { + log::warn!( + "[privacy][chat-factory] LocalOnly BLOCK (selected config): role={} external provider='{}' ({}) refused", + role, + provider.trim(), + label + ); + return Err(local_only_refusal(&label)); + } + enforce_local_only_inference(role, provider) +} + +fn local_only_refusal(label: &str) -> anyhow::Error { + anyhow::anyhow!( + "Local-only privacy mode is active: this action needs external provider {label}. \ + Switch to a local model (Ollama/LM Studio/etc.) or change privacy mode in Settings." + ) +} + /// Egress spine (privacy epic S2, #4436): emit an [`EgressDescriptor`] for a /// concrete inference provider string. `provider` is expected to be already /// resolved (no `""` / `"cloud"` / BYOK sentinels — those are handled before diff --git a/crates/openhuman-core/src/media/README.md b/crates/openhuman-core/src/media/README.md index a0e5e7940d6..9b89eb69d6f 100644 --- a/crates/openhuman-core/src/media/README.md +++ b/crates/openhuman-core/src/media/README.md @@ -67,9 +67,10 @@ Inside `generation/`: ## Key types and entry points -- `media_tools_for_config(generators, &Config, &Path, allowlist)` +- `media_tools_for_config(generators, &Config, &Path, allowlist).await` ([`generation/tools.rs`](./generation/tools.rs)) is the entry point a host's - tool source calls. + tool source calls. It is async because it fetches TinySecurity's + protected-path floor once for the reference policy. - `MediaGenerators` ([`generation/provider.rs`](./generation/provider.rs)) is the image + video pair the tools run over; `MediaGenerators::with_router` lets a host rebuild them per chat. @@ -110,8 +111,20 @@ Inside `generation/`: starts with `media_` (`tool_group()` in `tools/ops.rs`). Nothing else is tagged `DomainGroup::Media`. - Local reference files are limited by `reference_policy` to the action - directory or workspace, with no `..` and nothing under an always-forbidden - path (credential stores, system roots). Anything else must be an https URL. + directory or workspace, with no `..` and nothing TinySecurity's protected + floor covers (credential stores and pairs, system roots), session-filed + artifacts included. The path is resolved first (`.` segments, symlinks); + the floor is asked about the path as named and as resolved, the roots are + matched against the resolved path, and the resolved path is what is read. + The policy is a sync callback, so it asks TinySecurity's own + `ProtectedPath2` per path through the bounded sync bridge + (`modules::security::text::protected_path_check`, reached through the + builder's `root_config` by `ReferenceFloor::fetch`); the host keeps no copy + of the floor algorithm. Security disabled skips the floor, as + `SecurityPolicy::is_always_forbidden_async` does; a module that cannot + answer refuses every local reference (and so does the sync + `media_tools_from`). A refusal is logged by category only, never by path. + Anything else must be an https URL. ## Tests diff --git a/crates/openhuman-core/src/media/generation/README.md b/crates/openhuman-core/src/media/generation/README.md index b5b4c59f07f..1bdcce20706 100644 --- a/crates/openhuman-core/src/media/generation/README.md +++ b/crates/openhuman-core/src/media/generation/README.md @@ -23,7 +23,7 @@ layers, each with a different owner: | File | Role | | --- | --- | | [`provider.rs`](./provider.rs) | `MediaGenerators { image, video }` and `GeneratorRouter`: the pair the tools run over, with an optional router that rebuilds them around a turn's chat so egress disclosures reach it. The core ships no generators. | -| [`tools.rs`](./tools.rs) | `media_tools_for_config`: registers `media_generate_image`, `media_generate_video`, and `media_list_models` as `Tool` implementations over host-supplied generators. Also defines `reference_policy`, which restricts local reference files (for image edits or video first/last frames) to the action directory or workspace directory. | +| [`tools.rs`](./tools.rs) | `media_tools_for_config`: registers `media_generate_image`, `media_generate_video`, and `media_list_models` as `Tool` implementations over host-supplied generators. Also defines `reference_policy`, which restricts local reference files (for image edits or video first/last frames) to the action directory or workspace directory, outside TinySecurity's protected floor (`ReferenceFloor`, fetched once per tool set; fails closed when unavailable). | | [`artifact_tool.rs`](./artifact_tool.rs) | `MediaArtifactTool`: wraps a generation tool so every file it saves is also tracked as an OpenHuman artifact, through the same `Production` flow (reserve, write, complete) the document and presentation tools use. Runs the inner tool unchanged, then files each reported output and stamps an `artifact_id` (or `artifact_error`) onto its entry. | | [`progress.rs`](./progress.rs) | Progress for a long generation call: a heartbeat every 15s through `ToolRunContext::report_progress` while the inner tool runs, carrying the video job state the `WaitPolicy::progress` observer records on each poll. The harness emits these as `AgentEvent::ToolProgressDetail`, which the host publishes on the web channel as `tool_progress`; the chat UI does not render it yet. | | [`mod.rs`](./mod.rs) | Re-exports: `MediaArtifactTool`, `MediaGenerators`, `GeneratorRouter`, `media_tools_for_config`, `media_tools_from`, `MediaReferenceAllowlist`, `MediaListModelsTool`, and the three tool-name constants. | diff --git a/crates/openhuman-core/src/media/generation/tools.rs b/crates/openhuman-core/src/media/generation/tools.rs index 642801a392d..035fea8d479 100644 --- a/crates/openhuman-core/src/media/generation/tools.rs +++ b/crates/openhuman-core/src/media/generation/tools.rs @@ -55,13 +55,16 @@ const VIDEO_DESCRIPTION: &str = "Generate a short video clip via OpenRouter (def /// reference-file policy, the files roots and the video wait come from /// `root_config`; `allowed_references` is the session's shared allowlist of /// artifact paths. The generators come from the host that owns the media -/// service (the core has none of its own). -pub fn media_tools_for_config( +/// service (the core has none of its own). TinySecurity's protected-path +/// floor is reached here, through `root_config`'s module, for the sync +/// reference policy. +pub async fn media_tools_for_config( generators: MediaGenerators, root_config: &Config, action_dir: &Path, allowed_references: MediaReferenceAllowlist, ) -> Vec> { + let floor = ReferenceFloor::fetch(Some(root_config)).await; media_tools_from_with_allowlist( generators, action_dir, @@ -72,12 +75,15 @@ pub fn media_tools_for_config( // multi-minute wait is not silent. WaitPolicy::new(VIDEO_POLL_INTERVAL, VIDEO_WAIT_BUDGET), allowed_references, + floor, ) } /// Builds the tool set over any generators (the managed ones in production, /// mocks in tests), writing under `action_dir`; `video_wait` bounds each -/// video job. +/// video job. It has no async context to fetch TinySecurity's protected-path +/// floor, so it fails closed: local reference files are refused and URL +/// references still work. pub fn media_tools_from( generators: MediaGenerators, action_dir: &Path, @@ -92,6 +98,7 @@ pub fn media_tools_from( files_dir, video_wait, Arc::new(Mutex::new(HashSet::new())), + ReferenceFloor::Unavailable("media_tools_from does not fetch TinySecurity's floor".into()), ) } @@ -102,6 +109,7 @@ fn media_tools_from_with_allowlist( files_dir: impl Into, video_wait: WaitPolicy, allowed_artifacts: MediaReferenceAllowlist, + floor: ReferenceFloor, ) -> Vec> { let files = files_dir.into(); let generators = Arc::new(generators); @@ -113,6 +121,7 @@ fn media_tools_from_with_allowlist( action_dir, workspace_dir, Arc::clone(&allowed_artifacts), + floor, )); let output_blobs = Arc::clone(&output.blobs); let image_tool = |image: &Arc| { @@ -208,33 +217,192 @@ fn video_tool( .with_wait_policy(wait) } +/// A synchronous TinySecurity floor decision for one path: `Ok(true)` when +/// `ProtectedPath2` reports it protected. +pub(crate) type ProtectedPathCheck = Arc Result + Send + Sync>; + +/// TinySecurity's protected-path floor for local reference files. The +/// reference policy is a sync callback, so it asks the module through the +/// bounded sync bridge (`modules::security::text::protected_path_check`): the +/// decision is TinySecurity's own `ProtectedPath2`, not a host copy of it. +#[derive(Clone)] +pub(crate) enum ReferenceFloor { + /// Security is disabled, so no floor applies; the same switch as + /// `SecurityPolicy::is_always_forbidden_async` for the other file tools. + Disabled, + /// TinySecurity answers for each path. A failed answer refuses the path. + Enforced(ProtectedPathCheck), + /// The floor could not be reached: every local reference is refused. + Unavailable(String), +} + +impl std::fmt::Debug for ReferenceFloor { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Disabled => f.write_str("Disabled"), + Self::Enforced(_) => f.write_str("Enforced(..)"), + Self::Unavailable(why) => f.debug_tuple("Unavailable").field(why).finish(), + } + } +} + +/// Why a reference was refused, for the log: never the path itself. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Refusal { + Traversal, + FloorUnavailable, + Protected, + OutsideRoots, +} + +impl Refusal { + fn as_str(self) -> &'static str { + match self { + Self::Traversal => "parent_traversal", + Self::FloorUnavailable => "floor_unavailable", + Self::Protected => "protected_floor", + Self::OutsideRoots => "outside_roots", + } + } +} + +impl ReferenceFloor { + /// Asks TinySecurity, through `config`'s module, for its floor unless + /// security is disabled for `config` (or the process). With no `config` + /// the current dispatch's is used. A module that cannot answer fails + /// closed. + pub(crate) async fn fetch(config: Option<&Config>) -> Self { + if let Some(reason) = crate::security::switch::disabled_for(config) { + log::debug!( + "[media][reference] security disabled ({}); no protected floor", + reason.describe() + ); + return Self::Disabled; + } + #[cfg(feature = "security-module")] + { + match crate::modules::security::text::protected_path_check(config).await { + Ok(check) => Self::Enforced(check), + Err(error) => { + log::debug!( + "[media][reference] protected floor unavailable; local references refused: {error}" + ); + Self::Unavailable(error) + } + } + } + #[cfg(not(feature = "security-module"))] + { + Self::Unavailable("TinySecurity is not built into this host".into()) + } + } + + /// Why `paths` (the path as named and as resolved) may not be read as a + /// reference, when the floor covers any of them or cannot answer. + fn refusal(&self, named: &Path, paths: &[&Path]) -> Option<(Refusal, String)> { + let unavailable = || { + ( + Refusal::FloorUnavailable, + format!( + "reference path {} refused: TinySecurity's protected-path floor is unavailable, \ + so local reference files cannot be checked; use a URL instead", + named.display() + ), + ) + }; + match self { + Self::Disabled => None, + Self::Unavailable(_) => Some(unavailable()), + Self::Enforced(check) => { + for path in paths { + match check(path) { + Ok(false) => {} + Ok(true) => { + return Some(( + Refusal::Protected, + format!( + "reference path {} is in a protected location (a credential \ + store or system directory); use a URL or a file inside the \ + workspace", + named.display() + ), + )) + } + Err(_) => return Some(unavailable()), + } + } + None + } + } + } +} + +/// `path` with its `.` segments and symlinks resolved. A path that cannot be +/// resolved (missing, or unreadable to this process) is only normalized +/// lexically: nothing can be read from it, and `..` is refused before this +/// runs. +fn resolve(path: &Path) -> PathBuf { + path.canonicalize().unwrap_or_else(|_| { + path.components() + .filter(|component| !matches!(component, Component::CurDir)) + .collect() + }) +} + /// Local reference files may be read and uploaded only from the action /// directory or the workspace directory, never through `..`, and never from -/// an always-forbidden location (credential stores, system roots). +/// a location TinySecurity's protected floor covers (credential stores, +/// system roots) — session-filed artifacts included. The path is resolved +/// (`.` segments, symlinks) first; the floor is asked about the path as named +/// and as resolved, the roots are matched against the resolved path, and the +/// resolved path is what is returned for reading. pub(crate) fn reference_policy( action_dir: &Path, workspace_dir: &Path, allowed_artifacts: MediaReferenceAllowlist, + floor: ReferenceFloor, ) -> tinyagents_harness::media::ReferencePathPolicy { - let roots: Vec = vec![action_dir.to_path_buf(), workspace_dir.to_path_buf()]; + let mut roots: Vec = Vec::new(); + for root in [action_dir, workspace_dir] { + roots.push(root.to_path_buf()); + if let Ok(resolved) = root.canonicalize() { + roots.push(resolved); + } + } Arc::new(move |path: &Path| { + let refuse = |refusal: Refusal, message: String| { + tracing::debug!( + category = refusal.as_str(), + "[media][reference] refused local reference" + ); + Err(message) + }; if path.components().any(|c| matches!(c, Component::ParentDir)) { - return Err(format!( - "reference path {} may not contain '..'", - path.display() - )); + return refuse( + Refusal::Traversal, + format!("reference path {} may not contain '..'", path.display()), + ); } - let is_filed_artifact = allowed_artifacts - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .contains(path); - if !is_filed_artifact && !roots.iter().any(|root| path.starts_with(root)) { - return Err(format!( - "reference path {} is outside the workspace; use a URL or a file inside the workspace", - path.display() - )); + let resolved = resolve(path); + if let Some((refusal, message)) = floor.refusal(path, &[path, &resolved]) { + return refuse(refusal, message); + } + let is_filed_artifact = { + let allowed = allowed_artifacts + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + allowed.contains(path) || allowed.contains(&resolved) + }; + if !is_filed_artifact && !roots.iter().any(|root| resolved.starts_with(root)) { + return refuse( + Refusal::OutsideRoots, + format!( + "reference path {} is outside the workspace; use a URL or a file inside the workspace", + path.display() + ), + ); } - Ok(path.to_path_buf()) + Ok(resolved) }) } diff --git a/crates/openhuman-core/src/media/generation/tools_tests.rs b/crates/openhuman-core/src/media/generation/tools_tests.rs index 998dab33e7a..06dece722da 100644 --- a/crates/openhuman-core/src/media/generation/tools_tests.rs +++ b/crates/openhuman-core/src/media/generation/tools_tests.rs @@ -1,5 +1,5 @@ use std::collections::HashSet; -use std::path::Path; +use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex}; use serde_json::json; @@ -8,7 +8,8 @@ use tinyagents_harness::tinyinference_video::{MockVideoGenerator, MockVideoScrip use tinytools::{PermissionLevel, Tool, ToolCategory}; use super::{ - media_tools_from, reference_policy, IMAGE_TOOL_NAME, LIST_MODELS_TOOL_NAME, VIDEO_TOOL_NAME, + media_tools_from, reference_policy, ReferenceFloor, IMAGE_TOOL_NAME, LIST_MODELS_TOOL_NAME, + VIDEO_TOOL_NAME, }; use crate::media::generation::MediaGenerators; @@ -126,12 +127,59 @@ async fn list_models_reports_both_catalogs_and_defaults() { ); } -#[test] -fn reference_policy_admits_workspace_files_only() { +/// A scripted stand-in for TinySecurity's `ProtectedPath2` answer over the +/// names these tests use (credential stores, pairs, system roots, a Windows +/// root under any drive), case-insensitive as the module is. What the module +/// itself answers is pinned by `reference_policy_asks_tinysecurity_for_each_path`. +fn floor() -> ReferenceFloor { + ReferenceFloor::Enforced(Arc::new(|path: &Path| { + let lowered = path + .to_string_lossy() + .to_ascii_lowercase() + .replace('\\', "/"); + let segments: Vec<&str> = lowered.split('/').filter(|s| !s.is_empty()).collect(); + let stores = [ + ".ssh", + ".gnupg", + ".aws", + "keychains", + ".netrc", + ".git-credentials", + ]; + let pairs = [[".cargo", "credentials.toml"], ["microsoft", "credentials"]]; + let windows_root = segments.len() > 1 + && segments[0].len() == 2 + && segments[0].ends_with(':') + && segments[1] == "windows"; + Ok(segments.iter().any(|segment| stores.contains(segment)) + || segments + .windows(2) + .any(|w| pairs.iter().any(|[a, b]| w[0] == *a && w[1] == *b)) + || ["/etc", "/root"] + .iter() + .any(|root| lowered == *root || lowered.starts_with(&format!("{root}/"))) + || windows_root) + })) +} + +fn policy_over( + floor: ReferenceFloor, +) -> ( + &'static Path, + &'static Path, + super::MediaReferenceAllowlist, + tinyagents_harness::media::ReferencePathPolicy, +) { let action = Path::new("/home/user/OpenHuman/projects"); let workspace = Path::new("/home/user/.openhuman/users/u/workspace"); let allowed_artifacts = Arc::new(Mutex::new(HashSet::new())); - let policy = reference_policy(action, workspace, Arc::clone(&allowed_artifacts)); + let policy = reference_policy(action, workspace, Arc::clone(&allowed_artifacts), floor); + (action, workspace, allowed_artifacts, policy) +} + +#[test] +fn reference_policy_admits_workspace_files_only() { + let (action, workspace, allowed_artifacts, policy) = policy_over(floor()); assert!(policy(&action.join("art/ref.png")).is_ok()); assert!(policy(&workspace.join("attachments/photo.jpg")).is_ok()); @@ -150,3 +198,280 @@ fn reference_policy_admits_workspace_files_only() { "credential stores stay forbidden" ); } + +/// With the working folder set to the user's home, the floor still keeps +/// credential stores, credential pairs and system roots out of uploads. +#[test] +fn reference_policy_applies_the_protected_floor_inside_the_roots() { + let home = Path::new("/home/user"); + let allowed = Arc::new(Mutex::new(HashSet::new())); + let policy = reference_policy(home, Path::new("/root/.openhuman"), allowed, floor()); + + assert!(policy(&home.join("Pictures/cat.png")).is_ok()); + for refused in [ + home.join(".ssh/id_rsa"), + home.join(".SSH/id_rsa"), + home.join(".aws/credentials"), + home.join(".netrc"), + home.join("Library/Keychains/login.keychain-db"), + home.join(".cargo/credentials.toml"), + home.join(".Cargo/Credentials.toml"), + home.join("AppData/Roaming/Microsoft/Credentials/blob"), + PathBuf::from("/root/.openhuman/attachments/photo.png"), + PathBuf::from("/etc/ssl/private.png"), + ] { + let refusal = + policy(&refused).expect_err(&format!("{} must be refused", refused.display())); + assert!( + refusal.contains("protected"), + "{}: {refusal}", + refused.display() + ); + } + assert!( + policy(&home.join(".cargo/config.toml")).is_ok(), + "a pair matches only as a pair" + ); + assert!( + policy(&home.join("etc/notes.png")).is_ok(), + "a system prefix matches only at the root" + ); +} + +/// The Windows system roots are named with a `c:` drive; TinySecurity +/// matches them under every drive letter. +#[test] +fn reference_policy_matches_windows_system_roots_on_any_drive() { + let allowed = Arc::new(Mutex::new(HashSet::new())); + let root = Path::new("D:\\"); + let policy = reference_policy(root, root, allowed, floor()); + let refusal = policy(Path::new("D:\\Windows\\System32\\img.png")).unwrap_err(); + assert!(refusal.contains("protected"), "{refusal}"); + // Off Windows the backslash path is one component, so the roots check may + // still refuse it; the floor must not. + if let Err(other) = policy(Path::new("D:\\Pictures\\img.png")) { + assert!(!other.contains("protected"), "{other}"); + } +} + +/// A file the session filed itself still answers to the floor. +#[test] +fn reference_policy_refuses_a_filed_artifact_inside_a_credential_store() { + let (_, _, allowed_artifacts, policy) = policy_over(floor()); + let filed = PathBuf::from("/home/user/.gnupg/generated.png"); + allowed_artifacts.lock().unwrap().insert(filed.clone()); + let refusal = policy(&filed).unwrap_err(); + assert!(refusal.contains("protected"), "{refusal}"); +} + +/// No floor, no local references: every path is refused, even inside the +/// workspace. +#[test] +fn reference_policy_fails_closed_without_the_floor() { + let (action, workspace, allowed_artifacts, policy) = + policy_over(ReferenceFloor::Unavailable("module unavailable".into())); + let filed = PathBuf::from("/tmp/generated.png"); + allowed_artifacts.lock().unwrap().insert(filed.clone()); + for path in [action.join("art/ref.png"), workspace.join("a.jpg"), filed] { + let refusal = policy(&path).unwrap_err(); + assert!(refusal.contains("use a URL"), "{refusal}"); + } +} + +/// Security disabled: no floor, as for the other file tools; the roots and +/// `..` checks still apply. +#[test] +fn reference_policy_without_security_keeps_only_the_roots() { + let (action, _, _, policy) = policy_over(ReferenceFloor::Disabled); + assert!(policy(&action.join(".ssh/id_rsa")).is_ok()); + assert!(policy(Path::new("/etc/passwd")).is_err()); + assert!(policy(&action.join("../x.png")).is_err()); +} + +/// The real TinySecurity module answers each path (`ProtectedPath2`), reached +/// through the builder's own config with no ambient dispatch context, as a +/// SaaS tool build has. +#[cfg(feature = "security-module")] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn reference_policy_asks_tinysecurity_for_each_path() { + let config = crate::modules::security::test_host::boot().expect("staged TinySecurity module"); + assert!(crate::core::runtime::CoreContext::current_embedder_config().is_none()); + let fetched = ReferenceFloor::fetch(Some(&config)).await; + assert!( + matches!(fetched, ReferenceFloor::Enforced(_)), + "{fetched:?}" + ); + + let home = tempfile::tempdir().unwrap(); + let home = home.path().canonicalize().unwrap(); + for file in [ + "Pictures/cat.png", + ".ssh/id_rsa", + ".SSH/id_rsa", + ".aws/credentials", + ".netrc", + ".cargo/credentials.toml", + ".cargo/config.toml", + ] { + std::fs::create_dir_all(home.join(file).parent().unwrap()).unwrap(); + std::fs::write(home.join(file), b"fixture").unwrap(); + } + let allowed = Arc::new(Mutex::new(HashSet::new())); + let policy = reference_policy(&home, &home, allowed, fetched); + let policy = move |path: PathBuf| { + let policy = Arc::clone(&policy); + std::thread::spawn(move || policy(&path)).join().unwrap() + }; + + assert_eq!( + policy(home.join("Pictures/cat.png")).unwrap(), + home.join("Pictures/cat.png") + ); + assert!( + policy(home.join(".cargo/config.toml")).is_ok(), + "a pair matches only as a pair" + ); + for refused in [ + home.join(".ssh/id_rsa"), + home.join(".SSH/id_rsa"), + home.join(".aws/credentials"), + home.join(".netrc"), + home.join(".cargo/credentials.toml"), + home.join(".cargo/./credentials.toml"), + PathBuf::from("/etc/passwd"), + ] { + let refusal = + policy(refused.clone()).expect_err(&format!("{} must be refused", refused.display())); + assert!( + refusal.contains("protected"), + "{}: {refusal}", + refused.display() + ); + } +} + +#[cfg(feature = "security-module")] +#[tokio::test] +async fn reference_floor_is_fetched_from_tinysecurity_and_fails_closed() { + use crate::modules::security::gap::{ + install_path_floor_port, install_unavailable_path_floor_port, ScriptedPathFloorPort, + }; + { + let protected = PathBuf::from("/home/user/OpenHuman/projects/.ssh/id_rsa"); + let _port = install_path_floor_port(ScriptedPathFloorPort::new([protected], Vec::new())); + let fetched = ReferenceFloor::fetch(None).await; + assert!( + matches!(fetched, ReferenceFloor::Enforced(_)), + "{fetched:?}" + ); + let (action, _, _, policy) = policy_over(fetched); + assert!(policy(&action.join("a.png")).is_ok()); + assert!(policy(&action.join(".ssh/id_rsa")).is_err()); + } + let _port = install_unavailable_path_floor_port(); + let fetched = ReferenceFloor::fetch(None).await; + assert!( + matches!(fetched, ReferenceFloor::Unavailable(_)), + "{fetched:?}" + ); +} + +/// The sync `media_tools_from` cannot fetch the floor, so a local reference +/// is refused while a URL reference still reaches the generator. +#[tokio::test] +async fn media_tools_from_refuses_local_references_but_not_urls() { + let dir = tempfile::tempdir().unwrap(); + let local = dir.path().join("ref.png"); + std::fs::write(&local, b"png").unwrap(); + let tools = tools(dir.path()); + let image = by_name(&tools, IMAGE_TOOL_NAME); + let refused = image + .execute(json!({ "prompt": "cat", "references": [local.display().to_string()] })) + .await; + let refused = format!("{refused:?}"); + assert!(refused.contains("use a URL"), "{refused}"); + let result = image + .execute(json!({ "prompt": "cat", "references": ["https://example.com/ref.png"] })) + .await + .unwrap(); + assert!(!result.is_error, "{result:?}"); +} + +/// `.` segments and symlinks are resolved before the floor and the roots are +/// checked, and the resolved path is what is handed back for reading. +#[test] +fn reference_policy_resolves_path_aliases_before_the_floor() { + let home = tempfile::tempdir().unwrap(); + let home = home.path().canonicalize().unwrap(); + std::fs::create_dir_all(home.join(".cargo")).unwrap(); + std::fs::write(home.join(".cargo/credentials.toml"), b"token").unwrap(); + std::fs::create_dir_all(home.join("art")).unwrap(); + std::fs::write(home.join("art/ref.png"), b"png").unwrap(); + let allowed = Arc::new(Mutex::new(HashSet::new())); + let policy = reference_policy(&home, &home, allowed, floor()); + + let aliased = home.join(".cargo/./credentials.toml"); + let refusal = policy(&aliased).expect_err("a '.' alias must not split a protected pair"); + assert!(refusal.contains("protected"), "{refusal}"); + #[cfg(unix)] + { + std::os::unix::fs::symlink(home.join(".cargo"), home.join("art/cfg")).unwrap(); + let refusal = policy(&home.join("art/cfg/credentials.toml")) + .expect_err("a symlink into a credential store is refused"); + assert!(refusal.contains("protected"), "{refusal}"); + } + assert_eq!( + policy(&home.join("art/./ref.png")).unwrap(), + home.join("art/ref.png"), + "the checked, resolved path is the one read" + ); +} + +#[derive(Clone, Default)] +struct Capture(Arc>>); + +impl std::io::Write for Capture { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + self.0.lock().unwrap().extend_from_slice(bytes); + Ok(bytes.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for Capture { + type Writer = Self; + + fn make_writer(&'a self) -> Self::Writer { + self.clone() + } +} + +/// A refused reference is logged by its category only: the tool already gets +/// the refusal, and a credential file's full local path stays out of the log. +#[test] +fn a_refused_reference_is_logged_without_its_path() { + let capture = Capture::default(); + let subscriber = tracing_subscriber::fmt() + .with_writer(capture.clone()) + .with_ansi(false) + .with_max_level(tracing::Level::TRACE) + .finish(); + let _guard = tracing::subscriber::set_default(subscriber); + let (_, _, _, policy) = policy_over(floor()); + let secret = "/home/user/.ssh/id_rsa_reference_log_probe"; + + assert!(policy(Path::new(secret)).is_err()); + + let logs = String::from_utf8(capture.0.lock().unwrap().clone()).unwrap(); + assert!( + logs.contains("[media][reference] refused local reference"), + "the refusal is still logged: {logs:?}" + ); + assert!( + !logs.contains("id_rsa_reference_log_probe"), + "the refused path is not logged: {logs:?}" + ); +} diff --git a/crates/openhuman-core/src/modules/registry/records_security.rs b/crates/openhuman-core/src/modules/registry/records_security.rs index ec7ae69f79e..f608b1994b4 100644 --- a/crates/openhuman-core/src/modules/registry/records_security.rs +++ b/crates/openhuman-core/src/modules/registry/records_security.rs @@ -1,4 +1,4 @@ -//! Published TinySecurity admission pins copied verbatim from v0.20.0/checksum.toml. +//! Published TinySecurity admission pins copied verbatim from v0.21.0/checksum.toml. //! //! `LoadPolicy::Eager` is the "load at boot" policy (the issue calls it Boot): a missing //! security module changes behaviour, so it must be serving before the first request. diff --git a/crates/openhuman-core/src/modules/registry_release_manifest_tests.rs b/crates/openhuman-core/src/modules/registry_release_manifest_tests.rs index f55bf5999b8..ceb31bccaef 100644 --- a/crates/openhuman-core/src/modules/registry_release_manifest_tests.rs +++ b/crates/openhuman-core/src/modules/registry_release_manifest_tests.rs @@ -2,13 +2,13 @@ use super::*; #[cfg(feature = "security-module")] #[test] -fn tinysecurity_registry_matches_the_verified_v0190_release_manifest() { +fn tinysecurity_registry_matches_the_published_release_manifest() { let security = find("tinysecurity").expect("compiled TinySecurity module"); - assert_eq!(security.version, "0.20.0"); - assert_eq!(tinysecurity_bus::CONTRACT_VERSION, (2, 1)); + assert_eq!(security.version, "0.21.0"); + assert_eq!(tinysecurity_bus::CONTRACT_VERSION, (2, 2)); assert_eq!( security.release_url, - "https://github.com/tinyhumansai/tinysecurity/releases/tag/v0.20.0" + "https://github.com/tinyhumansai/tinysecurity/releases/tag/v0.21.0" ); let mut actual = security @@ -20,58 +20,58 @@ fn tinysecurity_registry_matches_the_verified_v0190_release_manifest() { let mut published = [ ( "macos-15-arm64", - "tinysecurity-module-0.20.0-macos-15-arm64.tar.gz", - "d0c80a5fc21527d812504d64dc25aeadc55327f17ff938ed18d9b5da36800239", + "tinysecurity-module-0.21.0-macos-15-arm64.tar.gz", + "0f8e2e15f6a13951ecf8396bd472a83f65701d5e139aef9be89a74dd4daad4f9", ), ( "macos-15-x86_64", - "tinysecurity-module-0.20.0-macos-15-x86_64.tar.gz", - "6d351306f7d970715199c6e9b9e4b566e4ff29dfd94701d6ce19716bf03114c1", + "tinysecurity-module-0.21.0-macos-15-x86_64.tar.gz", + "478fab9d675009570de65d8be2863f89bb6b6f3a9a552af8ab229ae5638ef455", ), ( "macos-26-arm64", - "tinysecurity-module-0.20.0-macos-26-arm64.tar.gz", - "9f51e6bfda60aa7d44520130cf4a3e1e88e5fee7b423ca663a979926e79e3d30", + "tinysecurity-module-0.21.0-macos-26-arm64.tar.gz", + "d02e23e87b227e7e9f8933c0525dc99d7b81e896cd34877b145bce10ce5708cd", ), ( "macos-26-x86_64", - "tinysecurity-module-0.20.0-macos-26-x86_64.tar.gz", - "4668ee65802f5aa55b8c9310f8dd11a3a290ff4e121895ba73f1e7951ad9fb21", + "tinysecurity-module-0.21.0-macos-26-x86_64.tar.gz", + "c12af96a7c0348c3c3ca942abb317072cffe6c982d174e25c5b155c6b9895861", ), ( "ubuntu-22.04-arm64", - "tinysecurity-module-0.20.0-ubuntu-22.04-arm64.tar.gz", - "3b89af12be97ccac2a2593ff9886cd8f9cb7fcba5405fe04c9d0986e4d6c110c", + "tinysecurity-module-0.21.0-ubuntu-22.04-arm64.tar.gz", + "23ffa7b0cf576f1488a3b7419c0ee873425f4141e9f7899e08925909e4fcf068", ), ( "ubuntu-22.04-x86_64", - "tinysecurity-module-0.20.0-ubuntu-22.04-x86_64.tar.gz", - "d531a36c266cb467c1fc258543ed4713ddd2234930fc3beeba386b48e4bbe0ac", + "tinysecurity-module-0.21.0-ubuntu-22.04-x86_64.tar.gz", + "cad96e016358b44b0179c8e23f7492c98c0521b148a123cbcb84158e36cf2b32", ), ( "ubuntu-24.04-arm64", - "tinysecurity-module-0.20.0-ubuntu-24.04-arm64.tar.gz", - "745b0583c73703644da49b9c741c8c8a487ea24116d51b797133f3cea0a5d680", + "tinysecurity-module-0.21.0-ubuntu-24.04-arm64.tar.gz", + "5d05e1678aec9c27705090902c6a8027b55492dad6cbf036f67643c18368afc4", ), ( "ubuntu-24.04-x86_64", - "tinysecurity-module-0.20.0-ubuntu-24.04-x86_64.tar.gz", - "e694059c8f2e9f4da4265ae8523fa8d6643236a4eff745e5e4290ee6ffe06fa9", + "tinysecurity-module-0.21.0-ubuntu-24.04-x86_64.tar.gz", + "793637899fd71bc232b215a486c51d9e888ce0aee12bb924a362b9d0729d907e", ), ( "windows-11-arm64", - "tinysecurity-module-0.20.0-windows-11-arm64.zip", - "5c45a750b61315609a88fb487bab0a2ee87292c5f2eff6d4a19d46c93a53ca15", + "tinysecurity-module-0.21.0-windows-11-arm64.zip", + "d888f4e60df0fd7ecc2e9226695ab3541d83206203e391331b8a78e81f5dee0b", ), ( "windows-2022-x86_64", - "tinysecurity-module-0.20.0-windows-2022-x86_64.zip", - "282f9e8cfff87da92b0f0c0aba2650edaf10def411a3a7423d46d890adfaae26", + "tinysecurity-module-0.21.0-windows-2022-x86_64.zip", + "b500a2e6161b85a06ad54644dfdb685b9369aadd0d868a0cdc11ab18abf9693d", ), ( "windows-2025-x86_64", - "tinysecurity-module-0.20.0-windows-2025-x86_64.zip", - "77359a4c2b3c1207e98e8c36e86bd014d7933cffbd4889bc4e7fc36c53adf3e7", + "tinysecurity-module-0.21.0-windows-2025-x86_64.zip", + "260884a7ca22f99969a162b464a47caa78380aeb6e9b903d2fa274f84fe46f7b", ), ]; published.sort_unstable(); diff --git a/crates/openhuman-core/src/modules/security/gap.rs b/crates/openhuman-core/src/modules/security/gap.rs index 980a885e465..6512b6a2ac3 100644 --- a/crates/openhuman-core/src/modules/security/gap.rs +++ b/crates/openhuman-core/src/modules/security/gap.rs @@ -532,7 +532,15 @@ pub(crate) async fn protected_paths(paths: &[PathBuf]) -> Result, Stri let config = crate::core::runtime::DispatchCtx::ambient() .load_config() .await?; - let response = super::client(&config) + protected_paths_with_config(&config, paths).await +} + +/// `ProtectedPath2` through `config`'s module, without the test port. +pub(super) async fn protected_paths_with_config( + config: &crate::config::Config, + paths: &[PathBuf], +) -> Result, String> { + let response = super::client(config) .await .map_err(|error| error.to_string())? .protected_path2(tinysecurity_bus::ProtectedPathRequest2 { @@ -546,6 +554,12 @@ pub(crate) async fn protected_paths(paths: &[PathBuf]) -> Result, Stri Ok(response.protected) } +/// The scripted path floor installed on this thread, if any. +#[cfg(any(test, feature = "test-keyring-consent"))] +pub(super) fn installed_path_floor_port() -> Option> { + TEST_PATH_FLOOR_PORT.with(|slot| slot.borrow().clone()) +} + /// `ProtectedFloor2` vocabulary for consumers that hand the floor to a jail. pub(crate) async fn protected_floor() -> Result { #[cfg(test)] diff --git a/crates/openhuman-core/src/modules/security/policy.rs b/crates/openhuman-core/src/modules/security/policy.rs index ef3bc4591cf..57e78f53ad0 100644 --- a/crates/openhuman-core/src/modules/security/policy.rs +++ b/crates/openhuman-core/src/modules/security/policy.rs @@ -169,6 +169,20 @@ const _: () = assert!(KEYRING_CONSENT_TIMEOUT_MS <= 300_000); const AUDIT_CALLBACK_TIMEOUT_MS: u32 = 20_000; +/// Secret work (pending master grants, cipher operations) TinySecurity admits +/// at once. Every tenant's runtime registration draws on this one process-wide +/// budget, so the single-scope default of four refused a fifth tenant's grant +/// while four others were mid-approval. TinySecurity accepts 1..=32 and still +/// refuses, without queueing, beyond it. +const SECRET_MAX_IN_FLIGHT: u32 = 32; + +/// Secret cipher operations one registration may run per minute. Every read +/// of an encrypted credential document is one, and every agent of a runtime +/// shares its config directory's registration, so the default of 120 refused +/// a busy runtime's credential reads within a second. TinySecurity accepts +/// 1..=4096 and refuses, without queueing, beyond it. +const SECRET_OPERATIONS_PER_MINUTE: u32 = 4096; + /// Init-time subject is deliberately separate from every registered user /// subject. Real audit rows are sent through `RecordAudit2` to the per-subject /// stream registered by `security::approval::native`. @@ -262,7 +276,11 @@ pub(crate) fn module_config_for_secret_authority( } result.secret = Some(SecretConfig2 { registrations: Vec::new(), - limits: SecretLimits2::default(), + limits: SecretLimits2 { + max_in_flight: SECRET_MAX_IN_FLIGHT, + operations_per_minute: SECRET_OPERATIONS_PER_MINUTE, + ..SecretLimits2::default() + }, callback_timeout_ms: AUDIT_CALLBACK_TIMEOUT_MS, }); result.secret_cipher = None; diff --git a/crates/openhuman-core/src/modules/security/policy_tests.rs b/crates/openhuman-core/src/modules/security/policy_tests.rs index 909d2773e92..0d1a28e9b84 100644 --- a/crates/openhuman-core/src/modules/security/policy_tests.rs +++ b/crates/openhuman-core/src/modules/security/policy_tests.rs @@ -186,6 +186,127 @@ fn secret_authority_boots_without_any_tenants_secret_scope() { ); } +/// Every tenant's secret registration draws on the one process-wide +/// TinySecurity work budget, so it is sized for many tenants at once (the +/// contract ceiling), not the single-scope default of four. +#[test] +fn secret_authority_admits_concurrent_work_across_tenants() { + let module = + module_config_for_secret_authority(&Config::default(), Some(":1.42".into()), None).unwrap(); + let limits = module + .secret + .expect("the secret authority is enabled") + .limits; + assert_eq!(limits.max_in_flight, 32, "the contract's maximum"); + assert!(limits.max_in_flight > tinysecurity_bus::SecretLimits2::default().max_in_flight); +} + +/// Every encrypted credential read is one secret cipher operation, and every +/// agent of a runtime shares its config directory's registration, so the +/// per-registration rate is sized at the contract ceiling: the default of 120 +/// refused a busy runtime's API-key reads within a second. +#[test] +fn secret_authority_rate_admits_a_busy_runtimes_credential_reads() { + let module = + module_config_for_secret_authority(&Config::default(), Some(":1.42".into()), None).unwrap(); + let limits = module + .secret + .expect("the secret authority is enabled") + .limits; + assert_eq!(limits.operations_per_minute, 4096, "the contract's maximum"); + assert!( + limits.operations_per_minute + > tinysecurity_bus::SecretLimits2::default().operations_per_minute + ); +} + +/// More tenants than the single-scope default budget unlock their config +/// secrets at the same moment, and every one of them is admitted: a tenant's +/// master grant is never refused because other tenants hold work in flight. +/// +/// The keyring namespace is the credential directory's last path component, so +/// each run names its tenants uniquely and removes every profile it stored, +/// whether or not the store succeeded: a fixed `tenant-N` would overwrite (and +/// leave behind) real `app-session:default` entries in the OS keyring. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn concurrent_tenants_each_unlock_their_config_secrets() { + const TENANTS: usize = 12; + let root = tempfile::tempdir().unwrap(); + let run = uuid::Uuid::new_v4().simple().to_string(); + let configs: Vec = (0..TENANTS) + .map(|tenant| { + let dir = root.path().join(tenant_dir_name(&run, tenant)); + Config { + config_path: dir.join("config.toml"), + workspace_dir: dir.join("workspace"), + action_dir: dir.join("workspace"), + ..Config::default() + } + }) + .collect(); + let barrier = std::sync::Arc::new(tokio::sync::Barrier::new(TENANTS)); + let stores = configs.iter().cloned().enumerate().map(|(tenant, config)| { + let barrier = std::sync::Arc::clone(&barrier); + tokio::spawn(async move { + barrier.wait().await; + crate::credentials::AuthService::from_config(&config) + .store_provider_token( + crate::credentials::APP_SESSION_PROVIDER, + crate::credentials::DEFAULT_AUTH_PROFILE_NAME, + &format!("session-{tenant}"), + Default::default(), + true, + ) + .await + .map(|_| ()) + .map_err(|error| format!("tenant {tenant}: {error:#}")) + }) + }); + let stored: Vec<_> = futures::future::join_all(stores).await; + // Clean up before asserting, so a failed store still leaves nothing behind. + let mut removed = Vec::with_capacity(TENANTS); + for config in &configs { + let auth = crate::credentials::AuthService::from_config(config); + let gone = auth + .remove_profile( + crate::credentials::APP_SESSION_PROVIDER, + crate::credentials::DEFAULT_AUTH_PROFILE_NAME, + ) + .await; + let left = auth + .get_profile(crate::credentials::APP_SESSION_PROVIDER, None) + .await + .map(|profile| profile.is_some()); + removed.push(( + gone.map_err(|e| format!("{e:#}")), + left.map_err(|e| format!("{e:#}")), + )); + } + for store in stored { + store + .expect("store task") + .expect("tenant unlocks its secrets"); + } + for (tenant, (gone, left)) in removed.into_iter().enumerate() { + assert_eq!(gone, Ok(true), "tenant {tenant}'s profile was removed"); + assert_eq!(left, Ok(false), "tenant {tenant} keeps no session behind"); + } +} + +/// A per-run tenant directory name: the keyring namespace it yields is never +/// shared with another run or with a real user's credential directory. +fn tenant_dir_name(run: &str, tenant: usize) -> String { + format!("oh-policy-test-{run}-tenant-{tenant}") +} + +#[test] +fn concurrent_tenant_fixtures_use_a_fresh_keyring_namespace_per_run() { + let first = uuid::Uuid::new_v4().simple().to_string(); + let second = uuid::Uuid::new_v4().simple().to_string(); + assert_ne!(tenant_dir_name(&first, 0), tenant_dir_name(&second, 0)); + assert_ne!(tenant_dir_name(&first, 0), "tenant-0"); +} + /// Audited permissions are appended on the init audit stream, so the identity /// the host correlates them on must be exactly the one TinySecurity was given. #[test] diff --git a/crates/openhuman-core/src/modules/security/secret_cipher.rs b/crates/openhuman-core/src/modules/security/secret_cipher.rs index 23ed41b9c2a..fdbeea5f32c 100644 --- a/crates/openhuman-core/src/modules/security/secret_cipher.rs +++ b/crates/openhuman-core/src/modules/security/secret_cipher.rs @@ -64,41 +64,50 @@ async fn resolve_user_master_inner( Some(outcome) => outcome, None => { use super::unattended_unlock::{answer_master_grant, mode_for, UnlockMode}; - let gate = crate::security::approval::ApprovalGate::try_global() - .ok_or_else(|| SecurityError::Unavailable("secret approval unavailable".into()))?; - match mode_for(config) { - UnlockMode::Unattended => { - answer_master_grant( - &gate, - MASTER_GRANT_TOOL, - MASTER_GRANT_SUMMARY, - registration_id, - ) - .await - } - mode => { - if mode == UnlockMode::IgnoredOnSaas { - tracing::warn!( + match crate::security::approval::ApprovalGate::try_global() { + // No gate yet: only a library host's own authorisation can + // answer (`gate_host_grant.rs`); anything else stays refused. + None => crate::security::approval::gate::host_authorised_grant_without_gate( + MASTER_GRANT_TOOL, + MASTER_GRANT_SUMMARY, + serde_json::json!({"registration_id": registration_id}), + ) + .await + .ok_or_else(|| SecurityError::Unavailable("secret approval unavailable".into()))?, + Some(gate) => match mode_for(config) { + UnlockMode::Unattended => { + answer_master_grant( + &gate, + MASTER_GRANT_TOOL, + MASTER_GRANT_SUMMARY, + registration_id, + ) + .await + } + mode => { + if mode == UnlockMode::IgnoredOnSaas { + tracing::warn!( "[security::unattended_unlock] secrets.unattended_unlock is set but \ this is a SaaS core; the user must approve over WebChat, and an unlock \ with no WebChat route is refused" ); - } - if mode == UnlockMode::IgnoredWithoutOperatorKey { - tracing::warn!( + } + if mode == UnlockMode::IgnoredWithoutOperatorKey { + tracing::warn!( "[security::unattended_unlock] secrets.unattended_unlock is set but the \ keyring master key was not supplied by the operator \ (OPENHUMAN_KEYRING_MASTER_KEY / OPENHUMAN_KEYRING_MASTER_KEY_FILE on a \ file or encrypted_file keyring); asking a person instead" ); + } + gate.intercept_forced( + MASTER_GRANT_TOOL, + MASTER_GRANT_SUMMARY, + serde_json::json!({"registration_id": registration_id}), + ) + .await } - gate.intercept_forced( - MASTER_GRANT_TOOL, - MASTER_GRANT_SUMMARY, - serde_json::json!({"registration_id": registration_id}), - ) - .await - } + }, } } }; diff --git a/crates/openhuman-core/src/modules/security/text.rs b/crates/openhuman-core/src/modules/security/text.rs index ddaf9ced489..9ca6d1191aa 100644 --- a/crates/openhuman-core/src/modules/security/text.rs +++ b/crates/openhuman-core/src/modules/security/text.rs @@ -107,3 +107,55 @@ pub(super) fn armed_config() -> Result { fn scrub_log(text: &str) -> Option { redact_blocking(RedactMode::CredentialsOnly, text, SYNC_TIMEOUT).ok() } + +/// A synchronous TinySecurity path decision: `Ok(true)` when the path is in +/// the protected floor. +pub(crate) type ProtectedPathCheck = + std::sync::Arc Result + Send + Sync>; + +const PATH_CHECK_TIMEOUT: Duration = Duration::from_secs(5); + +/// `ProtectedPath2` for a synchronous host seam that cannot await (the media +/// reference policy). Each call asks TinySecurity through the bounded sync +/// bridge, so the floor decision runs in the module, never in a host copy of +/// its algorithm. `config` names the module configuration the question goes +/// to; `None` uses the current dispatch's. The module is asked once here, so +/// one that cannot answer is reported before any path is. +pub(crate) async fn protected_path_check( + config: Option<&Config>, +) -> Result { + #[cfg(any(test, feature = "test-keyring-consent"))] + if let Some(port) = super::gap::installed_path_floor_port() { + port.protected_paths(&[]).await?; + return Ok(std::sync::Arc::new(move |path: &std::path::Path| { + let answers = futures::executor::block_on(port.protected_paths(&[path.to_path_buf()]))?; + answers + .first() + .copied() + .ok_or_else(|| "scripted TinySecurity ProtectedPath2 gave no answer".to_owned()) + })); + } + let config = match config { + Some(config) => config.clone(), + None => { + crate::core::runtime::DispatchCtx::ambient() + .load_config() + .await? + } + }; + super::gap::protected_paths_with_config(&config, &[]).await?; + if !super::sync_seam::arm_current() { + return Err("TinySecurity sync bridge is unavailable".into()); + } + Ok(std::sync::Arc::new(move |path: &std::path::Path| { + let config = config.clone(); + let paths = vec![path.to_path_buf()]; + let answers = super::sync_seam::run(PATH_CHECK_TIMEOUT, async move { + super::gap::protected_paths_with_config(&config, &paths).await + })?; + answers + .first() + .copied() + .ok_or_else(|| "TinySecurity ProtectedPath2 gave no answer".to_owned()) + })) +} diff --git a/crates/openhuman-core/src/platform/cost/catalog_tests.rs b/crates/openhuman-core/src/platform/cost/catalog_tests.rs index b8ae089e494..a96fbe24431 100644 --- a/crates/openhuman-core/src/platform/cost/catalog_tests.rs +++ b/crates/openhuman-core/src/platform/cost/catalog_tests.rs @@ -120,12 +120,9 @@ fn minimax_rows_and_vision_normalization() { lookup("minimax/minimax-m3").unwrap().context_window, 1_000_000 ); - assert_eq!( - lookup("minimax-m2.7-highspeed") - .unwrap() - .output_per_mtok_usd, - 2.40 - ); + assert_eq!(lookup("MiniMax-M3").unwrap().output_per_mtok_usd, 1.20); + // Retired upstream; it must not borrow M3's rates. + assert!(lookup("minimax-m2.7-highspeed").is_none()); assert!(model_accepts_image_input("MiniMax/minimax-m3:latest")); assert!(default_registry_entries() .iter() diff --git a/crates/openhuman-core/src/profiles/README.md b/crates/openhuman-core/src/profiles/README.md index fcef3db9226..07aff41a254 100644 --- a/crates/openhuman-core/src/profiles/README.md +++ b/crates/openhuman-core/src/profiles/README.md @@ -27,7 +27,7 @@ Two hosts drive it: /users// the desktop's users/ shape (config::schema::ProfileLayout) profile.toml ProfileMeta (only without a storage backend) config.toml the profile's config_path (never read in SaaS) - auth-profiles/secrets.enc its encrypted profile-local credential store + auth-profiles/secrets.enc its encrypted credential store (only without a storage backend) workspace/ threads, sessions, memory, cron, cost and run ledgers sandbox/ action_dir: the only place its tools may act /users//.lease the file-lock lease and its record (only without a storage backend) @@ -42,7 +42,7 @@ With a storage backend (`storage_url` / `OPENHUMAN_STORAGE_URL`): | --- | --- | | scope `cluster`, collection `profiles` | the profile registry (replaces `profile.toml`) | | scope `cluster`, collection `tsd.leases` (owner `profiles`) | the profile leases (replace the file locks) | -| scope `profile:` (`storage::scope_for_profile`) | that profile's records on the storage ports: approvals, cron, flows, ...; auth profiles remain in that profile's encrypted local file | +| scope `profile:` (`storage::scope_for_profile`) | that profile's records on the storage ports: approvals, cron, flows, ..., and its auth profiles (secret `auth-profiles`, replacing `auth-profiles/secrets.enc` and its lock file) | | session key `~` (`tenant::session_key`) | its session store: transcripts, turn states | A profile's files stay under `/users//` either way, so the nodes of a diff --git a/crates/openhuman-core/src/profiles/credentials.rs b/crates/openhuman-core/src/profiles/credentials.rs index 6fde129981f..1322e530114 100644 --- a/crates/openhuman-core/src/profiles/credentials.rs +++ b/crates/openhuman-core/src/profiles/credentials.rs @@ -2,8 +2,10 @@ //! //! The gateway hands the core each user's TinyHumans credential — a session //! JWT or an API key — through the operator plane. It is stored where every -//! backend caller already looks: the auth-profile store beside the profile's -//! `config_path` (`/users//`). Work running under that profile's +//! backend caller already looks: the auth-profile store of the profile's +//! `config_path` (`/users//`), which with a storage backend keeps +//! its document in the profile's storage scope, not beside the profile +//! (`credentials/profiles/backend.rs`). Work running under that profile's //! context loads the profile's config, so `resolve_backend_credential` finds //! that user's credential and no other. //! diff --git a/crates/openhuman-core/src/profiles/credentials_tests.rs b/crates/openhuman-core/src/profiles/credentials_tests.rs index 6df2f940a33..35dc1ec74db 100644 --- a/crates/openhuman-core/src/profiles/credentials_tests.rs +++ b/crates/openhuman-core/src/profiles/credentials_tests.rs @@ -12,7 +12,12 @@ fn profile(tmp: &tempfile::TempDir, user: &str) -> Config { ) .unwrap(); let layout = ProfileLayout::new(tmp.path(), &id); - std::fs::create_dir_all(&layout.workspace_dir).unwrap(); + // Both directories, as the host opens a profile: the profile's policy is + // enabled, and TinySecurity refuses to initialise over a missing + // `action_dir`. If this suite admits the module first in the process, that + // refusal is terminal and every later secret operation in the test binary + // fails as "security module unavailable". + crate::profiles::host::create_dirs(&layout).unwrap(); let mut config = profile_config(&layout, &id); // This suite verifies tenant isolation with synthetic credentials. The // profile document remains encrypted at rest; native cipher consent has @@ -21,6 +26,21 @@ fn profile(tmp: &tempfile::TempDir, user: &str) -> Config { config } +/// The fixture is a profile as the host opens it: an enabled policy over +/// directories that exist, so whichever test admits TinySecurity first in the +/// process does not fault it for the whole test binary. +#[test] +fn the_profile_fixture_has_the_directories_its_enabled_policy_names() { + let tmp = tempfile::tempdir().unwrap(); + let config = profile(&tmp, "fixture"); + assert!(config.autonomy.enabled); + assert!(config.workspace_dir.is_dir()); + assert!( + config.action_dir.is_dir(), + "TinySecurity requires action_dir" + ); +} + #[tokio::test] async fn each_profile_resolves_only_its_own_credential() { let tmp = tempfile::tempdir().unwrap(); diff --git a/crates/openhuman-core/src/profiles/tools.rs b/crates/openhuman-core/src/profiles/tools.rs index 9c79086b221..3b39e1394f8 100644 --- a/crates/openhuman-core/src/profiles/tools.rs +++ b/crates/openhuman-core/src/profiles/tools.rs @@ -24,6 +24,17 @@ //! does not park: it allows a tool from an allowlisted group, whose reach the //! sandbox and path policy already bound, and refuses anything else //! ([`gate_verdict`]). +//! +//! One call is decided before that verdict: a tenant's own secret master +//! grant (a forced `native_secret_grant` that unlocks the tenant's config +//! secrets) with nobody to ask. The host approves it itself, as +//! `saas_host_authorised`, only when the dispatch is bound to an +//! authenticated tenant profile and the live secret registration it names is +//! the `.secret_key` the profile layout places for that tenant; another +//! tenant's scope, the operator's, an unknown registration or an unbound +//! dispatch is refused. The approval still runs TinySecurity's `check` → +//! `decide` round trip and is audited on the tenant's secret scope stream +//! (`security/approval/gate_saas_grant.rs`, and the approval README). use std::path::Path; @@ -223,7 +234,9 @@ fn current_named_tools( } /// The approval gate's answer in SaaS, where it never parks: `Ok` for a tool -/// in an allowlisted group, otherwise the refusal. +/// in an allowlisted group, otherwise the refusal. A tenant's own secret +/// master grant is decided by the host before this verdict is asked (see the +/// module docs). pub fn gate_verdict_with(tool: &str, groups: &[SaasToolGroup]) -> Result<(), String> { if admits_with(tool, false, groups) { return Ok(()); diff --git a/crates/openhuman-core/src/sandbox/boxes/registry_tests.rs b/crates/openhuman-core/src/sandbox/boxes/registry_tests.rs index 2c68131e4ce..cc44d3acf43 100644 --- a/crates/openhuman-core/src/sandbox/boxes/registry_tests.rs +++ b/crates/openhuman-core/src/sandbox/boxes/registry_tests.rs @@ -97,6 +97,28 @@ fn deadlines_round_up_to_whole_seconds_of_at_least_one() { assert_eq!(whole_seconds(Duration::ZERO), 1); } +/// The configuration a command's call brought reaches every driver step made +/// for it, its create and its exec, so a driver reaches its backend with that +/// call's configuration rather than whichever call came last. +#[tokio::test(start_paused = true)] +async fn every_driver_step_gets_the_call_it_serves() { + let driver = ScriptedDriver::new(); + let boxes = registry(&driver, 10); + let module = ModuleConfig::new(&crate::config::Config::default()); + let served = BoxSettings { + module: module.clone(), + ..settings() + }; + + boxes + .exec(&user("u1"), &served, &request("true")) + .await + .unwrap(); + + assert_eq!(driver.calls()[0], Call::Create(served, None)); + assert_eq!(driver.last_exec().unwrap().module, module); +} + #[tokio::test(start_paused = true)] async fn embedded_users_of_one_host_get_separate_boxes() { let driver = ScriptedDriver::new(); diff --git a/crates/openhuman-core/src/sandbox/shell_exec.rs b/crates/openhuman-core/src/sandbox/shell_exec.rs index 661ae9875d0..6c9b7030491 100644 --- a/crates/openhuman-core/src/sandbox/shell_exec.rs +++ b/crates/openhuman-core/src/sandbox/shell_exec.rs @@ -168,6 +168,10 @@ pub(crate) async fn run_yielding( } } +/// The longest one TinyBox call runs a command before handing it back. +#[cfg(feature = "modules")] +const HOST_POLL: Duration = Duration::from_millis(50); + #[cfg(feature = "modules")] async fn run_owned( config: &Config, @@ -175,11 +179,20 @@ async fn run_owned( mut abandoned: tokio::sync::oneshot::Receiver, meter: Option, ) -> anyhow::Result { - let caller_wants_yield = run.yield_after.is_some(); - let yield_after_ms = run + // The module call always hands the process back within `HOST_POLL`; this + // worker owns the caller's own yield point. A bus call cannot be cancelled + // and awaited, so a long one would leave an abandoned command stopping + // after the turn's cleanup was acknowledged. + let caller_yield_at = run .yield_after - .or_else(|| meter.as_ref().map(|_| Duration::from_millis(50))) - .map(|duration| duration.as_millis().min(u64::MAX as u128) as u64); + .map(|after| tokio::time::Instant::now() + after); + let yield_after_ms = Some( + run.yield_after + .map_or(HOST_POLL, |after| after.min(HOST_POLL)) + .as_millis() + .min(u64::MAX as u128) as u64, + ); + let yield_due = || caller_yield_at.is_some_and(|at| tokio::time::Instant::now() >= at); let workspace = path_string(&run.workspace, "command workspace")?; let request = contract::RunNativeShellRequest { create: contract::CreateRequest { @@ -204,17 +217,35 @@ async fn run_owned( )?, yield_after_ms, }; - let outcome = tokio::select! { + let call = tinybox::run_native_shell(config, request); + tokio::pin!(call); + let started = tokio::select! { biased; - _ = &mut abandoned => anyhow::bail!("TinyBox native shell invocation was abandoned"), - result = tinybox::run_native_shell(config, request) => result - .map_err(|error| { - tracing::warn!(%error, "[sandbox:shell] TinyBox native shell lifecycle failed"); - anyhow::anyhow!("TinyBox native shell execution failed") - })?, + _ = &mut abandoned => None, + result = &mut call => Some(result), }; + // Abandoned while starting: dropping the call would leave the module to + // stop the command unawaited, so let it reach its (short) yield point and + // stop the process here, inside the turn's cleanup hold. + let gave_up = started.is_none(); + let started = match started { + Some(result) => result, + None => { + tracing::debug!( + "[sandbox:shell] abandoned while starting; stopping the command before release" + ); + call.await + } + }; + let outcome = started.map_err(|error| { + tracing::warn!(%error, "[sandbox:shell] TinyBox native shell lifecycle failed"); + anyhow::anyhow!("TinyBox native shell execution failed") + })?; match outcome { + contract::RunNativeShellResult::Finished { .. } if gave_up => { + anyhow::bail!("TinyBox native shell invocation was abandoned") + } contract::RunNativeShellResult::Finished { exit_code, stdout, @@ -246,25 +277,29 @@ async fn run_owned( let mut live = super::shell_live::LiveHandle::TinyBox( super::shell_live::TinyBoxLive::new(config.clone(), resource, process, cursor), ); - if caller_wants_yield { - tracing::debug!("[sandbox:shell] command still running at its yield point"); - return Ok(ShellRunOutcome::Running(LiveShell { - stdout: String::from_utf8_lossy(&stdout).into_owned(), - stderr: String::from_utf8_lossy(&stderr).into_owned(), - handle: live, - })); + if gave_up { + let _ = live.kill().await; + anyhow::bail!("TinyBox native shell invocation was abandoned") } let mut collected_stdout = stdout; let mut collected_stderr = stderr; loop { + if yield_due() { + tracing::debug!("[sandbox:shell] command still running at its yield point"); + return Ok(ShellRunOutcome::Running(LiveShell { + stdout: String::from_utf8_lossy(&collected_stdout).into_owned(), + stderr: String::from_utf8_lossy(&collected_stderr).into_owned(), + handle: live, + })); + } let read = tokio::select! { biased; _ = &mut abandoned => { let _ = live.kill().await; anyhow::bail!("TinyBox native shell invocation was abandoned") } - result = live.read(Duration::from_millis(50)) => result?, + result = live.read(HOST_POLL) => result?, }; if let Some(meter) = &meter { meter.record(read.stdout.as_bytes()); diff --git a/crates/openhuman-core/src/security/approval/README.md b/crates/openhuman-core/src/security/approval/README.md index 12aa7ea8837..8786881b100 100644 --- a/crates/openhuman-core/src/security/approval/README.md +++ b/crates/openhuman-core/src/security/approval/README.md @@ -20,6 +20,27 @@ pending request once after an audited decision; it cannot create a reusable grant or override a hard denial. OpenHuman's current TinySecurity config leaves Jev scoring disabled. +**SaaS secret master grant.** A SaaS core has no person to ask when a headless +tenant request (a gateway call, a background or delivery job, the embed +`profiles` API) must unlock that tenant's config secrets, which needs +TinySecurity's one-time (HumanOnce) master grant. `gate_saas_grant.rs` lets the +host approve that one grant, and only it, before the ordinary SaaS allowlist +decision (`profiles::tools::gate_verdict`): + +- only in SaaS, only for a forced `native_secret_grant` call, and only when no + person will decide it on a routable WebChat turn; +- only when the dispatch is bound to an authenticated tenant profile, the host's + profile layout places that tenant's `.secret_key`, and the live secret + registration named by `registration_id` is that same key. Another tenant's + scope, the operator's scope, an unknown registration or an unbound dispatch + is refused (fail closed); +- the approval runs the engine's own `check` → `decide` round trip, so + TinySecurity verifies and audits it on the tenant's secret scope stream under + the label and actor `saas_host_authorised`. Any other engine answer denies, + and a caller dropped mid-grant cancels the request it left pending. + +Outside SaaS a person still decides the secret master grant. + The `approval.*` RPC names and approval event names remain host wire contracts. The host may change how it stores callback documents or presents a prompt, but must not bypass TinySecurity's decision or durable-state checks. diff --git a/crates/openhuman-core/src/security/approval/engine.rs b/crates/openhuman-core/src/security/approval/engine.rs index 8e57447fac1..b972df6ffae 100644 --- a/crates/openhuman-core/src/security/approval/engine.rs +++ b/crates/openhuman-core/src/security/approval/engine.rs @@ -217,6 +217,13 @@ pub(crate) trait ApprovalEngine: sealed::Sealed + std::fmt::Debug + Send + Sync /// never stored in the current scope. async fn is_decided(&self, request_id: &str) -> Result, EngineError>; + /// Requests an earlier launch left undecided that the engine still holds + /// (pending orphans), oldest first. They are listed so a person can see and + /// dismiss them; deciding one resumes nothing. + async fn orphans(&self) -> Result, EngineError> { + Ok(Vec::new()) + } + /// The most recently decided requests of the current scope, newest first. async fn history( &self, diff --git a/crates/openhuman-core/src/security/approval/engine_stub.rs b/crates/openhuman-core/src/security/approval/engine_stub.rs index 94764286f03..a3443209778 100644 --- a/crates/openhuman-core/src/security/approval/engine_stub.rs +++ b/crates/openhuman-core/src/security/approval/engine_stub.rs @@ -74,6 +74,13 @@ pub(crate) struct StubEngine { fail_reserve: AtomicBool, fail_record_execution: AtomicBool, always_pending: AtomicBool, + /// Park `check` after the prompt was delivered, and `decide` before it + /// answers, so a test can drop the caller while either is in flight. + hold_after_delivery: AtomicBool, + hold_decides: AtomicBool, + /// Make `decide` wait for this signal, as the native engine waits for the + /// parked call's check to release its subject's stream. + decide_waits_for: Mutex>>, /// The durable flow trust the module keeps: `(flow, tool)` pairs. trust: Mutex>, /// Durable whole-tool trust keyed by the exact tenant and posture variant. @@ -129,6 +136,15 @@ impl StubEngine { .and_then(|row| row.attribution) } + /// The label a decision was recorded under, when one was. + pub(crate) fn label(&self, request_id: &str) -> Option { + self.rows + .lock() + .unwrap_or_else(PoisonError::into_inner) + .get(request_id) + .and_then(|row| row.label.clone()) + } + /// Every request id, oldest first. pub(crate) fn request_ids(&self) -> Vec { let rows = self.rows.lock().unwrap_or_else(PoisonError::into_inner); @@ -158,6 +174,24 @@ impl StubEngine { } /// Make every later `reserve` fail. + /// Hold every `check` after its prompt is delivered until the caller drops it. + pub(crate) fn hold_after_delivery(&self, hold: bool) { + self.hold_after_delivery.store(hold, Ordering::SeqCst); + } + + /// Hold every `decide` until the caller drops it. + pub(crate) fn hold_decides(&self, hold: bool) { + self.hold_decides.store(hold, Ordering::SeqCst); + } + + /// Make every later `decide` wait until `signal` is notified. + pub(crate) fn decide_waits_for(&self, signal: Arc) { + *self + .decide_waits_for + .lock() + .unwrap_or_else(PoisonError::into_inner) = Some(signal); + } + pub(crate) fn fail_reserve(&self, fail: bool) { self.fail_reserve.store(fail, Ordering::SeqCst); } @@ -342,6 +376,9 @@ impl ApprovalEngine for StubEngine { self.with(&request_id, |row| row.state = State::Cancelled); return Err(EngineError::Unavailable(error)); } + if self.hold_after_delivery.load(Ordering::SeqCst) { + std::future::pending::<()>().await; + } Ok(Checked::Pending { request_id, expires_at_ms: expires_ms, @@ -354,6 +391,17 @@ impl ApprovalEngine for StubEngine { choice: Choice, label: &str, ) -> Result { + if self.hold_decides.load(Ordering::SeqCst) { + std::future::pending::<()>().await; + } + let signal = self + .decide_waits_for + .lock() + .unwrap_or_else(PoisonError::into_inner) + .clone(); + if let Some(signal) = signal { + signal.notified().await; + } let now = now_ms(); self.with(request_id, |row| { if row.state != State::Pending || now >= row.expires_ms { diff --git a/crates/openhuman-core/src/security/approval/gate.rs b/crates/openhuman-core/src/security/approval/gate.rs index 9ab9af4c80e..99196e6b6ec 100644 --- a/crates/openhuman-core/src/security/approval/gate.rs +++ b/crates/openhuman-core/src/security/approval/gate.rs @@ -467,6 +467,8 @@ include!("gate_surface.rs"); include!("gate_intercept.rs"); include!("gate_intercept_decision.rs"); include!("gate_state.rs"); +include!("gate_saas_grant.rs"); +include!("gate_host_grant.rs"); fn now_ms() -> u64 { std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) diff --git a/crates/openhuman-core/src/security/approval/gate_host_grant.rs b/crates/openhuman-core/src/security/approval/gate_host_grant.rs new file mode 100644 index 00000000000..df11f2249d3 --- /dev/null +++ b/crates/openhuman-core/src/security/approval/gate_host_grant.rs @@ -0,0 +1,154 @@ +// An embedder's authorisation of its own runtime's secret master grant. +// +// A library host that hands its runtime a credential (the embed +// `RuntimeBuilder::api_key`) is the authority over that runtime's config +// directory. Storing the credential needs TinySecurity's HumanOnce master +// grant, and there is nobody to ask: no chat, and before the core boots not +// even a global gate. The host scopes the store with +// [`host_authorised_secret_grant`]. Inside that scope, and only for the secret +// scope of that exact config directory, the grant is approved through the same +// engine round trip a person's approval takes (`saas_host_authorised_grant`), +// recorded under [`EMBEDDER_HOST_AUTHORISED`]. Outside the scope nothing +// changes, and inside it a grant for any other scope is refused. +// +// The authorisation rides the store's `CoreContext` as a [`HostSecretGrant`]. +// It holds only on the host's own task and only until the store ends, so a +// task spawned from inside the scope, or a context captured there and used +// later, authorises nothing. + +/// The label (and approving actor) an embedder's own approval of its +/// runtime's secret master grant is recorded under. +pub(crate) const EMBEDDER_HOST_AUTHORISED: &str = "embedder_host_authorised"; + +/// A library host's authorisation of the secret master grant of its own +/// runtime's config directory, carried on the context of the store it scopes +/// ([`host_authorised_secret_grant`]). +pub(crate) struct HostSecretGrant { + /// The `.secret_key` the host authorises. + key: std::path::PathBuf, + /// The runtime config owning that key. + config: Config, + /// The host's own task: the only one the grant holds on. + task: Option, + /// Cleared when the store the host scoped ends. + live: AtomicBool, +} + +impl HostSecretGrant { + /// Whether the grant holds for work running here, now. + fn holds(&self) -> bool { + self.live.load(Ordering::Acquire) && tokio::task::try_id() == self.task + } +} + +/// Ends a host grant when the store it authorises ends, however it ends. +struct HostGrantEnds(Arc); + +impl Drop for HostGrantEnds { + fn drop(&mut self) { + self.0.live.store(false, Ordering::Release); + } +} + +/// The host grant in force for work running here, if any. +fn host_secret_grant() -> Option> { + crate::core::runtime::CoreContext::current_host_secret_grant().filter(|grant| grant.holds()) +} + +/// Run `fut` with the host authorising the secret master grant of `config`'s +/// own config directory, and of no other. For a library host storing the +/// credential it supplied itself; never for work a model or a remote caller +/// started. +pub async fn host_authorised_secret_grant( + config: &Config, + fut: F, +) -> F::Output { + let key = config + .config_path + .parent() + .unwrap_or_else(|| std::path::Path::new(".")) + .join(".secret_key"); + tracing::debug!("[security][host-grant] host authorises its own runtime's secret grant"); + let grant = Arc::new(HostSecretGrant { + key, + config: config.clone(), + task: tokio::task::try_id(), + live: AtomicBool::new(true), + }); + let _ends = HostGrantEnds(Arc::clone(&grant)); + crate::core::runtime::CoreContext::scope_with_host_secret_grant(grant, fut).await +} + +/// The approval label of a host-authorised grant made here. +fn host_grant_label() -> &'static str { + if host_secret_grant().is_some() && !crate::core::runtime::is_saas() { + EMBEDDER_HOST_AUTHORISED + } else { + SAAS_HOST_AUTHORISED + } +} + +/// Whether the host authorised the forced grant `args.registration_id` names: +/// not applicable outside [`host_authorised_secret_grant`], authorised only +/// for the scoped config directory's own live secret scope. +pub(crate) fn embedder_host_grant( + forced: bool, + tool_name: &str, + args: &serde_json::Value, +) -> SaasHostGrant { + let Some(grant) = host_secret_grant() else { + return SaasHostGrant::NotApplicable; + }; + let registration_id = args + .get("registration_id") + .and_then(serde_json::Value::as_str); + #[cfg(feature = "security-module")] + let requested = registration_id + .and_then(crate::modules::ops::security_tenant_by_registration) + .map(|tenant| (tenant.key_path.clone(), tenant.scope.scope_id().to_owned())); + #[cfg(not(feature = "security-module"))] + let requested: Option<(std::path::PathBuf, String)> = registration_id.and(None); + saas_host_grant_with( + true, + forced, + tool_name, + &SecretGrantClaim { + tenant_profile: Some("embedder"), + tenant_key: Some(&grant.key), + requested: requested + .as_ref() + .map(|(key, scope)| (key.as_path(), scope.as_str())), + }, + ) +} + +/// The host's answer for a secret master grant asked before any global gate +/// exists (the embed runtime storing its API key ahead of boot): approved +/// through a private gate over the real engine when +/// [`embedder_host_grant`] authorises it, `None` otherwise. +pub(crate) async fn host_authorised_grant_without_gate( + tool_name: &str, + action_summary: &str, + args: serde_json::Value, +) -> Option { + let config = host_secret_grant()?.config.clone(); + match embedder_host_grant(true, tool_name, &args) { + SaasHostGrant::Authorised { profile, scope_id } => { + let session = format!("session-{}", uuid::Uuid::new_v4()); + let gate = ApprovalGate::new(config, session, None); + let (outcome, _) = gate + .saas_host_authorised_grant(tool_name, action_summary, args, &profile, &scope_id) + .await; + Some(outcome) + } + SaasHostGrant::Refused(why) => { + tracing::warn!(why, "[security][host-grant] host authorisation refused"); + Some(GateOutcome::Deny { + reason: format!( + "{POLICY_DENIED_MARKER} The host cannot authorise '{tool_name}': {why}." + ), + }) + } + SaasHostGrant::NotApplicable => None, + } +} diff --git a/crates/openhuman-core/src/security/approval/gate_host_grant_tests.rs b/crates/openhuman-core/src/security/approval/gate_host_grant_tests.rs new file mode 100644 index 00000000000..9350cb5806e --- /dev/null +++ b/crates/openhuman-core/src/security/approval/gate_host_grant_tests.rs @@ -0,0 +1,167 @@ +use super::*; + +fn config_in(dir: &std::path::Path) -> Config { + Config { + config_path: dir.join("config.toml"), + workspace_dir: dir.join("workspace"), + ..Config::default() + } +} + +fn grant_args(registration_id: &str) -> serde_json::Value { + serde_json::json!({ "registration_id": registration_id }) +} + +/// Without the host's scope nothing changes: the grant is the gate's to decide. +#[tokio::test] +async fn outside_the_host_scope_a_secret_grant_is_not_host_authorised() { + let args = grant_args("never-registered"); + assert_eq!( + embedder_host_grant(true, NATIVE_SECRET_GRANT_TOOL, &args), + SaasHostGrant::NotApplicable + ); + assert!( + host_authorised_grant_without_gate(NATIVE_SECRET_GRANT_TOOL, "unlock", args) + .await + .is_none(), + "no gate and no host authorisation stays unanswered (refused upstream)" + ); +} + +/// Inside the scope only a forced secret master grant for the scoped config +/// directory's own live secret scope is authorised; anything else is refused +/// or left to the gate, never approved. +#[tokio::test] +async fn the_host_scope_authorises_only_its_own_live_secret_grant() { + let dir = tempfile::tempdir().unwrap(); + let config = config_in(dir.path()); + host_authorised_secret_grant(&config, async { + let args = grant_args("never-registered"); + assert_eq!( + embedder_host_grant(false, NATIVE_SECRET_GRANT_TOOL, &args), + SaasHostGrant::NotApplicable, + "an unforced call is not a master grant" + ); + assert_eq!( + embedder_host_grant(true, "shell", &args), + SaasHostGrant::NotApplicable, + "only the secret master grant" + ); + assert_eq!( + embedder_host_grant(true, NATIVE_SECRET_GRANT_TOOL, &args), + SaasHostGrant::Refused("the secret scope to unlock is not live"), + "a registration this process does not hold is never approved" + ); + match host_authorised_grant_without_gate(NATIVE_SECRET_GRANT_TOOL, "unlock", args).await { + Some(GateOutcome::Deny { reason }) => { + assert!(reason.starts_with(POLICY_DENIED_MARKER), "{reason}"); + } + other => panic!("an unknown registration must be denied, got {other:?}"), + } + }) + .await; +} + +/// The claim check the host scope reuses: another directory's key is refused. +#[test] +fn the_host_scope_refuses_another_directorys_secret_scope() { + let own = std::path::Path::new("/srv/embed/a/.secret_key"); + let other = std::path::Path::new("/srv/embed/b/.secret_key"); + let claim = SecretGrantClaim { + tenant_profile: Some("embedder"), + tenant_key: Some(own), + requested: Some((other, "scope-b")), + }; + assert_eq!( + saas_host_grant_with(true, true, NATIVE_SECRET_GRANT_TOOL, &claim), + SaasHostGrant::Refused("the secret scope is not this tenant's own") + ); +} + +/// Whether the host authorisation is in force here: inside it, a grant for a +/// registration this process does not hold is refused rather than left to the +/// gate. +fn host_authorises_here() -> bool { + embedder_host_grant( + true, + NATIVE_SECRET_GRANT_TOOL, + &grant_args("never-registered"), + ) != SaasHostGrant::NotApplicable +} + +fn booted_context(config: &Config) -> std::sync::Arc { + crate::core::runtime::CoreContext::for_test_with_config( + crate::core::runtime::DomainSet::full(), + config.clone(), + ) +} + +/// The authorisation belongs to the host's own task: a task spawned from +/// inside its scope, even one that carries the dispatch context, holds none. +#[tokio::test] +async fn a_task_spawned_inside_the_host_scope_is_not_host_authorised() { + let dir = tempfile::tempdir().unwrap(); + let config = config_in(dir.path()); + let context = booted_context(&config); + crate::core::runtime::CoreContext::scope(context, async { + host_authorised_secret_grant(&config, async { + assert!(host_authorises_here(), "the host's own task is authorised"); + let spawned = tokio::spawn(crate::core::runtime::CoreContext::propagate(async { + host_authorises_here() + })) + .await + .unwrap(); + assert!( + !spawned, + "a spawned task must not inherit the authorisation" + ); + }) + .await; + }) + .await; +} + +/// A context captured inside the host scope authorises nothing once the +/// scope has ended. +#[tokio::test] +async fn a_context_captured_inside_the_host_scope_authorises_nothing_after_it() { + let dir = tempfile::tempdir().unwrap(); + let config = config_in(dir.path()); + let context = booted_context(&config); + crate::core::runtime::CoreContext::scope(context, async { + let captured = host_authorised_secret_grant(&config, async { + crate::core::runtime::CoreContext::scoped() + }) + .await; + assert!(!host_authorises_here()); + if let Some(captured) = captured { + let after = crate::core::runtime::CoreContext::scope(captured, async { + host_authorises_here() + }) + .await; + assert!(!after, "a captured context must not outlive the host scope"); + } + }) + .await; +} + +/// Work inside the host scope that runs under another context (a derived or +/// tenant context scoped for one step) keeps the authorisation, as the host's +/// own task still does that work. +#[tokio::test] +async fn the_host_scope_survives_a_nested_context_scope() { + let dir = tempfile::tempdir().unwrap(); + let config = config_in(dir.path()); + let nested = booted_context(&config); + host_authorised_secret_grant(&config, async { + let inside = + crate::core::runtime::CoreContext::scope(nested, async { host_authorises_here() }) + .await; + assert!( + inside, + "a nested context scope keeps the host's authorisation" + ); + }) + .await; + assert!(!host_authorises_here(), "nothing outlives the scope"); +} diff --git a/crates/openhuman-core/src/security/approval/gate_intercept.rs b/crates/openhuman-core/src/security/approval/gate_intercept.rs index 6f56fdb06cc..674175c0829 100644 --- a/crates/openhuman-core/src/security/approval/gate_intercept.rs +++ b/crates/openhuman-core/src/security/approval/gate_intercept.rs @@ -93,16 +93,26 @@ impl ApprovalGate { let dispatch = crate::core::runtime::DispatchCtx::ambient(); let saas = crate::core::runtime::is_saas(); let saas_human_approval = saas_prompt_needed(&dispatch, saas, &origin, tool_name, forced); + // A SaaS tenant's own secret master grant with nobody to ask + // (`gate_saas_grant.rs`). + if let Some(decided) = self + .saas_host_grant_outcome( + &dispatch, + saas, + saas_human_approval, + forced, + tool_name, + action_summary, + &args_redacted, + ) + .await + { + return decided; + } // Deployment-allowlisted tools retain their audited automatic path. // A rejected tool can reach the normal approval engine only when this // exact SaaS WebChat turn has an authenticated, routable user surface. - match saas_outcome_with( - &dispatch, - saas, - &origin, - forced, - tool_name, - ) { + match saas_outcome_with(&dispatch, saas, &origin, forced, tool_name) { Some(GateOutcome::Allow) => { return self .saas_approved( @@ -407,12 +417,9 @@ impl ApprovalGate { error = %error, "[approval::gate] the approval engine could not decide — failing closed" ); - return ( - GateOutcome::Deny { - reason: engine_denial(&origin, tool_name, &error), - }, - None, - ); + let reason = super::ApprovalScope::closed_denial(scope.as_deref(), tool_name) + .unwrap_or_else(|| engine_denial(&origin, tool_name, &error)); + return (GateOutcome::Deny { reason }, None); } }; match checked { diff --git a/crates/openhuman-core/src/security/approval/gate_rpc_decide_tests.rs b/crates/openhuman-core/src/security/approval/gate_rpc_decide_tests.rs new file mode 100644 index 00000000000..c75bad14549 --- /dev/null +++ b/crates/openhuman-core/src/security/approval/gate_rpc_decide_tests.rs @@ -0,0 +1,71 @@ +//! The `approval_decide` RPC must not block the runtime it is called on. +//! +//! The gate's `decide` blocks on the engine, and the native engine's decision +//! waits for the parked call's own check to release its subject's audit stream +//! (`native/engine_impl.rs`). That check is still finishing on the task that +//! parked it, which is polled only by the runtime it was spawned on. When the +//! RPC is served on that same runtime (every in-process router on a +//! current-thread runtime), deciding inline stalls the only thread that could +//! let the check finish, and the decision never returns. + +use super::*; +use crate::security::approval::rpc::decide_off_the_caller_runtime; + +#[test] +fn an_rpc_decision_does_not_stall_the_runtime_the_parked_call_needs() { + let (done, finished) = std::sync::mpsc::channel(); + // Its own thread and current-thread runtime, so a stalled decision fails + // this test on the deadline below instead of hanging the binary. + std::thread::spawn(move || { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(); + let outcome = runtime.block_on(async { + let (gate, _dir) = test_gate(); + let gate = Arc::new(gate); + let parked = { + let gate = gate.clone(); + tokio::spawn(async move { + turn_origin::with_origin( + web_origin(), + gate.intercept( + &ApprovalTurnContext::chat(chat_ctx()), + "rpc_decide_tool", + "decide over rpc", + serde_json::json!({}), + ), + ) + .await + }) + }; + let pending = loop { + if let Some(row) = gate.list_pending().unwrap().into_iter().next() { + break row; + } + tokio::time::sleep(Duration::from_millis(5)).await; + }; + // What the engine's decision waits for can only happen on this + // runtime, as the parked check's release does. + let released = Arc::new(tokio::sync::Notify::new()); + stub_of(&gate).decide_waits_for(released.clone()); + tokio::spawn(async move { released.notify_one() }); + let decided = decide_off_the_caller_runtime( + gate.clone(), + crate::core::runtime::Tenant::default(), + None, + pending.request_id.clone(), + ApprovalDecision::Deny, + ) + .await + .unwrap(); + assert_eq!(decided.map(|row| row.request_id), Some(pending.request_id)); + parked.await.unwrap() + }); + let _ = done.send(outcome); + }); + let outcome = finished + .recv_timeout(Duration::from_secs(30)) + .expect("the decision stalled the runtime its parked call needs"); + assert!(matches!(outcome, GateOutcome::Deny { .. }), "{outcome:?}"); +} diff --git a/crates/openhuman-core/src/security/approval/gate_saas_grant.rs b/crates/openhuman-core/src/security/approval/gate_saas_grant.rs new file mode 100644 index 00000000000..ac61dc3717c --- /dev/null +++ b/crates/openhuman-core/src/security/approval/gate_saas_grant.rs @@ -0,0 +1,340 @@ +// SaaS host authorisation of a tenant's own secret master grant. +// +// A SaaS core serves many tenants, each with its own `.secret_key` scope in +// TinySecurity. Unlocking one needs the module's one-time (HumanOnce) master +// grant, and a headless tenant request (a gateway call, a background or +// delivery job, the embed `profiles` API) has nobody to ask. The host itself +// approves that grant, and only that grant, when the dispatch is bound to an +// authenticated tenant and the scope being unlocked is that tenant's own, as +// the host's profile layout places it. Every other case keeps the gate's +// fail-closed answer, and outside SaaS a person still decides. +// +// The approval runs through the same engine round trip a person's would +// (`check` → `decide`), so TinySecurity verifies and audits it on the tenant's +// own secret scope stream; the decision carries `SAAS_HOST_AUTHORISED` as its +// label and, in the native engine, as its actor. + +/// The label (and approving actor) a SaaS host's own approval of a tenant's +/// secret master grant is recorded under in that tenant's approval ledger. +pub(crate) const SAAS_HOST_AUTHORISED: &str = "saas_host_authorised"; + +/// Whether the SaaS host may approve a forced secret master grant itself. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum SaasHostGrant { + /// Not a SaaS secret master grant: the gate decides as it always did. + NotApplicable, + /// The dispatch's own tenant asks to unlock its own secret scope. + Authorised { profile: String, scope_id: String }, + /// A SaaS secret master grant the host must not approve. + Refused(&'static str), +} + +/// What the host checks a secret master grant against. +pub(crate) struct SecretGrantClaim<'a> { + /// The SaaS profile the dispatch is bound to. + pub tenant_profile: Option<&'a str>, + /// Where the host's profile layout puts that profile's `.secret_key`. + pub tenant_key: Option<&'a std::path::Path>, + /// The live registration the grant would unlock: its `.secret_key` and + /// its approval scope id. + pub requested: Option<(&'a std::path::Path, &'a str)>, +} + +/// [`saas_host_grant`] over already-resolved facts, so every branch is +/// testable without a SaaS process. +pub(crate) fn saas_host_grant_with( + saas: bool, + forced: bool, + tool_name: &str, + claim: &SecretGrantClaim<'_>, +) -> SaasHostGrant { + if !saas || !forced || tool_name != NATIVE_SECRET_GRANT_TOOL { + return SaasHostGrant::NotApplicable; + } + let Some(profile) = claim.tenant_profile.filter(|p| !p.is_empty()) else { + return SaasHostGrant::Refused("no authenticated tenant scope"); + }; + let Some(tenant_key) = claim.tenant_key else { + return SaasHostGrant::Refused("the host cannot place this tenant's secret scope"); + }; + let Some((requested_key, scope_id)) = claim.requested else { + return SaasHostGrant::Refused("the secret scope to unlock is not live"); + }; + if requested_key != tenant_key { + return SaasHostGrant::Refused("the secret scope is not this tenant's own"); + } + SaasHostGrant::Authorised { + profile: profile.to_owned(), + scope_id: scope_id.to_owned(), + } +} + +/// Whether the SaaS host may approve this forced call itself: resolve the +/// dispatch's tenant, where the profile host keeps that tenant's secret key, +/// and which live secret registration `args.registration_id` names. +pub(crate) fn saas_host_grant( + ctx: &crate::core::runtime::DispatchCtx, + saas: bool, + forced: bool, + tool_name: &str, + args: &serde_json::Value, +) -> SaasHostGrant { + if !saas { + // Outside SaaS only a library host's own scope authorises (`gate_host_grant.rs`). + return embedder_host_grant(forced, tool_name, args); + } + if !forced || tool_name != NATIVE_SECRET_GRANT_TOOL { + return SaasHostGrant::NotApplicable; + } + let profile = ctx.tenant().ok().and_then(|tenant| tenant.profile); + let tenant_key = profile + .as_deref() + .and_then(|profile| crate::profiles::ProfileId::parse(profile).ok()) + .and_then(|id| { + let host = crate::profiles::host::host()?; + let config_path = host.layout_of(&id).config_path; + Some( + config_path + .parent() + .unwrap_or_else(|| std::path::Path::new(".")) + .join(".secret_key"), + ) + }); + let registration_id = args + .get("registration_id") + .and_then(serde_json::Value::as_str); + #[cfg(feature = "security-module")] + let requested = registration_id + .and_then(crate::modules::ops::security_tenant_by_registration) + .map(|tenant| (tenant.key_path.clone(), tenant.scope.scope_id().to_owned())); + #[cfg(not(feature = "security-module"))] + let requested: Option<(std::path::PathBuf, String)> = registration_id.and(None); + saas_host_grant_with( + saas, + forced, + tool_name, + &SecretGrantClaim { + tenant_profile: profile.as_deref(), + tenant_key: tenant_key.as_deref(), + requested: requested + .as_ref() + .map(|(key, scope)| (key.as_path(), scope.as_str())), + }, + ) +} + +/// The prompt surface of a host-authorised grant: nobody is shown anything; +/// it only records which request the engine made durable for this call. +#[derive(Default)] +struct HostGrantSurface { + delivered: Mutex>, +} + +#[async_trait::async_trait] +impl PromptSurface for HostGrantSurface { + async fn deliver(&self, delivery: Delivery) -> Result<(), String> { + let mut delivered = self.delivered.lock(); + if delivered + .as_deref() + .is_some_and(|id| id != delivery.request_id) + { + return Err("this host grant already has a request".into()); + } + *delivered = Some(delivery.request_id); + Ok(()) + } +} + +/// Cancels the request a host grant's engine made durable when the grant's +/// future is dropped before it resolves (a turn backstop or a dropped gateway +/// call), mirroring the ordinary park's [`CancelGuard`]. It is installed +/// before `check` (the request can be delivered while the check is still in +/// flight) and disarmed on every normal exit, each of which already settles +/// the request itself. +struct HostGrantCancelGuard { + engine: SharedEngine, + surface: Arc, + armed: bool, +} + +impl HostGrantCancelGuard { + fn disarm(&mut self) { + self.armed = false; + } +} + +impl Drop for HostGrantCancelGuard { + fn drop(&mut self) { + if !self.armed { + return; + } + let Some(request_id) = self.surface.delivered.lock().clone() else { + return; + }; + let engine = Arc::clone(&self.engine); + let cancelled = request_id.clone(); + match tokio::runtime::Handle::try_current() { + Ok(handle) => { + handle.spawn(async move { + if let Err(error) = engine.cancel(&cancelled).await { + tracing::debug!( + request_id = %cancelled, + error = %error, + "[security][saas-grant] the engine did not cancel the dropped grant" + ); + } + }); + } + Err(_) => tracing::debug!( + request_id = %request_id, + "[security][saas-grant] no runtime to cancel the dropped grant; it expires on its own" + ), + } + tracing::warn!( + request_id = %request_id, + "[security][saas-grant] host grant dropped before it resolved; cancelling its request" + ); + } +} + +impl ApprovalGate { + /// The gate's answer for a SaaS secret master grant nobody can be asked + /// about, `None` for every other call (including one a person will + /// decide on a routable WebChat turn). + #[allow(clippy::too_many_arguments)] + async fn saas_host_grant_outcome( + &self, + dispatch: &crate::core::runtime::DispatchCtx, + saas: bool, + human_will_decide: bool, + forced: bool, + tool_name: &str, + action_summary: &str, + args_redacted: &serde_json::Value, + ) -> Option<(GateOutcome, Option)> { + if human_will_decide { + return None; + } + match saas_host_grant(dispatch, saas, forced, tool_name, args_redacted) { + SaasHostGrant::NotApplicable => None, + SaasHostGrant::Authorised { profile, scope_id } => Some( + self.saas_host_authorised_grant( + tool_name, + action_summary, + args_redacted.clone(), + &profile, + &scope_id, + ) + .await, + ), + SaasHostGrant::Refused(why) => { + tracing::warn!(why, "[security][saas-grant] host authorisation refused"); + Some(( + GateOutcome::Deny { + reason: format!( + "{POLICY_DENIED_MARKER} The host cannot authorise '{tool_name}': {why}." + ), + }, + None, + )) + } + } + } + + /// Approve a SaaS tenant's own secret master grant as the host. The + /// engine makes the request durable exactly as for a person, then the + /// host decides it once under [`SAAS_HOST_AUTHORISED`]. Any other answer + /// from the engine denies. + async fn saas_host_authorised_grant( + &self, + tool_name: &str, + action_summary: &str, + args_redacted: serde_json::Value, + profile: &str, + scope_id: &str, + ) -> (GateOutcome, Option) { + let deny = |why: &str| { + tracing::warn!( + tenant = profile, + scope_id, + why, + "[security][saas-grant] host authorisation failed; denying" + ); + ( + GateOutcome::Deny { + reason: format!( + "{POLICY_DENIED_MARKER} The host could not authorise '{tool_name}': {why}." + ), + }, + None, + ) + }; + let surface = Arc::new(HostGrantSurface::default()); + let mut guard = HostGrantCancelGuard { + engine: Arc::clone(&self.engine), + surface: Arc::clone(&surface), + armed: true, + }; + let input = CheckInput { + tenant: super::gate::current_route_tenant(), + variant: Variant::Forced, + posture: Posture { + require_approval: true, + ..Posture::default() + }, + legacy_tool_grants: Vec::new(), + call_id: fresh_call_id(), + tool: tool_name.to_string(), + args: object_arguments(args_redacted), + summary: action_summary.to_string(), + thread: None, + flow: None, + origin: CallOrigin::Operator, + ttl: self.effective_ttl(), + prompt: Arc::clone(&surface) as Arc, + }; + let checked = self.engine.check(input).await; + // Each arm below settles the request, or hands it to `decide`, which + // re-arms the guard; no await runs in between. + guard.disarm(); + let request_id = match checked { + Ok(Checked::Pending { request_id, .. }) + if surface.delivered.lock().as_deref() == Some(request_id.as_str()) => + { + request_id + } + Ok(Checked::Pending { request_id, .. }) | Ok(Checked::Approved { request_id }) => { + let _ = self.engine.cancel(&request_id).await; + return deny("the engine did not ask for this grant"); + } + Err(error) => return deny(&error.to_string()), + }; + // Re-armed for `decide`: a drop while it is in flight cancels the + // still-pending request. + guard.armed = true; + let decided = self + .engine + .decide(&request_id, Choice::Once, host_grant_label()) + .await; + guard.disarm(); + match decided { + Ok(super::engine::Decided::Approved) => { + // As for a person's approval of this grant: TinySecurity's + // ExecuteSecret2 consumes the HumanOnce grant itself. + self.engine.release(&request_id); + tracing::info!( + tenant = profile, + scope_id, + request_id = %request_id, + "[security][saas-grant] host authorised the tenant's own secret master grant" + ); + (GateOutcome::Allow, None) + } + Ok(super::engine::Decided::Denied) => deny("the engine recorded a denial"), + Err(error) => { + let _ = self.engine.cancel(&request_id).await; + deny(&error.to_string()) + } + } + } +} diff --git a/crates/openhuman-core/src/security/approval/gate_saas_grant_tests.rs b/crates/openhuman-core/src/security/approval/gate_saas_grant_tests.rs new file mode 100644 index 00000000000..d3a06063ecd --- /dev/null +++ b/crates/openhuman-core/src/security/approval/gate_saas_grant_tests.rs @@ -0,0 +1,291 @@ +use super::*; +use std::path::{Path, PathBuf}; + +fn key(profile: &str) -> PathBuf { + Path::new("/srv/saas/users") + .join(profile) + .join(".secret_key") +} + +fn claim<'a>( + profile: Option<&'a str>, + tenant_key: Option<&'a Path>, + requested_key: Option<&'a Path>, +) -> SecretGrantClaim<'a> { + SecretGrantClaim { + tenant_profile: profile, + tenant_key, + requested: requested_key.map(|path| (path, "scope-under-test")), + } +} + +#[test] +fn a_tenant_unlocking_its_own_secret_scope_is_host_authorised() { + let alice = key("alice"); + let verdict = saas_host_grant_with( + true, + true, + NATIVE_SECRET_GRANT_TOOL, + &claim(Some("alice"), Some(&alice), Some(&alice)), + ); + assert_eq!( + verdict, + SaasHostGrant::Authorised { + profile: "alice".into(), + scope_id: "scope-under-test".into(), + } + ); +} + +#[test] +fn a_tenant_unlocking_another_tenants_secret_scope_is_refused() { + let (alice, bob) = (key("alice"), key("bob")); + let verdict = saas_host_grant_with( + true, + true, + NATIVE_SECRET_GRANT_TOOL, + &claim(Some("alice"), Some(&alice), Some(&bob)), + ); + assert!(matches!(verdict, SaasHostGrant::Refused(_)), "{verdict:?}"); +} + +#[test] +fn a_tenant_unlocking_the_operator_scope_is_refused() { + let alice = key("alice"); + let operator = Path::new("/srv/saas/operator/.secret_key"); + let verdict = saas_host_grant_with( + true, + true, + NATIVE_SECRET_GRANT_TOOL, + &claim(Some("alice"), Some(&alice), Some(operator)), + ); + assert!(matches!(verdict, SaasHostGrant::Refused(_)), "{verdict:?}"); +} + +#[test] +fn a_secret_grant_without_a_tenant_scope_is_refused() { + let alice = key("alice"); + for unscoped in [ + claim(None, None, Some(&alice)), + claim(None, Some(&alice), Some(&alice)), + // The tenant is named but the host cannot place its secret scope. + claim(Some("alice"), None, Some(&alice)), + // The registration the grant would unlock is not live. + claim(Some("alice"), Some(&alice), None), + ] { + let verdict = saas_host_grant_with(true, true, NATIVE_SECRET_GRANT_TOOL, &unscoped); + assert!(matches!(verdict, SaasHostGrant::Refused(_)), "{verdict:?}"); + } +} + +#[test] +fn the_dispatch_without_a_profile_resolves_to_a_refusal_in_saas() { + // The test process is not SaaS, so an unbound dispatch reads the default + // tenant, which names no profile. + let verdict = saas_host_grant( + &crate::core::runtime::DispatchCtx::unbound(), + true, + true, + NATIVE_SECRET_GRANT_TOOL, + &serde_json::json!({"registration_id": "unknown-registration"}), + ); + assert!(matches!(verdict, SaasHostGrant::Refused(_)), "{verdict:?}"); +} + +#[test] +fn outside_saas_the_host_never_authorises_a_secret_grant() { + let alice = key("alice"); + let verdict = saas_host_grant_with( + false, + true, + NATIVE_SECRET_GRANT_TOOL, + &claim(Some("alice"), Some(&alice), Some(&alice)), + ); + assert_eq!(verdict, SaasHostGrant::NotApplicable); +} + +#[test] +fn other_forced_tools_in_saas_are_not_host_authorised() { + let alice = key("alice"); + for tool in ["browser", "shell", "native_secret_grant_extra"] { + let verdict = saas_host_grant_with( + true, + true, + tool, + &claim(Some("alice"), Some(&alice), Some(&alice)), + ); + assert_eq!(verdict, SaasHostGrant::NotApplicable, "{tool}"); + assert!( + matches!( + saas_outcome_with( + &crate::core::runtime::DispatchCtx::unbound(), + true, + &AgentTurnOrigin::Unknown, + true, + tool, + ), + Some(GateOutcome::Deny { .. }) + ), + "{tool}" + ); + } + // An unforced secret grant is no master grant request either. + let verdict = saas_host_grant_with( + true, + false, + NATIVE_SECRET_GRANT_TOOL, + &claim(Some("alice"), Some(&alice), Some(&alice)), + ); + assert_eq!(verdict, SaasHostGrant::NotApplicable); +} + +#[tokio::test] +async fn the_host_approves_a_matching_tenants_grant_and_audits_it_as_the_host() { + let (gate, _dir) = test_gate(); + let (outcome, tracked) = gate + .saas_host_authorised_grant( + NATIVE_SECRET_GRANT_TOOL, + "Unlock configuration secrets", + serde_json::json!({"registration_id": "alice-registration"}), + "alice", + "scope-under-test", + ) + .await; + assert!(matches!(outcome, GateOutcome::Allow), "{outcome:?}"); + assert_eq!(tracked, None, "the module consumes the grant itself"); + let stub = stub_of(&gate); + let requests = stub.request_ids(); + assert_eq!(requests.len(), 1); + assert_eq!( + stub.state(&requests[0]), + Some(crate::security::approval::engine_stub::State::Approved) + ); + assert_eq!( + stub.label(&requests[0]).as_deref(), + Some(SAAS_HOST_AUTHORISED) + ); + let seen = stub.seen(); + assert_eq!(seen[0].variant, Variant::Forced); + assert_eq!(seen[0].tool, NATIVE_SECRET_GRANT_TOOL); + assert!( + gate.list_pending().unwrap().is_empty(), + "no human prompt is left behind" + ); +} + +#[tokio::test] +async fn the_host_grant_fails_closed_when_the_engine_cannot_ask() { + let (gate, _dir) = test_gate(); + stub_of(&gate).refuse_checks(true); + let (outcome, _) = gate + .saas_host_authorised_grant( + NATIVE_SECRET_GRANT_TOOL, + "Unlock configuration secrets", + serde_json::json!({"registration_id": "alice-registration"}), + "alice", + "scope-under-test", + ) + .await; + assert!(matches!(outcome, GateOutcome::Deny { .. }), "{outcome:?}"); +} + +#[tokio::test] +async fn outside_saas_a_secret_grant_still_waits_for_a_person() { + let (gate, _dir) = test_gate(); + let gate = Arc::new(gate); + let worker = Arc::clone(&gate); + let asked = tokio::spawn(async move { + turn_origin::with_origin( + AgentTurnOrigin::Cli, + worker.intercept_forced( + NATIVE_SECRET_GRANT_TOOL, + "Unlock configuration secrets", + serde_json::json!({"registration_id": "desktop-registration"}), + ), + ) + .await + }); + let pending = tokio::time::timeout(Duration::from_secs(5), async { + loop { + if let Some(row) = gate.list_pending().unwrap().into_iter().next() { + break row; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("the secret grant never parked for a person"); + assert_eq!(pending.tool_name, NATIVE_SECRET_GRANT_TOOL); + assert!(!asked.is_finished(), "nobody approved it yet"); + let stub = stub_of(&gate); + assert_ne!( + stub.label(&pending.request_id).as_deref(), + Some(SAAS_HOST_AUTHORISED) + ); + decide_parked(&gate, &pending.request_id, ApprovalDecision::Deny); + assert!(matches!(asked.await.unwrap(), GateOutcome::Deny { .. })); +} + +/// Drop the host grant once the engine has made its request durable (while +/// `check` or `decide` is still in flight): the delivered request is cancelled, +/// so a later unlock never meets an abandoned pending row. +async fn dropped_host_grant_leaves_no_pending_request( + hold: fn(&crate::security::approval::engine_stub::StubEngine), +) { + let (gate, _dir) = test_gate(); + let gate = Arc::new(gate); + let stub = stub_of(&gate); + hold(&stub); + let worker = Arc::clone(&gate); + let grant = tokio::spawn(async move { + worker + .saas_host_authorised_grant( + NATIVE_SECRET_GRANT_TOOL, + "Unlock configuration secrets", + serde_json::json!({"registration_id": "alice-registration"}), + "alice", + "scope-under-test", + ) + .await + }); + let request_id = tokio::time::timeout(Duration::from_secs(5), async { + loop { + if let Some(id) = stub.request_ids().into_iter().next() { + break id; + } + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + .await + .expect("the engine never made the request durable"); + tokio::time::sleep(Duration::from_millis(20)).await; + assert!(!grant.is_finished(), "the grant is still in flight"); + grant.abort(); + let _ = grant.await; + let cancelled = tokio::time::timeout(Duration::from_secs(5), async { + loop { + if stub.state(&request_id) + == Some(crate::security::approval::engine_stub::State::Cancelled) + { + break; + } + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + .await; + assert!( + cancelled.is_ok(), + "the dropped grant left request {request_id} as {:?}", + stub.state(&request_id) + ); +} + +#[tokio::test] +async fn a_host_grant_dropped_while_check_is_in_flight_cancels_its_request() { + dropped_host_grant_leaves_no_pending_request(|stub| stub.hold_after_delivery(true)).await; +} + +#[tokio::test] +async fn a_host_grant_dropped_while_decide_is_in_flight_cancels_its_request() { + dropped_host_grant_leaves_no_pending_request(|stub| stub.hold_decides(true)).await; +} diff --git a/crates/openhuman-core/src/security/approval/gate_state.rs b/crates/openhuman-core/src/security/approval/gate_state.rs index d07c1dbff3b..194b89d5904 100644 --- a/crates/openhuman-core/src/security/approval/gate_state.rs +++ b/crates/openhuman-core/src/security/approval/gate_state.rs @@ -395,12 +395,29 @@ impl ApprovalGate { /// The requests this tenant has parked and not yet seen decided, oldest /// first. A SaaS profile sees every agent's; anything else sees only its own /// agent's (the process, for the default orchestrator). + /// + /// The process's own list also carries the requests an earlier launch left + /// undecided (the engine's pending orphans), after its parked ones. pub fn list_pending(&self) -> anyhow::Result> { let tenant = super::gate::current_route_tenant(); - Ok(self.pending_where(|route| { + let mut rows = self.pending_where(|route| { route.tenant.profile == tenant.profile && (tenant.profile.is_some() || route.tenant.agent == tenant.agent) - })) + }); + if tenant == crate::core::runtime::Tenant::default() { + // The parked list stands on its own: an engine that cannot answer + // costs only the orphans. + let orphans = self + .run_engine(|engine| async move { engine.orphans().await })? + .unwrap_or_else(|error| { + tracing::warn!(error = %error, "[approval::gate] pending orphans were not listed"); + Vec::new() + }); + let parked: std::collections::HashSet = + rows.iter().map(|row| row.request_id.clone()).collect(); + rows.extend(orphans.into_iter().filter(|row| !parked.contains(&row.request_id))); + } + Ok(rows) } /// [`Self::list_pending`] narrowed to `agent`'s requests; `None` lists the diff --git a/crates/openhuman-core/src/security/approval/gate_tests.rs b/crates/openhuman-core/src/security/approval/gate_tests.rs index 59b334d05f1..027c9e957eb 100644 --- a/crates/openhuman-core/src/security/approval/gate_tests.rs +++ b/crates/openhuman-core/src/security/approval/gate_tests.rs @@ -227,8 +227,14 @@ mod engine_tests; mod forced_tests; #[path = "gate_origin_class_tests.rs"] mod gate_origin_class_tests; +#[path = "gate_host_grant_tests.rs"] +mod host_grant_tests; #[path = "gate_origin_intercept_tests.rs"] mod origin_intercept_tests; +#[path = "gate_rpc_decide_tests.rs"] +mod rpc_decide_tests; +#[path = "gate_saas_grant_tests.rs"] +mod saas_grant_tests; #[path = "gate_subagent_tests.rs"] mod subagent_tests; #[path = "gate_tenant_tests.rs"] diff --git a/crates/openhuman-core/src/security/approval/native/engine_impl.rs b/crates/openhuman-core/src/security/approval/native/engine_impl.rs index b61c840da77..c1d0e1e6384 100644 --- a/crates/openhuman-core/src/security/approval/native/engine_impl.rs +++ b/crates/openhuman-core/src/security/approval/native/engine_impl.rs @@ -224,7 +224,16 @@ impl ApprovalEngine for NativeEngine { Choice::Once => ApprovalChoice2::Once, Choice::Deny => ApprovalChoice2::Deny, }, - ACTOR.to_owned(), + // A SaaS host's own approval of a tenant's secret grant is + // audited under its own actor, never as a person's. + if label == crate::security::approval::gate::SAAS_HOST_AUTHORISED { + crate::security::approval::gate::SAAS_HOST_AUTHORISED + } else if label == crate::security::approval::gate::EMBEDDER_HOST_AUTHORISED { + crate::security::approval::gate::EMBEDDER_HOST_AUTHORISED + } else { + ACTOR + } + .to_owned(), ), ); let decided = async { @@ -392,6 +401,18 @@ impl ApprovalEngine for NativeEngine { .map_err(|error| unavailable(error.to_string())) } + async fn orphans( + &self, + ) -> Result, EngineError> { + // Reaching the module runs the one-time legacy import first, which is + // where an earlier launch's undecided requests become orphans. + self.proxy().await?; + let now = u64::try_from(chrono::Utc::now().timestamp_millis()).unwrap_or(0); + super::super::view::orphans(&self.config, now, |id| host().request(id).is_some()) + .await + .map_err(|error| unavailable(error.to_string())) + } + async fn history(&self, limit: usize) -> Result, EngineError> { super::super::view::decided_history(&self.config, limit) .await diff --git a/crates/openhuman-core/src/security/approval/native/history_import.rs b/crates/openhuman-core/src/security/approval/native/history_import.rs index d621d70b63d..d2482cc5c49 100644 --- a/crates/openhuman-core/src/security/approval/native/history_import.rs +++ b/crates/openhuman-core/src/security/approval/native/history_import.rs @@ -6,7 +6,11 @@ //! //! - each decided request becomes inert history through `ImportApprovalHistory2` //! (the module keeps a sanitized copy in a denied row and never revives it as a -//! grant), at most [`HISTORY_LIMIT`] of the most recent; and +//! grant), at most [`HISTORY_LIMIT`] of the most recent; +//! - each request still undecided and unexpired becomes a pending orphan through +//! the same call (contract 2.2): the module stores it with its redacted tool +//! name, summary and arguments so it can be listed, binds it to a synthetic call +//! no real call can match, and accepts only a denial for it; and //! - each "approve always for this flow" grant becomes durable flow trust through //! `GrantFlowTool2`. //! @@ -101,11 +105,21 @@ pub(super) fn state_of(row: &LegacyApproval) -> ApprovalState { } } Some(_) => ApprovalState::Denied, - // An undecided request of an earlier launch can never be resumed. + // An undecided request of an earlier launch can never be resumed, but one + // still inside its window stays visible until a person dismisses it. + None if expiry(row) > chrono::Utc::now() => ApprovalState::Pending, None => ApprovalState::Expired, } } +/// When the legacy request's window closes. +fn expiry(row: &LegacyApproval) -> chrono::DateTime { + row.expires_at.unwrap_or_else(|| { + row.created_at + + chrono::Duration::milliseconds(i64::try_from(DEFAULT_WINDOW_MS).unwrap_or(i64::MAX)) + }) +} + fn millis(at: chrono::DateTime) -> u64 { u64::try_from(at.timestamp_millis()).unwrap_or(0) } @@ -124,6 +138,8 @@ pub(super) fn legacy_record(row: &LegacyApproval) -> ApprovalRecord { .as_bytes() ) ); + let state = state_of(row); + let pending = state == ApprovalState::Pending; ApprovalRecord { request_id: row.request_id.clone(), fingerprint, @@ -138,12 +154,12 @@ pub(super) fn legacy_record(row: &LegacyApproval) -> ApprovalRecord { expires_at_ms: row .expires_at .map_or_else(|| millis(row.created_at) + DEFAULT_WINDOW_MS, millis), - state: state_of(row), - // TinySecurity 0.21 carries these only for an undecided row it imports as a - // pending orphan; this import keeps sending decided history, as before. - tool_name: None, - summary: None, - args_redacted: None, + state, + // Only a pending orphan is rendered, so only it carries what a person + // needs to recognize it; the module redacts each again before storing. + tool_name: pending.then(|| row.tool_name.clone()), + summary: pending.then(|| row.summary.clone()).flatten(), + args_redacted: pending.then(|| row.args_redacted.clone()).flatten(), } } @@ -159,9 +175,34 @@ pub(super) fn recent_decided(history: &LegacyHistory) -> Vec<&LegacyApproval> { decided.split_off(skip) } +/// The undecided rows still inside their window, oldest first. +pub(super) fn open_requests(history: &LegacyHistory) -> Vec<&LegacyApproval> { + let mut open: Vec<&LegacyApproval> = history + .approvals + .iter() + .filter(|row| state_of(row) == ApprovalState::Pending) + .collect(); + open.sort_by_key(|row| row.created_at); + open.truncate(HISTORY_LIMIT); + open +} + +/// Read the legacy history on a thread of its own. +/// +/// The read is a synchronous storage call, and the gate reaches the engine from +/// the storage bridge's own runtime (`run_engine`), whose threads, blocking pool +/// included, refuse to re-enter the bridge. A plain OS thread is outside it. async fn read(config: Config) -> Result, EngineError> { - crate::core::runtime::DispatchCtx::ambient() - .spawn_blocking(move || read_legacy(&config)) + let (reply, result) = tokio::sync::oneshot::channel(); + std::thread::Builder::new() + .name("approval-history-import".into()) + .spawn(move || { + let _ = reply.send(read_legacy(&config)); + }) + .map_err(|error| { + EngineError::Unavailable(format!("the legacy read did not start: {error}")) + })?; + result .await .map_err(|error| { EngineError::Unavailable(format!("the legacy read did not finish: {error}")) @@ -180,7 +221,10 @@ pub(super) async fn run( let mut report = Report::default(); if !history.approvals.is_empty() { let scope = engine.history_scope(proxy, &tenant).await?; - for row in recent_decided(&history) { + for row in recent_decided(&history) + .into_iter() + .chain(open_requests(&history)) + { match import_row(proxy, &scope, row).await { Ok(()) => report.history += 1, Err(error @ EngineError::Unavailable(_)) => return Err(error), diff --git a/crates/openhuman-core/src/security/approval/native/history_import_tests.rs b/crates/openhuman-core/src/security/approval/native/history_import_tests.rs index 49395302905..75ca305a174 100644 --- a/crates/openhuman-core/src/security/approval/native/history_import_tests.rs +++ b/crates/openhuman-core/src/security/approval/native/history_import_tests.rs @@ -13,6 +13,8 @@ fn legacy(id: &str, decision: Option<&str>, executed: bool, age_minutes: i64) -> decided_at: decision.map(|_| created + Duration::seconds(5)), decision: decision.map(str::to_owned), executed, + summary: decision.is_none().then(|| format!("run {id}")), + args_redacted: decision.is_none().then(|| r#"{"cmd":"ls"}"#.to_owned()), } } @@ -30,13 +32,51 @@ fn a_legacy_decision_maps_to_the_module_state_it_ended_in() { state_of(&legacy("a", Some("deny"), false, 1)), ApprovalState::Denied ); - // A request an earlier launch left undecided can never be resumed. + // A request an earlier launch left undecided stays visible while its window + // is open, and is history once it closed. assert_eq!( state_of(&legacy("a", None, false, 1)), + ApprovalState::Pending + ); + assert_eq!( + state_of(&legacy("a", None, false, 11)), ApprovalState::Expired ); } +#[test] +fn an_undecided_row_in_its_window_is_sent_as_a_pending_orphan_a_person_can_recognize() { + let record = legacy_record(&legacy("still-pending", None, false, 1)); + assert_eq!(record.state, ApprovalState::Pending); + assert_eq!(record.tool_name.as_deref(), Some("composio")); + assert_eq!(record.summary.as_deref(), Some("run still-pending")); + assert_eq!(record.args_redacted.as_deref(), Some(r#"{"cmd":"ls"}"#)); + + // Once its window closed it is inert history and carries none of them. + let expired = legacy_record(&legacy("gone", None, false, 11)); + assert_eq!(expired.state, ApprovalState::Expired); + assert_eq!( + (expired.tool_name, expired.summary, expired.args_redacted), + (None, None, None) + ); +} + +#[test] +fn only_the_undecided_rows_still_in_their_window_are_imported_as_open_requests() { + let mut history = LegacyHistory::default(); + history + .approvals + .push(legacy("decided", Some("deny"), false, 1)); + history.approvals.push(legacy("expired", None, false, 11)); + history.approvals.push(legacy("newer", None, false, 1)); + history.approvals.push(legacy("older", None, false, 2)); + let open: Vec<&str> = open_requests(&history) + .iter() + .map(|row| row.request_id.as_str()) + .collect(); + assert_eq!(open, ["older", "newer"]); +} + #[test] fn the_legacy_record_carries_identity_without_the_arguments_or_summary() { let row = legacy("req-1", Some("deny"), false, 3); @@ -192,3 +232,19 @@ async fn a_legacy_import_that_cannot_reach_the_module_remains_retryable() { 1 ); } + +/// The gate reaches the engine from the storage bridge's runtime +/// (`run_engine`), and the first engine call runs this import, whose legacy +/// read is itself a synchronous storage call. +#[test] +fn the_legacy_read_works_from_inside_a_storage_bridge_call() { + let (_dir, config) = workspace(); + seed_legacy(&config); + let read_back = crate::storage::block_on_anyhow(async move { + read(config) + .await + .map_err(|error| anyhow::anyhow!("{error}")) + }) + .expect("the legacy history is readable from the bridge"); + assert_eq!(read_back.expect("seeded history").approvals.len(), 1); +} diff --git a/crates/openhuman-core/src/security/approval/native/rows.rs b/crates/openhuman-core/src/security/approval/native/rows.rs index c421e282904..16cc341d25b 100644 --- a/crates/openhuman-core/src/security/approval/native/rows.rs +++ b/crates/openhuman-core/src/security/approval/native/rows.rs @@ -347,6 +347,18 @@ impl Rows { page.items.iter().map(decode_row).collect() } + /// Pending rows whose window is still open, oldest first. + pub(super) async fn open(&self, now: u64, limit: usize) -> Result, String> { + self.ready().await?; + let cutoff = i64::try_from(now).unwrap_or(i64::MAX); + let query = + Query::filter(Filter::eq("pending", true).and(Filter::gt("expires_ts", cutoff))) + .sort(Sort::asc("expires_ts")) + .limit(limit); + let page = self.docs.query(ROWS, &query).await.map_err(storage)?; + page.items.iter().map(decode_row).collect() + } + /// Pending rows whose window elapsed, oldest first. pub(super) async fn stale(&self, now: u64, limit: usize) -> Result, String> { self.ready().await?; diff --git a/crates/openhuman-core/src/security/approval/native/view.rs b/crates/openhuman-core/src/security/approval/native/view.rs index aaa3a8df7f5..49c2ae9f2c9 100644 --- a/crates/openhuman-core/src/security/approval/native/view.rs +++ b/crates/openhuman-core/src/security/approval/native/view.rs @@ -4,7 +4,7 @@ use chrono::{DateTime, TimeZone, Utc}; use serde_json::Value; use tinysecurity_bus::{ApprovalChoice2, ApprovalLifecycle2, ApprovalRow2, JudgeEvidence2}; -use super::super::types::{ApprovalAuditEntry, ApprovalDecision, JudgeVerdict}; +use super::super::types::{ApprovalAuditEntry, ApprovalDecision, JudgeVerdict, PendingApproval}; use super::rows::{Rows, StoredRow}; use crate::config::Config; @@ -55,15 +55,21 @@ const FLOW_TRUST: &str = "flow-trust-grant"; /// The summary a flow pre-authorization has always shown in the history. const FLOW_TRUST_SUMMARY: &str = "Pre-authorized for this flow when it was saved and enabled"; -/// What an imported legacy request was decided as, from the record the module -/// kept (`legacy_history_json`). -fn imported_decision(row: &ApprovalRow2) -> Option { +/// What an imported legacy request was decided as, and the request id it had in +/// the earlier version, from the record the module kept (`legacy_history_json`). +fn imported_decision(row: &ApprovalRow2) -> Option<(ApprovalDecision, Option)> { let json = row.legacy_history_json.as_deref()?; let record: Value = serde_json::from_str(json).ok()?; - Some(match record.get("state").and_then(Value::as_str) { + let decision = match record.get("state").and_then(Value::as_str) { Some("allowed" | "executed") => ApprovalDecision::ApproveOnce, _ => ApprovalDecision::Deny, - }) + }; + let request_id = record + .get("request_id") + .and_then(Value::as_str) + .filter(|id| !id.is_empty()) + .map(str::to_owned); + Some((decision, request_id)) } fn entry(stored: &StoredRow, label: Option<&str>) -> Option { @@ -87,9 +93,9 @@ fn entry(stored: &StoredRow, label: Option<&str>) -> Option judge: None, }); } - if let Some(decision) = imported_decision(row) { + if let Some((decision, legacy_id)) = imported_decision(row) { return Some(ApprovalAuditEntry { - request_id: row.request_id.clone(), + request_id: legacy_id.unwrap_or_else(|| row.request_id.clone()), tool_name: "earlier approval".to_owned(), action_summary: "Recorded by an earlier version".to_owned(), args_redacted: Value::Null, @@ -135,6 +141,39 @@ pub(crate) async fn decided_history( Ok(entries) } +/// Pending rows no request of this process is waiting on: requests an earlier +/// launch left undecided, which the module imported as pending orphans. Oldest +/// window first. +pub(crate) async fn orphans( + config: &Config, + now_ms: u64, + live: impl Fn(&str) -> bool, +) -> anyhow::Result> { + let rows = Rows::current(config).await?; + let open = rows + .open(now_ms, 500) + .await + .map_err(|error| anyhow::anyhow!(error))?; + Ok(open + .iter() + .map(|stored| &stored.row) + .filter(|row| !live(&row.request_id)) + .map(|row| { + let mut pending = PendingApproval::new( + row.request_id.clone(), + row.tool_name.clone(), + row.summary.clone(), + serde_json::from_str::(&row.args_redacted).unwrap_or(Value::Null), + Some(instant( + i64::try_from(row.expires_at_ms).unwrap_or(i64::MAX), + )), + ); + pending.created_at = instant(i64::try_from(row.created_at_ms).unwrap_or(i64::MAX)); + pending + }) + .collect()) +} + /// Whether the request was stored and has left `Pending`. `None` when it is not /// stored at all. pub(crate) async fn row_decided(config: &Config, request_id: &str) -> anyhow::Result> { diff --git a/crates/openhuman-core/src/security/approval/native/view_tests.rs b/crates/openhuman-core/src/security/approval/native/view_tests.rs index 8224eb03827..92cfa0cdf2f 100644 --- a/crates/openhuman-core/src/security/approval/native/view_tests.rs +++ b/crates/openhuman-core/src/security/approval/native/view_tests.rs @@ -185,3 +185,19 @@ fn an_imported_legacy_request_reads_by_the_state_it_ended_in() { assert_eq!(shown.tool_name, "earlier approval"); } } + +#[test] +fn an_imported_legacy_request_keeps_the_request_id_it_had_in_the_earlier_version() { + let mut imported = row(ApprovalLifecycle2::Denied); + imported.tool_name = "imported-history".into(); + imported.choice = None; + imported.legacy_history_json = + Some(r#"{"request_id":"already-approved","state":"allowed"}"#.into()); + let shown = entry(&stored(imported.clone()), None).unwrap(); + assert_eq!(shown.request_id, "already-approved"); + + // A record without one keeps the module's row id. + imported.legacy_history_json = Some(r#"{"state":"allowed"}"#.into()); + let shown = entry(&stored(imported.clone()), None).unwrap(); + assert_eq!(shown.request_id, imported.request_id); +} diff --git a/crates/openhuman-core/src/security/approval/registration_scope.rs b/crates/openhuman-core/src/security/approval/registration_scope.rs index a171e42729a..3c387a3661d 100644 --- a/crates/openhuman-core/src/security/approval/registration_scope.rs +++ b/crates/openhuman-core/src/security/approval/registration_scope.rs @@ -27,6 +27,18 @@ impl ApprovalScope { self.reason.get().is_some() } + /// The denial for `tool_name` when its approval check failed and `scope` + /// has closed. A refused prompt delivery reaches the gate from the native + /// engine only as an opaque module-bus failure, so the closure reason is + /// named here, where the host still holds it. `None` while open. + pub(crate) fn closed_denial(scope: Option<&Self>, tool_name: &str) -> Option { + let reason = scope?.reason.get()?; + Some(format!( + "{} Agent approval registration closed for '{tool_name}': {reason}", + tinytools::status::POLICY_DENIED_MARKER + )) + } + /// Run synchronous registration or a decision while holding the removal barrier. pub(crate) fn with_open(&self, register: impl FnOnce() -> T) -> Result { let _closed = self diff --git a/crates/openhuman-core/src/security/approval/registration_scope_tests.rs b/crates/openhuman-core/src/security/approval/registration_scope_tests.rs index c358c94ceac..4b175a8e243 100644 --- a/crates/openhuman-core/src/security/approval/registration_scope_tests.rs +++ b/crates/openhuman-core/src/security/approval/registration_scope_tests.rs @@ -86,3 +86,22 @@ fn a_reused_agent_id_has_a_fresh_scope_and_preserves_the_old_removal_reason() { assert_eq!(old.with_open(|| ()), Err("agent_removed".to_owned())); assert_eq!(ApprovalScope::default().with_open(|| 42), Ok(42)); } + +#[test] +fn a_failed_check_on_a_closed_scope_is_denied_with_the_closure_reason() { + let scope = ApprovalScope::default(); + assert_eq!(ApprovalScope::closed_denial(None, "write_marker"), None); + assert_eq!( + ApprovalScope::closed_denial(Some(&scope), "write_marker"), + None + ); + scope.close("agent_removed"); + scope.close("later_reason"); + let denial = ApprovalScope::closed_denial(Some(&scope), "write_marker").unwrap(); + assert!( + denial.starts_with(tinytools::status::POLICY_DENIED_MARKER), + "{denial}" + ); + assert!(denial.contains("'write_marker'"), "{denial}"); + assert!(denial.ends_with(": agent_removed"), "{denial}"); +} diff --git a/crates/openhuman-core/src/security/approval/rpc.rs b/crates/openhuman-core/src/security/approval/rpc.rs index b791bfb9ce3..143ffb816eb 100644 --- a/crates/openhuman-core/src/security/approval/rpc.rs +++ b/crates/openhuman-core/src/security/approval/rpc.rs @@ -19,6 +19,32 @@ use super::types::{ /// writing unbounded rows. const MAX_PREAUTHORIZE_TOOLS: usize = 100; +/// Apply a decision for `tenant` without blocking the calling runtime. +/// +/// [`ApprovalGate::decide_as`] blocks on the engine, and the engine's decision +/// waits for the parked call's own check to release its subject's audit stream +/// (`native/engine_impl.rs`). That check finishes on the task that parked it, +/// which may be on the runtime serving this RPC (always so on a current-thread +/// runtime). Deciding inline would stall the thread that has to finish it, so +/// the decision runs on a blocking thread. +pub(crate) async fn decide_off_the_caller_runtime( + gate: std::sync::Arc, + tenant: crate::core::runtime::Tenant, + agent: Option, + request_id: String, + decision: ApprovalDecision, +) -> anyhow::Result> { + tracing::debug!( + request_id = %request_id, + decision = decision.as_str(), + "[rpc:approval_decide] deciding on a blocking thread" + ); + crate::core::runtime::DispatchCtx::ambient() + .spawn_blocking(move || gate.decide_as(&tenant, agent.as_deref(), &request_id, decision)) + .await + .map_err(|error| anyhow!("the approval decision worker failed: {error}"))? +} + /// Read the host-aware approval-gate boot decision so the UI banner can /// render the right state on first paint (rather than waiting for a /// connected socket subscriber to catch a transient boot-time event). @@ -264,7 +290,14 @@ pub async fn approval_decide( ); anyhow!(error) })?; - let decided = gate.decide_as(&tenant, agent_id, request_id, decision); + let decided = decide_off_the_caller_runtime( + std::sync::Arc::clone(&gate), + tenant, + agent_id.map(str::to_owned), + request_id.to_owned(), + decision, + ) + .await; let decided = match decided { Ok(row) => row, Err(err) => { diff --git a/crates/openhuman-core/src/security/approval/store_documents.rs b/crates/openhuman-core/src/security/approval/store_documents.rs index b2e2d9adc79..1863239b696 100644 --- a/crates/openhuman-core/src/security/approval/store_documents.rs +++ b/crates/openhuman-core/src/security/approval/store_documents.rs @@ -96,6 +96,24 @@ fn to_audit(stored: &Versioned) -> Option { }) } +#[cfg(feature = "security-module")] +fn to_undecided(stored: &Versioned) -> super::store_import::LegacyApproval { + let doc = &stored.doc; + let created_at = from_ms(millis(doc, "created_ms")).unwrap_or_else(Utc::now); + super::store_import::LegacyApproval { + request_id: stored.id.clone(), + tool_name: text(doc, "tool_name").unwrap_or_default().to_string(), + agent_id: text(doc, "agent_id").map(str::to_owned), + created_at, + expires_at: from_ms(millis(doc, "deadline_ms")), + decided_at: None, + decision: None, + executed: false, + summary: text(doc, "action_summary").map(str::to_owned), + args_redacted: text(doc, "args_redacted").map(str::to_owned), + } +} + #[cfg(feature = "security-module")] impl Docs { pub(super) fn new(scoped: &Storage) -> Self { @@ -134,6 +152,22 @@ impl Docs { }) } + /// Reads undecided requests for TinySecurity's one-time import, newest + /// first, with the redacted summary and arguments the store kept. + #[cfg(feature = "security-module")] + pub(super) fn list_undecided( + &self, + limit: usize, + ) -> Result> { + self.run(|docs| async move { + let query = Query::filter(Filter::eq("pending", true)) + .sort(Sort::desc("created_ms")) + .limit(limit); + let page = docs.query(APPROVALS, &query).await?; + Ok(page.items.iter().map(to_undecided).collect()) + }) + } + /// Reads historical flow grants for TinySecurity's one-time import. #[cfg(feature = "security-module")] pub(super) fn list_all_flow_trust(&self) -> Result> { diff --git a/crates/openhuman-core/src/security/approval/store_import.rs b/crates/openhuman-core/src/security/approval/store_import.rs index 88cd1a99717..94f0cde1e0e 100644 --- a/crates/openhuman-core/src/security/approval/store_import.rs +++ b/crates/openhuman-core/src/security/approval/store_import.rs @@ -29,6 +29,11 @@ pub(crate) struct LegacyApproval { pub(crate) decided_at: Option>, pub(crate) decision: Option, pub(crate) executed: bool, + /// The redacted summary the legacy store kept; read only for an undecided + /// row, which TinySecurity imports as a pending orphan a person can see. + pub(crate) summary: Option, + /// The redacted argument JSON the legacy store kept; undecided rows only. + pub(crate) args_redacted: Option, } /// One persisted legacy flow-and-tool grant. @@ -65,8 +70,13 @@ pub(crate) fn read_legacy(config: &Config) -> Result> { decided_at: Some(row.decided_at), decision: Some(row.decision.as_str().to_owned()), executed: false, + summary: None, + args_redacted: None, }) .collect(); + // Requests an earlier launch left undecided; the module keeps an unexpired + // one as a pending orphan and an expired one as inert history. + history.approvals.extend(docs.list_undecided(500)?); history.trust = docs .list_all_flow_trust()? .into_iter() diff --git a/crates/openhuman-core/src/security/live_policy.rs b/crates/openhuman-core/src/security/live_policy.rs index 9018a7e55ff..f7731390f40 100644 --- a/crates/openhuman-core/src/security/live_policy.rs +++ b/crates/openhuman-core/src/security/live_policy.rs @@ -73,7 +73,7 @@ pub fn install( policy } -#[cfg(test)] +#[cfg(any(test, feature = "test-keyring-consent"))] thread_local! { /// Test-only, **thread-scoped** [`PrivacyMode`] override. When set it wins /// over the process-global policy in [`current_privacy_mode`]. @@ -89,7 +89,10 @@ thread_local! { /// on the same thread while sibling tests on their own threads are unaffected. static TEST_PRIVACY_MODE: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} +#[cfg(test)] +thread_local! { /// Test-only, thread-scoped live-policy override. Approval-gate tests run /// in parallel on separate `#[tokio::test]` current-thread runtimes, so a /// process-global override can otherwise make an unrelated test observe a @@ -99,10 +102,11 @@ thread_local! { } /// RAII guard that restores the previous thread-local privacy override on drop. -#[cfg(test)] -pub(crate) struct TestPrivacyGuard(Option); +#[cfg(any(test, feature = "test-keyring-consent"))] +#[must_use = "the override lasts only while the guard is alive"] +pub struct TestPrivacyGuard(Option); -#[cfg(test)] +#[cfg(any(test, feature = "test-keyring-consent"))] impl Drop for TestPrivacyGuard { fn drop(&mut self) { TEST_PRIVACY_MODE.with(|c| c.set(self.0)); @@ -112,8 +116,13 @@ impl Drop for TestPrivacyGuard { /// Override [`current_privacy_mode`] for the current thread until the returned /// guard drops. Test-only; needs no `TEST_ENV_LOCK` because it never touches the /// process-global policy. -#[cfg(test)] -pub(crate) fn test_privacy_scope(mode: PrivacyMode) -> TestPrivacyGuard { +/// +/// Also test support for downstream crates (the hosted embedder's egress guard +/// tests), so they can drive a restrictive mode deterministically whether or not +/// TinySecurity is staged. Not built into the product (`test-keyring-consent` is +/// a test-only feature). +#[cfg(any(test, feature = "test-keyring-consent"))] +pub fn test_privacy_scope(mode: PrivacyMode) -> TestPrivacyGuard { let prev = TEST_PRIVACY_MODE.with(|c| c.replace(Some(mode))); TestPrivacyGuard(prev) } @@ -157,7 +166,7 @@ pub(crate) fn install_scoped( pub fn current_privacy_mode() -> PrivacyMode { // Test-only per-thread override (see `TEST_PRIVACY_MODE`) wins so a test can // drive the egress gate without mutating the shared process-global policy. - #[cfg(test)] + #[cfg(any(test, feature = "test-keyring-consent"))] if let Some(mode) = TEST_PRIVACY_MODE.with(|c| c.get()) { return mode; } diff --git a/crates/openhuman-core/src/security/prompt_injection/detector.rs b/crates/openhuman-core/src/security/prompt_injection/detector.rs index bd847441eaa..d18962d7fb8 100644 --- a/crates/openhuman-core/src/security/prompt_injection/detector.rs +++ b/crates/openhuman-core/src/security/prompt_injection/detector.rs @@ -284,10 +284,13 @@ pub(crate) async fn enforce_prompt_input_with_config( Ok(answer) } else { let (config, input) = (config.clone(), input.to_owned()); - let task = crate::modules::runtime::spawn_on_bus(async move { + // The bus task starts with no ambient context: carry the caller's, or + // a SaaS tenant's scan loads TinySecurity with no storage scope. + let scan = crate::core::runtime::CoreContext::propagate(async move { let _ = crate::modules::security::ensure_loaded(&config).await; scan_within_budget(&config, &input).await }); + let task = crate::modules::runtime::spawn_on_bus(scan); match task { Ok(task) => task .await diff --git a/crates/openhuman-core/src/storage/README.md b/crates/openhuman-core/src/storage/README.md index eec5db1ea38..b991234b755 100644 --- a/crates/openhuman-core/src/storage/README.md +++ b/crates/openhuman-core/src/storage/README.md @@ -316,8 +316,11 @@ without fencing). (`security::secret_storage::get` / `set` / `delete`) and the flow store's `http-credentials.json` become encrypted documents (`DocumentSecrets`, `enc2:`) in the acting agent's scope. Auth profiles use their own - profile-local `EncryptedFileSecrets` document at `auth-profiles/secrets.enc`. - Each + profile-local `EncryptedFileSecrets` document at `auth-profiles/secrets.enc`, + except a SaaS tenant's: under that tenant's context its document is the + secret `auth-profiles` in the tenant's scope, locked by compare-and-swap on + the backend, with nothing written beside the profile + (`credentials/profiles/backend.rs`). Each scope's data key is derived with HKDF-SHA256 from the keyring master key (`OPENHUMAN_KEYRING_MASTER_KEY` / `_FILE`, else the OS keychain); with no master key they fail closed. The config encryption key stays on the diff --git a/crates/openhuman-core/src/tools/impl/network/host.rs b/crates/openhuman-core/src/tools/impl/network/host.rs index 99beb8f97e6..222db7ce5c0 100644 --- a/crates/openhuman-core/src/tools/impl/network/host.rs +++ b/crates/openhuman-core/src/tools/impl/network/host.rs @@ -287,17 +287,28 @@ mod x402 { /// held here and the hook is built per call. #[derive(Debug)] pub(super) struct X402PaymentHook { - ctx: DispatchCtx, + /// Weak: `PerCallTool` also builds a prototype `http_request` when the + /// belt is assembled, under the building request's context, and a + /// cached chat session keeps that belt in its tenant's own state slots. + /// A strong context would keep the tenant in use + /// (`CoreContext::tenant_in_use`), so its profile slot never frees. + core: Option>, chat: Option, } impl X402PaymentHook { pub(super) fn new(ctx: &DispatchCtx, chat: Option<&ApprovalChatContext>) -> Self { Self { - ctx: ctx.clone(), + core: ctx.downgrade(), chat: chat.cloned(), } } + + /// The context the payment runs under: the one this hook was built + /// for while it lives, else the calling task's own. + fn ctx(&self) -> DispatchCtx { + DispatchCtx::from_weak(self.core.as_ref()) + } } #[async_trait] @@ -314,8 +325,8 @@ mod x402 { .ok_or_else(|| { "402 response is missing a valid PAYMENT-REQUIRED header".to_string() })?; - let config = self - .ctx + let ctx = self.ctx(); + let config = ctx .load_config() .await .map_err(|error| format!("x402 payment failed: {error}"))?; @@ -328,7 +339,7 @@ mod x402 { client_id: context.client_id.clone(), }); let (service, payment) = x402_service::prepare_payment( - &self.ctx, + &ctx, &config, url.to_owned(), challenge.to_owned(), diff --git a/crates/openhuman-core/src/web_chat/session.rs b/crates/openhuman-core/src/web_chat/session.rs index 4a7aa109c47..7260c5e5350 100644 --- a/crates/openhuman-core/src/web_chat/session.rs +++ b/crates/openhuman-core/src/web_chat/session.rs @@ -634,3 +634,7 @@ mod session_checkout_agents_tests; #[cfg(test)] #[path = "session_routing_tests.rs"] mod session_routing_tests; + +#[cfg(test)] +#[path = "session_tenant_release_tests.rs"] +mod session_tenant_release_tests; diff --git a/crates/openhuman-core/src/web_chat/session_tenant_release_tests.rs b/crates/openhuman-core/src/web_chat/session_tenant_release_tests.rs new file mode 100644 index 00000000000..dca7fa9f30f --- /dev/null +++ b/crates/openhuman-core/src/web_chat/session_tenant_release_tests.rs @@ -0,0 +1,59 @@ +//! A web-chat session agent is cached in its tenant's own state slots +//! (`web_chat::ops::thread_sessions`) once its turn ends, so anything in it +//! that holds the tenant's context strongly keeps the tenant in use +//! (`CoreContext::tenant_in_use`) and its SaaS profile slot never frees. + +use std::sync::Arc; + +use crate::core::runtime::{ContextOverlay, CoreContext, DispatchCtx, DomainSet}; +use crate::tools::toolpacks::ToolGroups; + +#[tokio::test] +async fn a_cached_session_agent_does_not_keep_its_tenant_in_use() { + let tmp = tempfile::tempdir().unwrap(); + let config = super::session_checkout_tests::test_config(&tmp).await; + let root = CoreContext::for_test(DomainSet::full(), None); + // Every domain and every tool group, so the whole belt is built. + let profile = root.derive_with( + ContextOverlay::new(config.clone(), DomainSet::full(), ToolGroups::advertised()) + .profile("p1"), + ); + let request = Arc::clone(&profile); + let agent = CoreContext::scope_with_turn_origin(Arc::clone(&profile), None, async move { + super::build_session_agent( + &DispatchCtx::new(request), + &config, + "client-1", + "thread-1", + "orchestrator", + None, + None, + ) + .await + }) + .await + .unwrap_or_else(|error| panic!("the session agent builds: {error}")); + let names: Vec<&str> = agent.tools().iter().map(|tool| tool.name()).collect(); + let mut expected = vec!["create_artifact", "http_request", "web_fetch", "curl"]; + if cfg!(feature = "web3") { + expected.push("x402_request"); + } + for expected in expected { + assert!( + names.contains(&expected), + "{expected} is in the belt: {names:?}" + ); + } + // Building the session starts short background work of its own (the + // flow-authoring prewarm) that holds the tenant while it runs; that has to + // finish. What may not happen is a hold that outlives it. + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + while profile.tenant_in_use() && std::time::Instant::now() < deadline { + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + } + assert!( + !profile.tenant_in_use(), + "the session agent kept past its turn pins the tenant; belt: {names:?}" + ); + drop(agent); +} diff --git a/crates/openhuman-embed/src/runtime/build.rs b/crates/openhuman-embed/src/runtime/build.rs index b92fbd6e571..cae0793756f 100644 --- a/crates/openhuman-embed/src/runtime/build.rs +++ b/crates/openhuman-embed/src/runtime/build.rs @@ -569,7 +569,11 @@ pub(crate) fn routed_provider_effective(provider: &Provider, config: Option<&Con } async fn store_api_key(config: &Config, key: &ApiKey) -> Result<(), RuntimeError> { - openhuman_core::credentials::api_key::store_api_key(config, key.expose()) + // The host supplied this key for its own runtime: it authorises the + // secret master grant of this config directory, which nobody else can + // answer before the core (and its approval gate) boots. + let store = openhuman_core::credentials::api_key::store_api_key(config, key.expose()); + openhuman_core::security::approval::gate::host_authorised_secret_grant(config, store) .await .map(|_| ()) .map_err(RuntimeError::Build) diff --git a/crates/openhuman-embed/tests/api_key_boot.rs b/crates/openhuman-embed/tests/api_key_boot.rs new file mode 100644 index 00000000000..367493e6d0b --- /dev/null +++ b/crates/openhuman-embed/tests/api_key_boot.rs @@ -0,0 +1,38 @@ +//! A library host that supplies its own API key boots with nobody to answer an +//! approval: storing the key needs TinySecurity's secret master grant before the +//! core (and its approval gate) exists, and the host's own key is what +//! authorises that grant. One test: the consent environment is process-wide. + +mod common; + +use common::{offline_config, runtime_without_master_key, stub_backend}; +use openhuman_embed::{Runtime, Workspace}; + +#[test] +fn a_runtime_built_with_its_own_api_key_boots_without_a_consent_answer() { + // Nothing may answer the grant on the host's behalf: no test responder. + std::env::remove_var("OPENHUMAN_TEST_KEYRING_CONSENT"); + std::thread::Builder::new() + .stack_size(openhuman_core::core::runtime::AGENT_WORKER_STACK_BYTES) + .spawn(|| { + runtime_without_master_key().block_on(async { + let backend = stub_backend().await; + let runtime = tokio::time::timeout( + std::time::Duration::from_secs(120), + Runtime::builder() + .config(offline_config()) + .workspace(Workspace::Ephemeral) + .backend_url(backend.uri()) + .api_key("sk-fixture") + .build(), + ) + .await + .expect("the build is not left waiting on an approval") + .expect("a runtime built with its own API key boots"); + drop(runtime); + }); + }) + .unwrap() + .join() + .unwrap(); +} diff --git a/crates/openhuman-embed/tests/profile_direct_providers.rs b/crates/openhuman-embed/tests/profile_direct_providers.rs index 30f3c0cc0c3..dde2909529b 100644 --- a/crates/openhuman-embed/tests/profile_direct_providers.rs +++ b/crates/openhuman-embed/tests/profile_direct_providers.rs @@ -228,9 +228,34 @@ async fn scenario() { "gemini answered" ); let exa_before = exa.received_requests().await.unwrap().len(); + // A canonical role name is not callable: the profile's capability + // hook refuses it as a tool error the model reads (the turn itself + // completes), and the search provider is never reached. + let requests_before = chat_requests(&chat).await.len(); + handle + .chat("t2", "use the canonical name") + .await + .expect("a refused unknown tool is a tool error, not a failed turn"); + let tool_results: Vec = chat_requests(&chat).await[requests_before..] + .iter() + .flat_map(|request| { + let body: Value = serde_json::from_slice(&request.body).unwrap(); + body["messages"].as_array().cloned().unwrap_or_default() + }) + .filter(|message| message["role"] == "tool") + .map(|message| message["content"].to_string()) + .collect(); + let refused = tool_results.iter().any(|content| { + content.contains("denied web_search_tool") + && content.contains("outside the hosted profile capability boundary") + }); + if !refused { + // The linked module's panic hook drops assertion payloads. + eprintln!("profile_direct_providers: tool results {tool_results:?}"); + } assert!( - handle.chat("t2", "use the canonical name").await.is_err(), - "a canonical role name is not callable" + refused, + "a canonical role name is not callable: {tool_results:?}" ); assert_eq!(exa.received_requests().await.unwrap().len(), exa_before); } diff --git a/crates/openhuman-embed/tests/profile_host_capabilities.rs b/crates/openhuman-embed/tests/profile_host_capabilities.rs index 9913b74bf71..bf4f95e7199 100644 --- a/crates/openhuman-embed/tests/profile_host_capabilities.rs +++ b/crates/openhuman-embed/tests/profile_host_capabilities.rs @@ -1,15 +1,15 @@ //! Profile-owned host tools and a shared memory engine stay within each tenant. //! One runtime and one test: SaaS operating mode is process-wide. +#[path = "profile_host_capabilities/call_tools.rs"] +mod call_tools; mod common; use std::sync::{Arc, Mutex}; use std::time::Duration; -use common::{ - chat_completion, chat_requests, runtime_without_master_key, tool_call_completion, tool_names, - PointedInference, -}; +use call_tools::CallTools; +use common::{chat_requests, runtime_without_master_key, tool_names, PointedInference}; use openhuman_embed::memory::api::conformance::ReferenceEngine; use openhuman_embed::memory::api::{LearningKind, MemoryEngine, MemoryMeta, StoreItem}; use openhuman_embed::profiles::ProfileCredentialKind; @@ -21,7 +21,7 @@ use openhuman_embed::{ ToolScopeSpec, }; use serde_json::{json, Value}; -use wiremock::{Mock, Request, Respond, ResponseTemplate}; +use wiremock::{Mock, ResponseTemplate}; struct TenantTool { name: &'static str, @@ -105,81 +105,6 @@ impl Tool for TenantTool { } } -struct CallTools; -impl Respond for CallTools { - fn respond(&self, request: &Request) -> ResponseTemplate { - let body: Value = serde_json::from_slice(&request.body).unwrap(); - let messages = body["messages"].as_array().unwrap(); - let last_user = messages - .iter() - .rposition(|message| message["role"] == "user") - .unwrap(); - let has_tool_results = messages[last_user + 1..] - .iter() - .any(|message| message["role"] == "tool"); - let completion = if common::last_user_message(&body).contains("deny callback request") - && !has_tool_results - { - tool_call_completion("tenant_probe", r#"{"deny":true}"#) - } else if common::last_user_message(&body).contains("unsafe fixture request") { - let mut completion = tool_call_completion("shell", "{}"); - completion["choices"][0]["message"]["tool_calls"] = json!(["shell", "spawn_subagent", "http_request", "run_workflow"].iter().enumerate().map(|(i, name)| json!({"id":format!("unsafe_{i}"),"type":"function","function":{"name":name,"arguments":"{}"}})).collect::>()); - completion - } else if has_tool_results - || !tool_names(request) - .iter() - .any(|name| name == "tenant_probe") - { - let message = common::last_user_message(&body); - let user = if message.contains("alice") { - "alice" - } else { - "bob" - }; - let channel = if message.contains("\"telegram\" channel") { - "relay" - } else { - "chat" - }; - let reopened = if message.contains("after reopening") { - "reopened-" - } else { - "" - }; - chat_completion(&format!("done: {reopened}{channel}:{user}")) - } else { - let mut completion = tool_call_completion("tenant_probe", "{}"); - let names = ["tenant_probe"]; - completion["choices"][0]["message"]["tool_calls"] = json!(names.iter().enumerate().map(|(i, name)| json!({"id":format!("call_{i}"),"type":"function","function":{"name":name,"arguments":"{}"}})).collect::>()); - let message = common::last_user_message(&body); - let user = if message.contains("alice") { - "alice" - } else { - "bob" - }; - completion["choices"][0]["message"]["tool_calls"].as_array_mut().unwrap().push(json!({ - "id":"native-memory", "type":"function", "function":{"name":"memory", "arguments":json!({"action":"learn", "text":format!("{user}-native-learning")}).to_string()} - })); - completion - }; - if body.get("stream").and_then(Value::as_bool) != Some(true) { - return ResponseTemplate::new(200).set_body_json(completion); - } - let mut delta = completion["choices"][0]["message"].clone(); - if let Some(calls) = delta["tool_calls"].as_array_mut() { - for (index, call) in calls.iter_mut().enumerate() { - call["index"] = json!(index); - } - } - let chunk = json!({"id":"fixture", "object":"chat.completion.chunk", "created":1700000000_u64, "model":"fixture", "choices":[{"index":0,"delta":delta,"finish_reason":null}]}); - let done = json!({"id":"fixture", "object":"chat.completion.chunk", "created":1700000000_u64, "model":"fixture", "choices":[{"index":0,"delta":{},"finish_reason":completion["choices"][0]["finish_reason"]}], "usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}); - ResponseTemplate::new(200).set_body_raw( - format!("data: {chunk}\n\ndata: {done}\n\ndata: [DONE]\n\n"), - "text/event-stream", - ) - } -} - #[test] fn chat_and_relay_use_only_selected_tools_inside_their_profile() { let _ = tracing_subscriber::fmt() @@ -383,19 +308,60 @@ async fn scenario() { ); } let executions_before_denied_turn = calls.lock().unwrap().len(); - assert!( - handles[0] - .chat("denied", "unsafe fixture request") - .await - .is_err(), - "unregistered unsafe model calls must fail closed" - ); + // Unregistered unsafe names fail closed at the profile's capability hook + // as tool errors the model reads (the turn itself completes): each one is + // refused by name, and none of them runs. + let requests_before_denied_turn = chat_requests(&inference).await.len(); + handles[0] + .chat("denied", "unsafe fixture request") + .await + .expect("a refused tool call is a tool error, not a failed turn"); + let tool_results: Vec = chat_requests(&inference).await[requests_before_denied_turn..] + .iter() + .flat_map(|request| { + let body: Value = serde_json::from_slice(&request.body).unwrap(); + body["messages"].as_array().cloned().unwrap_or_default() + }) + .filter(|message| message["role"] == "tool") + .map(|message| message["content"].to_string()) + .collect(); + for name in ["shell", "spawn_subagent", "http_request", "run_workflow"] { + let refused = tool_results.iter().any(|content| { + content.contains(&format!("denied {name}:")) + && content.contains("outside the hosted profile capability boundary") + }); + if !refused { + // The linked module's panic hook drops assertion payloads. + eprintln!( + "profile_host_capabilities: {name} not refused; tool results {tool_results:?}" + ); + } + assert!( + refused, + "unregistered unsafe model call {name} must be refused" + ); + } assert_eq!(calls.lock().unwrap().len(), executions_before_denied_turn); + // The operator callback refuses even a registered safe name, again as a + // tool error the model reads; the tool does not run. + let requests_before_callback_denial = chat_requests(&inference).await.len(); + handles[0] + .chat("callback-denied", "deny callback request") + .await + .expect("a refused tool call is a tool error, not a failed turn"); + let callback_refused = chat_requests(&inference).await[requests_before_callback_denial..] + .iter() + .any(|request| { + let body = String::from_utf8_lossy(&request.body); + body.contains("denied tenant_probe") && body.contains("operator refused this call") + }); + if !callback_refused { + eprintln!( + "profile_host_capabilities: the operator callback's refusal did not reach the model" + ); + } assert!( - handles[0] - .chat("callback-denied", "deny callback request") - .await - .is_err(), + callback_refused, "the operator callback must refuse even a registered safe name" ); assert_eq!(calls.lock().unwrap().len(), executions_before_denied_turn); diff --git a/crates/openhuman-embed/tests/profile_host_capabilities/call_tools.rs b/crates/openhuman-embed/tests/profile_host_capabilities/call_tools.rs new file mode 100644 index 00000000000..b9f63d0bda6 --- /dev/null +++ b/crates/openhuman-embed/tests/profile_host_capabilities/call_tools.rs @@ -0,0 +1,83 @@ +//! Scripted inference for `profile_host_capabilities`: each user turn names the +//! tools the model calls, so the test drives chat and relay deterministically. + +use serde_json::{json, Value}; +use wiremock::{Request, Respond, ResponseTemplate}; + +use super::common::{chat_completion, tool_call_completion, tool_names}; + +pub(crate) struct CallTools; +impl Respond for CallTools { + fn respond(&self, request: &Request) -> ResponseTemplate { + let body: Value = serde_json::from_slice(&request.body).unwrap(); + let messages = body["messages"].as_array().unwrap(); + let last_user = messages + .iter() + .rposition(|message| message["role"] == "user") + .unwrap(); + let has_tool_results = messages[last_user + 1..] + .iter() + .any(|message| message["role"] == "tool"); + let completion = if super::common::last_user_message(&body) + .contains("deny callback request") + && !has_tool_results + { + tool_call_completion("tenant_probe", r#"{"deny":true}"#) + } else if super::common::last_user_message(&body).contains("unsafe fixture request") { + let mut completion = tool_call_completion("shell", "{}"); + completion["choices"][0]["message"]["tool_calls"] = json!(["shell", "spawn_subagent", "http_request", "run_workflow"].iter().enumerate().map(|(i, name)| json!({"id":format!("unsafe_{i}"),"type":"function","function":{"name":name,"arguments":"{}"}})).collect::>()); + completion + } else if has_tool_results + || !tool_names(request) + .iter() + .any(|name| name == "tenant_probe") + { + let message = super::common::last_user_message(&body); + let user = if message.contains("alice") { + "alice" + } else { + "bob" + }; + let channel = if message.contains("\"telegram\" channel") { + "relay" + } else { + "chat" + }; + let reopened = if message.contains("after reopening") { + "reopened-" + } else { + "" + }; + chat_completion(&format!("done: {reopened}{channel}:{user}")) + } else { + let mut completion = tool_call_completion("tenant_probe", "{}"); + let names = ["tenant_probe"]; + completion["choices"][0]["message"]["tool_calls"] = json!(names.iter().enumerate().map(|(i, name)| json!({"id":format!("call_{i}"),"type":"function","function":{"name":name,"arguments":"{}"}})).collect::>()); + let message = super::common::last_user_message(&body); + let user = if message.contains("alice") { + "alice" + } else { + "bob" + }; + completion["choices"][0]["message"]["tool_calls"].as_array_mut().unwrap().push(json!({ + "id":"native-memory", "type":"function", "function":{"name":"memory", "arguments":json!({"action":"learn", "text":format!("{user}-native-learning")}).to_string()} + })); + completion + }; + if body.get("stream").and_then(Value::as_bool) != Some(true) { + return ResponseTemplate::new(200).set_body_json(completion); + } + let mut delta = completion["choices"][0]["message"].clone(); + if let Some(calls) = delta["tool_calls"].as_array_mut() { + for (index, call) in calls.iter_mut().enumerate() { + call["index"] = json!(index); + } + } + let chunk = json!({"id":"fixture", "object":"chat.completion.chunk", "created":1700000000_u64, "model":"fixture", "choices":[{"index":0,"delta":delta,"finish_reason":null}]}); + let done = json!({"id":"fixture", "object":"chat.completion.chunk", "created":1700000000_u64, "model":"fixture", "choices":[{"index":0,"delta":{},"finish_reason":completion["choices"][0]["finish_reason"]}], "usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}); + ResponseTemplate::new(200).set_body_raw( + format!("data: {chunk}\n\ndata: {done}\n\ndata: [DONE]\n\n"), + "text/event-stream", + ) + } +} diff --git a/crates/openhuman-embed/tests/profile_operator_tools.rs b/crates/openhuman-embed/tests/profile_operator_tools.rs index 49cd9934155..9256f1151e7 100644 --- a/crates/openhuman-embed/tests/profile_operator_tools.rs +++ b/crates/openhuman-embed/tests/profile_operator_tools.rs @@ -22,9 +22,27 @@ use wiremock::{Mock, MockServer, Request, Respond, ResponseTemplate}; const CAP: usize = 3; +/// How far ahead of the model's `cron` call the scheduled one-shot fires. +/// Counted from the call, not from the start of the test: the scheduler +/// refuses an `at` that has already passed, so a window that also had to +/// cover the turns before the call failed whenever a loaded machine made +/// them slower than the window. +const FIRE_LEAD: chrono::Duration = chrono::Duration::seconds(5); + /// Scripts the model from the last user message. +#[derive(Default)] struct Script { - fire_at: String, + /// When the agent job the model scheduled fires, set as it asks for it. + fire_at: Arc>>>, +} + +impl Script { + /// A fire time `FIRE_LEAD` from now, recorded for the test to wait on. + fn next_fire_at(&self) -> String { + let at = chrono::Utc::now() + FIRE_LEAD; + *self.fire_at.lock().unwrap() = Some(at); + at.to_rfc3339() + } } impl Respond for Script { @@ -49,13 +67,13 @@ impl Respond for Script { call( "cron", json!({"action":"add","job_type":"agent","name":"ping", - "schedule":{"kind":"at","at":self.fire_at},"prompt":"reminder ping"}), + "schedule":{"kind":"at","at":self.next_fire_at()},"prompt":"reminder ping"}), ) } else if prompt.contains("shell job") && results == 0 { call( "cron", json!({"action":"add","job_type":"shell","name":"sh", - "schedule":{"kind":"at","at":self.fire_at},"command":"echo hi"}), + "schedule":{"kind":"at","at":self.next_fire_at()},"command":"echo hi"}), ) } else if prompt.contains("reminder ping") { chat_completion("pong") @@ -104,13 +122,12 @@ fn operator_named_cron_and_time_tools_run_on_a_direct_provider_within_the_iterat async fn scenario() { let (managed, chat) = (MockServer::start().await, MockServer::start().await); - let fire_at = chrono::Utc::now() + chrono::Duration::seconds(6); + let script = Script::default(); + let fire_at = Arc::clone(&script.fire_at); Mock::given(method("POST")) .and(path_regex(r"/v1/chat/completions$")) .and(header("authorization", "Bearer operator-chat-key")) - .respond_with(Script { - fire_at: fire_at.to_rfc3339(), - }) + .respond_with(script) .mount(&chat) .await; // No managed credential exists, so any managed traffic is a failure. @@ -175,6 +192,10 @@ async fn scenario() { // An agent job made through the tool binds to this thread and fires. handle.chat("t1", "schedule it").await.unwrap(); + let fire_at = fire_at + .lock() + .unwrap() + .expect("the model scheduled the job"); common::wait_until(fire_at).await; assert_eq!(runtime.sweep_cron_at(chrono::Utc::now()).await.ran, 1); tokio::time::timeout(Duration::from_secs(30), async { diff --git a/crates/openhuman-embed/tests/runtime_agents.rs b/crates/openhuman-embed/tests/runtime_agents.rs index 8dff86b44d5..80d220c5b6b 100644 --- a/crates/openhuman-embed/tests/runtime_agents.rs +++ b/crates/openhuman-embed/tests/runtime_agents.rs @@ -105,8 +105,10 @@ fn one_runtime_hosts_independently_configured_agents() { .mount(&provider_b) .await; let mut budget_completion = chat_completion("budget-metered"); - budget_completion["usage"]["prompt_tokens"] = serde_json::json!(1_000_000); - budget_completion["usage"]["total_tokens"] = serde_json::json!(1_000_001); + // Below gpt-5.5's 272K long-context step, so the call bills at the + // standard $5/MTok input rate: $1.25 against the $1 cap. + budget_completion["usage"]["prompt_tokens"] = serde_json::json!(250_000); + budget_completion["usage"]["total_tokens"] = serde_json::json!(250_001); Mock::given(method("POST")) .and(path("/v1/chat/completions")) .respond_with(ResponseTemplate::new(200).set_body_json(budget_completion)) @@ -309,12 +311,12 @@ fn one_runtime_hosts_independently_configured_agents() { assert_eq!(common::chat_requests(&budget_provider).await.len(), 1); assert_eq!( stop_reason.lock().expect("stop reason lock").as_deref(), - Some("turn cost $5.0000 reached cap $1.0000") + Some("turn cost $1.2500 reached cap $1.0000") ); let usage = budgeted_turn .usage .expect("runtime-owned agent reports turn usage"); - assert_eq!(usage.input_tokens, 1_000_000); + assert_eq!(usage.input_tokens, 250_000); assert!( usage.cost_usd.is_some_and(|usd| usd >= 1.0), "budgeted usage: {usage:?}" @@ -609,10 +611,14 @@ fn one_runtime_hosts_independently_configured_agents() { panic!("the test is the runtime's sole owner once every agent is dropped"); }; drop(runtime); - assert!( - !workspace_dir.exists(), - "an ephemeral workspace must be removed with its runtime" - ); + // The workspace goes with the last holder of the runtime's guard: + // the runtime, or a dropped agent's deferred MCP cleanup, which keeps + // the files until the module acknowledges its close (`EphemeralRoot`). + common::eventually( + "the ephemeral workspace to be removed with its runtime", + || (!workspace_dir.exists()).then_some(()), + ) + .await; }) .await .expect("library host task did not panic"); diff --git a/crates/openhuman-rpc/src/server/socketio.rs b/crates/openhuman-rpc/src/server/socketio.rs index 7be534d6fe0..82852bd0f14 100644 --- a/crates/openhuman-rpc/src/server/socketio.rs +++ b/crates/openhuman-rpc/src/server/socketio.rs @@ -30,6 +30,7 @@ use serde::Serialize; use serde_json::json; use serde_json::Value; use socketioxide::extract::{AckSender, Data, SocketRef, TryData}; +use socketioxide::handler::ConnectHandler as _; use socketioxide::SocketIo; use crate::core_host::web_chat::{GuardrailPayload, ScopedWebEvent}; @@ -269,64 +270,19 @@ pub(crate) fn attach_socketio_with_preflight( io.config().engine_config.req_path ); - let handshake_gate = preflight_gate.clone(); io.ns( "/", - // Everything runs in the closure body, not in the future it returns: - // socketioxide 0.18 sends the namespace CONNECT packet before calling - // this handler and spawns the returned future, so handlers registered - // inside an `async` block could miss a client's first events. - move |socket: SocketRef, TryData(handshake): TryData| { + // CONNECT reaches the client after the middleware and before this + // handler (socketioxide 0.18 `Namespace::connect`). A socket the + // middleware refused has no handlers and no auth mark; drop it here. + (move |socket: SocketRef| { let client_id = socket.id.to_string(); - - if handshake_gate.as_ref().is_some_and(|gate| gate.is_active()) { - log::info!("[socketio] rejecting connect during startup preflight client={client_id}"); + if !socket_is_authed(&socket) { + log::warn!("[socketio] disconnecting unauthorized socket client={client_id}"); let _ = socket.clone().disconnect(); return std::future::ready(()); } - // Reject cross-origin browser pages before the handshake completes. - // Native clients (Tauri shell, CLI) do not set an `Origin` header and - // are accepted; only browser pages from origins outside the local - // app surface are dropped here. See `origin_is_allowed`. - let origin = socket - .req_parts() - .headers - .get(axum::http::header::ORIGIN) - .and_then(|v| v.to_str().ok()) - .map(|s| s.to_string()); - if !origin_is_allowed(origin.as_deref()) { - log::warn!( - "[socketio] rejecting connect: bad origin {:?} client={}", - origin, - client_id - ); - let _ = socket.clone().disconnect(); - return std::future::ready(()); - } - - // Verify the handshake bearer matches the per-process RPC token. - // `TryData` lets us treat a missing/malformed `auth` payload as a - // soft failure (no panic) and reject the connect cleanly. - let supplied = handshake.ok().and_then(|h| h.token).unwrap_or_default(); - if !crate::core_host::core::auth::verify_bearer_token(&supplied) { - log::warn!( - "[socketio] rejecting connect: missing or invalid bearer client={}", - client_id - ); - let _ = socket.clone().disconnect(); - return std::future::ready(()); - } - socket.extensions.insert(AuthedConnection); - let Some(tenant) = socket_tenant_from_request_extensions( - &socket.req_parts().extensions, - ) else { - log::warn!("[socketio] rejecting socket without a tenant scope in SaaS mode"); - let _ = socket.clone().disconnect(); - return std::future::ready(()); - }; - socket.extensions.insert(tenant); - log::info!("[socketio] client connected id={client_id} (authenticated)"); // Join a room named after the client ID for targeted event delivery. join_room_logged(&socket, &client_id, &client_id); @@ -347,8 +303,8 @@ pub(crate) fn attach_socketio_with_preflight( // would otherwise have no idea which workspace is active and // could not scope anything. // - // Spawned so the event handlers below are registered without - // waiting on the resolve. Emitting to `socket` rather than + // Spawned so `ready` goes out without waiting on the resolve. + // Emitting to `socket` rather than // broadcasting keeps a late-joining client from re-announcing a // workspace every other client already knows about. { @@ -380,234 +336,21 @@ pub(crate) fn attach_socketio_with_preflight( }); } - // Handler for JSON-RPC over WebSocket. - let rpc_gate = preflight_gate.clone(); - socket.on( - "rpc:request", - move |socket: SocketRef, Data(payload): Data| { - let rpc_gate = rpc_gate.clone(); - async move { - if rpc_gate.as_ref().is_some_and(|gate| gate.is_active()) { - let _ = socket.emit( - "rpc:error", - &json!({ - "id": payload.id, - "error": { - "code": -32003, - "message": "RPC is unavailable during startup approval preflight" - } - }), - ); - return; - } - if !socket_is_authed(&socket) { - drop_unauthed(&socket, "rpc:request from unauthenticated socket"); - return; - } - let client_id = socket.id.to_string(); - log::info!( - "[socketio] rpc:request method={} id={} client={}", - payload.method, - payload.id, - client_id - ); - - // Invoke the method through the same logic used by the HTTP RPC endpoint. - let response = match crate::core_host::core::invoke::invoke_method( - // A Socket.IO event is not scoped to a request, so it - // runs under the process default context. - crate::core_host::core::runtime::DispatchCtx::process_default(), - crate::core_host::core::invoke::default_state(), - payload.method.as_str(), - payload.params, - ) - .await - { - Ok(result) => ( - "rpc:response", - json!({ "id": payload.id, "result": result }), - ), - Err(message) => ( - "rpc:error", - json!({ - "id": payload.id, - "error": { "code": -32000, "message": message } - }), - ), - }; - - let _ = socket.emit(response.0, &response.1); - } - }, - ); - - // Handler for starting a chat turn. - socket.on( - "chat:start", - |socket: SocketRef, Data(payload): Data| async move { - if !socket_is_authed(&socket) { - drop_unauthed(&socket, "chat:start from unauthenticated socket"); - return; - } - let client_id = socket.id.to_string(); - let thread_id = payload.thread_id.clone(); - let model_override = payload.model_override.or(payload.model); - log::debug!( - "[socketio] recv event=chat:start client_id={} thread_id={} message_bytes={}", - client_id, - thread_id, - payload.message.len() - ); - if let Some(run_mode) = payload.run_mode.as_deref() { - match crate::core_host::agent::tinyagents::run_mode::parse_mode_label(run_mode) { - Some(mode) => { - crate::core_host::agent::tinyagents::run_mode::set_mode( - &crate::core_host::core::runtime::DispatchCtx::host_default(), - &thread_id, - mode, - ); - } - None => log::warn!( - "[socketio] chat:start thread_id={thread_id} ignoring unrecognized run_mode={run_mode}" - ), - } - } - - // Trigger the web channel's chat logic. - match crate::core_host::web_chat::start_chat( - // Outside SaaS the host's one context; in SaaS the socket task's own scope. - &crate::core_host::core::runtime::DispatchCtx::host_default(), - &client_id, - &payload.thread_id, - &payload.message, - model_override, - payload.temperature, - payload.locale, - payload.queue_mode, - crate::core_host::web_chat::ChatRequestMetadata::default(), - ) - .await - { - Ok(request_id) => { - let accepted_payload = json!({ - "event": "chat_accepted", - "client_id": client_id, - "thread_id": thread_id, - "request_id": request_id, - }); - emit_with_aliases(&socket, "chat_accepted", &accepted_payload); - } - Err(error) => { - let mut error_payload = json!({ - "event": "chat_error", - "client_id": client_id, - "thread_id": thread_id, - "request_id": "", - "message": error.to_string(), - "error_type": "inference", - }); - // A guardrail rejection is structured (verdict/ - // score/reasons), not just a user-facing message — - // surface it the same way the frontend classifies - // every other `chat_error`: by `error_type`, plus - // a typed `guardrail` payload it doesn't have to - // parse out of `message`. - if let crate::core_host::web_chat::StartChatError::Guardrail { - verdict, - score, - reasons, - } = &error - { - error_payload["error_type"] = json!("guardrail"); - error_payload["guardrail"] = json!(GuardrailPayload { - verdict: verdict.clone(), - score: *score, - reasons: reasons.clone(), - }); - } - emit_with_aliases(&socket, "chat_error", &error_payload); - } - } - }, - ); - - // Handler for cancelling an active chat turn. - socket.on( - "chat:cancel", - |socket: SocketRef, Data(payload): Data| async move { - if !socket_is_authed(&socket) { - drop_unauthed(&socket, "chat:cancel from unauthenticated socket"); - return; - } - let client_id = socket.id.to_string(); - log::debug!( - "[socketio] recv event=chat:cancel client_id={} thread_id={}", - client_id, - payload.thread_id - ); - let _ = crate::core_host::web_chat::cancel_chat_scoped( - &crate::core_host::core::runtime::DispatchCtx::host_default(), - &client_id, - &payload.thread_id, - payload.request_id.as_deref(), - ) - .await; - }, - ); - - // Handler for subscribing this socket to a thread's room. - // - // Chat-stream events are delivered to BOTH the initiating client's - // own room AND a per-thread room (`thread:`). After a socket - // reconnects it has a NEW client_id, so it would miss an in-flight - // turn's remaining stream (delivered to the OLD client_id room). The - // frontend emits this on connect/reconnect for the active thread, so - // the new socket re-joins the thread room and keeps receiving the - // stream. Membership is dropped automatically on disconnect. - // - // The join is acknowledged so a client can *order* work against it. - // A reconnecting client re-reads the thread to pick up a reply that - // landed while it was away (#6034); firing that read before the join - // is processed leaves a window where the read misses the row and the - // turn's `chat_done` is emitted to a room this socket has not joined - // yet, so the reply stays invisible until a manual reload. The ack - // closes it. Clients that ignore the ack are unaffected — an unused - // acknowledgement is inert. - socket.on( - "thread:subscribe", - |socket: SocketRef, Data(payload): Data, ack: AckSender| async move { - if !socket_is_authed(&socket) { - drop_unauthed(&socket, "thread:subscribe from unauthenticated socket"); - return; - } - let thread_id = payload.thread_id.trim(); - if thread_id.is_empty() { - // Still acknowledge: a client awaiting this must not be - // left hanging on its own malformed payload. - ack.send(&ThreadSubscribeAck { joined: false }).ok(); - return; - } - let room = format!("thread:{thread_id}"); - // The ack is sent only after the join, so a client that - // reads on the strength of it is already in the room. - join_room_logged(&socket, &room, &socket.id.to_string()); - // Hand this socket whatever the approval gate still has - // parked on the thread, BEFORE acknowledging the join, so a - // client that orders its recovery reads against the ack - // already holds the card. - replay_parked_approval(&socket, thread_id); - replay_parked_plan_review(&socket, thread_id); - ack.send(&ThreadSubscribeAck { joined: true }).ok(); - }, - ); - - // `ready` goes out last, so a client that waits for it can rely on - // every handler above being registered. + // `ready` goes out last, after the rooms are joined; every event + // handler was registered by the middleware before CONNECT. let ready_payload = json!({ "sid": client_id }); log::debug!("[socketio] emit event=ready to_client={}", socket.id); let _ = socket.emit("ready", &ready_payload); std::future::ready(()) - }, + }) + .with(move |socket: SocketRef, TryData(handshake): TryData| { + let gate = preflight_gate.clone(); + async move { + let token = handshake.ok().and_then(|h| h.token); + events::authorize_and_register(&socket, token, gate); + Ok::<(), std::convert::Infallible>(()) + } + }), ); (layer, io) @@ -1361,3 +1104,6 @@ fn stamp_replay_timestamp(event: &mut crate::core_host::web_chat::WebChannelEven #[cfg(test)] #[path = "socketio_tests.rs"] mod tests; + +#[path = "socketio_events.rs"] +mod events; diff --git a/crates/openhuman-rpc/src/server/socketio_events.rs b/crates/openhuman-rpc/src/server/socketio_events.rs new file mode 100644 index 00000000000..400e845d78e --- /dev/null +++ b/crates/openhuman-rpc/src/server/socketio_events.rs @@ -0,0 +1,299 @@ +//! Socket.IO connect authorization and the per-socket event handlers. +//! +//! Both run in the namespace's connect middleware. socketioxide 0.18 sends the +//! namespace CONNECT packet after the middleware and before the connect +//! handler, and drops an event that arrives for a handler not yet registered. +//! Registered in the connect handler, a client's first event (the app sends +//! `thread:subscribe` as soon as it sees CONNECT) could land in that gap and +//! never be answered. + +use super::*; + +/// Authorizes a connecting socket and, when it passes, marks it authenticated +/// and registers its event handlers. A refused socket gets neither; the +/// connect handler disconnects it. +pub(super) fn authorize_and_register( + socket: &SocketRef, + token: Option, + preflight_gate: Option, +) { + if authorize(socket, token, &preflight_gate) { + register_event_handlers(socket, preflight_gate); + } +} + +fn authorize( + socket: &SocketRef, + token: Option, + handshake_gate: &Option, +) -> bool { + let client_id = socket.id.to_string(); + if handshake_gate.as_ref().is_some_and(|gate| gate.is_active()) { + log::info!("[socketio] rejecting connect during startup preflight client={client_id}"); + return false; + } + + // Reject cross-origin browser pages before the handshake completes. + // Native clients (Tauri shell, CLI) do not set an `Origin` header and + // are accepted; only browser pages from origins outside the local + // app surface are dropped here. See `origin_is_allowed`. + let origin = socket + .req_parts() + .headers + .get(axum::http::header::ORIGIN) + .and_then(|v| v.to_str().ok()) + .map(|s| s.to_string()); + if !origin_is_allowed(origin.as_deref()) { + log::warn!( + "[socketio] rejecting connect: bad origin {:?} client={}", + origin, + client_id + ); + return false; + } + + // Verify the handshake bearer matches the per-process RPC token. + // `TryData` lets us treat a missing/malformed `auth` payload as a + // soft failure (no panic) and reject the connect cleanly. + let supplied = token.unwrap_or_default(); + if !crate::core_host::core::auth::verify_bearer_token(&supplied) { + log::warn!( + "[socketio] rejecting connect: missing or invalid bearer client={}", + client_id + ); + return false; + } + socket.extensions.insert(AuthedConnection); + let Some(tenant) = socket_tenant_from_request_extensions(&socket.req_parts().extensions) else { + log::warn!("[socketio] rejecting socket without a tenant scope in SaaS mode"); + return false; + }; + socket.extensions.insert(tenant); + true +} + +fn register_event_handlers( + socket: &SocketRef, + preflight_gate: Option, +) { + // Handler for JSON-RPC over WebSocket. + let rpc_gate = preflight_gate.clone(); + socket.on( + "rpc:request", + move |socket: SocketRef, Data(payload): Data| { + let rpc_gate = rpc_gate.clone(); + async move { + if rpc_gate.as_ref().is_some_and(|gate| gate.is_active()) { + let _ = socket.emit( + "rpc:error", + &json!({ + "id": payload.id, + "error": { + "code": -32003, + "message": "RPC is unavailable during startup approval preflight" + } + }), + ); + return; + } + if !socket_is_authed(&socket) { + drop_unauthed(&socket, "rpc:request from unauthenticated socket"); + return; + } + let client_id = socket.id.to_string(); + log::info!( + "[socketio] rpc:request method={} id={} client={}", + payload.method, + payload.id, + client_id + ); + + // Invoke the method through the same logic used by the HTTP RPC endpoint. + let response = match crate::core_host::core::invoke::invoke_method( + // A Socket.IO event is not scoped to a request, so it + // runs under the process default context. + crate::core_host::core::runtime::DispatchCtx::process_default(), + crate::core_host::core::invoke::default_state(), + payload.method.as_str(), + payload.params, + ) + .await + { + Ok(result) => ( + "rpc:response", + json!({ "id": payload.id, "result": result }), + ), + Err(message) => ( + "rpc:error", + json!({ + "id": payload.id, + "error": { "code": -32000, "message": message } + }), + ), + }; + + let _ = socket.emit(response.0, &response.1); + } + }, + ); + + // Handler for starting a chat turn. + socket.on( + "chat:start", + |socket: SocketRef, Data(payload): Data| async move { + if !socket_is_authed(&socket) { + drop_unauthed(&socket, "chat:start from unauthenticated socket"); + return; + } + let client_id = socket.id.to_string(); + let thread_id = payload.thread_id.clone(); + let model_override = payload.model_override.or(payload.model); + log::debug!( + "[socketio] recv event=chat:start client_id={} thread_id={} message_bytes={}", + client_id, + thread_id, + payload.message.len() + ); + if let Some(run_mode) = payload.run_mode.as_deref() { + match crate::core_host::agent::tinyagents::run_mode::parse_mode_label(run_mode) { + Some(mode) => { + crate::core_host::agent::tinyagents::run_mode::set_mode( + &crate::core_host::core::runtime::DispatchCtx::host_default(), + &thread_id, + mode, + ); + } + None => log::warn!( + "[socketio] chat:start thread_id={thread_id} ignoring unrecognized run_mode={run_mode}" + ), + } + } + + // Trigger the web channel's chat logic. + match crate::core_host::web_chat::start_chat( + // Outside SaaS the host's one context; in SaaS the socket task's own scope. + &crate::core_host::core::runtime::DispatchCtx::host_default(), + &client_id, + &payload.thread_id, + &payload.message, + model_override, + payload.temperature, + payload.locale, + payload.queue_mode, + crate::core_host::web_chat::ChatRequestMetadata::default(), + ) + .await + { + Ok(request_id) => { + let accepted_payload = json!({ + "event": "chat_accepted", + "client_id": client_id, + "thread_id": thread_id, + "request_id": request_id, + }); + emit_with_aliases(&socket, "chat_accepted", &accepted_payload); + } + Err(error) => { + let mut error_payload = json!({ + "event": "chat_error", + "client_id": client_id, + "thread_id": thread_id, + "request_id": "", + "message": error.to_string(), + "error_type": "inference", + }); + // A guardrail rejection is structured (verdict/ + // score/reasons), not just a user-facing message — + // surface it the same way the frontend classifies + // every other `chat_error`: by `error_type`, plus + // a typed `guardrail` payload it doesn't have to + // parse out of `message`. + if let crate::core_host::web_chat::StartChatError::Guardrail { + verdict, + score, + reasons, + } = &error + { + error_payload["error_type"] = json!("guardrail"); + error_payload["guardrail"] = json!(GuardrailPayload { + verdict: verdict.clone(), + score: *score, + reasons: reasons.clone(), + }); + } + emit_with_aliases(&socket, "chat_error", &error_payload); + } + } + }, + ); + + // Handler for cancelling an active chat turn. + socket.on( + "chat:cancel", + |socket: SocketRef, Data(payload): Data| async move { + if !socket_is_authed(&socket) { + drop_unauthed(&socket, "chat:cancel from unauthenticated socket"); + return; + } + let client_id = socket.id.to_string(); + log::debug!( + "[socketio] recv event=chat:cancel client_id={} thread_id={}", + client_id, + payload.thread_id + ); + let _ = crate::core_host::web_chat::cancel_chat_scoped( + &crate::core_host::core::runtime::DispatchCtx::host_default(), + &client_id, + &payload.thread_id, + payload.request_id.as_deref(), + ) + .await; + }, + ); + + // Handler for subscribing this socket to a thread's room. + // + // Chat-stream events are delivered to BOTH the initiating client's + // own room AND a per-thread room (`thread:`). After a socket + // reconnects it has a NEW client_id, so it would miss an in-flight + // turn's remaining stream (delivered to the OLD client_id room). The + // frontend emits this on connect/reconnect for the active thread, so + // the new socket re-joins the thread room and keeps receiving the + // stream. Membership is dropped automatically on disconnect. + // + // The join is acknowledged so a client can *order* work against it. + // A reconnecting client re-reads the thread to pick up a reply that + // landed while it was away (#6034); firing that read before the join + // is processed leaves a window where the read misses the row and the + // turn's `chat_done` is emitted to a room this socket has not joined + // yet, so the reply stays invisible until a manual reload. The ack + // closes it. Clients that ignore the ack are unaffected — an unused + // acknowledgement is inert. + socket.on( + "thread:subscribe", + |socket: SocketRef, Data(payload): Data, ack: AckSender| async move { + if !socket_is_authed(&socket) { + drop_unauthed(&socket, "thread:subscribe from unauthenticated socket"); + return; + } + let thread_id = payload.thread_id.trim(); + if thread_id.is_empty() { + // Still acknowledge: a client awaiting this must not be + // left hanging on its own malformed payload. + ack.send(&ThreadSubscribeAck { joined: false }).ok(); + return; + } + let room = format!("thread:{thread_id}"); + // The ack is sent only after the join, so a client that + // reads on the strength of it is already in the room. + join_room_logged(&socket, &room, &socket.id.to_string()); + // Hand this socket whatever the approval gate still has + // parked on the thread, BEFORE acknowledging the join, so a + // client that orders its recovery reads against the ack + // already holds the card. + replay_parked_approval(&socket, thread_id); + replay_parked_plan_review(&socket, thread_id); + ack.send(&ThreadSubscribeAck { joined: true }).ok(); + }, + ); +} diff --git a/crates/openhuman-tinyhumans/src/inference/managed_embedding.rs b/crates/openhuman-tinyhumans/src/inference/managed_embedding.rs index 546756ae60d..78a1fcf10a8 100644 --- a/crates/openhuman-tinyhumans/src/inference/managed_embedding.rs +++ b/crates/openhuman-tinyhumans/src/inference/managed_embedding.rs @@ -3,12 +3,17 @@ //! This module constructs the owning `CloudEmbeddingModel` with OpenHuman's //! live credential resolver and the per-request egress disclosure guard. It //! does not wrap or forward the embedding implementation. +//! +//! The doctor's read-only inspection model is the one exception to the guard: +//! it freezes the selected profile's credential, sends only the doctor's fixed +//! probe, and never asks TinySecurity, which the doctor does not load. use std::sync::Arc; use openhuman_embed::__host::egress::{emit_external_transfer, EgressDescriptor}; -use openhuman_embed::__host::inference_registry::{EmbeddingRequest, ProviderContext}; -use openhuman_embed::__host::security::approval::ApprovalChatContext; +use openhuman_embed::__host::inference_registry::{ + EmbeddingCallContext, EmbeddingRequest, ProviderContext, +}; use tinyinference_embeddings::{BearerResolver, CloudEmbeddingModel, EmbeddingEgressGuard}; use super::managed_session::resolve_session_bearer; @@ -16,27 +21,27 @@ use crate::backend::url::effective_api_url; use crate::client::endpoint::is_managed_endpoint_for_api_key; /// Builds the owning cloud embedding implementation with the credential scope -/// and turn context supplied by the inference registry. +/// and turn context supplied by the inference registry. Every batch it sends +/// first passes the TinySecurity egress guard. pub(super) fn from_request(request: EmbeddingRequest) -> CloudEmbeddingModel { let context = request .context .embedding .as_ref() .expect("embedding host context"); - build_cloud_model( + guarded_cloud_model( context .config .as_ref() .and_then(|config| config.api_url.clone()), - context.state_dir.clone(), - context.secrets_encrypt, + context, &request.model, request.dimensions, - context.chat.clone(), - None, ) } +/// Builds the doctor's managed embedding probe from the selected profile's +/// frozen, read-only credential. pub(super) async fn from_request_for_inspection( request: &EmbeddingRequest, ) -> tinyinference_embeddings::Result { @@ -57,44 +62,85 @@ pub(super) async fn from_request_for_inspection( "selected managed embedding credential is unavailable".to_owned(), ) })?; - Ok(build_cloud_model( + // No egress guard: the doctor never loads TinySecurity, and this model + // only ever carries the doctor's fixed probe string. The core runs the + // host-side local-only check before asking for it, as for the chat probe. + // Real embedding traffic is built by `from_request`, which keeps the guard. + let frozen: BearerResolver = Arc::new(move || { + let bearer = bearer.clone(); + Box::pin(async move { Ok(bearer) }) + }); + Ok(cloud_model( config.api_url.clone(), - context.state_dir.clone(), - context.secrets_encrypt, &request.model, request.dimensions, - None, - Some(bearer), + frozen, )) } -fn build_cloud_model( +/// The managed endpoint's embedding model with `bearer`, and no host policy. +fn cloud_model( api_url: Option, - state_dir: std::path::PathBuf, - secrets_encrypt: bool, model: &str, dimensions: usize, - chat: Option, - frozen_bearer: Option, + bearer: BearerResolver, ) -> CloudEmbeddingModel { - let base_url = format!( + CloudEmbeddingModel::new( + managed_base_url(&api_url), + model.to_owned(), + dimensions, + bearer, + ) +} + +fn managed_base_url(api_url: &Option) -> String { + format!( "{}/openai/v1", - effective_api_url(&api_url).trim_end_matches('/') - ); - let key_endpoint = base_url.clone(); - let bearer: BearerResolver = Arc::new(move || { - let frozen_bearer = frozen_bearer.clone(); + effective_api_url(api_url).trim_end_matches('/') + ) +} + +/// The managed endpoint's embedding model with OpenHuman's live credential +/// resolver for `context`, and the TinySecurity egress guard on every batch. +fn guarded_cloud_model( + api_url: Option, + context: &EmbeddingCallContext, + model: &str, + dimensions: usize, +) -> CloudEmbeddingModel { + let bearer = bearer_resolver(managed_base_url(&api_url), context); + + let guarded_model = model.to_owned(); + let guarded_chat = context.chat.clone(); + let egress_guard: EmbeddingEgressGuard = Arc::new(move |_, _| { + let egress = EgressDescriptor::embedding("cloud", &guarded_model); + openhuman_embed::__host::egress::enforce_egress_blocking(&egress) + .map_err(|error| tinyinference_embeddings::Error::Embedding(error.to_string()))?; + emit_external_transfer(guarded_chat.as_ref(), egress); + Ok(()) + }); + + cloud_model(api_url, model, dimensions, bearer).with_egress_guard(egress_guard) +} + +/// Resolves the bearer for each embedding batch from `context`'s credential +/// scope: a stored TinyHumans API key first, else the app session, read +/// through the store bound to `context.config` when it owns that scope. +fn bearer_resolver(key_endpoint: String, context: &EmbeddingCallContext) -> BearerResolver { + let state_dir = context.state_dir.clone(); + let secrets_encrypt = context.secrets_encrypt; + let config = context.config.clone().map(Arc::new); + Arc::new(move || { let state_dir = state_dir.clone(); let key_endpoint = key_endpoint.clone(); + let config = config.clone(); Box::pin(async move { - if let Some(bearer) = frozen_bearer { - return Ok(bearer); - } // A stored TinyHumans API key is the bearer outright, with the // plaintext guard: never put the key on a non-HTTPS, non-loopback wire. if let Some(key) = openhuman_embed::__host::credentials::api_key::get_api_key_in( &state_dir, secrets_encrypt, + config.as_deref(), ) .await .map_err(|error| tinyinference_embeddings::Error::Embedding(error.to_string()))? @@ -113,28 +159,20 @@ fn build_cloud_model( &key_endpoint, &state_dir, secrets_encrypt, + config.as_deref(), None, "managed_embedding.resolve_bearer", ) .await .map_err(|error| tinyinference_embeddings::Error::Embedding(error.to_string())) }) - }); - - let guarded_model = model.to_owned(); - let guarded_chat = chat; - let egress_guard: EmbeddingEgressGuard = Arc::new(move |_, _| { - let egress = EgressDescriptor::embedding("cloud", &guarded_model); - openhuman_embed::__host::egress::enforce_egress_blocking(&egress) - .map_err(|error| tinyinference_embeddings::Error::Embedding(error.to_string()))?; - emit_external_transfer(guarded_chat.as_ref(), egress); - Ok(()) - }); - - CloudEmbeddingModel::new(base_url, model.to_owned(), dimensions, bearer) - .with_egress_guard(egress_guard) + }) } #[cfg(test)] #[path = "managed_embedding_tests.rs"] mod tests; + +#[cfg(test)] +#[path = "managed_embedding_inspection_tests.rs"] +mod inspection_tests; diff --git a/crates/openhuman-tinyhumans/src/inference/managed_embedding_inspection_tests.rs b/crates/openhuman-tinyhumans/src/inference/managed_embedding_inspection_tests.rs new file mode 100644 index 00000000000..a9bde383469 --- /dev/null +++ b/crates/openhuman-tinyhumans/src/inference/managed_embedding_inspection_tests.rs @@ -0,0 +1,187 @@ +//! The doctor's read-only managed embedding probe versus real embedding traffic. +//! +//! The doctor never loads TinySecurity, so its inspection embedder must not +//! ask it; ordinary embedders must keep asking it on every batch. The guard +//! tests pin this thread's privacy mode to `LocalOnly`, which refuses external +//! user content whether or not the TinySecurity module is staged, so they hold +//! both in a plain `cargo test` and in CI's staged-module run. + +use super::{from_request, from_request_for_inspection}; +use axum::{routing::post, Json, Router}; +use openhuman_embed::__host::config::Config; +use openhuman_embed::__host::inference_registry::{ + EmbeddingCallContext, EmbeddingRequest, ProviderContext, +}; +use std::sync::{ + atomic::{AtomicUsize, Ordering}, + Arc, +}; +use tinyinference_embeddings::EmbeddingModel; + +const PROBE: &str = "OpenHuman doctor embedding probe"; + +/// A loopback `/openai/v1/embeddings` mock that answers two-wide vectors and +/// counts the requests it receives. +async fn mock_embeddings() -> (String, Arc) { + let requests = Arc::new(AtomicUsize::new(0)); + let app = Router::new().route( + "/openai/v1/embeddings", + post({ + let requests = Arc::clone(&requests); + move || async move { + requests.fetch_add(1, Ordering::SeqCst); + Json(serde_json::json!({ + "object": "list", + "data": [{ "object": "embedding", "index": 0, "embedding": [0.5, 0.25] }], + "model": "m" + })) + } + }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + (base, requests) +} + +/// A config pointed at `api_url` whose credential scope holds a TinyHumans +/// API key, so both the frozen and the live bearer resolve without a session. +async fn config_with_api_key(tmp: &tempfile::TempDir, api_url: &str) -> Config { + let mut config = Config { + config_path: tmp.path().join("config.toml"), + api_url: Some(api_url.to_owned()), + ..Config::default() + }; + config.secrets.encrypt = false; + openhuman_embed::__host::credentials::api_key::store_api_key_in( + tmp.path(), + false, + "tiny_test_doctor_probe", + ) + .await + .unwrap(); + config +} + +fn request_for(config: &Config) -> EmbeddingRequest { + EmbeddingRequest { + model: "m".to_owned(), + dimensions: 2, + context: ProviderContext { + config: config.clone(), + egress: openhuman_embed::__host::egress::EgressLedger::none(), + embedding: Some(EmbeddingCallContext { + config: Some(config.clone()), + chat: None, + state_dir: config.config_path.parent().unwrap().to_path_buf(), + secrets_encrypt: config.secrets.encrypt, + }), + catalog: None, + }, + } +} + +/// The doctor's probe reaches the managed endpoint although TinySecurity is +/// not loaded: inspection is read-only and sends one fixed, non-user string. +#[tokio::test] +async fn inspection_embedder_probes_without_the_security_module() { + let (base, requests) = mock_embeddings().await; + let tmp = tempfile::tempdir().unwrap(); + let config = config_with_api_key(&tmp, &base).await; + + let model = from_request_for_inspection(&request_for(&config)) + .await + .expect("the frozen API key builds an inspection embedder"); + let vectors = model + .embed(&[PROBE.to_owned()]) + .await + .expect("the inspection probe does not depend on TinySecurity"); + + assert_eq!(vectors.first().map(Vec::len), Some(2)); + assert_eq!(requests.load(Ordering::SeqCst), 1); +} + +/// An inspection embedder pointed at a closed port fails the probe instead of +/// reporting a vector width. +#[tokio::test] +async fn inspection_embedder_reports_an_unreachable_endpoint() { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let closed = format!("http://{}", listener.local_addr().unwrap()); + drop(listener); + let tmp = tempfile::tempdir().unwrap(); + let config = config_with_api_key(&tmp, &closed).await; + + let model = from_request_for_inspection(&request_for(&config)) + .await + .expect("the frozen API key builds an inspection embedder"); + let error = model + .embed(&[PROBE.to_owned()]) + .await + .expect_err("a closed endpoint cannot answer the probe"); + + assert!( + !error.to_string().contains("security module"), + "the failure is the transport, not the egress guard: {error}" + ); +} + +/// Pins this thread's privacy mode to `LocalOnly`, under which the egress +/// guard refuses external user content with or without TinySecurity. Thread +/// scoped: `#[tokio::test]` runs the embedder on this thread, and parallel +/// tests never observe it. +fn local_only() -> openhuman_core::security::live_policy::TestPrivacyGuard { + openhuman_core::security::live_policy::test_privacy_scope( + openhuman_core::config::PrivacyMode::LocalOnly, + ) +} + +/// Real embedding traffic applies the egress guard before a batch leaves: +/// under `LocalOnly` the runtime embedder refuses and sends nothing, even with +/// a valid credential and a reachable endpoint. +#[tokio::test] +async fn runtime_embedder_still_enforces_the_egress_guard() { + let _local_only = local_only(); + let (base, requests) = mock_embeddings().await; + let tmp = tempfile::tempdir().unwrap(); + let config = config_with_api_key(&tmp, &base).await; + + let error = from_request(request_for(&config)) + .embed(&["user text".to_owned()]) + .await + .expect_err("a local-only egress must be refused"); + + // The refusal wording depends on whether TinySecurity answered (a + // local-only refusal) or was absent (could not confirm); both are the + // privacy guard, not the transport or the credential. + assert!( + error + .to_string() + .to_lowercase() + .contains("privacy mode is active"), + "{error}" + ); + assert_eq!(requests.load(Ordering::SeqCst), 0); +} + +/// The inspection embedder carries no egress guard at all: in the same +/// `LocalOnly` mode that refuses the runtime embedder, it still sends its probe. +/// The local-only refusal for the doctor belongs to the core's doctor factory, +/// which checks before it ever asks for this model. +#[tokio::test] +async fn inspection_embedder_skips_the_egress_guard_under_local_only() { + let _local_only = local_only(); + let (base, requests) = mock_embeddings().await; + let tmp = tempfile::tempdir().unwrap(); + let config = config_with_api_key(&tmp, &base).await; + + let model = from_request_for_inspection(&request_for(&config)) + .await + .expect("the frozen API key builds an inspection embedder"); + let vectors = model + .embed(&[PROBE.to_owned()]) + .await + .expect("the inspection embedder has no egress guard to refuse it"); + + assert_eq!(vectors.first().map(Vec::len), Some(2)); + assert_eq!(requests.load(Ordering::SeqCst), 1); +} diff --git a/crates/openhuman-tinyhumans/src/inference/managed_embedding_tests.rs b/crates/openhuman-tinyhumans/src/inference/managed_embedding_tests.rs index 00fb0597d1e..84792169285 100644 --- a/crates/openhuman-tinyhumans/src/inference/managed_embedding_tests.rs +++ b/crates/openhuman-tinyhumans/src/inference/managed_embedding_tests.rs @@ -1,6 +1,7 @@ use super::*; use openhuman_embed::__host::config::Config; use openhuman_embed::__host::credentials::AuthService; +use openhuman_embed::__host::security::approval::ApprovalChatContext; use std::collections::HashMap; use tinyinference_embeddings::{ CloudEmbeddingModel, EmbeddingModel, DEFAULT_CLOUD_DIMENSIONS, DEFAULT_CLOUD_MODEL, @@ -23,6 +24,25 @@ fn state_dir_of(config: &Config) -> std::path::PathBuf { .unwrap_or_default() } +/// The guarded managed embedder for an explicit credential directory with no +/// owning config, as a directory-only caller builds it. +fn build_cloud_model( + api_url: Option, + state_dir: std::path::PathBuf, + secrets_encrypt: bool, + model: &str, + dimensions: usize, + chat: Option, +) -> CloudEmbeddingModel { + let context = openhuman_embed::__host::inference_registry::EmbeddingCallContext { + config: None, + chat, + state_dir, + secrets_encrypt, + }; + guarded_cloud_model(api_url, &context, model, dimensions) +} + /// Builds the embedder the way the core's managed factory does: through the /// registered embedding provider, with the config's credential scope. fn build_through_registry(config: &Config, model: &str, dimensions: usize) -> CloudEmbeddingModel { @@ -90,7 +110,6 @@ async fn api_key_alone_authenticates_cloud_embeddings() { "m", 2, None, - None, ); let vectors = provider @@ -125,7 +144,6 @@ async fn api_key_is_refused_over_plaintext_non_loopback() { "m", 2, None, - None, ); let err = provider.embed(&["hello".to_string()]).await.unwrap_err(); assert!( @@ -184,7 +202,6 @@ fn unreachable_embedder_with_chat( model, DEFAULT_CLOUD_DIMENSIONS, chat, - None, ) .with_egress_guard(std::sync::Arc::new(move |_, _| { openhuman_embed::__host::egress::emit_external_transfer( @@ -465,6 +482,42 @@ async fn default_provider_with_config_authenticates_with_config_scoped_token() { ); } +/// Sign-in stores the app session through the config-bound store (the keyring +/// under `security-module`). The managed embedder built for that config must +/// read the session through the same store, not a directory-only one that sees +/// no token and reports "No backend session". +#[tokio::test] +async fn managed_embedding_bearer_reads_the_session_sign_in_stored_through_the_config() { + let tmp = tempfile::TempDir::new().unwrap(); + let config = Config { + config_path: tmp.path().join("config.toml"), + workspace_dir: tmp.path().join("workspace"), + api_url: Some("http://127.0.0.1:9".to_owned()), + ..Config::default() + }; + AuthService::from_config(&config) + .store_provider_token( + openhuman_embed::__host::credentials::APP_SESSION_PROVIDER, + openhuman_embed::__host::credentials::DEFAULT_AUTH_PROFILE_NAME, + "signed.in.jwt", + HashMap::new(), + true, + ) + .await + .expect("sign-in stores the app session through the config"); + let context = openhuman_embed::__host::inference_registry::EmbeddingCallContext { + config: Some(config.clone()), + chat: None, + state_dir: state_dir_of(&config), + secrets_encrypt: config.secrets.encrypt, + }; + + let bearer = bearer_resolver(managed_base_url(&config.api_url), &context)() + .await + .expect("the managed embedder reads the signed-in session"); + assert_eq!(bearer, "signed.in.jwt"); +} + /// With no stored `app-session` token and no API key, the bearer resolver /// short-circuits to the backend-session error before any network call. #[tokio::test] @@ -526,7 +579,6 @@ async fn offline_local_session_is_refused_before_embedding_request() { "m", 2, None, - None, ); let err = provider @@ -598,7 +650,6 @@ async fn expired_session_publishes_session_expired_before_embedding_request() { "m", 2, None, - None, ); let err = provider diff --git a/crates/openhuman-tinyhumans/src/inference/managed_model.rs b/crates/openhuman-tinyhumans/src/inference/managed_model.rs index 891a5244e96..16c5d6a3cbd 100644 --- a/crates/openhuman-tinyhumans/src/inference/managed_model.rs +++ b/crates/openhuman-tinyhumans/src/inference/managed_model.rs @@ -28,6 +28,11 @@ pub struct ManagedOptions { pub secrets_encrypt: bool, /// An auth-profile name to use instead of the default app session. pub auth_profile_override: Option, + /// The runtime config that owns `openhuman_dir`. With it the session is + /// read through the config-bound store sign-in wrote it with (whose + /// secrets live in the keyring under `security-module`); without it the + /// store falls back to the ambient owner of the directory, if any. + pub config: Option>, } impl ManagedOptions { @@ -51,6 +56,7 @@ impl ManagedOptions { if let Some(key) = openhuman_embed::__host::credentials::api_key::get_api_key_in( &self.state_dir(), self.secrets_encrypt, + self.config.as_deref(), ) .await? { @@ -70,6 +76,7 @@ impl ManagedOptions { endpoint, &self.state_dir(), self.secrets_encrypt, + self.config.as_deref(), self.auth_profile_override.as_deref(), "openhuman_backend_model.resolve_bearer", ) diff --git a/crates/openhuman-tinyhumans/src/inference/managed_model_tests.rs b/crates/openhuman-tinyhumans/src/inference/managed_model_tests.rs index def146f7585..d2edeaab223 100644 --- a/crates/openhuman-tinyhumans/src/inference/managed_model_tests.rs +++ b/crates/openhuman-tinyhumans/src/inference/managed_model_tests.rs @@ -210,6 +210,84 @@ async fn managed_bearer_resolves_exp_less_hosted_app_sessions() { ); } +/// Sign-in (`auth.set_credential`) stores the app session through the +/// config-bound store, which under `security-module` keeps the token in the +/// keyring and clears it from the profile document. The managed model built for +/// that config must read the session through the same store; a directory-only +/// store sees no token and every turn failed with "No backend session". +#[tokio::test] +async fn managed_bearer_reads_the_session_sign_in_stored_through_the_config() { + use openhuman_embed::__host::config::Config; + use openhuman_embed::__host::credentials::{ + AuthService, APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME, + }; + + let tmp = tempfile::TempDir::new().expect("temporary credentials"); + let config = Config { + config_path: tmp.path().join("config.toml"), + workspace_dir: tmp.path().join("workspace"), + ..Config::default() + }; + AuthService::from_config(&config) + .store_provider_token( + APP_SESSION_PROVIDER, + DEFAULT_AUTH_PROFILE_NAME, + "signed.in.jwt", + std::collections::HashMap::new(), + true, + ) + .await + .expect("sign-in stores the app session through the config"); + + assert_eq!( + super::super::managed_options(&config) + .resolve_bearer("http://127.0.0.1:9/openai/v1") + .await + .expect("the managed model reads the signed-in session"), + "signed.in.jwt" + ); +} + +/// A config that does not own the credential directory lends it nothing: the +/// session it signed in stays its own, and the other directory reads none. +#[tokio::test] +async fn managed_bearer_never_reads_through_a_config_for_another_directory() { + use openhuman_embed::__host::config::Config; + use openhuman_embed::__host::credentials::{ + AuthService, APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME, + }; + + let tenant = tempfile::TempDir::new().expect("tenant credentials"); + let other = tempfile::TempDir::new().expect("other credentials"); + let config = Config { + config_path: tenant.path().join("config.toml"), + workspace_dir: tenant.path().join("workspace"), + ..Config::default() + }; + AuthService::from_config(&config) + .store_provider_token( + APP_SESSION_PROVIDER, + DEFAULT_AUTH_PROFILE_NAME, + "tenant.session.jwt", + std::collections::HashMap::new(), + true, + ) + .await + .expect("the tenant signs in through its config"); + let options = ManagedOptions { + openhuman_dir: Some(other.path().to_path_buf()), + secrets_encrypt: config.secrets.encrypt, + config: Some(std::sync::Arc::new(config)), + ..ManagedOptions::default() + }; + + let error = options + .resolve_bearer("http://127.0.0.1:9/openai/v1") + .await + .expect_err("another directory must not read the tenant's session"); + assert!(error.to_string().contains("No backend session"), "{error}"); +} + #[tokio::test] async fn managed_api_key_precedes_an_expired_app_session() { let tmp = tempfile::TempDir::new().expect("temporary credentials"); diff --git a/crates/openhuman-tinyhumans/src/inference/managed_session.rs b/crates/openhuman-tinyhumans/src/inference/managed_session.rs index 24852ac38a2..6366106629f 100644 --- a/crates/openhuman-tinyhumans/src/inference/managed_session.rs +++ b/crates/openhuman-tinyhumans/src/inference/managed_session.rs @@ -11,10 +11,16 @@ use tinyinference_llm::providers::tinyhumans::{ /// Both chat and embeddings use this path so signed-out state, expiry checks, /// offline-local credential refusal, and the plaintext-endpoint refusal stay /// consistent. +/// +/// `config` is the runtime config the caller was built for. The session is +/// read through the store bound to the config owning `state_dir` (see +/// `AuthService::for_state_dir`) — the store sign-in wrote it with, whose +/// secrets live in the keyring under `security-module`. pub(super) async fn resolve_session_bearer( endpoint: &str, state_dir: &std::path::Path, secrets_encrypt: bool, + config: Option<&openhuman_embed::__host::config::Config>, profile_override: Option<&str>, operation: &str, ) -> anyhow::Result { @@ -27,7 +33,7 @@ pub(super) async fn resolve_session_bearer( if openhuman_embed::__host::platform::llm_gate::is_signed_out() { anyhow::bail!("SESSION_EXPIRED: backend session not active — sign in to resume LLM work"); } - let auth = AuthService::new(state_dir, secrets_encrypt); + let auth = AuthService::for_state_dir(state_dir, secrets_encrypt, config); let profile = auth .get_profile(APP_SESSION_PROVIDER, profile_override) .await?; diff --git a/crates/openhuman-tinyhumans/src/inference/mod.rs b/crates/openhuman-tinyhumans/src/inference/mod.rs index fe47fbe3db1..0f07077dc08 100644 --- a/crates/openhuman-tinyhumans/src/inference/mod.rs +++ b/crates/openhuman-tinyhumans/src/inference/mod.rs @@ -47,6 +47,7 @@ fn managed_options(config: &Config) -> ManagedOptions { openhuman_dir: config.config_path.parent().map(std::path::PathBuf::from), secrets_encrypt: config.secrets.encrypt, auth_profile_override: None, + config: Some(Arc::new(config.clone())), } } diff --git a/crates/openhuman-tinyhumans/src/integrations/file_storage/artifact_publisher_tests.rs b/crates/openhuman-tinyhumans/src/integrations/file_storage/artifact_publisher_tests.rs index 7503cedf756..b8bea2bd6cb 100644 --- a/crates/openhuman-tinyhumans/src/integrations/file_storage/artifact_publisher_tests.rs +++ b/crates/openhuman-tinyhumans/src/integrations/file_storage/artifact_publisher_tests.rs @@ -13,6 +13,7 @@ use openhuman_embed::__host::artifact_publisher::versioned_store; use openhuman_embed::__host::security::AutonomyLevel; fn publisher(server_uri: String, autonomy: AutonomyLevel) -> StorageArtifactPublisher { + crate::test_workspace::isolate(); StorageArtifactPublisher::new( Arc::new(IntegrationClient::new(server_uri, "tok".to_string())), Arc::new(SecurityPolicy { @@ -55,6 +56,29 @@ async fn mount_link(server: &MockServer, expect: u64) { .await; } +/// Every test here is its own process under nextest, and each reaches +/// TinySecurity through the ambient configuration. Resolved from the runner's +/// home, that is one store every parallel process appends its audited +/// permissions to, so their audit sequences collide and the module refuses +/// the check. The suite must resolve a workspace of its own instead. +#[tokio::test] +async fn the_ambient_config_these_tests_audit_through_is_not_the_runners_home() { + let _ = publisher("http://127.0.0.1:9".into(), AutonomyLevel::Full); + let config = openhuman_embed::__host::core::runtime::DispatchCtx::ambient() + .load_config() + .await + .unwrap(); + let home = directories::UserDirs::new() + .expect("a home directory") + .home_dir() + .to_path_buf(); + assert!( + !config.workspace_dir.starts_with(&home) && !config.config_path.starts_with(&home), + "ambient config resolved under the runner's home: {}", + config.config_path.display() + ); +} + #[tokio::test] async fn a_text_version_uploads_its_own_content_behind_a_private_link() { let server = MockServer::start().await; diff --git a/crates/openhuman-tinyhumans/src/integrations/file_storage/tools_tests.rs b/crates/openhuman-tinyhumans/src/integrations/file_storage/tools_tests.rs index d018d7f59cb..ce23dc1fc7b 100644 --- a/crates/openhuman-tinyhumans/src/integrations/file_storage/tools_tests.rs +++ b/crates/openhuman-tinyhumans/src/integrations/file_storage/tools_tests.rs @@ -13,6 +13,8 @@ use tinytools::{PermissionLevel, Tool, ToolCategory}; fn dummy_client() -> Arc { // No requests are made in these tests; the URL/token are placeholders. + // The tools still ask TinySecurity (autonomy budget) before refusing. + crate::test_workspace::isolate(); Arc::new(IntegrationClient::new( "http://127.0.0.1:0".to_string(), "test-token".to_string(), @@ -251,6 +253,7 @@ use wiremock::matchers::{body_string_contains, header, method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; fn client_for(server: &MockServer) -> Arc { + crate::test_workspace::isolate(); Arc::new(IntegrationClient::new(server.uri(), "tok".to_string())) } diff --git a/crates/openhuman-tinyhumans/src/integrations/media/mod.rs b/crates/openhuman-tinyhumans/src/integrations/media/mod.rs index 757ac1b7355..dd977a43b4a 100644 --- a/crates/openhuman-tinyhumans/src/integrations/media/mod.rs +++ b/crates/openhuman-tinyhumans/src/integrations/media/mod.rs @@ -39,6 +39,7 @@ pub(crate) fn register() { ctx.action_dir, Arc::clone(&ctx.security.media_artifact_paths), ) + .await }) }, ); diff --git a/crates/openhuman-tinyhumans/src/lib.rs b/crates/openhuman-tinyhumans/src/lib.rs index e576e53f7fd..056152ecf7a 100644 --- a/crates/openhuman-tinyhumans/src/lib.rs +++ b/crates/openhuman-tinyhumans/src/lib.rs @@ -93,6 +93,8 @@ mod register; mod runtime; pub mod session; pub(crate) mod socket; +#[cfg(test)] +pub(crate) mod test_workspace; pub mod transport; #[cfg(feature = "voice")] pub mod voice; diff --git a/crates/openhuman-tinyhumans/src/test_workspace.rs b/crates/openhuman-tinyhumans/src/test_workspace.rs new file mode 100644 index 00000000000..aecfd57c439 --- /dev/null +++ b/crates/openhuman-tinyhumans/src/test_workspace.rs @@ -0,0 +1,27 @@ +//! A workspace of this test process's own, for suites that reach TinySecurity. +//! +//! Module-backed checks (privacy, action budget, path floor) resolve the +//! ambient configuration, which otherwise loads from the runner's home +//! (`~/.openhuman/users/local`). Every audited permission then lands on the +//! TinySecurity init audit stream in that one store. nextest runs each test +//! as its own process, so parallel processes claim the same audit sequence, +//! the host's sink refuses the duplicate, and the module fails the check +//! closed for a reason that has nothing to do with the test. A test process +//! also must not write into a developer's real profile. + +use std::sync::OnceLock; + +/// Point this process's ambient configuration at a workspace of its own, +/// once per process, before the first module call resolves it. +pub(crate) fn isolate() { + static WORKSPACE: OnceLock = OnceLock::new(); + WORKSPACE.get_or_init(|| { + let dir = tempfile::tempdir().expect("a per-process test workspace"); + log::debug!( + "[test-workspace] OPENHUMAN_WORKSPACE -> {}", + dir.path().display() + ); + std::env::set_var("OPENHUMAN_WORKSPACE", dir.path()); + dir + }); +} diff --git a/scripts/__tests__/install-ci-packages.test.mjs b/scripts/__tests__/install-ci-packages.test.mjs new file mode 100644 index 00000000000..c7c8ac0edc6 --- /dev/null +++ b/scripts/__tests__/install-ci-packages.test.mjs @@ -0,0 +1,84 @@ +// The container lanes install jq, tomli and unzip from Ubuntu's archive. Pins +// that an unreachable archive falls back to another mirror, that a host which +// already carries the tools makes no apt call, and that the workflow uses the +// script instead of a bare `apt-get`. +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; + +const repoRoot = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", ".."); +const script = path.join(repoRoot, "scripts", "ci", "install-ci-packages.sh"); + +/** A fake host: stub commands on PATH, an apt sources file, a call log. */ +function fakeHost({ present = [], reachable = [] } = {}) { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "oh-ci-packages-")); + const bin = path.join(dir, "bin"); + fs.mkdirSync(bin); + const sources = path.join(dir, "sources.list"); + fs.writeFileSync(sources, "deb http://archive.ubuntu.com/ubuntu/ jammy main universe\n"); + const calls = path.join(dir, "calls"); + const stub = (name, body) => { + fs.writeFileSync(path.join(bin, name), `#!/usr/bin/env bash\n${body}\n`, { mode: 0o755 }); + }; + for (const tool of present) stub(tool, "exit 0"); + if (!present.includes("python3")) stub("python3", "exit 1"); + // apt-get update always "succeeds", as the real one does when every index + // fails to download; install only works once a reachable mirror is listed. + stub( + "apt-get", + `echo "apt-get $*" >> ${JSON.stringify(calls)} +if [ "$1" = install ]; then + for host in ${reachable.join(" ")}; do + grep -q "$host" ${JSON.stringify(sources)} && exit 0 + done + echo "E: Unable to locate package unzip" >&2 + exit 100 +fi +exit 0`, + ); + const run = () => + spawnSync("bash", [script], { + encoding: "utf8", + env: { + PATH: `${bin}:/usr/bin:/bin`, + CI_APT_SOURCES: sources, + CI_APT_RETRY_DELAY: "0", + }, + }); + const log = () => (fs.existsSync(calls) ? fs.readFileSync(calls, "utf8").trim().split("\n") : []); + return { run, log, sources }; +} + +test("an unreachable Ubuntu archive falls back to another mirror", () => { + const host = fakeHost({ reachable: ["azure.archive.ubuntu.com"] }); + const result = host.run(); + assert.equal(result.status, 0, result.stderr); + assert.match(fs.readFileSync(host.sources, "utf8"), /azure\.archive\.ubuntu\.com/); + assert.ok(host.log().filter((call) => call.startsWith("apt-get install")).length >= 2); +}); + +test("a host that already carries the tools makes no apt call", () => { + const host = fakeHost({ present: ["jq", "unzip", "python3"] }); + const result = host.run(); + assert.equal(result.status, 0, result.stderr); + assert.deepEqual(host.log(), []); +}); + +test("no reachable mirror fails the step", () => { + const host = fakeHost({ reachable: [] }); + const result = host.run(); + assert.notEqual(result.status, 0); +}); + +test("the container lanes install their tools through the script", () => { + const workflow = fs.readFileSync(path.join(repoRoot, ".github", "workflows", "ci-lanes.yml"), "utf8"); + const step = workflow.match( + /- name: Install jq and unzip for release-script tests\n(?:\s+#.*\n)*\s+if: .+\n\s+run: (.+)\n/, + ); + assert.ok(step, "the install step exists"); + assert.equal(step[1].trim(), "bash scripts/ci/install-ci-packages.sh"); +}); diff --git a/scripts/ci/install-ci-packages.sh b/scripts/ci/install-ci-packages.sh new file mode 100755 index 00000000000..65ef052efa5 --- /dev/null +++ b/scripts/ci/install-ci-packages.sh @@ -0,0 +1,58 @@ +#!/usr/bin/env bash +# Install the tools the container lanes need but the CI image does not carry: +# jq and tomli for the release-script tests, and unzip, which stage-modules.mjs +# unpacks module archives with. +# +# The image's apt sources point at archive.ubuntu.com, and the hosted runners +# sometimes cannot resolve it: `apt-get update` then "succeeds" with no index +# and the install fails with "Unable to locate package". So each install is +# retried, and after a failed attempt the sources move to the next mirror. A +# host that already has every tool makes no apt call at all. +# +# bash scripts/ci/install-ci-packages.sh +# +# CI_APT_SOURCES and CI_APT_RETRY_DELAY exist for the script's own test. +set -euo pipefail + +PACKAGES=(jq python3-tomli unzip) +SOURCES="${CI_APT_SOURCES:-/etc/apt/sources.list}" +DELAY="${CI_APT_RETRY_DELAY:-5}" +# archive.ubuntu.com as shipped, then mirrors carrying the same suites +# (including -security). +MIRRORS=(azure.archive.ubuntu.com mirrors.edge.kernel.org) + +have_tools() { + command -v jq >/dev/null 2>&1 && + command -v unzip >/dev/null 2>&1 && + python3 -c 'import tomli' >/dev/null 2>&1 +} + +attempt() { + apt-get update || true + apt-get install -y --no-install-recommends "${PACKAGES[@]}" +} + +use_mirror() { + local mirror=$1 + echo "[ci][apt] switching apt sources to ${mirror}" + sed -i -E "s#https?://[a-z.]*(archive|security)\.ubuntu\.com/ubuntu#http://${mirror}/ubuntu#g; s#https?://mirrors\.edge\.kernel\.org/ubuntu#http://${mirror}/ubuntu#g" "$SOURCES" +} + +if have_tools; then + echo "[ci][apt] jq, tomli and unzip are already installed" + exit 0 +fi + +if attempt; then + exit 0 +fi +for mirror in "${MIRRORS[@]}"; do + echo "[ci][apt] install failed; retrying in ${DELAY}s via ${mirror}" >&2 + sleep "$DELAY" + use_mirror "$mirror" + if attempt; then + exit 0 + fi +done +echo "[ci][apt] could not install ${PACKAGES[*]} from any mirror" >&2 +exit 1 diff --git a/scripts/ci/process-statics.json b/scripts/ci/process-statics.json index 7a741f7afbd..18ebd640c12 100644 --- a/scripts/ci/process-statics.json +++ b/scripts/ci/process-statics.json @@ -878,5 +878,15 @@ "category": "B", "reason": "The process's agent37 box registry holds one box per owner, keyed on the authenticated Tenant (profile and agent) together with an OwnerScope hashed from the active workspace and [runtime.agent37] retention_namespace; a call with no tenant is refused before the registry is touched, so no two tenants or signed-in users share a box. Deployments share a box only when they share an agent37 key, tenant and workspace path with a blank retention_namespace; distinct nonblank namespaces keep them apart.", "verification": "sandbox/boxes/registry_tests.rs: embedded_users_of_one_host_get_separate_boxes; sandbox/boxes/registry_retain_tests.rs: equal_tenants_in_two_scopes_never_share_a_retained_box; sandbox/boxes/mod_tests.rs: an_unscoped_command_creates_no_box" + }, + { + "file": "crates/openhuman-core/src/credentials/profiles/backend.rs", + "scope": "", + "name": "HELD", + "type": "std::sync::OnceLock>,Condvar)>>", + "count": 1, + "category": "B", + "reason": "An in-process write exclusion for backend-stored auth-profile documents, keyed by the authenticated profile id; it holds only which tenant documents have a read-modify-write in flight (no credential data) and serialises writers of the same tenant only, while the backend's compare-and-swap remains the cross-process guard.", + "verification": "credentials/profiles_storage_tests.rs: a_tenant_store_keeps_its_document_and_lock_in_the_configured_backend; credentials/profiles/backend_tests.rs: a_tenant_store_outside_its_own_scope_is_refused_in_saas" } ] diff --git a/scripts/ci/security-native-fixture.sh b/scripts/ci/security-native-fixture.sh index ee2fdee8555..a23e70615c7 100644 --- a/scripts/ci/security-native-fixture.sh +++ b/scripts/ci/security-native-fixture.sh @@ -51,8 +51,8 @@ export OPENHUMAN_MODULE_PATH="$module_dir${OPENHUMAN_MODULE_PATH:+:$OPENHUMAN_MO core_features="$(scripts/ci/product-features.sh | sed 's/,os-keyring//' | sed 's/,security-module//')" security_pin="$(git -C vendor/tinysecurity rev-parse HEAD)" -release_source="$(git -C vendor/tinysecurity rev-parse 24921baa4cc0f92375d1d384a945429998e529d0)" -printf 'TinySecurity pin: %s\nPublished v0.20.0 source: %s\n' "$security_pin" "$release_source" +release_source="$(git -C vendor/tinysecurity rev-parse 740dafc4449e5ad21521371b1724d339f5e01482)" +printf 'TinySecurity pin: %s\nPublished v0.21.0 source: %s\n' "$security_pin" "$release_source" git -C vendor/tinysecurity merge-base --is-ancestor "$release_source" "$security_pin" # Prove the library builds without the new gate before exercising it enabled. diff --git a/tests/agent_harness_e2e.rs b/tests/agent_harness_e2e.rs index 3d7a4433a54..4d7aeeba046 100644 --- a/tests/agent_harness_e2e.rs +++ b/tests/agent_harness_e2e.rs @@ -1543,7 +1543,7 @@ async fn managed_tinysearch_answer_reaches_followup_model_request_inner() { let _lock = env_lock(); let pinned = openhuman_core::modules::registry::find("tinysearch") .expect("TinySearch is registered in the module asset registry"); - assert_eq!(pinned.version, "0.5.6", "use the pinned module release"); + assert_eq!(pinned.version, "0.5.7", "use the pinned module release"); assert!( std::env::var_os("OPENHUMAN_MODULE_SOURCE").is_none() && std::env::var_os("OPENHUMAN_MODULE_SOURCE_DIR").is_none() @@ -1613,7 +1613,7 @@ async fn managed_tinysearch_answer_reaches_followup_model_request_inner() { .unwrap_or_else(|| panic!("modules_list omitted TinySearch: {modules_response}")); assert_eq!( tinysearch.get("version").and_then(Value::as_str), - Some("0.5.6") + Some("0.5.7") ); assert_eq!( tinysearch.get("state").and_then(Value::as_str), diff --git a/tests/security_approval_characterization.rs b/tests/security_approval_characterization.rs index 803dffd6458..7647f301f47 100644 --- a/tests/security_approval_characterization.rs +++ b/tests/security_approval_characterization.rs @@ -97,6 +97,24 @@ async fn wait_pending(gate: &ApprovalGate, tool: &str) -> PendingApproval { panic!("no pending approval appeared for {tool}"); } +/// Decide a parked call from a blocking thread, as a person's answer arrives. +/// +/// `ApprovalGate::decide` blocks on the engine, and the engine's decision waits +/// for the parked call's check to release its subject's audit stream. That +/// check finishes on the task `intercept` was spawned as, on this test's +/// current-thread runtime: deciding inline here would stall the only thread +/// that can finish it, and the test would hang whenever the row became visible +/// before the check returned. +async fn decide_parked(gate: &Arc, request_id: &str, decision: ApprovalDecision) { + let gate = Arc::clone(gate); + let request_id = request_id.to_owned(); + let decided = tokio::task::spawn_blocking(move || gate.decide(&request_id, decision)) + .await + .expect("the decision thread") + .expect("the gate applies the decision"); + assert!(decided.is_some(), "the parked request was decided"); +} + fn secs_until_expiry(p: &PendingApproval) -> i64 { (p.expires_at.expect("parked rows carry an expiry") - Utc::now()).num_seconds() } @@ -135,8 +153,7 @@ async fn park_and_approve( .await }); let pending = wait_pending(&gate, tool).await; - gate.decide(&pending.request_id, ApprovalDecision::ApproveOnce) - .unwrap(); + decide_parked(&gate, &pending.request_id, ApprovalDecision::ApproveOnce).await; assert!(matches!(handle.await.unwrap(), GateOutcome::Allow)); pending } @@ -194,8 +211,7 @@ async fn detached_subagent_park_is_clamped_to_180s_and_marked_detached() { let pending = wait_pending(&gate, "char_ttl_subagent").await; assert_window(&pending, 180); assert!(gate.request_is_detached(&pending.request_id)); - gate.decide(&pending.request_id, ApprovalDecision::Deny) - .unwrap(); + decide_parked(&gate, &pending.request_id, ApprovalDecision::Deny).await; assert!(matches!(handle.await.unwrap(), GateOutcome::Deny { .. })); } @@ -498,9 +514,7 @@ async fn flow_trust_is_scoped_to_the_exact_flow_and_tool() { pending.source_context.is_some(), "flow parks carry flow/run context" ); - fx.gate - .decide(&pending.request_id, ApprovalDecision::Deny) - .unwrap(); + decide_parked(&fx.gate, &pending.request_id, ApprovalDecision::Deny).await; assert!(matches!(handle.await.unwrap(), GateOutcome::Deny { .. })); // Revocation removes the grant. diff --git a/tests/security_native_fixture.rs b/tests/security_native_fixture.rs index e7d4b4d32f0..6f0ccbf78a2 100644 --- a/tests/security_native_fixture.rs +++ b/tests/security_native_fixture.rs @@ -1,4 +1,3 @@ -use openhuman_core::storage::DocumentStore as _; use openhuman_core::{ config::Config, core::runtime::{ diff --git a/vendor/tinyagents b/vendor/tinyagents index b178a40c4d6..6d1416d1bc4 160000 --- a/vendor/tinyagents +++ b/vendor/tinyagents @@ -1 +1 @@ -Subproject commit b178a40c4d6d770a71de8e21a5786d5975c4c79a +Subproject commit 6d1416d1bc49d6e160449227dfb51927dc4a78e2