diff --git a/Cargo.lock b/Cargo.lock index 86245ded75b..c9d1898bae1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8991,6 +8991,7 @@ version = "0.1.1" dependencies = [ "anyhow", "async-trait", + "cap-fs-ext", "cap-std", "serde", "serde_json", @@ -10345,7 +10346,7 @@ dependencies = [ [[package]] name = "tinysecurity-bus" -version = "0.18.4" +version = "0.19.0" dependencies = [ "serde", "thiserror 2.0.21", @@ -10495,6 +10496,7 @@ dependencies = [ name = "tinystoragedrivers-fence" version = "2.1.2" dependencies = [ + "libc", "sysinfo", ] diff --git a/app/scripts/e2e-run-session.sh b/app/scripts/e2e-run-session.sh index 26e932db779..3ce292fdc88 100755 --- a/app/scripts/e2e-run-session.sh +++ b/app/scripts/e2e-run-session.sh @@ -233,6 +233,9 @@ trap cleanup EXIT export VITE_BACKEND_URL="http://127.0.0.1:${E2E_MOCK_PORT}" export BACKEND_URL="http://127.0.0.1:${E2E_MOCK_PORT}" export OPENHUMAN_E2E_MODE="1" +# Sign-in stores the session through TinySecurity's keyring, which asks the +# user to approve each operation; the e2e-test-support app answers for them. +export OPENHUMAN_TEST_KEYRING_CONSENT="${OPENHUMAN_TEST_KEYRING_CONSENT:-approve}" export APPIUM_PORT # Redirect Telegram Bot API calls to the mock server during E2E runs. # The mock server (WS-A) serves /bot/* routes on the same port as the @@ -382,7 +385,7 @@ if [ "$OS" = "Linux" ] && [ "${E2E_USE_TAURI_DRIVER:-0}" = "1" ]; then OPENHUMAN_TINYMCP_TEST_MODULE OPENHUMAN_CEF_CACHE_PATH \ OPENHUMAN_SERVICE_MOCK OPENHUMAN_SERVICE_MOCK_STATE_FILE \ OPENHUMAN_TELEGRAM_BOT_API_BASE OPENHUMAN_COMPOSIO_DIRECT_BASE_V2 \ - OPENHUMAN_COMPOSIO_DIRECT_BASE_V3 XDG_DATA_HOME; do + OPENHUMAN_COMPOSIO_DIRECT_BASE_V3 OPENHUMAN_TEST_KEYRING_CONSENT XDG_DATA_HOME; do if declare -p "$env_name" >/dev/null 2>&1; then printf 'export %s=%q\n' "$env_name" "${!env_name}" fi diff --git a/app/scripts/e2e-web-session.sh b/app/scripts/e2e-web-session.sh index 1c8d70d1831..d2ef8a5702c 100755 --- a/app/scripts/e2e-web-session.sh +++ b/app/scripts/e2e-web-session.sh @@ -308,6 +308,9 @@ export OPENHUMAN_CORE_TOKEN="$PW_CORE_RPC_TOKEN" # disclosure choreography. Advertise the compiled tool packs for this harness # core only; production hosts retain the fail-closed packed default. export OPENHUMAN_E2E=1 +# Sign-in stores the session through TinySecurity's keyring, which asks the +# user to approve each operation; the e2e-test-support core answers for them. +export OPENHUMAN_TEST_KEYRING_CONSENT="${OPENHUMAN_TEST_KEYRING_CONSENT:-approve}" # The skills registry defaults to a public HermesHub fetch. The browser E2E # lane must remain deterministic and offline, so serve its compact catalog # fixture from the local mock backend instead. The registry's fetch guard diff --git a/app/src/hooks/useKeyringOperationApprovals.test.ts b/app/src/hooks/useKeyringOperationApprovals.test.ts index 8ecb80177de..954a6310b74 100644 --- a/app/src/hooks/useKeyringOperationApprovals.test.ts +++ b/app/src/hooks/useKeyringOperationApprovals.test.ts @@ -1,5 +1,5 @@ import { act, renderHook } from '@testing-library/react'; -import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { useKeyringOperationApprovals } from './useKeyringOperationApprovals'; @@ -16,7 +16,10 @@ const off = vi.hoisted(() => handlers.get(event)?.delete(cb); }) ); -vi.mock('../services/socketService', () => ({ socketService: { on, off } })); +const isConnected = vi.hoisted(() => vi.fn(() => true)); +vi.mock('../services/socketService', () => ({ socketService: { on, off, isConnected } })); +const listPending = vi.hoisted(() => vi.fn(async (): Promise => [])); +vi.mock('../services/keyringApi', () => ({ listPendingKeyringOperations: listPending })); const EVENTS = ['keyring:access_approval_requested', 'keyring_access_approval_requested']; const REQUEST = { @@ -42,6 +45,12 @@ describe('useKeyringOperationApprovals', () => { handlers.clear(); on.mockClear(); off.mockClear(); + isConnected.mockReset().mockReturnValue(true); + listPending.mockReset().mockResolvedValue([]); + }); + + afterEach(() => { + vi.useRealTimers(); }); it('subscribes to both Socket.IO aliases', () => { @@ -88,4 +97,33 @@ describe('useKeyringOperationApprovals', () => { expect(off).toHaveBeenCalledWith(event, expect.any(Function)); } }); + + it('asks the core for pending requests while no socket is connected', async () => { + vi.useFakeTimers(); + isConnected.mockReturnValue(false); + listPending.mockResolvedValue([REQUEST]); + const { result } = renderHook(() => useKeyringOperationApprovals()); + + await act(async () => { + await vi.advanceTimersByTimeAsync(1_000); + }); + + expect(listPending).toHaveBeenCalled(); + expect(result.current.requests).toEqual([REQUEST]); + + // The same request arriving over the socket later is not shown twice. + emit(REQUEST); + expect(result.current.requests).toEqual([REQUEST]); + }); + + it('does not poll once the socket is connected', async () => { + vi.useFakeTimers(); + renderHook(() => useKeyringOperationApprovals()); + + await act(async () => { + await vi.advanceTimersByTimeAsync(3_000); + }); + + expect(listPending).not.toHaveBeenCalled(); + }); }); diff --git a/app/src/hooks/useKeyringOperationApprovals.ts b/app/src/hooks/useKeyringOperationApprovals.ts index 2b137ff3a9f..739803038b8 100644 --- a/app/src/hooks/useKeyringOperationApprovals.ts +++ b/app/src/hooks/useKeyringOperationApprovals.ts @@ -1,9 +1,12 @@ import { useCallback, useEffect, useState } from 'react'; +import { listPendingKeyringOperations } from '../services/keyringApi'; import { socketService } from '../services/socketService'; const EVENT_COLON = 'keyring:access_approval_requested'; const EVENT_UNDERSCORE = 'keyring_access_approval_requested'; +/** How often to ask the core for pending requests while no socket is connected. */ +const POLL_INTERVAL_MS = 1_000; export type KeyringOperationAccess = 'read' | 'write' | 'delete'; @@ -68,10 +71,25 @@ export function useKeyringOperationApprovals(): { const now = Date.now(); setRequests(current => current.filter(request => request.expires_at_ms > now)); }, 1_000); + // The socket connects only once a session exists, so a keyring write made + // while signing in would never be shown. Until it connects, ask the core. + let polling = false; + const pollTimer = window.setInterval(() => { + if (polling || socketService.isConnected()) return; + polling = true; + listPendingKeyringOperations() + .then(pending => pending.forEach(handleRequest)) + // A failed poll is retried on the next tick. + .catch(() => undefined) + .finally(() => { + polling = false; + }); + }, POLL_INTERVAL_MS); return () => { socketService.off(EVENT_COLON, handleRequest); socketService.off(EVENT_UNDERSCORE, handleRequest); window.clearInterval(expiryTimer); + window.clearInterval(pollTimer); }; }, [handleRequest]); diff --git a/app/src/services/__tests__/keyringApi.test.ts b/app/src/services/__tests__/keyringApi.test.ts index 36d58d6fc78..fb541f00252 100644 --- a/app/src/services/__tests__/keyringApi.test.ts +++ b/app/src/services/__tests__/keyringApi.test.ts @@ -3,6 +3,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; import { decideKeyringConsent, fetchKeyringStatus, + listPendingKeyringOperations, respondToKeyringOperation, retryKeyringProbe, } from '../keyringApi'; @@ -55,4 +56,16 @@ describe('keyringApi', () => { params: { request_id: 'request-1', approved: true }, }); }); + + it('lists pending keyring operations and tolerates a non-array result', async () => { + const pending = [{ request_id: 'request-1' }]; + mockRpc.mockResolvedValueOnce({ result: pending }); + await expect(listPendingKeyringOperations()).resolves.toEqual(pending); + expect(mockRpc).toHaveBeenCalledWith({ + method: 'openhuman.keyring_consent_list_pending_operations', + }); + + mockRpc.mockResolvedValueOnce({ result: null }); + await expect(listPendingKeyringOperations()).resolves.toEqual([]); + }); }); diff --git a/app/src/services/keyringApi.ts b/app/src/services/keyringApi.ts index 05dcf9cdf15..d1e32156937 100644 --- a/app/src/services/keyringApi.ts +++ b/app/src/services/keyringApi.ts @@ -35,3 +35,14 @@ export const respondToKeyringOperation = async ( params: { request_id: requestId, approved }, }); }; + +/** + * Keyring operations waiting for approval. The renderer polls this when it has + * no socket yet (before sign-in), so the approval prompt still reaches it. + */ +export const listPendingKeyringOperations = async (): Promise => { + const response = await callCoreRpc<{ result: unknown }>({ + method: 'openhuman.keyring_consent_list_pending_operations', + }); + return Array.isArray(response.result) ? response.result : []; +}; diff --git a/crates/openhuman-app/Cargo.lock b/crates/openhuman-app/Cargo.lock index 230a380aabd..6573f3234ba 100644 --- a/crates/openhuman-app/Cargo.lock +++ b/crates/openhuman-app/Cargo.lock @@ -7539,6 +7539,7 @@ version = "0.1.1" dependencies = [ "anyhow", "async-trait", + "cap-fs-ext", "cap-std", "serde", "serde_json", @@ -8223,7 +8224,7 @@ dependencies = [ [[package]] name = "tinysecurity-bus" -version = "0.18.4" +version = "0.19.0" dependencies = [ "serde", "thiserror 2.0.21", @@ -8373,6 +8374,7 @@ dependencies = [ name = "tinystoragedrivers-fence" version = "2.1.2" dependencies = [ + "libc", "sysinfo", ] diff --git a/crates/openhuman-cli/Cargo.toml b/crates/openhuman-cli/Cargo.toml index 0101e0e41a4..85ad03e7840 100644 --- a/crates/openhuman-cli/Cargo.toml +++ b/crates/openhuman-cli/Cargo.toml @@ -87,6 +87,24 @@ name = "security_native_fixture" path = "../../tests/security_native_fixture.rs" required-features = ["security-module"] +[[test]] +# TinySecurity from a pinned release (no local-file source) serves later loads. +name = "security_release_reuse_fixture" +path = "../../tests/security_release_reuse_fixture.rs" +required-features = ["security-module"] + +[[test]] +# Callback-bound modules from a pinned release (no local-file source) load and reload. +name = "callback_module_release_fixture" +path = "../../tests/callback_module_release_fixture.rs" +required-features = ["security-module"] + +[[test]] +# Desktop sign-in stores its token through TinySecurity's OS keyring after approval. +name = "desktop_sign_in_fixture" +path = "../../tests/desktop_sign_in_fixture.rs" +required-features = ["security-module"] + [[test]] # Loads tinydocs from the linked executable and calls GenerateDocx end to end. # `scripts/test-rust-e2e.sh --suite tinydocs_linked_e2e` enables its local-only @@ -478,7 +496,9 @@ uuid = { version = "1", features = ["v4"] } # the library crates' own manifests (`default-features = false`; the gates come # from this crate's features through `openhuman-rpc`), so the dev graphs unify # and `cargo test -p` reuses one core build. -openhuman-core = { path = "../openhuman-core", package = "openhuman", default-features = false } +# `test-keyring-consent` answers the credential store's keyring prompts in the +# in-process tests; dev-dependency features never reach the shipped binary. +openhuman-core = { path = "../openhuman-core", package = "openhuman", default-features = false, features = ["test-keyring-consent"] } openhuman-embed = { workspace = true } openhuman-tinyhumans = { workspace = true } tinymemory-tools = { path = "../../vendor/tinymemory/crates/tinymemory-tools" } diff --git a/crates/openhuman-core/Cargo.toml b/crates/openhuman-core/Cargo.toml index 174d1991f5a..1e3f6b94f8e 100644 --- a/crates/openhuman-core/Cargo.toml +++ b/crates/openhuman-core/Cargo.toml @@ -833,6 +833,10 @@ channels = ["modules"] # build (app/scripts/e2e-build.sh) flips it on. Shipped binaries never have # this feature so the wipe RPC isn't even registered, let alone reachable. e2e-test-support = [] +# Answers the credential store's keyring prompts in the in-process integration +# tests (`OPENHUMAN_TEST_KEYRING_CONSENT`). Only the CLI's core dev-dependency +# enables it; no product build or default may (check-feature-forwarding.mjs). +test-keyring-consent = [] # Library-side gate for the embedded-RSS benchmark (#5046): the one prompt # renderer hook in `agent/prompts/render_helpers` (and the mock provider) that # the benchmark bins need. Default-OFF and absent from diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_native_security.rs b/crates/openhuman-core/src/agent/tinyagents/turn_native_security.rs index f70880fe235..cac4fa847dd 100644 --- a/crates/openhuman-core/src/agent/tinyagents/turn_native_security.rs +++ b/crates/openhuman-core/src/agent/tinyagents/turn_native_security.rs @@ -104,7 +104,7 @@ impl Drop for NativeSecurityAudit { fn drop(&mut self) { if !self.recorded { self.record( - crate::security::approval::ExecutionOutcome::Failure, + crate::security::approval::ExecutionOutcome::Aborted, Some("tool execution ended before reporting a result".to_string()), ); } diff --git a/crates/openhuman-core/src/artifacts/files.rs b/crates/openhuman-core/src/artifacts/files.rs index d709e780db3..fa5ed638333 100644 --- a/crates/openhuman-core/src/artifacts/files.rs +++ b/crates/openhuman-core/src/artifacts/files.rs @@ -219,7 +219,7 @@ pub(crate) async fn resolve_file( Ok(file) } -async fn check_protected_artifact_path(path: &Path) -> Result<(), String> { +pub(super) async fn check_protected_artifact_path(path: &Path) -> Result<(), String> { if SecurityPolicy::is_always_forbidden_async(path).await { return Err("[artifacts] file is in a protected location".into()); } diff --git a/crates/openhuman-core/src/artifacts/production_tests.rs b/crates/openhuman-core/src/artifacts/production_tests.rs index e915f9f24a0..d19d07ba69a 100644 --- a/crates/openhuman-core/src/artifacts/production_tests.rs +++ b/crates/openhuman-core/src/artifacts/production_tests.rs @@ -228,8 +228,12 @@ async fn a_completion_that_records_nothing_fails_the_record_too() { } #[cfg(unix)] +#[cfg(feature = "security-module")] #[tokio::test] async fn a_saved_version_the_card_cannot_show_succeeds_and_says_so() { + let _floor = crate::modules::security::gap::install_path_floor_port( + crate::modules::security::gap::ScriptedPathFloorPort::new([], vec![]), + ); use std::os::unix::fs::PermissionsExt; // The CI container runs as root, which bypasses the file mode bits used diff --git a/crates/openhuman-core/src/artifacts/tiny_store.rs b/crates/openhuman-core/src/artifacts/tiny_store.rs index a7699bf1492..68865adbe8b 100644 --- a/crates/openhuman-core/src/artifacts/tiny_store.rs +++ b/crates/openhuman-core/src/artifacts/tiny_store.rs @@ -171,8 +171,7 @@ async fn import_legacy_file( legacy: &FileRef, key: &str, ) -> anyhow::Result { - let source = roots.resolve(&legacy.key).await?; - let bytes = tokio::fs::read(&source.path).await?; + let (source, bytes) = roots.read(&legacy.key).await?; let media_type = legacy .media_type .as_deref() @@ -306,11 +305,10 @@ impl LegacyUiBridge { if let Some(file) = latest.file.as_ref() { self.write_file_version(file, &dest).await? } else { - let source = self.source_roots.resolve(&latest.body).await?; + let (source, bytes) = self.source_roots.read(&latest.body).await?; if same_file(&source.path, &dest) { tokio::fs::metadata(&dest).await?.len() } else { - let bytes = tokio::fs::read(&source.path).await?; self.write_visible_file(&dest, &bytes, source.media_type.as_deref()) .await? } @@ -460,11 +458,16 @@ fn contains(folder: &Path, inside: &Path) -> bool { canon(inside).starts_with(canon(folder)) } -/// [`file_roots`] as the crate's folders. Protected-path policy is checked in -/// the async artifact resolver through TinySecurity; this synchronous adapter -/// carries only the trusted-root list. +/// [`file_roots`] as the crate's folders, guarded by TinySecurity's +/// protected-path policy. The crate runs the guard on the canonical path and +/// keeps that file open while it reads, so a protected file's bytes are never +/// read and a swapped path cannot be read in its place. pub fn guarded_roots(roots: Vec) -> tiny_artifacts::FileRoots { - tiny_artifacts::FileRoots::new(roots) + tiny_artifacts::FileRoots::new(roots).with_async_guard(|path| async move { + super::files::check_protected_artifact_path(&path) + .await + .err() + }) } /// The artifact service for one workspace: OpenHuman's store and UI bridge, diff --git a/crates/openhuman-core/src/artifacts/tiny_store_tests.rs b/crates/openhuman-core/src/artifacts/tiny_store_tests.rs index 2e8159d8c47..e0e46c91f90 100644 --- a/crates/openhuman-core/src/artifacts/tiny_store_tests.rs +++ b/crates/openhuman-core/src/artifacts/tiny_store_tests.rs @@ -4,7 +4,7 @@ use std::sync::Mutex; use tiny_artifacts::{ ArtifactAuthor, ArtifactKind, ArtifactRecord, ArtifactStore, ArtifactVersion, Author, Content, - FileRef, FileStore, PublishOptions, PublishedLink, + PublishOptions, PublishedLink, }; use super::*; @@ -74,8 +74,12 @@ async fn seeded( store } +#[cfg(feature = "security-module")] #[tokio::test] async fn legacy_path_refs_are_guarded_and_imported_as_opaque_file_keys() { + let _floor = crate::modules::security::gap::install_path_floor_port( + crate::modules::security::gap::ScriptedPathFloorPort::new([], vec![]), + ); let dir = tempfile::tempdir().unwrap(); let source_root = dir.path().join("Files"); let blobs_root = dir.path().join("blobs"); @@ -85,7 +89,8 @@ async fn legacy_path_refs_are_guarded_and_imported_as_opaque_file_keys() { let records = Arc::new(MemoryArtifactStore::default()); let base: Arc = records.clone(); - let blobs: Arc = Arc::new(tiny_artifacts::FsFileStore::new(&blobs_root)); + let blobs: Arc = + Arc::new(tiny_artifacts::FsFileStore::new(&blobs_root)); let importing = LegacyFileImportStore { records: base, files: blobs.clone(), @@ -98,7 +103,7 @@ async fn legacy_path_refs_are_guarded_and_imported_as_opaque_file_keys() { "agent", 1, ); - version.file = Some(FileRef { + version.file = Some(tiny_artifacts::FileRef { key: source.display().to_string(), size_bytes: 12, media_type: None, @@ -122,7 +127,7 @@ async fn legacy_path_refs_are_guarded_and_imported_as_opaque_file_keys() { "agent", 1, ); - blocked_version.file = Some(FileRef { + blocked_version.file = Some(tiny_artifacts::FileRef { key: outside.display().to_string(), size_bytes: 17, media_type: None, @@ -133,8 +138,12 @@ async fn legacy_path_refs_are_guarded_and_imported_as_opaque_file_keys() { assert!(importing.get("a-outside").await.is_err()); } +#[cfg(feature = "security-module")] #[tokio::test] async fn explicit_artifact_context_binds_records_and_blobs_to_the_same_profile() { + let _floor = crate::modules::security::gap::install_path_floor_port( + crate::modules::security::gap::ScriptedPathFloorPort::new([], vec![]), + ); use crate::core::runtime::{ContextOverlay, CoreContext, DispatchCtx, DomainSet}; let (workspace, files) = temp_dirs(); @@ -273,12 +282,16 @@ async fn missing_artifact_storage_binding_does_not_fall_back_to_ambient_records( .await; } +#[cfg(feature = "security-module")] #[tokio::test] async fn legacy_bridge_does_not_overwrite_an_existing_card_file_outside_trusted_roots() { + let _floor = crate::modules::security::gap::install_path_floor_port( + crate::modules::security::gap::ScriptedPathFloorPort::new([], vec![]), + ); let (workspace, files) = temp_dirs(); let root = files.parent().unwrap(); let records: Arc = Arc::new(MemoryArtifactStore::default()); - let file_store: Arc = + let file_store: Arc = Arc::new(tiny_artifacts::FsFileStore::new(root.join("blobs"))); let ctx = crate::core::runtime::DispatchCtx::unbound(); let bridge = Arc::new(LegacyUiBridge::new( @@ -397,8 +410,12 @@ async fn a_missing_artifact_is_an_error() { assert!(err.contains("not found"), "{err}"); } +#[cfg(feature = "security-module")] #[tokio::test] async fn an_image_filed_through_the_service_gets_a_card_and_a_copy_in_files() { + let _floor = crate::modules::security::gap::install_path_floor_port( + crate::modules::security::gap::ScriptedPathFloorPort::new([], vec![]), + ); let (workspace, files) = temp_dirs(); let action = workspace.parent().unwrap().join("projects"); std::fs::create_dir_all(&action).unwrap(); @@ -516,8 +533,12 @@ fn share_artifact_is_offered_only_with_a_publisher() { assert!(with.contains(&"share_artifact".to_string()), "{with:?}"); } +#[cfg(feature = "security-module")] #[tokio::test] async fn a_file_in_an_earlier_files_folder_can_still_be_revised() { + let _floor = crate::modules::security::gap::install_path_floor_port( + crate::modules::security::gap::ScriptedPathFloorPort::new([], vec![]), + ); let (workspace, files) = temp_dirs(); let earlier = files.parent().unwrap().join("OldFiles"); std::fs::create_dir_all(&earlier).unwrap(); @@ -581,6 +602,26 @@ async fn a_protected_file_inside_the_working_folder_is_refused() { assert!(err.to_string().contains("protected location"), "{err}"); } +#[cfg(feature = "security-module")] +#[tokio::test] +async fn the_guarded_roots_refuse_to_read_a_protected_file() { + let (workspace, _files) = temp_dirs(); + let home = workspace.parent().unwrap().join("home"); + std::fs::create_dir_all(home.join(".ssh")).unwrap(); + std::fs::write(home.join(".ssh/id_ed25519"), b"PRIVATE").unwrap(); + std::fs::write(home.join("notes.txt"), b"hello").unwrap(); + let key = home.join(".ssh/id_ed25519").canonicalize().unwrap(); + let _floor = crate::modules::security::gap::install_path_floor_port( + crate::modules::security::gap::ScriptedPathFloorPort::new([key], vec![]), + ); + let roots = guarded_roots(vec![home]); + + let err = roots.read(".ssh/id_ed25519").await.unwrap_err(); + assert!(err.to_string().contains("protected location"), "{err}"); + let (_, bytes) = roots.read("notes.txt").await.unwrap(); + assert_eq!(bytes, b"hello"); +} + #[test] fn a_working_folder_that_contains_the_workspace_is_not_trusted() { let (workspace, files) = temp_dirs(); diff --git a/crates/openhuman-core/src/config/schema/load/secrets.rs b/crates/openhuman-core/src/config/schema/load/secrets.rs index 81e4343887b..9747882eeff 100644 --- a/crates/openhuman-core/src/config/schema/load/secrets.rs +++ b/crates/openhuman-core/src/config/schema/load/secrets.rs @@ -19,6 +19,7 @@ async fn decrypt_optional_secret( ) -> Result { if let Some(raw) = value.clone() { if crate::security::secret_storage::SecretStore::is_encrypted(&raw) { + log::debug!("[security][config] opening sealed secret '{field_name}'"); match store.decrypt_and_migrate_via_security(&raw).await { Ok((plaintext, migrated)) => { if migrated.is_some() { diff --git a/crates/openhuman-core/src/config/user_scope.rs b/crates/openhuman-core/src/config/user_scope.rs index 977f8197ca0..5f05ec92975 100644 --- a/crates/openhuman-core/src/config/user_scope.rs +++ b/crates/openhuman-core/src/config/user_scope.rs @@ -46,63 +46,130 @@ pub(crate) fn operator_user_activation_allowed() -> bool { #[path = "user_scope_tests.rs"] mod tests; +/// What [`activate_user_scope`] changed, so a sign-in that fails before its +/// credential is committed can put it back. +pub(crate) struct UserScopeActivation { + pub(crate) logs: Vec, + /// `None` when this host may not touch the operator's active user. + root_dir: Option, + previous_active: Option, + /// The user directory, when this activation created it. + created_dir: Option, +} + /// Activate `~/.openhuman/users//` as the current user directory. /// -/// On the very first activation (no previous `active_user.toml`) the -/// anonymous pre-login conversation store is purged so a fresh account never -/// inherits demo or scratch threads from the pre-login bucket (#1157). -/// Returns human-readable log lines for the RPC outcome. -pub(crate) fn activate_user_scope(ctx: &DispatchCtx, user_id: &str) -> Result, String> { - let mut logs = Vec::new(); +/// Nothing here is irreversible: the pre-login purge waits for +/// [`complete_user_scope_activation`], after the credential is committed, and +/// [`roll_back_user_scope_activation`] restores the previous active user. +pub(crate) fn activate_user_scope( + _ctx: &DispatchCtx, + user_id: &str, +) -> Result { + let mut activation = UserScopeActivation { + logs: Vec::new(), + root_dir: None, + previous_active: None, + created_dir: None, + }; if !operator_user_activation_allowed() { log::debug!("{LOG_PREFIX} embedder host; skipping global user activation for {user_id}"); - return Ok(logs); + return Ok(activation); } let root_dir = default_root_openhuman_dir().map_err(|error| error.to_string())?; // Snapshot before overwriting `active_user.toml` so first activation can be // told apart from an in-place account switch. - let previous_active = read_active_user_id(&root_dir); + activation.previous_active = read_active_user_id(&root_dir); let user_dir = user_openhuman_dir(&root_dir, user_id); + if !user_dir.exists() { + activation.created_dir = Some(user_dir.clone()); + } std::fs::create_dir_all(&user_dir).map_err(|error| error.to_string())?; - write_active_user_id(&root_dir, user_id).map_err(|error| error.to_string())?; - logs.push(format!("user directory activated for {user_id}")); + activation.root_dir = Some(root_dir.clone()); + if let Err(error) = write_active_user_id(&root_dir, user_id) { + let _ = roll_back_user_scope_activation(activation); + return Err(error.to_string()); + } + activation + .logs + .push(format!("user directory activated for {user_id}")); tracing::info!(user_id = %user_id, user_dir = %user_dir.display(), "{LOG_PREFIX} user-scoped directory activated"); + Ok(activation) +} - if previous_active.is_none() { - // Shares `threads::store`' process-wide mutex with - // `list_threads` / `purge_threads` on any workspace, so purge and - // concurrent thread RPC in this process cannot interleave. - // The pre-login profile's workspace follows its layout (`workspace` - // for v1, `files` for v2). Detection only: this must not create the - // profile directory as a side effect. - let pre_dir = pre_login_user_dir(&root_dir); - let pre_ws = crate::config::schema::ProfileLayout::with_version( - pre_dir.clone(), - crate::config::schema::profile_layout::LayoutVersion::detect(&pre_dir), - ) - .workspace_dir; - let pre_ws_log = pre_ws.display().to_string(); - match conversations::purge_threads(ctx, pre_ws) { - Ok(stats) => { - tracing::info!( - pre_login_workspace = %pre_ws_log, - threads = stats.thread_count, - messages = stats.message_count, - "{LOG_PREFIX} purged pre-login conversation threads after first activation" - ); - logs.push(format!( - "purged pre-login conversation history (threads={}, messages={})", - stats.thread_count, stats.message_count - )); - } - Err(e) => tracing::debug!( - error = %e, +/// Finish an activation whose credential is committed. On the very first +/// activation (no previous `active_user.toml`) the anonymous pre-login +/// conversation store is purged so a fresh account never inherits demo or +/// scratch threads from the pre-login bucket (#1157). +pub(crate) fn complete_user_scope_activation( + ctx: &DispatchCtx, + activation: &UserScopeActivation, +) -> Vec { + let mut logs = Vec::new(); + let Some(root_dir) = activation.root_dir.as_deref() else { + return logs; + }; + if activation.previous_active.is_some() { + return logs; + } + // Shares `threads::store`' process-wide mutex with + // `list_threads` / `purge_threads` on any workspace, so purge and + // concurrent thread RPC in this process cannot interleave. + // The pre-login profile's workspace follows its layout (`workspace` + // for v1, `files` for v2). Detection only: this must not create the + // profile directory as a side effect. + let pre_dir = pre_login_user_dir(root_dir); + let pre_ws = crate::config::schema::ProfileLayout::with_version( + pre_dir.clone(), + crate::config::schema::profile_layout::LayoutVersion::detect(&pre_dir), + ) + .workspace_dir; + let pre_ws_log = pre_ws.display().to_string(); + match conversations::purge_threads(ctx, pre_ws) { + Ok(stats) => { + tracing::info!( pre_login_workspace = %pre_ws_log, - "{LOG_PREFIX} pre-login conversation purge skipped (non-fatal)" - ), + threads = stats.thread_count, + messages = stats.message_count, + "{LOG_PREFIX} purged pre-login conversation threads after first activation" + ); + logs.push(format!( + "purged pre-login conversation history (threads={}, messages={})", + stats.thread_count, stats.message_count + )); } + Err(e) => tracing::debug!( + error = %e, + pre_login_workspace = %pre_ws_log, + "{LOG_PREFIX} pre-login conversation purge skipped (non-fatal)" + ), } - Ok(logs) + logs +} + +/// Undo an activation whose sign-in failed: the previous user is active again +/// (or none, as before), and a user directory this activation created is +/// removed with whatever the failed sign-in wrote into it. +pub(crate) fn roll_back_user_scope_activation( + activation: UserScopeActivation, +) -> Result<(), String> { + let Some(root_dir) = activation.root_dir else { + return Ok(()); + }; + match &activation.previous_active { + Some(previous) => write_active_user_id(&root_dir, previous), + None => crate::config::clear_active_user(&root_dir), + } + .map_err(|error| error.to_string())?; + if let Some(created) = activation.created_dir { + match std::fs::remove_dir_all(&created) { + Ok(()) => {} + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => return Err(error.to_string()), + } + } + tracing::info!("{LOG_PREFIX} user-scoped directory activation rolled back"); + Ok(()) } /// Clear `active_user.toml` so subsequent config loads fall back to the diff --git a/crates/openhuman-core/src/config/user_scope_tests.rs b/crates/openhuman-core/src/config/user_scope_tests.rs index 5567ceac215..2bd36045c97 100644 --- a/crates/openhuman-core/src/config/user_scope_tests.rs +++ b/crates/openhuman-core/src/config/user_scope_tests.rs @@ -54,7 +54,16 @@ fn first_user_activation_queues_prelogin_purge_in_the_removed_workspace() { vec!["prelogin-channel-thread"] ); - activate_user_scope(&ctx, "new-user").unwrap(); + let activation = activate_user_scope(&ctx, "new-user").unwrap(); + // Activation alone is reversible: nothing is purged before the credential + // is committed. + assert_eq!( + list_threads(&ctx, prelogin_workspace.clone()) + .unwrap() + .len(), + 1 + ); + complete_user_scope_activation(&ctx, &activation); assert!(list_threads(&ctx, prelogin_workspace.clone()) .unwrap() @@ -67,3 +76,83 @@ fn first_user_activation_queues_prelogin_purge_in_the_removed_workspace() { ); assert!(pending(&active_workspace).is_empty()); } + +#[test] +fn a_rolled_back_first_activation_keeps_prelogin_threads_and_leaves_no_profile() { + use crate::threads::store::{ensure_thread, list_threads, CreateConversationThread}; + + let tmp = tempfile::tempdir().unwrap(); + let env = crate::config::test_env::EnvVarGuard::locked().with("HOME", tmp.path()); + let root = crate::config::default_root_openhuman_dir().unwrap(); + let _env = env.with("OPENHUMAN_WORKSPACE", &root); + let prelogin_workspace = crate::config::pre_login_user_dir(&root).join("workspace"); + let user_dir = crate::config::user_openhuman_dir(&root, "failed-user"); + crate::storage::local::use_persistent_default_for_test(&prelogin_workspace); + let ctx = crate::core::runtime::DispatchCtx::unbound(); + ensure_thread( + &ctx, + prelogin_workspace.clone(), + CreateConversationThread { + id: "prelogin-thread".to_string(), + title: "Pre-login thread".to_string(), + created_at: "2026-11-04T00:00:00Z".to_string(), + parent_thread_id: None, + labels: None, + personality_id: None, + working_dir: None, + }, + ) + .unwrap(); + + let activation = activate_user_scope(&ctx, "failed-user").unwrap(); + assert_eq!( + crate::config::read_active_user_id(&root).as_deref(), + Some("failed-user") + ); + std::fs::write( + user_dir.join("config.toml"), + "# written by the failed sign-in", + ) + .unwrap(); + roll_back_user_scope_activation(activation).unwrap(); + + assert!(crate::config::read_active_user_id(&root).is_none()); + assert!( + !user_dir.exists(), + "the half-created profile must be removed" + ); + assert_eq!( + list_threads(&ctx, prelogin_workspace) + .unwrap() + .iter() + .map(|thread| thread.id.as_str()) + .collect::>(), + vec!["prelogin-thread"] + ); +} + +#[test] +fn a_rolled_back_account_switch_restores_the_previous_user_and_keeps_their_profile() { + let tmp = tempfile::tempdir().unwrap(); + let env = crate::config::test_env::EnvVarGuard::locked().with("HOME", tmp.path()); + let root = crate::config::default_root_openhuman_dir().unwrap(); + let _env = env.with("OPENHUMAN_WORKSPACE", &root); + let ctx = crate::core::runtime::DispatchCtx::unbound(); + let user_a = crate::config::user_openhuman_dir(&root, "user-a"); + std::fs::create_dir_all(&user_a).unwrap(); + crate::config::write_active_user_id(&root, "user-a").unwrap(); + + let activation = activate_user_scope(&ctx, "user-b").unwrap(); + assert_eq!( + crate::config::read_active_user_id(&root).as_deref(), + Some("user-b") + ); + roll_back_user_scope_activation(activation).unwrap(); + + assert_eq!( + crate::config::read_active_user_id(&root).as_deref(), + Some("user-a") + ); + assert!(user_a.is_dir()); + assert!(!crate::config::user_openhuman_dir(&root, "user-b").exists()); +} diff --git a/crates/openhuman-core/src/core/all_bound_controller_tests.rs b/crates/openhuman-core/src/core/all_bound_controller_tests.rs index 5da7c4883db..13cba3652eb 100644 --- a/crates/openhuman-core/src/core/all_bound_controller_tests.rs +++ b/crates/openhuman-core/src/core/all_bound_controller_tests.rs @@ -21,6 +21,7 @@ fn staged_bound_methods() -> Vec<&'static str> { "keyring_consent.decide", "keyring_consent.retry_probe", "keyring_consent.respond_operation", + "keyring_consent.list_pending_operations", ]); methods.extend([ "approval.list_pending", diff --git a/crates/openhuman-core/src/core/all_keyring_consent_controller_tests.rs b/crates/openhuman-core/src/core/all_keyring_consent_controller_tests.rs index 652577269af..027c4dde9f6 100644 --- a/crates/openhuman-core/src/core/all_keyring_consent_controller_tests.rs +++ b/crates/openhuman-core/src/core/all_keyring_consent_controller_tests.rs @@ -25,6 +25,10 @@ fn raw_keyring_consent_registry_matches_its_independent_contract() { "keyring_consent.respond_operation", "openhuman.keyring_consent_respond_operation", ), + ( + "keyring_consent.list_pending_operations", + "openhuman.keyring_consent_list_pending_operations", + ), ], }; registry_test_support::verify_family_contract( @@ -122,8 +126,8 @@ fn raw_keyring_consent_decide_rejects_before_persistence() { #[test] fn raw_keyring_consent_wire_fields_are_exact() { let entries = keyring_consent_entries(); - assert_eq!(entries.len(), 4); - for entry in [&entries[0], &entries[2]] { + assert_eq!(entries.len(), 5); + for entry in [&entries[0], &entries[2], &entries[4]] { assert_eq!( crate::core::all::verify_wire_fields(&entry.schema.inputs, &[]), Ok(()), diff --git a/crates/openhuman-core/src/core/cli.rs b/crates/openhuman-core/src/core/cli.rs index f878b0db1ad..08e43e28ca1 100644 --- a/crates/openhuman-core/src/core/cli.rs +++ b/crates/openhuman-core/src/core/cli.rs @@ -603,9 +603,20 @@ fn run_namespace_command( .map_err(anyhow::Error::msg)?; println!("{}", serde_json::to_string_pretty(&value)?); + if restart_required(&value) { + // EX_TEMPFAIL: the profile switch completes in the next process. + eprintln!("restart required to finish switching profiles"); + std::process::exit(75); + } Ok(()) } +/// Whether an auth response asks the host to restart the process. +fn restart_required(value: &Value) -> bool { + value.get("restartRequired") == Some(&Value::Bool(true)) + || value.get("result").is_some_and(restart_required) +} + /// Parses namespace-style command-line arguments into a JSON map based on a /// function's schema, without dispatching the command or starting a runtime. /// diff --git a/crates/openhuman-core/src/core/cli_tests.rs b/crates/openhuman-core/src/core/cli_tests.rs index ad5498427cc..2c22f3e28e8 100644 --- a/crates/openhuman-core/src/core/cli_tests.rs +++ b/crates/openhuman-core/src/core/cli_tests.rs @@ -1,6 +1,6 @@ use super::{ grouped_schemas, is_help_only, load_dotenv_for_cli, parse_function_params, parse_input_value, - parse_launch_options, + parse_launch_options, restart_required, }; use crate::config::test_env::EnvVarGuard; use crate::core::{ControllerSchema, FieldSchema, TypeSchema}; @@ -406,3 +406,18 @@ fn default_build_leaves_the_generic_namespace_path_unchanged() { "`memory_diff` was removed and must not be listed" ); } + +#[test] +fn an_auth_response_asking_for_a_restart_is_recognised_at_any_depth() { + use serde_json::json; + assert!(restart_required(&json!({"restartRequired": true}))); + assert!(restart_required( + &json!({"result": {"result": {"restartRequired": true}}}) + )); + assert!(!restart_required( + &json!({"result": {"restartRequired": false}}) + )); + assert!(!restart_required( + &json!({"result": {"isAuthenticated": true}}) + )); +} diff --git a/crates/openhuman-core/src/core/runtime/builder.rs b/crates/openhuman-core/src/core/runtime/builder.rs index 6022554bcee..df53ce67f3d 100644 --- a/crates/openhuman-core/src/core/runtime/builder.rs +++ b/crates/openhuman-core/src/core/runtime/builder.rs @@ -541,6 +541,7 @@ impl CoreRuntime { .expect("core config lock poisoned") .clone() .ok_or_else(|| anyhow::anyhow!("secret preflight has no loaded config"))?; + log::debug!("[core-runtime] secret preflight: decrypting config secrets"); let migrated = config.decrypt_secrets_after_preflight().await?; if migrated { if let Err(error) = config.save().await { @@ -550,17 +551,21 @@ impl CoreRuntime { } } self.ctx.replace_latest_embedder_config(config.clone()); + log::debug!("[core-runtime] secret preflight: loading startup credentials"); crate::core::runtime::subscribers::finish_secret_preflight_credentials( &crate::core::runtime::DispatchCtx::new(Arc::clone(&self.ctx)), &config, ) .await; + log::debug!("[core-runtime] secret preflight: running legacy migrations"); crate::core::runtime::services::run_legacy_migrations(&config).await; + log::debug!("[core-runtime] secret preflight: starting the startup sweep"); let sweep = start_startup_sweep(&config.workspace_dir).await; *self.startup_sweep.lock().await = sweep; *self.config.write().expect("core config lock poisoned") = Some(config); self.secret_preflight_complete .store(true, std::sync::atomic::Ordering::Release); + log::debug!("[core-runtime] secret preflight: complete"); Ok(()) } diff --git a/crates/openhuman-core/src/credentials/ops/credential/set.rs b/crates/openhuman-core/src/credentials/ops/credential/set.rs index a5c91136f03..3d69d2cd885 100644 --- a/crates/openhuman-core/src/credentials/ops/credential/set.rs +++ b/crates/openhuman-core/src/credentials/ops/credential/set.rs @@ -1,6 +1,7 @@ use super::*; use crate::config::user_scope::{ - activate_user_scope, rebind_after_credential_change, reload_config_or, + activate_user_scope, complete_user_scope_activation, rebind_after_credential_change, + reload_config_or, roll_back_user_scope_activation, UserScopeActivation, }; use crate::core::observability::sentry_scope; use crate::credentials::session_state::{ @@ -11,19 +12,31 @@ use crate::credentials::{ api_key, identity, AuthService, APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME, }; -async fn rollback_failed_credential_rebind(auth: &AuthService, cause: &str) -> String { +async fn rollback_failed_credential_rebind( + auth: &AuthService, + activation: Option, + cause: &str, +) -> String { if let Err(rollback) = auth .remove_profile(APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME) .await { return format!("credential rebind failed: {cause}; rollback failed: {rollback}"); } - if let Err(rollback) = crate::config::user_scope::deactivate_user_scope() { - return format!( - "credential rebind failed: {cause}; active-user rollback failed: {rollback}" - ); + rollback_failed_activation(activation, cause) +} + +/// Undo the directory activation of a sign-in that failed before its +/// credential was committed, so a failure leaves the previous user active and +/// no half-created profile behind. +fn rollback_failed_activation(activation: Option, cause: &str) -> String { + let Some(activation) = activation else { + return cause.to_string(); + }; + match roll_back_user_scope_activation(activation) { + Ok(()) => cause.to_string(), + Err(rollback) => format!("{cause}; active-user rollback failed: {rollback}"), } - cause.to_string() } /// Install a backend credential. See the module docs for what the core does @@ -86,6 +99,7 @@ pub async fn set_credential( .clone() .expect("session and local credentials always resolve a user id"); let mut logs = Vec::new(); + let needs_restart = sign_in_needs_restart(&user_id).await; // Refresh vs. install vs. account switch, decided on the stored profile. let existing = load_app_session_profile(config).await?; @@ -145,14 +159,23 @@ pub async fn set_credential( metadata.insert(SESSION_EXPIRES_AT_META.to_string(), exp.to_rfc3339()); } + let mut activation = None; let effective_config = if refresh { logs.push("credential refreshed (same secret, same user)".to_string()); config.clone() } else { - logs.extend(activate_user_scope(ctx, &user_id)?); + if needs_restart { + return sign_in_across_restart(ctx, &user_id, logs); + } + let activated = activate_user_scope(ctx, &user_id)?; + logs.extend(activated.logs.iter().cloned()); + activation = Some(activated); // Reload so auth-profiles.json, the encryption key and the workspace // resolve to the user-scoped location before the profile is written. - let effective = reload_config_or(ctx, config).await?; + let effective = match reload_config_or(ctx, config).await { + Ok(effective) => effective, + Err(error) => return Err(rollback_failed_activation(activation, &error)), + }; if resolved.kind == CredentialKind::Local { match crate::config::ops::set_onboarding_completed(ctx, false).await { Ok(_) => { @@ -168,15 +191,18 @@ pub async fn set_credential( }; let auth = AuthService::from_config(&effective_config); - auth.store_provider_token( - APP_SESSION_PROVIDER, - DEFAULT_AUTH_PROFILE_NAME, - &resolved.token, - metadata, - true, - ) - .await - .map_err(|e| e.to_string())?; + if let Err(error) = auth + .store_provider_token( + APP_SESSION_PROVIDER, + DEFAULT_AUTH_PROFILE_NAME, + &resolved.token, + metadata, + true, + ) + .await + { + return Err(rollback_failed_activation(activation, &error.to_string())); + } logs.push(format!("{} credential stored", resolved.kind.as_str())); if !refresh { @@ -186,9 +212,12 @@ pub async fn set_credential( { // A retry of the same credential takes the refresh fast-path, so // leaving its profile behind would let it skip this required bind. - return Err(rollback_failed_credential_rebind(&auth, &error).await); + return Err(rollback_failed_credential_rebind(&auth, activation, &error).await); } logs.push("process globals rebound after credential install".to_string()); + if let Some(activation) = &activation { + logs.extend(complete_user_scope_activation(ctx, activation)); + } start_credential_gated_services(ctx, &effective_config).await; logs.push("credential-gated services started".to_string()); } @@ -226,6 +255,68 @@ pub async fn set_credential( Ok(Outcome::new(state, logs)) } +/// Whether signing `user_id` in moves this process to a profile its +/// TinySecurity was not admitted for. That identity is fixed for the life of +/// the process, so the sign-in completes only after a restart. +async fn sign_in_needs_restart(user_id: &str) -> bool { + #[cfg(feature = "security-module")] + { + if !crate::config::user_scope::operator_user_activation_allowed() { + return false; + } + let Some(admitted) = crate::modules::ops::security_admitted_key_path().await else { + return false; + }; + let Ok(root) = crate::config::default_root_openhuman_dir() else { + return false; + }; + crate::credentials::session_state::is_profile_switch( + &admitted, + &crate::config::user_openhuman_dir(&root, user_id).join(".secret_key"), + ) + } + #[cfg(not(feature = "security-module"))] + { + let _ = user_id; + false + } +} + +/// Refusal text for a sign-in that needs the process restarted first. +const SIGN_IN_AGAIN: &str = + "restart required to finish switching profiles; sign in again after restarting"; + +/// Activate `user_id`'s profile and report that the process must restart: +/// this process's TinySecurity cannot serve it. Nothing is stored under this +/// process's profile; the user signs in again once it has restarted. +fn sign_in_across_restart( + ctx: &DispatchCtx, + user_id: &str, + mut logs: Vec, +) -> Result, String> { + let activation = activate_user_scope(ctx, user_id)?; + logs.push(SIGN_IN_AGAIN.to_string()); + logs.extend(activation.logs.iter().cloned()); + tracing::info!( + domain = "credentials", + operation = "set_credential", + "{LOG_PREFIX} profile switch: restart required" + ); + Ok(Outcome::new( + AuthStateResponse { + is_authenticated: false, + user_id: Some(user_id.to_owned()), + user: None, + profile_id: None, + credential: None, + expires_at: None, + issuing_backend: None, + restart_required: true, + }, + logs, + )) +} + #[cfg(test)] #[path = "../../ops_credential_scope_rollback_tests.rs"] mod scope_rollback_tests; diff --git a/crates/openhuman-core/src/credentials/ops_credential_scope_rollback_tests.rs b/crates/openhuman-core/src/credentials/ops_credential_scope_rollback_tests.rs index 20c09e45574..cd8439ef43e 100644 --- a/crates/openhuman-core/src/credentials/ops_credential_scope_rollback_tests.rs +++ b/crates/openhuman-core/src/credentials/ops_credential_scope_rollback_tests.rs @@ -7,8 +7,13 @@ async fn failed_credential_rebind_removes_profile_and_active_user_scope() { let _env_guard = crate::config::TEST_ENV_LOCK.lock().await; let tmp = TempDir::new().unwrap(); let _home = EnvVarGuard::set("HOME", tmp.path()); + let _workspace = EnvVarGuard::set("OPENHUMAN_WORKSPACE", tmp.path().join(".openhuman")); let root = crate::config::default_root_openhuman_dir().unwrap(); - crate::config::write_active_user_id(&root, "new-user").unwrap(); + let activation = crate::config::user_scope::activate_user_scope( + &crate::core::runtime::DispatchCtx::unbound(), + "new-user", + ) + .unwrap(); let user_dir = crate::config::user_openhuman_dir(&root, "new-user"); std::fs::create_dir_all(user_dir.join("workspace")).unwrap(); let config = crate::config::Config { @@ -28,10 +33,19 @@ async fn failed_credential_rebind_removes_profile_and_active_user_scope() { .await .unwrap(); - let error = super::rollback_failed_credential_rebind(&auth, "workspace rebind failed").await; + let error = super::rollback_failed_credential_rebind( + &auth, + Some(activation), + "workspace rebind failed", + ) + .await; assert!(error.contains("workspace rebind failed")); assert!(crate::config::read_active_user_id(&root).is_none()); + assert!( + !user_dir.exists(), + "the profile this sign-in created must be removed" + ); assert!(auth .get_profile(APP_SESSION_PROVIDER, Some(DEFAULT_AUTH_PROFILE_NAME)) .await diff --git a/crates/openhuman-core/src/credentials/responses.rs b/crates/openhuman-core/src/credentials/responses.rs index 9cfb21990d3..235716e3214 100644 --- a/crates/openhuman-core/src/credentials/responses.rs +++ b/crates/openhuman-core/src/credentials/responses.rs @@ -22,6 +22,12 @@ pub struct AuthStateResponse { /// Backend that issued this session. Legacy sessions have no association. #[serde(default, skip_serializing_if = "Option::is_none")] pub issuing_backend: Option, + /// The active profile is not the one this process's TinySecurity serves: + /// a sign-in, sign-out or account switch completes only after the host + /// restarts the process. `user_id` names the profile it restarts into + /// (absent for the signed-out profile). + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub restart_required: bool, } /// `AuthStateResponse::credential` value for an app-session JWT. diff --git a/crates/openhuman-core/src/credentials/session_state.rs b/crates/openhuman-core/src/credentials/session_state.rs index 98e677ee682..46238f881e0 100644 --- a/crates/openhuman-core/src/credentials/session_state.rs +++ b/crates/openhuman-core/src/credentials/session_state.rs @@ -205,6 +205,22 @@ pub fn user_id_from_jwt_claims(token: &str) -> Option { } pub async fn build_session_state(config: &Config) -> Result { + // A profile this process's TinySecurity was not admitted for cannot read + // or write its credentials; report the restart it is waiting for instead. + if profile_restart_pending(config).await { + return Ok(AuthStateResponse { + is_authenticated: false, + user_id: crate::config::default_root_openhuman_dir() + .ok() + .and_then(|root| crate::config::read_active_user_id(&root)), + user: None, + profile_id: None, + credential: None, + expires_at: None, + issuing_backend: None, + restart_required: true, + }); + } // The API key wins whenever both are present — same precedence as // `resolve_backend_credential`, which every backend request actually // authenticates with. Checked before the session profile loads: a host @@ -223,6 +239,7 @@ pub async fn build_session_state(config: &Config) -> Result) -> AuthStateRes credential: None, expires_at: None, issuing_backend: None, + restart_required: false, }; }; @@ -413,6 +431,7 @@ pub fn session_state_from_profile(profile: Option<&AuthProfile>) -> AuthStateRes .metadata .get(SESSION_ISSUING_BACKEND_META) .and_then(|backend| normalize_session_backend(backend).ok()), + restart_required: false, } } @@ -428,6 +447,44 @@ pub fn session_token_from_profile(profile: Option<&AuthProfile>) -> Option bool { + #[cfg(feature = "security-module")] + { + let Some(admitted) = crate::modules::ops::security_admitted_key_path().await else { + return false; + }; + is_profile_switch(&admitted, &profile_key_path(&config.config_path)) + } + #[cfg(not(feature = "security-module"))] + { + let _ = config; + false + } +} + +/// Whether TinySecurity admitted for `admitted` cannot serve `target`, another +/// profile of this installation. Both must sit under the installation's root: +/// a key path outside it (an explicit workspace, another process's scratch +/// home) is not a profile a restart switches to. +pub(crate) fn is_profile_switch(admitted: &std::path::Path, target: &std::path::Path) -> bool { + let Ok(root) = crate::config::default_root_openhuman_dir() else { + return false; + }; + admitted != target && admitted.starts_with(&root) && target.starts_with(&root) +} + +/// The secret key path TinySecurity is admitted for when a profile's config +/// lives at `config_path` (see `modules::security::host_callbacks`). +pub(crate) fn profile_key_path(config_path: &std::path::Path) -> std::path::PathBuf { + config_path + .parent() + .unwrap_or_else(|| std::path::Path::new(".")) + .join(".secret_key") +} + #[cfg(test)] #[path = "session_state_tests.rs"] mod tests; diff --git a/crates/openhuman-core/src/credentials/session_state_tests.rs b/crates/openhuman-core/src/credentials/session_state_tests.rs index a2e250b7858..6a47ddaca6c 100644 --- a/crates/openhuman-core/src/credentials/session_state_tests.rs +++ b/crates/openhuman-core/src/credentials/session_state_tests.rs @@ -560,3 +560,22 @@ async fn direct_backend_credential_returns_a_live_session() { Some(BackendCredential::Session("raw-session-token".into())) ); } + +#[test] +fn only_two_profiles_of_this_installation_make_a_profile_switch() { + let tmp = tempfile::tempdir().unwrap(); + let _env = crate::config::test_env::EnvVarGuard::locked().with("HOME", tmp.path()); + let root = crate::config::default_root_openhuman_dir().unwrap(); + let local = root.join("users/local/.secret_key"); + let user = root.join("users/u1/.secret_key"); + let elsewhere = tmp.path().join("scratch/.secret_key"); + + assert!(is_profile_switch(&local, &user)); + assert!(is_profile_switch(&user, &local)); + assert!(!is_profile_switch(&user, &user)); + assert!( + !is_profile_switch(&elsewhere, &user), + "another root is not this installation" + ); + assert!(!is_profile_switch(&user, &elsewhere)); +} diff --git a/crates/openhuman-core/src/modules/ops.rs b/crates/openhuman-core/src/modules/ops.rs index 5e18c85202a..c86e3af6603 100644 --- a/crates/openhuman-core/src/modules/ops.rs +++ b/crates/openhuman-core/src/modules/ops.rs @@ -307,6 +307,12 @@ pub(crate) async fn security_secret_registration_id() -> Option { super::security::host_callbacks::secret_registration_id().await } +/// The secret key path the admitted TinySecurity serves, if it is admitted. +#[cfg(feature = "security-module")] +pub(crate) async fn security_admitted_key_path() -> Option { + super::security::host_callbacks::admitted_key_path().await +} + #[cfg(feature = "security-module")] pub(crate) async fn security_callback_identity() -> Option { super::security::host_callbacks::identity().await diff --git a/crates/openhuman-core/src/modules/registry/records_security.rs b/crates/openhuman-core/src/modules/registry/records_security.rs index dc3da952776..95cc87e9b97 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.18.4/checksum.toml. +//! Published TinySecurity admission pins copied verbatim from v0.19.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. @@ -9,73 +9,73 @@ pub(crate) const TINYSECURITY: ModuleRecord = ModuleRecord { description: "Native security policy and durable approval tool grants", bus_name: tinysecurity_bus::names::INTERFACE, object_path: tinysecurity_bus::names::OBJECT_PATH, - version: "0.18.4", - release_url: "https://github.com/tinyhumansai/tinysecurity/releases/tag/v0.18.4", + version: "0.19.0", + release_url: "https://github.com/tinyhumansai/tinysecurity/releases/tag/v0.19.0", assets: &[ PlatformAsset { host_key: "ubuntu-24.04-x86_64", - archive: "tinysecurity-module-0.18.4-ubuntu-24.04-x86_64.tar.gz", - sha256: "2e51299127281ae7c524c606590bb41ae2f635536c63791abe327d7f6abed0ba", + archive: "tinysecurity-module-0.19.0-ubuntu-24.04-x86_64.tar.gz", + sha256: "a52f41593935b71b644753776bca041fded2baf2fd9ad6aa0d8dc8fbb478acf8", library_sha256: None, }, PlatformAsset { host_key: "ubuntu-24.04-arm64", - archive: "tinysecurity-module-0.18.4-ubuntu-24.04-arm64.tar.gz", - sha256: "61cb28f3ebc5bfb77503b20abf128a4dbf55f2c5ba9f826ba240edf8bd51ff2c", + archive: "tinysecurity-module-0.19.0-ubuntu-24.04-arm64.tar.gz", + sha256: "8e5a9d1e2b4ef0c985647c23f6cf0b9dc3a3258f810348e86fa8e2ee914b29b5", library_sha256: None, }, PlatformAsset { host_key: "ubuntu-22.04-x86_64", - archive: "tinysecurity-module-0.18.4-ubuntu-22.04-x86_64.tar.gz", - sha256: "d56513cfc8d3f0ad2552abf31918365e3bbbdb700010a03e3273c79d6ac53b06", + archive: "tinysecurity-module-0.19.0-ubuntu-22.04-x86_64.tar.gz", + sha256: "4eba772220e02e4f9b3589e78a84c7a73f7000ed2d9ca20bd83e34a2f514afe6", library_sha256: None, }, PlatformAsset { host_key: "ubuntu-22.04-arm64", - archive: "tinysecurity-module-0.18.4-ubuntu-22.04-arm64.tar.gz", - sha256: "f406c66e69817160527b55cd037e5421ddaadbb586702014e9c78d04622de991", + archive: "tinysecurity-module-0.19.0-ubuntu-22.04-arm64.tar.gz", + sha256: "d0ebd99f0bd6697d4e4bd4bce205a10c84275798d53dc3074c8c8b5eabc2d70d", library_sha256: None, }, PlatformAsset { host_key: "macos-26-arm64", - archive: "tinysecurity-module-0.18.4-macos-26-arm64.tar.gz", - sha256: "107f42a9cedaae3a95edf09c82818ad85195e7f0668cf1255b51ee4fbc8ac26e", + archive: "tinysecurity-module-0.19.0-macos-26-arm64.tar.gz", + sha256: "4a45348f65346b2c02999be625d8d56a4ef91175155c30fff4ad8e33e8f78f76", library_sha256: None, }, PlatformAsset { host_key: "macos-26-x86_64", - archive: "tinysecurity-module-0.18.4-macos-26-x86_64.tar.gz", - sha256: "b408ab2832246c1c66630c21ad2a274d6d6592a0f3eaf59039aa517e9955d8a4", + archive: "tinysecurity-module-0.19.0-macos-26-x86_64.tar.gz", + sha256: "8beb108fb78bc1bbb9513e976081b2cf30418e64fe7e8646c9dd498c5796775a", library_sha256: None, }, PlatformAsset { host_key: "macos-15-arm64", - archive: "tinysecurity-module-0.18.4-macos-15-arm64.tar.gz", - sha256: "17d143697610cb7ab391d50d7d08d55165c1074ea1b454de08c9486cda19cc28", + archive: "tinysecurity-module-0.19.0-macos-15-arm64.tar.gz", + sha256: "2e225d2e3b1b76517182c0f27f07f37f0217a3663c9ede326e1837606fa99b68", library_sha256: None, }, PlatformAsset { host_key: "macos-15-x86_64", - archive: "tinysecurity-module-0.18.4-macos-15-x86_64.tar.gz", - sha256: "b11d3ffe0a7a99e0a0fd71fd6fdb87d209e9b8e09c1cb4d3af9656376f368e8b", + archive: "tinysecurity-module-0.19.0-macos-15-x86_64.tar.gz", + sha256: "b3eac95abc3f013eae8853fc24abe50450db143de2b6269bba208ce13ddb0be1", library_sha256: None, }, PlatformAsset { host_key: "windows-2025-x86_64", - archive: "tinysecurity-module-0.18.4-windows-2025-x86_64.zip", - sha256: "fe1f64a199a820d5b58347eea41e29109096b62d81d00e0ed5df083a6fd5005a", + archive: "tinysecurity-module-0.19.0-windows-2025-x86_64.zip", + sha256: "d2edf257fab30fea9e463b2a4c76dae7358714c8104bfca4658daa4c7adb5021", library_sha256: None, }, PlatformAsset { host_key: "windows-2022-x86_64", - archive: "tinysecurity-module-0.18.4-windows-2022-x86_64.zip", - sha256: "8aa5719147a32209f14f9ad9fd4300e9c114a56dfe31d8f59d019b7540b0f111", + archive: "tinysecurity-module-0.19.0-windows-2022-x86_64.zip", + sha256: "7bbddf0b10da1abb68ce1d4f37b4ba716365a0633981c2e2a71096d10fba5a78", library_sha256: None, }, PlatformAsset { host_key: "windows-11-arm64", - archive: "tinysecurity-module-0.18.4-windows-11-arm64.zip", - sha256: "825d2fde75cea1ffb11ff88cc037d1ec9428d784b2d5041f5eec828179f92020", + archive: "tinysecurity-module-0.19.0-windows-11-arm64.zip", + sha256: "d1431618ae6aecd442887cea946c21de5f6ac494eb727e5d2edfb2be8d9873bb", library_sha256: None, }, ], 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 1c39458420d..bc20e3dc95a 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_v0184_release_manifest() { +fn tinysecurity_registry_matches_the_verified_v0190_release_manifest() { let security = find("tinysecurity").expect("compiled TinySecurity module"); - assert_eq!(security.version, "0.18.4"); - assert_eq!(tinysecurity_bus::CONTRACT_VERSION, (1, 35)); + assert_eq!(security.version, "0.19.0"); + assert_eq!(tinysecurity_bus::CONTRACT_VERSION, (2, 0)); assert_eq!( security.release_url, - "https://github.com/tinyhumansai/tinysecurity/releases/tag/v0.18.4" + "https://github.com/tinyhumansai/tinysecurity/releases/tag/v0.19.0" ); let mut actual = security @@ -20,58 +20,58 @@ fn tinysecurity_registry_matches_the_verified_v0184_release_manifest() { let mut published = [ ( "macos-15-arm64", - "tinysecurity-module-0.18.4-macos-15-arm64.tar.gz", - "17d143697610cb7ab391d50d7d08d55165c1074ea1b454de08c9486cda19cc28", + "tinysecurity-module-0.19.0-macos-15-arm64.tar.gz", + "2e225d2e3b1b76517182c0f27f07f37f0217a3663c9ede326e1837606fa99b68", ), ( "macos-15-x86_64", - "tinysecurity-module-0.18.4-macos-15-x86_64.tar.gz", - "b11d3ffe0a7a99e0a0fd71fd6fdb87d209e9b8e09c1cb4d3af9656376f368e8b", + "tinysecurity-module-0.19.0-macos-15-x86_64.tar.gz", + "b3eac95abc3f013eae8853fc24abe50450db143de2b6269bba208ce13ddb0be1", ), ( "macos-26-arm64", - "tinysecurity-module-0.18.4-macos-26-arm64.tar.gz", - "107f42a9cedaae3a95edf09c82818ad85195e7f0668cf1255b51ee4fbc8ac26e", + "tinysecurity-module-0.19.0-macos-26-arm64.tar.gz", + "4a45348f65346b2c02999be625d8d56a4ef91175155c30fff4ad8e33e8f78f76", ), ( "macos-26-x86_64", - "tinysecurity-module-0.18.4-macos-26-x86_64.tar.gz", - "b408ab2832246c1c66630c21ad2a274d6d6592a0f3eaf59039aa517e9955d8a4", + "tinysecurity-module-0.19.0-macos-26-x86_64.tar.gz", + "8beb108fb78bc1bbb9513e976081b2cf30418e64fe7e8646c9dd498c5796775a", ), ( "ubuntu-22.04-arm64", - "tinysecurity-module-0.18.4-ubuntu-22.04-arm64.tar.gz", - "f406c66e69817160527b55cd037e5421ddaadbb586702014e9c78d04622de991", + "tinysecurity-module-0.19.0-ubuntu-22.04-arm64.tar.gz", + "d0ebd99f0bd6697d4e4bd4bce205a10c84275798d53dc3074c8c8b5eabc2d70d", ), ( "ubuntu-22.04-x86_64", - "tinysecurity-module-0.18.4-ubuntu-22.04-x86_64.tar.gz", - "d56513cfc8d3f0ad2552abf31918365e3bbbdb700010a03e3273c79d6ac53b06", + "tinysecurity-module-0.19.0-ubuntu-22.04-x86_64.tar.gz", + "4eba772220e02e4f9b3589e78a84c7a73f7000ed2d9ca20bd83e34a2f514afe6", ), ( "ubuntu-24.04-arm64", - "tinysecurity-module-0.18.4-ubuntu-24.04-arm64.tar.gz", - "61cb28f3ebc5bfb77503b20abf128a4dbf55f2c5ba9f826ba240edf8bd51ff2c", + "tinysecurity-module-0.19.0-ubuntu-24.04-arm64.tar.gz", + "8e5a9d1e2b4ef0c985647c23f6cf0b9dc3a3258f810348e86fa8e2ee914b29b5", ), ( "ubuntu-24.04-x86_64", - "tinysecurity-module-0.18.4-ubuntu-24.04-x86_64.tar.gz", - "2e51299127281ae7c524c606590bb41ae2f635536c63791abe327d7f6abed0ba", + "tinysecurity-module-0.19.0-ubuntu-24.04-x86_64.tar.gz", + "a52f41593935b71b644753776bca041fded2baf2fd9ad6aa0d8dc8fbb478acf8", ), ( "windows-11-arm64", - "tinysecurity-module-0.18.4-windows-11-arm64.zip", - "825d2fde75cea1ffb11ff88cc037d1ec9428d784b2d5041f5eec828179f92020", + "tinysecurity-module-0.19.0-windows-11-arm64.zip", + "d1431618ae6aecd442887cea946c21de5f6ac494eb727e5d2edfb2be8d9873bb", ), ( "windows-2022-x86_64", - "tinysecurity-module-0.18.4-windows-2022-x86_64.zip", - "8aa5719147a32209f14f9ad9fd4300e9c114a56dfe31d8f59d019b7540b0f111", + "tinysecurity-module-0.19.0-windows-2022-x86_64.zip", + "7bbddf0b10da1abb68ce1d4f37b4ba716365a0633981c2e2a71096d10fba5a78", ), ( "windows-2025-x86_64", - "tinysecurity-module-0.18.4-windows-2025-x86_64.zip", - "fe1f64a199a820d5b58347eea41e29109096b62d81d00e0ed5df083a6fd5005a", + "tinysecurity-module-0.19.0-windows-2025-x86_64.zip", + "d2edf257fab30fea9e463b2a4c76dae7358714c8104bfca4658daa4c7adb5021", ), ]; published.sort_unstable(); diff --git a/crates/openhuman-core/src/modules/security/client.rs b/crates/openhuman-core/src/modules/security/client.rs index a12d81119d7..2aecb9af0e0 100644 --- a/crates/openhuman-core/src/modules/security/client.rs +++ b/crates/openhuman-core/src/modules/security/client.rs @@ -4,12 +4,12 @@ use serde::{de::DeserializeOwned, Serialize}; use tinysecurity_bus::{ BudgetDecision2, BudgetRequest2, CheckRequest, CheckResponse, CommandDecision, CommandPolicy, CommandPolicyId, CommandRequest, CredentialRootsRequest2, CredentialRootsResponse2, Decision, - HostActionClassRequest2, HostActionClassResponse2, KeyringRequest2, KeyringResponse2, - PathBatchRequest2, PathBatchResponse2, PathPolicy, PathPolicyId, PathValidationRequest, - PathValidationResult, PolicyInfo, PrivacyCheckRequest2, PrivacyCheckResponse2, ProtectedFloor2, - ProtectedPathRequest2, ProtectedPathResponse2, RedactMode, RedactRequest, RedactResponse, - RedactWithRequest, ScanPromptScoredRequest2, ScanPromptScoredResponse2, ScanResponse, - ScanToolDefinitionRequest, Secret, + HostActionClassRequest2, HostActionClassResponse2, PathBatchRequest2, PathBatchResponse2, + PathPolicy, PathPolicyId, PathValidationRequest, PathValidationResult, PolicyInfo, + PrivacyCheckRequest2, PrivacyCheckResponse2, ProtectedFloor2, ProtectedPathRequest2, + ProtectedPathResponse2, RedactMode, RedactRequest, RedactResponse, RedactWithRequest, + ScanPromptScoredRequest2, ScanPromptScoredResponse2, ScanResponse, ScanToolDefinitionRequest, + Secret, }; use super::MODULE_ID; @@ -550,21 +550,6 @@ impl Client { .map_err(|error| SecurityError::Unavailable(error.to_string())) } - /// Perform one OS keyring operation through TinySecurity. The module - /// obtains fresh, operation-scoped consent before touching the backend. - pub async fn keyring_access2( - &self, - request: KeyringRequest2, - ) -> Result { - self.object - .call_confidential( - tinysecurity_bus::names::methods::KEYRING_ACCESS2, - (request,), - ) - .await - .map_err(|error| SecurityError::Unavailable(error.to_string())) - } - /// Persist intent for one routine config cipher operation. pub(crate) async fn evaluate_secret_cipher2( &self, @@ -740,6 +725,9 @@ impl Client { } } +#[path = "client_keyring.rs"] +mod keyring; + #[cfg(test)] #[path = "client_tests.rs"] mod tests; diff --git a/crates/openhuman-core/src/modules/security/client_keyring.rs b/crates/openhuman-core/src/modules/security/client_keyring.rs new file mode 100644 index 00000000000..fdf067eeae6 --- /dev/null +++ b/crates/openhuman-core/src/modules/security/client_keyring.rs @@ -0,0 +1,41 @@ +//! OS keyring operations through TinySecurity, which wait on the user. + +use super::super::policy::KEYRING_CONSENT_TIMEOUT_MS; +use super::{Client, SecurityError, SecurityProxy}; +use tinysecurity_bus::{KeyringRequest2, KeyringResponse2}; + +/// The host's deadline for one keyring operation: the module's consent +/// deadline plus the keyring store itself. +const KEYRING_ACCESS_DEADLINE: std::time::Duration = + std::time::Duration::from_millis(KEYRING_CONSENT_TIMEOUT_MS as u64 + 15_000); +const _: () = assert!(KEYRING_ACCESS_DEADLINE.as_millis() > KEYRING_CONSENT_TIMEOUT_MS as u128); + +impl SecurityProxy { + /// The same binding with `timeout` as its call deadline. The test-only + /// module client keeps its own. + fn with_timeout(&self, timeout: std::time::Duration) -> Self { + match self { + Self::Callback(proxy) => Self::Callback(proxy.clone().with_timeout(timeout)), + Self::Module(proxy) => Self::Module(proxy.clone()), + } + } +} + +impl Client { + /// Perform one OS keyring operation through TinySecurity. The module + /// obtains fresh, operation-scoped consent before touching the backend, + /// so the call waits as long as the user may take to answer the prompt. + pub async fn keyring_access2( + &self, + request: KeyringRequest2, + ) -> Result { + self.object + .with_timeout(KEYRING_ACCESS_DEADLINE) + .call_confidential( + tinysecurity_bus::names::methods::KEYRING_ACCESS2, + (request,), + ) + .await + .map_err(|error| SecurityError::Unavailable(error.to_string())) + } +} diff --git a/crates/openhuman-core/src/modules/security/host_callbacks.rs b/crates/openhuman-core/src/modules/security/host_callbacks.rs index 18d7048ff4b..111289525b4 100644 --- a/crates/openhuman-core/src/modules/security/host_callbacks.rs +++ b/crates/openhuman-core/src/modules/security/host_callbacks.rs @@ -158,6 +158,24 @@ impl SecurityCallbackState { } } +/// The secret key path TinySecurity serves, if it is admitted: its live +/// owner, or once released the admitting scope, the only durable scope that +/// may take it over ([`claim_scope`]). +pub(in crate::modules) async fn admitted_key_path() -> Option { + let admitted = SECURITY_CALLBACK_LOADS + .lock() + .await + .get(super::MODULE_ID) + .map(|state| state.key_path.clone())?; + Some( + ownership() + .owners + .get(super::MODULE_ID) + .cloned() + .unwrap_or(admitted), + ) +} + pub(in crate::modules) async fn binding() -> Option> { SECURITY_CALLBACK_LOADS .lock() diff --git a/crates/openhuman-core/src/modules/security/policy.rs b/crates/openhuman-core/src/modules/security/policy.rs index 2d3faffbc4f..54ce59ac1dc 100644 --- a/crates/openhuman-core/src/modules/security/policy.rs +++ b/crates/openhuman-core/src/modules/security/policy.rs @@ -81,7 +81,7 @@ pub fn module_config(config: &Config) -> tinysecurity_bus::ModuleConfig { keyring: Some(tinysecurity_bus::KeyringConfig2 { service: "openhuman".into(), backend: tinysecurity_bus::KeyringBackend2::Os, - consent_timeout_ms: 120_000, + consent_timeout_ms: KEYRING_CONSENT_TIMEOUT_MS, }), pairing: None, }), @@ -89,6 +89,14 @@ pub fn module_config(config: &Config) -> tinysecurity_bus::ModuleConfig { } } +/// TinySecurity's deadline for the host's answer to one keyring prompt. It +/// outlasts the host's own wait, so an unanswered prompt comes back as +/// pending from the host rather than racing the module's timer. +pub(crate) const KEYRING_CONSENT_TIMEOUT_MS: u32 = + crate::security::keyring_consent::operation_approval::MAX_CONSENT_WAIT_MS + 5_000; +// TinySecurity accepts up to 300 s. +const _: () = assert!(KEYRING_CONSENT_TIMEOUT_MS <= 300_000); + const AUDIT_CALLBACK_TIMEOUT_MS: u32 = 20_000; /// Init-time subject is deliberately separate from every registered user diff --git a/crates/openhuman-core/src/modules/security/policy_tests.rs b/crates/openhuman-core/src/modules/security/policy_tests.rs index e7e2eac920d..8db711e4913 100644 --- a/crates/openhuman-core/src/modules/security/policy_tests.rs +++ b/crates/openhuman-core/src/modules/security/policy_tests.rs @@ -74,7 +74,7 @@ fn first_load_and_reinit_share_one_policy_translator() { .expect("profile keyring backend is configured"); assert_eq!(keyring.service, "openhuman"); assert_eq!(keyring.backend, tinysecurity_bus::KeyringBackend2::Os); - assert_eq!(keyring.consent_timeout_ms, 120_000); + assert_eq!(keyring.consent_timeout_ms, KEYRING_CONSENT_TIMEOUT_MS); } #[test] @@ -187,13 +187,11 @@ fn enabled_policy_rejects_commands_the_module_cannot_represent() { #[test] fn module_contract_requires_the_exact_host_wire_version() { - assert!(supports_contract((1, 35))); + assert!(supports_contract((2, 0))); + assert!(!supports_contract((1, 35))); + assert!(!supports_contract((2, 1))); + assert!(!supports_contract((3, 0))); assert!(!supports_contract((1, 34))); - assert!(!supports_contract((1, 36))); - assert!(!supports_contract((1, 28))); - assert!(!supports_contract((1, 29))); - assert!(!supports_contract((1, 32))); - assert!(!supports_contract((2, 0))); assert!(!supports_contract((1, 27))); } diff --git a/crates/openhuman-core/src/security/approval/native/engine.rs b/crates/openhuman-core/src/security/approval/native/engine.rs index 206e5fd31ec..932688d7c03 100644 --- a/crates/openhuman-core/src/security/approval/native/engine.rs +++ b/crates/openhuman-core/src/security/approval/native/engine.rs @@ -110,7 +110,7 @@ fn module_outcome(outcome: ExecutionOutcome) -> ModuleOutcome { match outcome { ExecutionOutcome::Success => ModuleOutcome::Succeeded, ExecutionOutcome::Failure => ModuleOutcome::Failed, - ExecutionOutcome::Aborted => ModuleOutcome::Cancelled, + ExecutionOutcome::Aborted => ModuleOutcome::Abandoned, } } @@ -308,3 +308,7 @@ impl NativeEngine { #[path = "engine_impl.rs"] mod engine_impl; + +#[cfg(test)] +#[path = "engine_outcome_tests.rs"] +mod outcome_tests; diff --git a/crates/openhuman-core/src/security/approval/native/engine_outcome_tests.rs b/crates/openhuman-core/src/security/approval/native/engine_outcome_tests.rs new file mode 100644 index 00000000000..776e89a12cc --- /dev/null +++ b/crates/openhuman-core/src/security/approval/native/engine_outcome_tests.rs @@ -0,0 +1,19 @@ +use super::*; + +#[test] +fn an_aborted_execution_is_recorded_as_abandoned() { + assert_eq!( + module_outcome(ExecutionOutcome::Success), + ModuleOutcome::Succeeded + ); + assert_eq!( + module_outcome(ExecutionOutcome::Failure), + ModuleOutcome::Failed + ); + // Nothing the host calls aborted proves the tool never ran, so its effects + // are unknown: abandoned, never cancelled. + assert_eq!( + module_outcome(ExecutionOutcome::Aborted), + ModuleOutcome::Abandoned + ); +} diff --git a/crates/openhuman-core/src/security/approval/types.rs b/crates/openhuman-core/src/security/approval/types.rs index 78c39ce274f..e6248fa8876 100644 --- a/crates/openhuman-core/src/security/approval/types.rs +++ b/crates/openhuman-core/src/security/approval/types.rs @@ -254,8 +254,8 @@ pub enum ExecutionOutcome { Success, /// Tool ran and returned an error [`ToolResult`] (or panicked). Failure, - /// Tool did not run because the runtime aborted (timeout, - /// cancellation, supervisor shutdown). + /// Execution ended without reporting a result (timeout, cancellation, + /// supervisor shutdown); the tool may already have had side effects. Aborted, } diff --git a/crates/openhuman-core/src/security/keyring_consent/mod.rs b/crates/openhuman-core/src/security/keyring_consent/mod.rs index d0c9c2ab567..e644c0fdda6 100644 --- a/crates/openhuman-core/src/security/keyring_consent/mod.rs +++ b/crates/openhuman-core/src/security/keyring_consent/mod.rs @@ -5,6 +5,8 @@ pub(crate) mod operation_approval; pub mod ops; pub mod policy; mod schemas; +#[cfg(any(test, feature = "e2e-test-support", feature = "test-keyring-consent"))] +mod test_responder; pub mod types; pub(crate) use schemas::all_keyring_consent_controller_entries; diff --git a/crates/openhuman-core/src/security/keyring_consent/operation_approval.rs b/crates/openhuman-core/src/security/keyring_consent/operation_approval.rs index 062fa35ddbc..4063cc8b03e 100644 --- a/crates/openhuman-core/src/security/keyring_consent/operation_approval.rs +++ b/crates/openhuman-core/src/security/keyring_consent/operation_approval.rs @@ -5,6 +5,11 @@ use std::sync::{Mutex, OnceLock}; use tokio::sync::oneshot; pub(crate) const MAX_PENDING_APPROVALS: usize = 64; +/// The longest the host waits for the user to answer one keyring prompt. +pub(crate) const MAX_CONSENT_WAIT_MS: u32 = 120_000; +/// How long a decided outcome waits for its caller. The caller takes it as +/// soon as the module answers; one still here is from a caller that has gone. +const OUTCOME_TTL_MS: u64 = 30_000; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum OperationOutcome { @@ -24,7 +29,10 @@ pub(crate) struct ApprovalPrompt { pub(crate) struct PendingConsentRegistry { pending: HashMap>, reserved_call_ids: HashSet, - outcomes: HashMap, + outcomes: HashMap, + /// The prompt each pending request shows, for a renderer that cannot + /// receive the approval event (no socket before sign-in). + prompts: HashMap, } static PENDING: OnceLock> = OnceLock::new(); @@ -41,6 +49,9 @@ impl PendingConsentRegistry { call_id: &str, timeout: std::time::Duration, ) -> Result<(ApprovalPrompt, oneshot::Receiver), &'static str> { + let now = now_ms(); + self.outcomes + .retain(|_, (_, decided_at)| now.saturating_sub(*decided_at) < OUTCOME_TTL_MS); if self.reserved_call_ids.len() + self.outcomes.len() >= MAX_PENDING_APPROVALS { return Err("too many pending keyring consent requests"); } @@ -57,7 +68,7 @@ impl PendingConsentRegistry { request_id, access: access.to_owned(), name: name.to_owned(), - expires_at_ms: now_ms() + expires_at_ms: now .saturating_add(timeout.as_millis().try_into().unwrap_or(u64::MAX)), }, receiver, @@ -65,6 +76,7 @@ impl PendingConsentRegistry { } pub(crate) fn resolve(&mut self, request_id: &str, approved: bool) -> bool { + self.prompts.remove(request_id); self.pending .remove(request_id) .is_some_and(|sender| sender.send(approved).is_ok()) @@ -72,19 +84,39 @@ impl PendingConsentRegistry { pub(crate) fn cancel(&mut self, request_id: &str) { self.pending.remove(request_id); + self.prompts.remove(request_id); + } + + /// The prompts still waiting for a decision at `now_ms`. + pub(crate) fn pending_prompts( + &self, + now_ms: u64, + ) -> Vec { + let mut prompts: Vec<_> = self + .prompts + .values() + .filter(|prompt| { + prompt.expires_at_ms > now_ms && self.pending.contains_key(&prompt.request_id) + }) + .cloned() + .collect(); + prompts.sort_by_key(|prompt| prompt.expires_at_ms); + prompts } fn finish(&mut self, request_id: &str, call_id: &str, outcome: Option) { self.pending.remove(request_id); + self.prompts.remove(request_id); if self.reserved_call_ids.remove(call_id) { if let Some(outcome) = outcome { - self.outcomes.insert(call_id.to_owned(), outcome); + self.outcomes + .insert(call_id.to_owned(), (outcome, now_ms())); } } } fn take_operation_outcome(&mut self, call_id: &str) -> Option { - self.outcomes.remove(call_id) + self.outcomes.remove(call_id).map(|(outcome, _)| outcome) } } @@ -101,39 +133,66 @@ pub(crate) async fn request_approval( KeyringAccess2::Write => "write", KeyringAccess2::Delete => "delete", }; - let timeout = std::time::Duration::from_millis(u64::from(request.timeout_ms.min(120_000))); + let timeout = + std::time::Duration::from_millis(u64::from(request.timeout_ms.min(MAX_CONSENT_WAIT_MS))); let call_id = request.caller.call_id; - let (prompt, waiter) = pending() - .lock() - .ok()? - .register(access, &request.name, &call_id, timeout) - .ok()?; - crate::core::bus::BUS.publish( - crate::core::events::DomainEvent::KeyringAccessApprovalRequested( - crate::core::events::KeyringAccessApprovalRequest { - request_id: prompt.request_id.clone(), - caller_agent: request.caller.agent.clone(), - origin: format!("{:?}", request.caller.origin), - purpose: request.purpose, - access: prompt.access, - name: prompt.name, - expires_at_ms: prompt.expires_at_ms, - }, - ), - ); + let (prompt, waiter, shown) = { + let mut registry = pending().lock().ok()?; + let (prompt, waiter) = registry + .register(access, &request.name, &call_id, timeout) + .ok()?; + let shown = crate::core::events::KeyringAccessApprovalRequest { + request_id: prompt.request_id.clone(), + caller_agent: request.caller.agent.clone(), + origin: format!("{:?}", request.caller.origin), + purpose: request.purpose, + access: prompt.access.clone(), + name: prompt.name.clone(), + expires_at_ms: prompt.expires_at_ms, + }; + registry + .prompts + .insert(prompt.request_id.clone(), shown.clone()); + (prompt, waiter, shown) + }; + let mut reservation = Reservation { + request_id: prompt.request_id.clone(), + call_id, + outcome: None, + }; + crate::core::bus::BUS + .publish(crate::core::events::DomainEvent::KeyringAccessApprovalRequested(shown)); + #[cfg(any(test, feature = "e2e-test-support", feature = "test-keyring-consent"))] + if let Some(approved) = super::test_responder::decision(&request.caller.agent) { + resolve_approval(&prompt.request_id, approved); + } let decision = await_decision(pending(), &prompt.request_id, waiter, timeout).await; - let outcome = match decision { + reservation.outcome = match decision { Some(false) => Some(OperationOutcome::Denied), None => Some(OperationOutcome::Pending), Some(true) => None, }; - if let Ok(mut registry) = pending().lock() { - registry.finish(&prompt.request_id, &call_id, outcome); - } + drop(reservation); decision } +/// One registered operation, finished when dropped: with its outcome once +/// decided, or with none if the waiting caller goes away first. +struct Reservation { + request_id: String, + call_id: String, + outcome: Option, +} + +impl Drop for Reservation { + fn drop(&mut self) { + if let Ok(mut registry) = pending().lock() { + registry.finish(&self.request_id, &self.call_id, self.outcome); + } + } +} + /// Consume the decision for one host-generated keyring operation id. pub(crate) fn take_operation_outcome(call_id: &str) -> Option { pending() @@ -159,6 +218,15 @@ async fn await_decision( } } +/// The keyring operations waiting for a decision. Display-safe metadata only, +/// the same the approval event carries; never a secret value. +pub(crate) fn pending_requests() -> Vec { + pending() + .lock() + .map(|registry| registry.pending_prompts(now_ms())) + .unwrap_or_default() +} + /// Resolve one currently pending request. Each id can be consumed once. pub(crate) fn resolve_approval(request_id: &str, approved: bool) -> bool { pending() diff --git a/crates/openhuman-core/src/security/keyring_consent/operation_approval_tests.rs b/crates/openhuman-core/src/security/keyring_consent/operation_approval_tests.rs index f9a92188de1..ba1c8c26b72 100644 --- a/crates/openhuman-core/src/security/keyring_consent/operation_approval_tests.rs +++ b/crates/openhuman-core/src/security/keyring_consent/operation_approval_tests.rs @@ -180,3 +180,152 @@ fn unconsumed_denials_reserve_capacity_before_new_requests_register() { ) .is_ok()); } + +fn shown(prompt: &ApprovalPrompt) -> crate::core::events::KeyringAccessApprovalRequest { + crate::core::events::KeyringAccessApprovalRequest { + request_id: prompt.request_id.clone(), + caller_agent: "openhuman.credentials".into(), + origin: "LocalOperator".into(), + purpose: "OpenHuman auth profile credential access".into(), + access: prompt.access.clone(), + name: prompt.name.clone(), + expires_at_ms: prompt.expires_at_ms, + } +} + +#[test] +fn a_pending_prompt_is_listed_until_it_is_decided_or_expires() { + let mut registry = PendingConsentRegistry::default(); + let timeout = std::time::Duration::from_secs(120); + let (decided, _decided_waiter) = registry + .register("write", "app-session:default", "call-decided", timeout) + .unwrap(); + let (open, _open_waiter) = registry + .register("read", "auth:openai:default", "call-open", timeout) + .unwrap(); + for prompt in [&decided, &open] { + registry + .prompts + .insert(prompt.request_id.clone(), shown(prompt)); + } + + let listed = registry.pending_prompts(now_ms()); + assert_eq!(listed.len(), 2); + assert!(listed + .iter() + .all(|prompt| prompt.caller_agent == "openhuman.credentials")); + + assert!(registry.resolve(&decided.request_id, true)); + let listed = registry.pending_prompts(now_ms()); + assert_eq!( + listed + .iter() + .map(|prompt| prompt.request_id.as_str()) + .collect::>(), + [open.request_id.as_str()] + ); + + assert!(registry.pending_prompts(open.expires_at_ms).is_empty()); + registry.cancel(&open.request_id); + assert!(registry.pending_prompts(now_ms()).is_empty()); +} + +fn consent_request(call_id: &str, timeout_ms: u32) -> tinysecurity_bus::KeyringConsentRequest2 { + tinysecurity_bus::KeyringConsentRequest2 { + caller: tinysecurity_bus::CallerContext { + // Not the credential store, which test builds answer. + agent: "registry-test".into(), + call_id: call_id.into(), + ..Default::default() + }, + purpose: "OpenHuman auth profile credential access".into(), + access: tinysecurity_bus::KeyringAccess2::Write, + name: "user-1:auth:app-session:default".into(), + timeout_ms, + } +} + +#[tokio::test] +async fn unanswered_prompts_in_a_row_never_exhaust_the_capacity() { + // The keychain takes each outcome once the module answers; more + // unanswered prompts than the capacity must all still register. + for index in 0..=MAX_PENDING_APPROVALS { + let call_id = format!("unanswered-in-a-row-{index}"); + assert_eq!(request_approval(consent_request(&call_id, 1)).await, None); + assert_eq!( + take_operation_outcome(&call_id), + Some(OperationOutcome::Pending), + "prompt {index} registered and timed out" + ); + } +} + +#[test] +fn an_outcome_no_caller_took_frees_its_slot_once_stale() { + let mut registry = PendingConsentRegistry::default(); + for index in 0..MAX_PENDING_APPROVALS { + let call_id = format!("abandoned-{index}"); + let (prompt, _waiter) = registry + .register( + "write", + "auth:profile", + &call_id, + std::time::Duration::from_secs(120), + ) + .unwrap(); + registry.finish(&prompt.request_id, &call_id, Some(OperationOutcome::Denied)); + } + for (_, decided_at) in registry.outcomes.values_mut() { + *decided_at = decided_at.saturating_sub(OUTCOME_TTL_MS); + } + + assert!(registry + .register( + "write", + "auth:next", + "call:next", + std::time::Duration::from_secs(120) + ) + .is_ok()); + assert!(registry.outcomes.is_empty()); +} + +#[tokio::test] +async fn a_caller_that_goes_away_releases_its_reservation() { + let call_id = "caller-goes-away"; + let waiting = tokio::spawn(request_approval(consent_request(call_id, 60_000))); + let reserved = || { + pending() + .lock() + .unwrap() + .reserved_call_ids + .contains(call_id) + }; + for _ in 0..200 { + if reserved() { + break; + } + tokio::time::sleep(std::time::Duration::from_millis(5)).await; + } + assert!(reserved(), "the prompt registered"); + + waiting.abort(); + assert!(waiting.await.unwrap_err().is_cancelled()); + assert!(!reserved()); + assert_eq!(take_operation_outcome(call_id), None); +} + +#[tokio::test] +async fn a_test_build_answers_the_credential_stores_prompts() { + let mut request = consent_request("credential-store-prompt", 5_000); + request.caller.agent = "openhuman.credentials".into(); + // Unit tests approve unless the lane says otherwise. + let expected = match std::env::var("OPENHUMAN_TEST_KEYRING_CONSENT").as_deref() { + Ok("deny") => Some(false), + Ok("approve") | Err(_) => Some(true), + Ok(_) => None, + }; + if expected.is_some() { + assert_eq!(request_approval(request).await, expected); + } +} diff --git a/crates/openhuman-core/src/security/keyring_consent/schemas.rs b/crates/openhuman-core/src/security/keyring_consent/schemas.rs index ca2df1280ad..b57b4163202 100644 --- a/crates/openhuman-core/src/security/keyring_consent/schemas.rs +++ b/crates/openhuman-core/src/security/keyring_consent/schemas.rs @@ -14,6 +14,7 @@ pub fn all_keyring_consent_controller_schemas() -> Vec { keyring_consent_schema("decide"), keyring_consent_schema("retry_probe"), keyring_consent_schema("respond_operation"), + keyring_consent_schema("list_pending_operations"), ] } @@ -35,6 +36,10 @@ pub fn all_keyring_consent_registered_controllers() -> Vec schema: keyring_consent_schema("respond_operation"), handler: handle_respond_operation, }, + RegisteredController { + schema: keyring_consent_schema("list_pending_operations"), + handler: handle_list_pending_operations, + }, ] } @@ -44,6 +49,7 @@ pub(crate) fn all_keyring_consent_controller_entries() -> Vec { ControllerEntry::bound(decide_controller()), ControllerEntry::bound(retry_probe_controller()), ControllerEntry::bound(respond_operation_controller()), + ControllerEntry::bound(list_pending_operations_controller()), ] } @@ -121,6 +127,18 @@ fn keyring_consent_schema(function: &str) -> ControllerSchema { required: true, }], }, + "list_pending_operations" => ControllerSchema { + namespace: "keyring_consent", + function: "list_pending_operations", + description: "List the TinySecurity keyring operations waiting for approval, for a renderer that has no socket yet (before sign-in).", + inputs: vec![], + outputs: vec![FieldSchema { + name: "result", + ty: TypeSchema::Json, + comment: "Array of pending operations, oldest expiry first, each shaped like the keyring access approval event: { request_id, caller_agent, origin, purpose, access, name, expires_at_ms }. Never includes a secret value.", + required: true, + }], + }, _ => ControllerSchema { namespace: "keyring_consent", function: "unknown", @@ -152,6 +170,13 @@ fn handle_respond_operation(ctx: DispatchCtx, params: Map) -> Con respond_operation_controller().invoke(ctx, params) } +fn handle_list_pending_operations( + ctx: DispatchCtx, + params: Map, +) -> ControllerFuture { + list_pending_operations_controller().invoke(ctx, params) +} + fn status_controller() -> BoundRegisteredController { BoundRegisteredController::typed(keyring_consent_schema("status"), parse_status, run_status) } @@ -176,6 +201,14 @@ fn respond_operation_controller() -> BoundRegisteredController { ) } +fn list_pending_operations_controller() -> BoundRegisteredController { + BoundRegisteredController::typed( + keyring_consent_schema("list_pending_operations"), + parse_status, + run_list_pending_operations, + ) +} + fn parse_status(_params: Map) -> Result<(), String> { Ok(()) } @@ -239,6 +272,13 @@ fn run_respond_operation( }) } +fn run_list_pending_operations(_ctx: DispatchCtx, (): ()) -> ControllerFuture { + Box::pin(async move { + serde_json::to_value(super::operation_approval::pending_requests()) + .map_err(|error| error.to_string()) + }) +} + #[cfg(test)] #[path = "schemas_tests.rs"] mod tests; diff --git a/crates/openhuman-core/src/security/keyring_consent/schemas_tests.rs b/crates/openhuman-core/src/security/keyring_consent/schemas_tests.rs index 23716509fe8..18da6a064f4 100644 --- a/crates/openhuman-core/src/security/keyring_consent/schemas_tests.rs +++ b/crates/openhuman-core/src/security/keyring_consent/schemas_tests.rs @@ -37,6 +37,12 @@ pub(crate) fn parameter_contracts() -> Vec { optional: &[], examples: vec![json!({ "request_id": "approval-1", "approved": true })], }, + ControllerParamContract { + method: "keyring_consent.list_pending_operations", + required: &[], + optional: &[], + examples: vec![json!({})], + }, ] } diff --git a/crates/openhuman-core/src/security/keyring_consent/test_responder.rs b/crates/openhuman-core/src/security/keyring_consent/test_responder.rs new file mode 100644 index 00000000000..d9a194ead2c --- /dev/null +++ b/crates/openhuman-core/src/security/keyring_consent/test_responder.rs @@ -0,0 +1,29 @@ +//! Answers the credential store's keyring prompts in test builds. +//! +//! Every keyring operation TinySecurity performs waits for the user to +//! approve it. Tests that save credentials have no user, so each save would +//! wait out the whole consent window. This module is compiled only into test +//! builds, `e2e-test-support` builds and the integration tests' +//! `test-keyring-consent` builds, never a product build. +//! +//! `OPENHUMAN_TEST_KEYRING_CONSENT` selects the answer: `approve`, `deny`, or +//! `off` to leave prompts unanswered. Unit tests approve by default; the +//! other builds answer only when the variable says so. Only the +//! credential store's prompts are answered, so a test of an unanswered +//! prompt raises it under another caller. + +/// The caller TinySecurity reports for the credential store's keyring use. +const CREDENTIAL_STORE: &str = "openhuman.credentials"; + +/// The answer for a prompt raised by `caller_agent`, if this build answers it. +pub(super) fn decision(caller_agent: &str) -> Option { + if caller_agent != CREDENTIAL_STORE { + return None; + } + match std::env::var("OPENHUMAN_TEST_KEYRING_CONSENT").as_deref() { + Ok("approve") => Some(true), + Ok("deny") => Some(false), + Ok(_) => None, + Err(_) => cfg!(test).then_some(true), + } +} diff --git a/crates/openhuman-rpc/src/server/auth.rs b/crates/openhuman-rpc/src/server/auth.rs index fa14388c259..7a0e414a5f9 100644 --- a/crates/openhuman-rpc/src/server/auth.rs +++ b/crates/openhuman-rpc/src/server/auth.rs @@ -66,6 +66,10 @@ const PREFLIGHT_RPC_METHODS: &[&str] = &[ "openhuman.update_version", "openhuman.approval_list_pending", "openhuman.approval_decide", + // Reading a keyring-held session token at startup asks the user to + // approve the read; the socket that would carry the prompt is not up yet. + "openhuman.keyring_consent_list_pending_operations", + "openhuman.keyring_consent_respond_operation", ]; pub(crate) fn preflight_rpc_method_allowed(method: &str) -> bool { diff --git a/crates/openhuman-rpc/src/server/auth_tests.rs b/crates/openhuman-rpc/src/server/auth_tests.rs index 8714d17908e..1bea7de8161 100644 --- a/crates/openhuman-rpc/src/server/auth_tests.rs +++ b/crates/openhuman-rpc/src/server/auth_tests.rs @@ -106,6 +106,15 @@ fn startup_preflight_allows_only_health_and_approval_rpc_methods() { assert!(super::preflight_rpc_method_allowed( "openhuman.approval_decide" )); + assert!(super::preflight_rpc_method_allowed( + "openhuman.keyring_consent_list_pending_operations" + )); + assert!(super::preflight_rpc_method_allowed( + "openhuman.keyring_consent_respond_operation" + )); + assert!(!super::preflight_rpc_method_allowed( + "openhuman.keyring_consent_status" + )); assert!(!super::preflight_rpc_method_allowed("core.config")); assert!(!super::preflight_rpc_method_allowed("openhuman.config_get")); assert!(!super::preflight_rpc_method_allowed( diff --git a/crates/openhuman-rpc/src/server/serve.rs b/crates/openhuman-rpc/src/server/serve.rs index de99ccb5f67..a964dfb5f64 100644 --- a/crates/openhuman-rpc/src/server/serve.rs +++ b/crates/openhuman-rpc/src/server/serve.rs @@ -262,6 +262,7 @@ pub async fn serve( Err(error) } Ok(Ok(())) => { + log::debug!("[core] secret preflight complete; starting services"); let startup_runtime = Arc::clone(&runtime); let mut service_start = tokio::spawn(async move { startup_runtime.start_services().await }); @@ -278,6 +279,7 @@ pub async fn serve( // config have been refreshed, then expose the full // router. A concurrent shutdown must still stop // the listener while these services are starting. + log::debug!("[core] services started; opening the full router"); gate.open(); await_http_server(&mut server, server_shutdown.as_ref()).await } diff --git a/scripts/__tests__/feature-forwarding.test.mjs b/scripts/__tests__/feature-forwarding.test.mjs index 833eeb42be3..dac16bbcaea 100644 --- a/scripts/__tests__/feature-forwarding.test.mjs +++ b/scripts/__tests__/feature-forwarding.test.mjs @@ -11,6 +11,7 @@ import { CHAIN_LOCAL_GATES, checkLinkedModulesIsolation, checkProductForwarding, + checkTestOnlyGatesIsolation, diffChainForwarding, diffForwarding, formatChainReport, @@ -968,3 +969,42 @@ test('deliberate violations of linked-modules isolation are each reported', () = [] ); }); + +// ── test-only gate isolation ─────────────────────────────────────────────── + +test('the real manifests keep the test-only gates out of every shipped build', () => { + const read = rel => readFileSync(join(REPO_ROOT, rel), 'utf8'); + const table = rel => parseFeatureTable(read(rel)); + assert.deepEqual( + checkTestOnlyGatesIsolation({ + productFeatures: parseProductFeatures(read('scripts/ci/product-features.txt')), + featureTables: { + openhuman: table('crates/openhuman-core/Cargo.toml'), + 'openhuman-embed': table('crates/openhuman-embed/Cargo.toml'), + 'openhuman-tinyhumans': table('crates/openhuman-tinyhumans/Cargo.toml'), + 'openhuman-rpc': table('crates/openhuman-rpc/Cargo.toml'), + 'openhuman-cli': table('crates/openhuman-cli/Cargo.toml'), + 'openhuman-tui': table('crates/openhuman-tui/Cargo.toml'), + 'openhuman-app': table('crates/openhuman-app/Cargo.toml'), + }, + }), + [] + ); +}); + +test('a test-only gate in the product set or reached from a default is reported', () => { + const clean = { + productFeatures: ['voice'], + featureTables: { core: new Map([['default', ['voice']], ['voice', []], ['e2e-test-support', []]]) }, + }; + assert.deepEqual(checkTestOnlyGatesIsolation(clean), []); + assert.deepEqual( + checkTestOnlyGatesIsolation({ ...clean, productFeatures: ['voice', 'test-keyring-consent'] }), + ['test-keyring-consent is listed in the product feature set'] + ); + // Reached through another gate, not named in `default` itself. + const transitive = new Map([['default', ['voice']], ['voice', ['e2e-test-support']], ['e2e-test-support', []]]); + assert.deepEqual(checkTestOnlyGatesIsolation({ ...clean, featureTables: { core: transitive } }), [ + "core's default features enable e2e-test-support", + ]); +}); diff --git a/scripts/ci/check-feature-forwarding.mjs b/scripts/ci/check-feature-forwarding.mjs index 12a9da526db..749524ade65 100644 --- a/scripts/ci/check-feature-forwarding.mjs +++ b/scripts/ci/check-feature-forwarding.mjs @@ -32,6 +32,8 @@ import { CHAIN_GATES_NOT_FORWARDED, CHAIN_LOCAL_GATES, checkLinkedModulesIsolation, + checkTestOnlyGatesIsolation, + TEST_ONLY_GATES, LINKED_MODULES_FEATURE, checkProductForwarding, diffChainForwarding, @@ -239,4 +241,29 @@ if (linkedViolations.length === 0) { for (const violation of linkedViolations) console.log(` - ${violation}`); } -process.exit(product.ok && defaults.ok && chainOk && linkedViolations.length === 0 ? 0 : 1); +// The test-only gates must stay out of every shipped build. +const testOnlyViolations = checkTestOnlyGatesIsolation({ + productFeatures, + featureTables: { + openhuman: parseFeatureTable(coreToml), + 'openhuman-embed': embedFeatures, + 'openhuman-tinyhumans': tinyhumansFeatures, + 'openhuman-rpc': rpcFeatures, + 'openhuman-cli': cliFeatures, + 'openhuman-tui': tuiFeatures, + 'openhuman-app': parseFeatureTable(shellToml), + }, +}); +console.log(''); +if (testOnlyViolations.length === 0) { + console.log(`${TEST_ONLY_GATES.join(', ')} isolation: OK (not product gates, not reached from any default).`); +} else { + console.log(`${TEST_ONLY_GATES.join(', ')} isolation: FAIL`); + for (const violation of testOnlyViolations) console.log(` - ${violation}`); +} + +process.exit( + product.ok && defaults.ok && chainOk && linkedViolations.length === 0 && testOnlyViolations.length === 0 + ? 0 + : 1 +); diff --git a/scripts/ci/ignored-test-baseline.json b/scripts/ci/ignored-test-baseline.json index 6483a51ae11..5750b1984d0 100644 --- a/scripts/ci/ignored-test-baseline.json +++ b/scripts/ci/ignored-test-baseline.json @@ -7,5 +7,5 @@ "openhuman-rpc": 0, "openhuman-tinyhumans": 0, "openhuman-tui": 0, - "tests": 22 + "tests": 24 } diff --git a/scripts/ci/rust-coverage.sh b/scripts/ci/rust-coverage.sh index 51163378fc1..263aa0ca945 100755 --- a/scripts/ci/rust-coverage.sh +++ b/scripts/ci/rust-coverage.sh @@ -271,6 +271,9 @@ if [ "${OH_COV_RUNNER:-cargo}" = "nextest" ]; then # schedule itself is pinned by a unit test that ignores this variable. export OPENHUMAN_MODEL_RETRY_BACKOFF_MS="${OPENHUMAN_MODEL_RETRY_BACKOFF_MS:-100}" fi +# Credential saves ask the user to approve each TinySecurity keyring operation; +# the test builds answer for them (keyring_consent/test_responder.rs). +export OPENHUMAN_TEST_KEYRING_CONSENT="${OPENHUMAN_TEST_KEYRING_CONSENT:-approve}" log "running complete instrumented Rust suite (runner: ${OH_COV_RUNNER:-cargo})" llvm_cov clean --workspace diff --git a/scripts/ci/security-native-fixture.sh b/scripts/ci/security-native-fixture.sh index 6c242e78336..744ee59aadb 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 b53eceb948bd8dedce2176af6f0ec7bb1bd74151)" -printf 'TinySecurity pin: %s\nPublished v0.18.4 source: %s\n' "$security_pin" "$release_source" +release_source="$(git -C vendor/tinysecurity rev-parse 17c12844c64fe6c561f6eacd4693dcae10623642)" +printf 'TinySecurity pin: %s\nPublished v0.19.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. @@ -122,3 +122,146 @@ bash scripts/ci-cancel-aware.sh cargo test --manifest-path Cargo.toml -p openhum --features "$core_features,security-module" \ a_different_secret_scope_is_refused_while_the_admitting_runtime_is_live \ -- --ignored --exact --nocapture + +# The shipped app loads TinySecurity as a pinned release, never from a local +# file. Present the same verified archive as a bundled module instead, with no +# local-file source, so later loads exercise the retained callback binding. +release_version="${archive#tinysecurity-module-}" +release_version="${release_version%%-"$host_key"*}" +bundled_dir="$OPENHUMAN_TEST_SECURITY_FIXTURE_DIR/bundled" +rm -rf "$bundled_dir" +# Lay a verified archive out as an installer bundle does +# (scripts/release/stage-modules.mjs): `///` holding the +# archive and its extracted module side by side. +stage_bundled() { + local id="$1" version="$2" source="$3" name="$4" + local dir="$bundled_dir/$id/$version/$host_key" + mkdir -p "$dir" + cp "$source" "$dir/$name" + if [[ "$name" == *.zip ]]; then + powershell.exe -NoProfile -Command \ + "Expand-Archive -LiteralPath '$(cygpath -w "$dir/$name")' -DestinationPath '$(cygpath -w "$dir")' -Force" + else + tar --no-same-owner -xzf "$dir/$name" -C "$dir" + fi +} +# Download a registry-pinned release, check its digest and stage it; leaves the +# staged directory in $module_dir. +fetch_bundled() { + local id="$1" url="$2" archive="$3" sha="$4" path version + path="$OPENHUMAN_TEST_SECURITY_FIXTURE_DIR/$archive" + curl --fail --location --silent --show-error --retry 4 --retry-delay 2 \ + "$url" --output "$path" + node - "$path" "$sha" <<'NODE' +const { createHash } = require("node:crypto"); +const { readFileSync } = require("node:fs"); + +const [file, expected] = process.argv.slice(2); +const actual = createHash("sha256").update(readFileSync(file)).digest("hex"); +if (actual !== expected) { + throw new Error(`module fixture digest mismatch: expected ${expected}, got ${actual}`); +} +NODE + version="${archive#"$id"-module-}" + version="${version#"$id"-}" + version="${version%%-"$host_key"*}" + stage_bundled "$id" "$version" "$path" "$archive" + module_dir="$bundled_dir/$id/$version/$host_key" +} +stage_bundled tinysecurity "$release_version" "$archive_path" "$archive" +env -u OPENHUMAN_MODULE_PATH OPENHUMAN_BUNDLED_MODULES="$bundled_dir" \ + bash scripts/ci-cancel-aware.sh cargo test --manifest-path Cargo.toml -p openhuman-cli \ + --test security_release_reuse_fixture --no-default-features \ + --features "$core_features,security-module" \ + native_fixture_serves_later_calls_after_a_release_admission \ + -- --ignored --exact --nocapture + +# The callback-bound modules load the same way in the shipped app: a pinned +# release with no local-file source. Stage each verified archive as a bundled +# module and check that it admits and reloads. +callback_modules="tinymcp,tinyeventqueues,tinychannels,tinycomputer" +loadable_modules="" +while IFS=$'\t' read -r module_id module_url module_archive module_sha; do + fetch_bundled "$module_id" "$module_url" "$module_archive" "$module_sha" + # A Linux module that links a system library this runner lacks (TinyComputer + # links libxdo and libasound) cannot be dlopened here at all; say so and + # check the rest rather than fail on the runner's package set. + if [[ "$(uname -s)" == Linux ]]; then + missing="$(find "$module_dir" -name '*.so' -exec ldd {} + | awk '/not found/ {print $1}' | sort -u | tr '\n' ' ')" + if [[ -n "$missing" ]]; then + echo "callback module fixture: skipping $module_id; this runner lacks: $missing" >&2 + continue + fi + fi + loadable_modules="${loadable_modules:+$loadable_modules,}$module_id" +done < <(node scripts/ci/self-hosted/test-module-assets.mjs "$host_key" "$callback_modules") +echo "callback module fixture: checking $loadable_modules" >&2 +test -n "$loadable_modules" +env -u OPENHUMAN_MODULE_PATH OPENHUMAN_BUNDLED_MODULES="$bundled_dir" \ + OPENHUMAN_TEST_CALLBACK_MODULES="$loadable_modules" \ + OPENHUMAN_KEYRING_MASTER_KEY="$(node -e 'process.stdout.write(require("node:crypto").randomBytes(32).toString("hex"))')" \ + bash scripts/ci-cancel-aware.sh cargo test --manifest-path Cargo.toml -p openhuman-cli \ + --test callback_module_release_fixture --no-default-features \ + --features "$core_features,security-module" \ + native_fixture_loads_callback_modules_from_a_release_source \ + -- --ignored --exact --nocapture + +# Desktop sign-in, end to end: the desktop core with TinySecurity from its +# bundled release and no socket stores the session token in the OS keyring +# once the keyring prompt is approved, and stays signed out when it is denied. +# TinySecurity's Linux build keeps keyring entries in the Secret Service, so +# each run gets a private D-Bus session and an unlocked throwaway keyring. A +# runner without one skips it, as above for missing system libraries, unless +# OPENHUMAN_TEST_REQUIRE_KEYRING_E2E=1 says this runner must run it. +sign_in_fixture() { + local keyring_home + keyring_home="$(mktemp -d)" + mkdir -p "$keyring_home/data" "$keyring_home/run" && chmod 700 "$keyring_home/run" + env -u OPENHUMAN_MODULE_PATH OPENHUMAN_BUNDLED_MODULES="$bundled_dir" \ + XDG_DATA_HOME="$keyring_home/data" XDG_RUNTIME_DIR="$keyring_home/run" \ + OPENHUMAN_TEST_SIGN_IN_WORKSPACE="$keyring_home/workspace" \ + OPENHUMAN_KEYRING_MASTER_KEY="$(node -e 'process.stdout.write(require("node:crypto").randomBytes(32).toString("hex"))')" \ + FIXTURE_FEATURES="$core_features,security-module" \ + dbus-run-session -- bash -c ' + set -euo pipefail + printf "fixture-keyring" | gnome-keyring-daemon --unlock --components=secrets >/dev/null + # The cases share one keyring and one workspace, in order. + for test_name in "$@"; do + bash scripts/ci-cancel-aware.sh cargo test --manifest-path Cargo.toml -p openhuman-cli \ + --test desktop_sign_in_fixture --no-default-features --features "$FIXTURE_FEATURES" \ + "$test_name" -- --ignored --exact --nocapture + done + # An approved sign-in leaves its entry in the OS keyring; a denied one does not. + if command -v secret-tool >/dev/null; then + echo "Secret Service entries for service=openhuman:" + secret-tool search --all service openhuman 2>&1 | grep -E "^(label|attribute)" || echo "(none)" + else + echo "secret-tool is not installed; the keyring listing is skipped" + fi + ' sign-in-fixture "$@" + rm -rf "$keyring_home" +} +sign_in_missing="" +if [[ "$(uname -s)" != Linux ]]; then + sign_in_missing="a Linux Secret Service" +else + for tool in gnome-keyring-daemon dbus-run-session; do + command -v "$tool" >/dev/null || sign_in_missing="${sign_in_missing:+$sign_in_missing }$tool" + done +fi +if [[ -n "$sign_in_missing" ]]; then + echo "desktop sign-in E2E: skipping; this runner lacks: $sign_in_missing" >&2 + if [[ "${OPENHUMAN_TEST_REQUIRE_KEYRING_E2E:-}" == 1 ]]; then + echo "desktop sign-in E2E: OPENHUMAN_TEST_REQUIRE_KEYRING_E2E=1, so a skip is a failure" >&2 + exit 1 + fi +else + # Signing in prunes retired cron jobs through TinyFlows before it commits + # (config/user_scope.rs), and the shipped app bundles TinyFlows too. + while IFS=$'\t' read -r module_id module_url module_archive module_sha; do + fetch_bundled "$module_id" "$module_url" "$module_archive" "$module_sha" + done < <(node scripts/ci/self-hosted/test-module-assets.mjs "$host_key" tinyflows) + sign_in_fixture desktop_sign_in_stores_the_token_in_the_os_keyring_after_approval \ + desktop_restart_reads_the_keyring_token_once_approved_at_startup + sign_in_fixture desktop_sign_in_denied_at_the_keyring_prompt_leaves_the_device_signed_out +fi diff --git a/scripts/lib/feature-forwarding.mjs b/scripts/lib/feature-forwarding.mjs index e71f391f90a..4fa9e68c992 100644 --- a/scripts/lib/feature-forwarding.mjs +++ b/scripts/lib/feature-forwarding.mjs @@ -470,6 +470,8 @@ export const CHAIN_GATES_NOT_FORWARDED = { 'Test scaffolding for the session testkit is only used by embed-local tests and is not a TinyHumans or host runtime capability.', }, 'openhuman-embed': { + 'test-keyring-consent': + 'Answers keyring prompts in the in-process integration tests only; the CLI enables it on its core dev-dependency, and no host or product build may (see checkTestOnlyGatesIsolation).', 'rss-bench': 'Library-side hook for the embedded-RSS benchmark (#5046). Its binaries live in tinyhumansai/openhuman-benchmarks (`profile/`, #6944), which enables the core gate directly; no host in this repository turns it on.', }, @@ -539,6 +541,35 @@ export function checkLinkedModulesIsolation({ productFeatures, shellToml, cliFea return violations; } +/** + * Gates for test builds only: `e2e-test-support` (the E2E apps' test RPCs and + * keyring prompt answers) and `test-keyring-consent` (keyring prompt answers + * for the in-process integration tests, enabled on the CLI's dev-dependency). + */ +export const TEST_ONLY_GATES = ['e2e-test-support', 'test-keyring-consent']; + +/** + * The test-only gates must never ship. Returns human-readable violations: a + * test-only gate in the product feature set, or reached from any crate's + * `default` features (transitively, so a default that turns on another gate + * that turns one on is caught too). `featureTables` maps a crate name to its + * parsed `[features]` table. + */ +export function checkTestOnlyGatesIsolation({ productFeatures, featureTables }) { + const violations = []; + for (const gate of TEST_ONLY_GATES) { + if (productFeatures.includes(gate)) { + violations.push(`${gate} is listed in the product feature set`); + } + for (const [crate, table] of Object.entries(featureTables)) { + if (resolveEnabledFeatures(table, ['default']).has(gate)) { + violations.push(`${crate}'s default features enable ${gate}`); + } + } + } + return violations; +} + /** * The `[features]` table of any manifest, as `name -> [items]`. * diff --git a/scripts/test-rust-e2e.sh b/scripts/test-rust-e2e.sh index 7392a90d58c..7a5089a1c5c 100755 --- a/scripts/test-rust-e2e.sh +++ b/scripts/test-rust-e2e.sh @@ -193,6 +193,9 @@ fi # tests, not a logic failure. Mirror scripts/test-rust-with-mock.sh and give the # suite a larger stack unless the caller already pinned one explicitly. export RUST_MIN_STACK="${RUST_MIN_STACK:-16777216}" +# Credential saves ask the user to approve each TinySecurity keyring operation; +# the test builds answer for them (keyring_consent/test_responder.rs). +export OPENHUMAN_TEST_KEYRING_CONSENT="${OPENHUMAN_TEST_KEYRING_CONSENT:-approve}" cd "$REPO_ROOT" source "$HOME/.cargo/env" 2>/dev/null || true diff --git a/tests/callback_module_release_fixture.rs b/tests/callback_module_release_fixture.rs new file mode 100644 index 00000000000..ab6f9b8522d --- /dev/null +++ b/tests/callback_module_release_fixture.rs @@ -0,0 +1,123 @@ +//! Callback-bound modules admitted from a pinned release, not a staged file. +//! +//! TinyMCP, TinyEventQueues and TinyChannels take a host storage callback and +//! TinyComputer a consequence callback, all bound to their exact admitted +//! instance. The shipped app loads them as pinned releases, so both the first +//! load and every later one must work without a local-file source. This target +//! runs in its own process because module admission is process-wide. + +use openhuman_core::config::Config; +use openhuman_core::modules::{ensure_loaded, state_of, ModuleState}; +use openhuman_rpc::{ + embed::ServiceSet, + host::{desktop_builder, serve_desktop, DesktopOptions, EmbeddedReadySignal}, +}; +use tokio_util::sync::CancellationToken; + +/// Boot a desktop core in this process, so the modules find the host storage +/// and secret store a product host installs before any of them loads. +async fn start_desktop_core(config: Config) -> (CancellationToken, tokio::task::JoinHandle<()>) { + openhuman_rpc::host::prepare_cli_host(); + let options = DesktopOptions { + host: Some("127.0.0.1".into()), + port: Some( + std::net::TcpListener::bind("127.0.0.1:0") + .expect("reserve ephemeral port") + .local_addr() + .expect("ephemeral address") + .port(), + ), + socketio: false, + rpc_token: Some(std::sync::Arc::new("callback-module-fixture-token".into())), + }; + let shutdown = CancellationToken::new(); + let (ready_tx, ready_rx) = tokio::sync::oneshot::channel::(); + let services = ServiceSet { + rpc_http: true, + socketio: false, + cron: false, + channels: false, + login_gated: false, + update_scheduler: false, + memory_queue: false, + skill_catalog_refresh: false, + mcp_boot: false, + integrations: false, + memory_sync: false, + }; + let builder = desktop_builder(&options) + .config_source(openhuman_tinyhumans::embed::ConfigSource::Resolved) + .config(config) + .boot_mode(openhuman_tinyhumans::embed::CoreBootMode::Normal) + .services(services); + let mut server = tokio::spawn(serve_desktop(builder, shutdown.clone(), ready_tx)); + tokio::select! { + ready = tokio::time::timeout(std::time::Duration::from_secs(120), ready_rx) => { + ready.expect("desktop host ready signal").expect("desktop host ready"); + } + result = &mut server => panic!("desktop host exited before ready: {result:?}"), + } + let task = tokio::spawn(async move { + let _ = server.await; + }); + (shutdown, task) +} + +#[test] +#[ignore = "loads the pinned callback-bound module releases from a bundled-modules directory"] +fn native_fixture_loads_callback_modules_from_a_release_source() { + std::thread::Builder::new() + .name("callback-module-fixture".into()) + .stack_size(openhuman_core::core::runtime::AGENT_WORKER_STACK_BYTES) + .spawn(|| { + tokio::runtime::Builder::new_multi_thread() + .worker_threads(2) + .thread_stack_size(openhuman_core::core::runtime::AGENT_WORKER_STACK_BYTES) + .enable_all() + .build() + .expect("build fixture runtime") + .block_on(loads_callback_modules()); + }) + .expect("spawn fixture runtime") + .join() + .expect("callback module fixture should not panic"); +} + +async fn loads_callback_modules() { + assert!( + std::env::var_os("OPENHUMAN_MODULE_PATH").is_none(), + "this fixture must not stage a local-file source" + ); + let modules = std::env::var("OPENHUMAN_TEST_CALLBACK_MODULES") + .expect("the fixture script names the bundled callback modules"); + let scratch = tempfile::tempdir().expect("scratch workspace"); + std::env::set_var("OPENHUMAN_WORKSPACE", scratch.path()); + // TinyMCP's storage grant carries secrets, which the storage host binds only + // under a master key; a product host supplies one from the OS keychain. + assert!( + std::env::var_os("OPENHUMAN_KEYRING_MASTER_KEY").is_some(), + "the fixture script supplies a test master key" + ); + std::env::set_var("OPENHUMAN_KEYRING_BACKEND", "encrypted_file"); + let mut config = Config::default(); + config.modules.enabled = true; + config.modules.allow_download = false; + config.modules.install_dir = Some(scratch.path().join("modules").display().to_string()); + config.workspace_dir = scratch.path().to_path_buf(); + config.config_path = scratch.path().join("config.toml"); + config.save().await.expect("save fixture config"); + let (shutdown, server) = start_desktop_core(config.clone()).await; + + for id in modules.split(',').filter(|id| !id.is_empty()) { + ensure_loaded(&config, id) + .await + .unwrap_or_else(|error| panic!("{id} should admit from its release: {error}")); + ensure_loaded(&config, id) + .await + .unwrap_or_else(|error| panic!("{id} should reuse its retained binding: {error}")); + assert_eq!(state_of(id), ModuleState::Ready, "{id}"); + } + + shutdown.cancel(); + let _ = server.await; +} diff --git a/tests/desktop_sign_in_fixture.rs b/tests/desktop_sign_in_fixture.rs new file mode 100644 index 00000000000..ca5c585d476 --- /dev/null +++ b/tests/desktop_sign_in_fixture.rs @@ -0,0 +1,483 @@ +//! Desktop sign-in through TinySecurity's OS keyring, end to end. +//! +//! Boots the desktop core the way the shell does (`desktop_builder`, secret +//! preflight, embedder host) with TinySecurity from its pinned release and no +//! Socket.IO, as on a first sign-in. Storing the session token asks the user to +//! approve each keyring operation; with no socket, the only way to see those +//! prompts is `openhuman.keyring_consent_list_pending_operations`. Each test +//! runs in its own process because module admission is process-wide, and needs +//! an unlocked Secret Service (the fixture script starts one). + +use openhuman_core::config::Config; +use openhuman_rpc::{ + embed::ServiceSet, + host::{desktop_builder, serve_desktop, DesktopOptions, EmbeddedReadySignal}, +}; +use serde_json::{json, Value}; +use std::time::Duration; +use tokio_util::sync::CancellationToken; + +const TOKEN: &str = "desktop-sign-in-fixture-token"; +const USER_ID: &str = "desktop-sign-in-fixture-user"; +/// Each case answers its prompts within seconds; this only bounds a wedge. +const FIXTURE_DEADLINE: Duration = Duration::from_secs(600); + +fn run_on_agent_stack(future_factory: F) +where + F: FnOnce() -> Fut + Send + 'static, + Fut: std::future::Future + Send + 'static, +{ + std::thread::Builder::new() + .name("desktop-sign-in-fixture".into()) + .stack_size(openhuman_core::core::runtime::AGENT_WORKER_STACK_BYTES) + .spawn(move || { + let runtime = tokio::runtime::Builder::new_multi_thread() + .thread_stack_size(openhuman_core::core::runtime::AGENT_WORKER_STACK_BYTES) + .enable_all() + .build() + .expect("build fixture runtime"); + let finished = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + runtime.block_on(async { + tokio::time::timeout(FIXTURE_DEADLINE, future_factory()) + .await + .expect("the fixture finishes before its deadline"); + }) + })); + if finished.is_err() { + // The loaded modules' threads keep a panicked runtime from + // dropping; fail the process instead of hanging the job. + std::process::exit(101); + } + runtime.shutdown_timeout(Duration::from_secs(10)); + }) + .expect("spawn fixture runtime") + .join() + .expect("desktop sign-in fixture should not panic"); +} + +async fn rpc(port: u16, method: &str, params: Value, timeout: Duration) -> Value { + reqwest::Client::builder() + .no_proxy() + .timeout(timeout) + .build() + .expect("build RPC client") + .post(format!("http://127.0.0.1:{port}/rpc")) + .bearer_auth(TOKEN) + .json(&json!({"jsonrpc":"2.0","id":1,"method":method,"params":params})) + .send() + .await + .unwrap_or_else(|error| panic!("{method}: {error}")) + .json() + .await + .expect("JSON-RPC response") +} + +fn result(response: &Value) -> &Value { + assert!(response.get("error").is_none(), "{response}"); + let result = &response["result"]; + if result.get("logs").is_some() { + &result["result"] + } else { + result + } +} + +/// A session JWT the core accepts: it reads the claims and never checks the +/// signature (the shell validated the token with the backend already). +fn session_token() -> String { + use base64::Engine as _; + let encode = + |value: Value| base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(value.to_string()); + format!( + "{}.{}.fixture-signature", + encode(json!({"alg":"HS256","typ":"JWT"})), + encode(json!({"sub": USER_ID, "exp": 4_102_444_800_u64})), + ) +} + +/// Approve every keyring prompt pending now; the number approved. Before the +/// secret preflight opens this is one of the few methods it lets through. +async fn approve_pending_keyring_prompts(port: u16) -> usize { + let listed = rpc( + port, + "openhuman.keyring_consent_list_pending_operations", + json!({}), + Duration::from_secs(5), + ) + .await; + if listed.get("error").is_some() { + return 0; + } + let prompts = result(&listed).as_array().cloned().unwrap_or_default(); + for prompt in &prompts { + rpc( + port, + "openhuman.keyring_consent_respond_operation", + json!({"request_id": prompt["request_id"], "approved": true}), + Duration::from_secs(5), + ) + .await; + } + prompts.len() +} + +/// The fixture workspace: the script's, shared by a sign-in and the restart +/// after it, or a fresh one of this case's own. +fn fixture_workspace() -> std::path::PathBuf { + match std::env::var_os("OPENHUMAN_TEST_SIGN_IN_WORKSPACE") { + Some(shared) => { + let shared = std::path::PathBuf::from(shared); + std::fs::create_dir_all(&shared).expect("shared fixture workspace"); + shared + } + // Kept when a case fails, for its logs; a passing case removes it. + None => tempfile::tempdir().expect("scratch workspace").keep(), + } +} + +fn remove_own_workspace(scratch: &std::path::Path) { + if std::env::var_os("OPENHUMAN_TEST_SIGN_IN_WORKSPACE").is_none() { + let _ = std::fs::remove_dir_all(scratch); + } +} + +/// A booted desktop core whose secret preflight has opened. +struct Desktop { + port: u16, + shutdown: CancellationToken, + scratch: std::path::PathBuf, + /// The auth state once ordinary methods answer. + state: Value, + /// Keyring prompts approved while the preflight was still closed. + startup_prompts: usize, +} + +/// Boot the shell's desktop core over the fixture workspace and wait until +/// its secret preflight lets ordinary methods through, approving any keyring +/// prompt it raises meanwhile as the login screen's overlay would. +async fn start_desktop() -> Desktop { + assert!( + std::env::var_os("OPENHUMAN_MODULE_PATH").is_none(), + "the shipped app never loads TinySecurity from a local file" + ); + let _ = tracing_subscriber::fmt() + .with_env_filter(tracing_subscriber::EnvFilter::from_default_env()) + .with_writer(std::io::stderr) + .try_init(); + let scratch = fixture_workspace(); + eprintln!("fixture workspace: {}", scratch.display()); + std::env::set_var("OPENHUMAN_WORKSPACE", &scratch); + std::env::set_var("HOME", &scratch); + // Nothing here may reach a real backend. + std::env::set_var("BACKEND_URL", "http://127.0.0.1:9"); + std::env::remove_var("OPENHUMAN_BACKEND_API_KEY"); + std::env::remove_var("OPENHUMAN_BACKEND_SESSION_TOKEN"); + // The host master key lives in the kernel session keyring, which a CI + // process may not have; a desktop keeps it there. The token under test + // goes to TinySecurity's own keyring either way. + assert!( + std::env::var_os("OPENHUMAN_KEYRING_MASTER_KEY").is_some(), + "the fixture script supplies a test host master key" + ); + let mut config = Config::default(); + config.modules.enabled = true; + config.modules.allow_download = false; + config.modules.install_dir = Some(scratch.join("modules").display().to_string()); + config.workspace_dir = scratch.clone(); + config.config_path = scratch.join("config.toml"); + // A restart keeps the configuration the earlier run left. + if !config.config_path.exists() { + config.save().await.expect("save fixture config"); + } + // Names only: a sealed field makes the secret preflight unlock it. + let saved = std::fs::read_to_string(&config.config_path).expect("read fixture config"); + let sealed: Vec<&str> = saved + .lines() + .filter(|line| line.contains("\"enc2:") || line.contains("\"enc:")) + .filter_map(|line| line.split('=').next().map(str::trim)) + .collect(); + eprintln!("fixture config sealed fields: {sealed:?}"); + + openhuman_rpc::host::prepare_cli_host(); + let options = DesktopOptions { + host: Some("127.0.0.1".into()), + port: Some( + std::net::TcpListener::bind("127.0.0.1:0") + .expect("reserve ephemeral port") + .local_addr() + .expect("ephemeral address") + .port(), + ), + // First sign-in: the renderer's socket waits for a session. + socketio: false, + rpc_token: Some(std::sync::Arc::new(TOKEN.into())), + }; + // The shell's boot (secret preflight, resolved config); only the + // background services that would reach the network are off. + let services = ServiceSet { + rpc_http: true, + socketio: false, + cron: false, + channels: false, + login_gated: false, + update_scheduler: false, + memory_queue: false, + skill_catalog_refresh: false, + mcp_boot: false, + integrations: false, + memory_sync: false, + }; + let builder = desktop_builder(&options).services(services); + let shutdown = CancellationToken::new(); + let (ready_tx, ready_rx) = tokio::sync::oneshot::channel::(); + let mut server = tokio::spawn(serve_desktop(builder, shutdown.clone(), ready_tx)); + let ready = tokio::select! { + ready = tokio::time::timeout(Duration::from_secs(120), ready_rx) => { + ready.expect("desktop host ready signal").expect("desktop host ready") + } + result = &mut server => panic!("desktop host exited before ready: {result:?}"), + }; + + let mut state = Value::Null; + let mut startup_prompts = 0; + for attempt in 0..600 { + state = rpc( + ready.port, + "openhuman.auth_get_state", + json!({}), + Duration::from_secs(5), + ) + .await; + if state.get("error").is_none() { + break; + } + // A host that failed to start its services keeps serving only the + // preflight methods; fail with its error instead of waiting. + if server.is_finished() { + panic!("desktop host stopped during startup: {:?}", server.await); + } + startup_prompts += approve_pending_keyring_prompts(ready.port).await; + // Still in the secret preflight: say what it waits on. Only the + // preflight methods answer here. + if attempt % 50 == 0 { + let pending = rpc( + ready.port, + "openhuman.approval_list_pending", + json!({}), + Duration::from_secs(5), + ) + .await; + let keyring = rpc( + ready.port, + "openhuman.keyring_consent_list_pending_operations", + json!({}), + Duration::from_secs(5), + ) + .await; + eprintln!( + "secret preflight still closed; pending approvals: {pending}; \ + pending keyring operations: {keyring}" + ); + } + tokio::time::sleep(Duration::from_millis(100)).await; + } + Desktop { + port: ready.port, + shutdown, + scratch, + state: result(&state).clone(), + startup_prompts, + } +} + +async fn start_signed_out_desktop() -> Desktop { + let desktop = start_desktop().await; + assert_eq!( + desktop.state["isAuthenticated"], + json!(false), + "a fresh desktop starts signed out: {}", + desktop.state + ); + assert_eq!( + desktop.startup_prompts, 0, + "nothing to read on a fresh desktop" + ); + desktop +} + +/// Read the session token back, approving the keyring reads it asks for. +async fn read_token_approving(port: u16) -> Value { + let token_read = tokio::spawn(async move { + rpc( + port, + "openhuman.auth_get_session_token", + json!({}), + Duration::from_secs(180), + ) + .await + }); + let mut read_prompts = 0; + while !token_read.is_finished() { + read_prompts += approve_pending_keyring_prompts(port).await; + tokio::time::sleep(Duration::from_millis(100)).await; + } + eprintln!("token read prompts: {read_prompts}"); + token_read.await.expect("token read task") +} + +/// Sign in with a session credential and answer every keyring prompt the +/// sign-in raises with `approved`, seen only through the pending list. Returns +/// the sign-in response and the prompts answered. +async fn sign_in_answering(port: u16, approved: bool) -> (Value, Vec) { + let sign_in = tokio::spawn(async move { + rpc( + port, + "openhuman.auth_set_credential", + json!({"token": session_token(), "kind": "session", "userId": USER_ID}), + Duration::from_secs(180), + ) + .await + }); + let mut answered: Vec = Vec::new(); + while !sign_in.is_finished() { + let listed = rpc( + port, + "openhuman.keyring_consent_list_pending_operations", + json!({}), + Duration::from_secs(5), + ) + .await; + for prompt in result(&listed).as_array().cloned().unwrap_or_default() { + let id = prompt["request_id"].clone(); + if answered.iter().any(|seen| seen["request_id"] == id) { + continue; + } + let responded = rpc( + port, + "openhuman.keyring_consent_respond_operation", + json!({"request_id": id, "approved": approved}), + Duration::from_secs(5), + ) + .await; + assert_eq!(result(&responded), &json!(true), "{prompt}"); + answered.push(prompt); + } + tokio::time::sleep(Duration::from_millis(100)).await; + } + (sign_in.await.expect("sign-in task"), answered) +} + +#[test] +#[ignore = "boots the desktop core with the pinned TinySecurity release and an unlocked Secret Service"] +fn desktop_sign_in_stores_the_token_in_the_os_keyring_after_approval() { + run_on_agent_stack(|| async { + let Desktop { + port, + shutdown, + scratch, + .. + } = start_signed_out_desktop().await; + let (signed_in, answered) = sign_in_answering(port, true).await; + eprintln!("approved prompts: {answered:#?}"); + let state = result(&signed_in); + assert_eq!(state["isAuthenticated"], json!(true), "{signed_in}"); + assert_ne!(state["restartRequired"], json!(true), "{signed_in}"); + assert!( + answered.iter().any(|prompt| prompt["access"] == "write" + && prompt["caller_agent"] == "openhuman.credentials"), + "storing the token asks to approve a keyring write: {answered:?}" + ); + + // Same process, no relaunch: the token reads back from the keyring. + let token_read = read_token_approving(port).await; + assert_eq!( + result(&token_read)["token"], + json!(session_token()), + "{token_read}" + ); + let state = rpc( + port, + "openhuman.auth_get_state", + json!({}), + Duration::from_secs(5), + ) + .await; + assert_eq!(result(&state)["isAuthenticated"], json!(true), "{state}"); + shutdown.cancel(); + remove_own_workspace(&scratch); + }); +} + +#[test] +#[ignore = "boots the desktop core with the pinned TinySecurity release and an unlocked Secret Service"] +fn desktop_sign_in_denied_at_the_keyring_prompt_leaves_the_device_signed_out() { + run_on_agent_stack(|| async { + let Desktop { + port, + shutdown, + scratch, + .. + } = start_signed_out_desktop().await; + let (refused, answered) = sign_in_answering(port, false).await; + eprintln!("denied prompts: {answered:#?}"); + assert!( + refused.get("error").is_some(), + "a denied keyring write fails sign-in: {refused}" + ); + assert!( + answered.iter().any(|prompt| prompt["access"] == "write"), + "the denial answered the keyring write prompt: {answered:?}" + ); + let state = rpc( + port, + "openhuman.auth_get_state", + json!({}), + Duration::from_secs(5), + ) + .await; + assert_eq!(result(&state)["isAuthenticated"], json!(false), "{state}"); + let token = rpc( + port, + "openhuman.auth_get_session_token", + json!({}), + Duration::from_secs(30), + ) + .await; + assert_eq!(result(&token)["token"], json!(null), "{token}"); + shutdown.cancel(); + remove_own_workspace(&scratch); + }); +} + +/// Run after the approved sign-in on its workspace: a restarted desktop reads +/// the keyring-held token during its secret preflight, which asks the user, +/// and comes up signed in once the prompt is approved. +#[test] +#[ignore = "restarts the desktop core over the approved sign-in's workspace"] +fn desktop_restart_reads_the_keyring_token_once_approved_at_startup() { + assert!( + std::env::var_os("OPENHUMAN_TEST_SIGN_IN_WORKSPACE").is_some(), + "the fixture script passes the approved sign-in's workspace" + ); + run_on_agent_stack(|| async { + let desktop = start_desktop().await; + eprintln!("startup keyring prompts: {}", desktop.startup_prompts); + assert!( + desktop.startup_prompts > 0, + "reading the stored token at startup asks the user" + ); + assert_eq!( + desktop.state["isAuthenticated"], + json!(true), + "{}", + desktop.state + ); + let token_read = read_token_approving(desktop.port).await; + assert_eq!( + result(&token_read)["token"], + json!(session_token()), + "{token_read}" + ); + desktop.shutdown.cancel(); + }); +} diff --git a/tests/security_native_fixture.rs b/tests/security_native_fixture.rs index 1ad4d86b127..be9f168cedc 100644 --- a/tests/security_native_fixture.rs +++ b/tests/security_native_fixture.rs @@ -181,7 +181,7 @@ async fn native_fixture_exercises_the_pinned_release_contracts() { .await .expect("the loaded module should answer its typed policy-info contract"); - assert_eq!(info.contract_version, (1, 35)); + assert_eq!(info.contract_version, (2, 0)); reinitialize(&config) .await @@ -190,7 +190,7 @@ async fn native_fixture_exercises_the_pinned_release_contracts() { .policy_info() .await .expect("the reinitialized module should continue answering policy info"); - assert_eq!(reinitialized_info.contract_version, (1, 35)); + assert_eq!(reinitialized_info.contract_version, (2, 0)); let redacted = client .redact(RedactMode::Text, "token=sk-ant-example-secret-value") diff --git a/tests/security_release_reuse_fixture.rs b/tests/security_release_reuse_fixture.rs new file mode 100644 index 00000000000..9edb40e9cf8 --- /dev/null +++ b/tests/security_release_reuse_fixture.rs @@ -0,0 +1,67 @@ +//! TinySecurity admitted from a pinned release, not a staged local file. +//! +//! The shipped app never sets `OPENHUMAN_MODULE_PATH`, so its TinySecurity is +//! a pinned release. The first load binds its host callbacks through the +//! callback factory; every later load must reuse that retained binding. This +//! target runs in its own process because module admission is process-wide. + +use openhuman_core::{config::Config, modules::security::client}; +use std::path::PathBuf; +use tinysecurity_bus::ProtectedPathRequest2; + +#[tokio::test] +#[ignore = "loads the pinned TinySecurity release from a bundled-modules directory"] +async fn native_fixture_serves_later_calls_after_a_release_admission() { + assert!( + std::env::var_os("OPENHUMAN_MODULE_PATH").is_none(), + "this fixture must not stage a local-file source" + ); + assert!( + std::env::var_os("OPENHUMAN_BUNDLED_MODULES").is_some(), + "the fixture script provides the verified release as a bundled module" + ); + let scratch = tempfile::tempdir().expect("scratch workspace"); + std::env::set_var("OPENHUMAN_WORKSPACE", scratch.path()); + std::env::set_var("OPENHUMAN_KEYRING_BACKEND", "file"); + let mut config = Config::default(); + config.modules.enabled = true; + config.modules.allow_download = false; + config.modules.install_dir = Some(scratch.path().join("modules").display().to_string()); + config.workspace_dir = scratch.path().to_path_buf(); + config.config_path = scratch.path().join("config.toml"); + config.action_dir = scratch.path().join("action"); + config.action_dir_override = Some(config.action_dir.clone()); + config.save().await.expect("save fixture config"); + openhuman_core::security::secret_storage::init_workspace(scratch.path()); + + let first = client(&config) + .await + .expect("the pinned release should admit with its callback factory"); + first + .policy_info() + .await + .expect("the admitted module should answer policy info"); + + // Each later caller loads again; this is the path that refused every + // non-local-file source. + let second = client(&config) + .await + .expect("a later load must reuse the retained callback binding"); + let floor = second + .protected_path2(ProtectedPathRequest2 { + paths: vec![PathBuf::from("ordinary.txt")], + }) + .await + .expect("the protected floor should answer after admission"); + assert_eq!(floor.protected, vec![false]); + + // Redaction runs in the module on the same admitted binding. + let redacted = second + .redact( + tinysecurity_bus::RedactMode::Text, + "token=sk-ant-example-secret-value", + ) + .await + .expect("redaction should serve after admission"); + assert!(!redacted.text.contains("sk-ant-example-secret-value")); +} diff --git a/vendor/tiny-artifacts b/vendor/tiny-artifacts index b8920f77b90..6ee41adb4f0 160000 --- a/vendor/tiny-artifacts +++ b/vendor/tiny-artifacts @@ -1 +1 @@ -Subproject commit b8920f77b90b69bc565f95e294d48e63ee5e2d72 +Subproject commit 6ee41adb4f0469b58e2bca1fe41e61988da27d09 diff --git a/vendor/tinysecurity b/vendor/tinysecurity index b53eceb948b..17c12844c64 160000 --- a/vendor/tinysecurity +++ b/vendor/tinysecurity @@ -1 +1 @@ -Subproject commit b53eceb948bd8dedce2176af6f0ec7bb1bd74151 +Subproject commit 17c12844c64fe6c561f6eacd4693dcae10623642 diff --git a/vendor/tinystoragedrivers b/vendor/tinystoragedrivers index 2d23a6a6009..5e8c8378983 160000 --- a/vendor/tinystoragedrivers +++ b/vendor/tinystoragedrivers @@ -1 +1 @@ -Subproject commit 2d23a6a6009fa52d1e7aa18de589bdd109a54b6a +Subproject commit 5e8c8378983a60c8de0a014a77cdba40c242b455