The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
feat(core): add core module with auth, bus, dispatch, event bind tokens, and socketio
Steven Enamakelc2100cb67291
diff --git a/crates/openhuman-core/src/core/auth.rs b/crates/openhuman-core/src/core/auth.rsindex 54c1c32835..2c698e97fa 100644--- a/crates/openhuman-core/src/core/auth.rs+++ b/crates/openhuman-core/src/core/auth.rs@@ -483,214 +483,7 @@ fn write_token_file(path: &Path, token: &str) -> anyhow::Result<()> {Ok(())}-#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn generate_token_produces_64_hex_chars() {- let t = generate_token();- assert_eq!(t.len(), 64, "256 bits → 64 hex chars");- assert!(t.chars().all(|c| c.is_ascii_hexdigit()), "must be hex");- }-- #[test]- fn generate_token_is_not_constant() {- assert_ne!(generate_token(), generate_token());- }-- #[test]- fn write_and_read_token_roundtrips() {- let tmp = std::env::temp_dir().join(format!("core-auth-test-{}", std::process::id()));- std::fs::create_dir_all(&tmp).unwrap();- let path = tmp.join("core.token");- let token = "cafebabe1234567890abcdef0123456789abcdef0123456789abcdef01234567";- write_token_file(&path, token).unwrap();- let back = std::fs::read_to_string(&path).unwrap();- assert_eq!(back, token);- std::fs::remove_dir_all(&tmp).ok();- }-- #[test]- fn bearer_matches_rejects_empty_supplied() {- let expected = "cafebabe";- assert!(!bearer_matches("", expected));- }-- #[test]- fn bearer_matches_rejects_mismatch() {- assert!(!bearer_matches("deadbeef", "cafebabe"));- }-- #[test]- fn bearer_matches_rejects_prefix_match() {- assert!(!bearer_matches("cafeba", "cafebabe"));- }-- #[test]- fn bearer_matches_accepts_exact() {- assert!(bearer_matches("cafebabe", "cafebabe"));- }-- #[test]- fn verify_bearer_token_returns_false_when_token_uninitialized() {- // RPC_TOKEN is a process-global OnceLock; on a fresh test binary it- // may already be set by another test that ran first, so we cannot- // assert the uninitialized branch here without process isolation.- // We can however confirm that an empty supplied value is always- // rejected, which exercises the second-leg invariant.- assert!(!verify_bearer_token(""));- }-- #[test]- fn init_rpc_token_with_value_rejects_empty() {- // Trimmed-empty values must error rather than seed an empty bearer.- assert!(init_rpc_token_with_value("").is_err());- assert!(init_rpc_token_with_value(" ").is_err());- }-- /// `init_rpc_token_with_value` populates the same `RPC_TOKEN` OnceLock- /// that `get_rpc_token` reads — i.e. the in-memory handoff path produces- /// the bearer everyone else (HTTP middleware, Socket.IO verifier,- /// approval-gate session_id) reads from. We can't deterministically- /// assert the *value* set here (the OnceLock may already be seeded by a- /// sibling test that ran first in the same binary), but we can assert- /// the OnceLock is initialised after this call returns Ok, and that the- /// helper is idempotent.- #[test]- fn init_rpc_token_with_value_seeds_and_is_idempotent() {- // First call: either we seed, or a sibling test already did. Either- // way the helper must return Ok and leave `get_rpc_token` populated.- let token = "cafebabe1234567890abcdef0123456789abcdef0123456789abcdef01234567";- init_rpc_token_with_value(token).expect("seed succeeds");- assert!(- get_rpc_token().is_some(),- "after init_rpc_token_with_value, get_rpc_token must return Some"- );- // Second call is a no-op (matching init_rpc_token semantics) — must- // not error, must not flip the in-memory value.- let before = get_rpc_token().map(str::to_string);- init_rpc_token_with_value("a-different-value-that-must-be-ignored")- .expect("idempotent re-init succeeds");- let after = get_rpc_token().map(str::to_string);- assert_eq!(- before, after,- "second init_rpc_token_with_value must not flip the in-memory bearer"- );- }-- #[cfg(feature = "http-server")]- #[test]- fn extract_query_token_returns_none_on_missing_query() {- assert_eq!(extract_query_token(None), None);- }- #[cfg(feature = "http-server")]- #[test]- fn extract_query_token_returns_none_when_key_absent() {- assert_eq!(extract_query_token(Some("other=1&foo=bar")), None);- }-- #[cfg(feature = "http-server")]- #[test]- fn extract_query_token_returns_none_on_empty_value() {- assert_eq!(extract_query_token(Some("token=")), None);- assert_eq!(extract_query_token(Some("token=%20%20")), None);- }-- #[cfg(feature = "http-server")]- #[test]- fn extract_query_token_returns_first_value_on_duplicate_keys() {- // Last-wins vs first-wins is a question the FE never hits; pin- // first-wins so any future ambiguity is documented.- assert_eq!(- extract_query_token(Some("token=alpha&token=beta")),- Some("alpha".to_string())- );- }-- #[cfg(feature = "http-server")]- #[test]- fn extract_query_token_url_decodes_value() {- // `encodeURIComponent` on the FE may percent-encode a hex token- // accidentally (it shouldn't, but defensive); confirm round-trip.- assert_eq!(- extract_query_token(Some("token=cafe%2Dbabe")),- Some("cafe-babe".to_string())- );- }-- #[cfg(feature = "http-server")]- #[test]- fn public_paths_include_desktop_auth_callback() {- assert!(PUBLIC_PATHS.contains(&"/auth"));- }-- #[cfg(feature = "http-server")]- #[test]- fn agentbox_run_and_jobs_paths_are_no_longer_public() {- // These bypassed bearer auth only to serve the AgentBox marketplace- // surface, which moved to tinybox. Nothing mounts them now, so they- // must authenticate like any other path — a re-added entry here would- // silently open an unauthenticated route.- assert!(!is_public_path("/run"));- assert!(!is_public_path("/jobs/abc-123"));- assert!(!is_public_path(- "/jobs/00000000-0000-0000-0000-000000000000"- ));- // Sanity: still protect the executable surface.- assert!(!is_public_path("/rpc"));- assert!(!is_public_path("/v1/chat/completions"));- }-- #[cfg(unix)]- #[test]- fn token_file_has_owner_only_permissions() {- use std::os::unix::fs::PermissionsExt as _;-- let tmp = std::env::temp_dir().join(format!("core-auth-perms-{}", std::process::id()));- std::fs::create_dir_all(&tmp).unwrap();- let path = tmp.join("core.token");- write_token_file(&path, "abc").unwrap();- let mode = std::fs::metadata(&path).unwrap().permissions().mode();- assert_eq!(mode & 0o777, 0o600, "token file must be 0o600");- std::fs::remove_dir_all(&tmp).ok();- }-- #[cfg(feature = "http-server")]- #[test]- fn is_external_inference_path_matches_only_v1_routes() {- assert!(is_external_inference_path("/v1"));- assert!(is_external_inference_path("/v1/models"));- assert!(is_external_inference_path("/v1/chat/completions"));- assert!(!is_external_inference_path("/rpc"));- assert!(!is_external_inference_path("/v10/models"));- }-- #[cfg(feature = "http-server")]- #[test]- fn verify_external_inference_bearer_for_config_accepts_stored_key() {- let tmp = tempfile::tempdir().unwrap();- let mut config = Config::default();- config.config_path = tmp.path().join("config.toml");-- let auth = AuthService::from_config(&config);- auth.store_provider_token(- EXTERNAL_OPENAI_COMPAT_PROVIDER,- "default",- "external-test-key",- std::collections::HashMap::new(),- true,- )- .unwrap();-- assert!(verify_external_inference_bearer_for_config(- &config,- "external-test-key"- ));- assert!(!verify_external_inference_bearer_for_config(- &config,- "wrong-key"- ));- }-}+#[cfg(test)]+#[path = "auth_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/core/auth_tests.rs b/crates/openhuman-core/src/core/auth_tests.rsnew file mode 100644index 0000000000..d5dbff0eb9--- /dev/null+++ b/crates/openhuman-core/src/core/auth_tests.rs@@ -0,0 +1,208 @@+use super::*;++#[test]+fn generate_token_produces_64_hex_chars() {+ let t = generate_token();+ assert_eq!(t.len(), 64, "256 bits → 64 hex chars");+ assert!(t.chars().all(|c| c.is_ascii_hexdigit()), "must be hex");+}++#[test]+fn generate_token_is_not_constant() {+ assert_ne!(generate_token(), generate_token());+}++#[test]+fn write_and_read_token_roundtrips() {+ let tmp = std::env::temp_dir().join(format!("core-auth-test-{}", std::process::id()));+ std::fs::create_dir_all(&tmp).unwrap();+ let path = tmp.join("core.token");+ let token = "cafebabe1234567890abcdef0123456789abcdef0123456789abcdef01234567";+ write_token_file(&path, token).unwrap();+ let back = std::fs::read_to_string(&path).unwrap();+ assert_eq!(back, token);+ std::fs::remove_dir_all(&tmp).ok();+}++#[test]+fn bearer_matches_rejects_empty_supplied() {+ let expected = "cafebabe";+ assert!(!bearer_matches("", expected));+}++#[test]+fn bearer_matches_rejects_mismatch() {+ assert!(!bearer_matches("deadbeef", "cafebabe"));+}++#[test]+fn bearer_matches_rejects_prefix_match() {+ assert!(!bearer_matches("cafeba", "cafebabe"));+}++#[test]+fn bearer_matches_accepts_exact() {+ assert!(bearer_matches("cafebabe", "cafebabe"));+}++#[test]+fn verify_bearer_token_returns_false_when_token_uninitialized() {+ // RPC_TOKEN is a process-global OnceLock; on a fresh test binary it+ // may already be set by another test that ran first, so we cannot+ // assert the uninitialized branch here without process isolation.+ // We can however confirm that an empty supplied value is always+ // rejected, which exercises the second-leg invariant.+ assert!(!verify_bearer_token(""));+}++#[test]+fn init_rpc_token_with_value_rejects_empty() {+ // Trimmed-empty values must error rather than seed an empty bearer.+ assert!(init_rpc_token_with_value("").is_err());+ assert!(init_rpc_token_with_value(" ").is_err());+}++/// `init_rpc_token_with_value` populates the same `RPC_TOKEN` OnceLock+/// that `get_rpc_token` reads — i.e. the in-memory handoff path produces+/// the bearer everyone else (HTTP middleware, Socket.IO verifier,+/// approval-gate session_id) reads from. We can't deterministically+/// assert the *value* set here (the OnceLock may already be seeded by a+/// sibling test that ran first in the same binary), but we can assert+/// the OnceLock is initialised after this call returns Ok, and that the+/// helper is idempotent.+#[test]+fn init_rpc_token_with_value_seeds_and_is_idempotent() {+ // First call: either we seed, or a sibling test already did. Either+ // way the helper must return Ok and leave `get_rpc_token` populated.+ let token = "cafebabe1234567890abcdef0123456789abcdef0123456789abcdef01234567";+ init_rpc_token_with_value(token).expect("seed succeeds");+ assert!(+ get_rpc_token().is_some(),+ "after init_rpc_token_with_value, get_rpc_token must return Some"+ );+ // Second call is a no-op (matching init_rpc_token semantics) — must+ // not error, must not flip the in-memory value.+ let before = get_rpc_token().map(str::to_string);+ init_rpc_token_with_value("a-different-value-that-must-be-ignored")+ .expect("idempotent re-init succeeds");+ let after = get_rpc_token().map(str::to_string);+ assert_eq!(+ before, after,+ "second init_rpc_token_with_value must not flip the in-memory bearer"+ );+}++#[cfg(feature = "http-server")]+#[test]+fn extract_query_token_returns_none_on_missing_query() {+ assert_eq!(extract_query_token(None), None);+}++#[cfg(feature = "http-server")]+#[test]+fn extract_query_token_returns_none_when_key_absent() {+ assert_eq!(extract_query_token(Some("other=1&foo=bar")), None);+}++#[cfg(feature = "http-server")]+#[test]+fn extract_query_token_returns_none_on_empty_value() {+ assert_eq!(extract_query_token(Some("token=")), None);+ assert_eq!(extract_query_token(Some("token=%20%20")), None);+}++#[cfg(feature = "http-server")]+#[test]+fn extract_query_token_returns_first_value_on_duplicate_keys() {+ // Last-wins vs first-wins is a question the FE never hits; pin+ // first-wins so any future ambiguity is documented.+ assert_eq!(+ extract_query_token(Some("token=alpha&token=beta")),+ Some("alpha".to_string())+ );+}++#[cfg(feature = "http-server")]+#[test]+fn extract_query_token_url_decodes_value() {+ // `encodeURIComponent` on the FE may percent-encode a hex token+ // accidentally (it shouldn't, but defensive); confirm round-trip.+ assert_eq!(+ extract_query_token(Some("token=cafe%2Dbabe")),+ Some("cafe-babe".to_string())+ );+}++#[cfg(feature = "http-server")]+#[test]+fn public_paths_include_desktop_auth_callback() {+ assert!(PUBLIC_PATHS.contains(&"/auth"));+}++#[cfg(feature = "http-server")]+#[test]+fn agentbox_run_and_jobs_paths_are_no_longer_public() {+ // These bypassed bearer auth only to serve the AgentBox marketplace+ // surface, which moved to tinybox. Nothing mounts them now, so they+ // must authenticate like any other path — a re-added entry here would+ // silently open an unauthenticated route.+ assert!(!is_public_path("/run"));+ assert!(!is_public_path("/jobs/abc-123"));+ assert!(!is_public_path(+ "/jobs/00000000-0000-0000-0000-000000000000"+ ));+ // Sanity: still protect the executable surface.+ assert!(!is_public_path("/rpc"));+ assert!(!is_public_path("/v1/chat/completions"));+}++#[cfg(unix)]+#[test]+fn token_file_has_owner_only_permissions() {+ use std::os::unix::fs::PermissionsExt as _;++ let tmp = std::env::temp_dir().join(format!("core-auth-perms-{}", std::process::id()));+ std::fs::create_dir_all(&tmp).unwrap();+ let path = tmp.join("core.token");+ write_token_file(&path, "abc").unwrap();+ let mode = std::fs::metadata(&path).unwrap().permissions().mode();+ assert_eq!(mode & 0o777, 0o600, "token file must be 0o600");+ std::fs::remove_dir_all(&tmp).ok();+}++#[cfg(feature = "http-server")]+#[test]+fn is_external_inference_path_matches_only_v1_routes() {+ assert!(is_external_inference_path("/v1"));+ assert!(is_external_inference_path("/v1/models"));+ assert!(is_external_inference_path("/v1/chat/completions"));+ assert!(!is_external_inference_path("/rpc"));+ assert!(!is_external_inference_path("/v10/models"));+}++#[cfg(feature = "http-server")]+#[test]+fn verify_external_inference_bearer_for_config_accepts_stored_key() {+ let tmp = tempfile::tempdir().unwrap();+ let mut config = Config::default();+ config.config_path = tmp.path().join("config.toml");++ let auth = AuthService::from_config(&config);+ auth.store_provider_token(+ EXTERNAL_OPENAI_COMPAT_PROVIDER,+ "default",+ "external-test-key",+ std::collections::HashMap::new(),+ true,+ )+ .unwrap();++ assert!(verify_external_inference_bearer_for_config(+ &config,+ "external-test-key"+ ));+ assert!(!verify_external_inference_bearer_for_config(+ &config,+ "wrong-key"+ ));+}diff --git a/crates/openhuman-core/src/core/bus.rs b/crates/openhuman-core/src/core/bus.rsindex a402413548..2c5cc0fda4 100644--- a/crates/openhuman-core/src/core/bus.rs+++ b/crates/openhuman-core/src/core/bus.rs@@ -166,62 +166,7 @@ impl tinybus::EventHandler<DomainEvent> for TracingSubscriber {}}-#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn the_catalog_address_constants_are_valid() {- // These are `expect`ed at runtime, so a typo must fail here rather than- // at startup in a user's process.- let _ = config();- let _ = manifest();- }-- #[test]- fn the_manifest_declares_the_catalog_in_both_directions() {- let manifest = manifest();- let interface = EVENTS_INTERFACE.try_into().unwrap();- assert!(- manifest.provided(&interface).is_some(),- "openhuman publishes"- );- assert!(- manifest.consumed(&interface).is_some(),- "openhuman subscribes"- );- }-- #[tokio::test]- async fn isolated_bus_delivers() {- use std::sync::Arc;- use tinybus::EventHandler;- use tokio::sync::Mutex;-- struct Capture(Arc<Mutex<Vec<DomainEvent>>>);- #[async_trait::async_trait]- impl EventHandler<DomainEvent> for Capture {- fn name(&self) -> &str {- "test::capture"- }- async fn handle(&self, event: &DomainEvent) {- self.0.lock().await.push(event.clone());- }- }-- let bus = crate::core::bus_testing::isolated_bus().await;-- let seen = Arc::new(Mutex::new(Vec::new()));- let _handle = bus.subscribe(Arc::new(Capture(seen.clone())));- bus.publish(DomainEvent::SystemStartup {- component: "test".into(),- });-- let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(5);- while seen.lock().await.is_empty() {- assert!(tokio::time::Instant::now() < deadline, "no delivery");- tokio::task::yield_now().await;- }- }-}+#[cfg(test)]+#[path = "bus_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/core/bus_tests.rs b/crates/openhuman-core/src/core/bus_tests.rsnew file mode 100644index 0000000000..9b0c52ce07--- /dev/null+++ b/crates/openhuman-core/src/core/bus_tests.rs@@ -0,0 +1,56 @@+use super::*;++#[test]+fn the_catalog_address_constants_are_valid() {+ // These are `expect`ed at runtime, so a typo must fail here rather than+ // at startup in a user's process.+ let _ = config();+ let _ = manifest();+}++#[test]+fn the_manifest_declares_the_catalog_in_both_directions() {+ let manifest = manifest();+ let interface = EVENTS_INTERFACE.try_into().unwrap();+ assert!(+ manifest.provided(&interface).is_some(),+ "openhuman publishes"+ );+ assert!(+ manifest.consumed(&interface).is_some(),+ "openhuman subscribes"+ );+}++#[tokio::test]+async fn isolated_bus_delivers() {+ use std::sync::Arc;+ use tinybus::EventHandler;+ use tokio::sync::Mutex;++ struct Capture(Arc<Mutex<Vec<DomainEvent>>>);++ #[async_trait::async_trait]+ impl EventHandler<DomainEvent> for Capture {+ fn name(&self) -> &str {+ "test::capture"+ }+ async fn handle(&self, event: &DomainEvent) {+ self.0.lock().await.push(event.clone());+ }+ }++ let bus = crate::core::bus_testing::isolated_bus().await;++ let seen = Arc::new(Mutex::new(Vec::new()));+ let _handle = bus.subscribe(Arc::new(Capture(seen.clone())));+ bus.publish(DomainEvent::SystemStartup {+ component: "test".into(),+ });++ let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(5);+ while seen.lock().await.is_empty() {+ assert!(tokio::time::Instant::now() < deadline, "no delivery");+ tokio::task::yield_now().await;+ }+}diff --git a/crates/openhuman-core/src/core/dispatch.rs b/crates/openhuman-core/src/core/dispatch.rsindex 124644562d..c67361a739 100644--- a/crates/openhuman-core/src/core/dispatch.rs+++ b/crates/openhuman-core/src/core/dispatch.rs@@ -266,249 +266,7 @@ fn type_name(value: &Value) -> &'static str {}}-#[cfg(test)]-mod tests {- use super::*;- use serde_json::json;- use std::ffi::OsString;-- /// Holds the shared config-env lock while an RPC handler reads the active- /// workspace. The controller path loads and may initialize config, so it- /// cannot safely share another test's transient workspace.- struct WorkspaceEnvGuard {- _lock: std::sync::MutexGuard<'static, ()>,- previous: Option<OsString>,- }-- impl WorkspaceEnvGuard {- fn set(path: &std::path::Path) -> Self {- let lock = crate::config::TEST_ENV_LOCK- .lock()- .unwrap_or_else(|poisoned| poisoned.into_inner());- let previous = std::env::var_os("OPENHUMAN_WORKSPACE");- std::env::set_var("OPENHUMAN_WORKSPACE", path);- Self {- _lock: lock,- previous,- }- }- }-- impl Drop for WorkspaceEnvGuard {- fn drop(&mut self) {- match self.previous.take() {- Some(value) => std::env::set_var("OPENHUMAN_WORKSPACE", value),- None => std::env::remove_var("OPENHUMAN_WORKSPACE"),- }- }- }-- fn test_state() -> AppState {- AppState {- core_version: "9.9.9-test".to_string(),- }- }-- #[tokio::test]- async fn dispatch_core_ping_returns_ok_true() {- let out = dispatch(test_state(), "core.ping", json!({}))- .await- .expect("core.ping should succeed");- assert_eq!(out, json!({ "ok": true }));- }-- #[tokio::test]- async fn dispatch_core_version_returns_state_version() {- let out = dispatch(test_state(), "core.version", json!({}))- .await- .expect("core.version should succeed");- assert_eq!(out, json!({ "version": "9.9.9-test" }));- }-- #[tokio::test]- async fn dispatch_core_ignores_params() {- // Params must be tolerated even when the method takes none.- let out = dispatch(test_state(), "core.ping", json!({ "extra": 1 }))- .await- .expect("core.ping should ignore extra params");- assert_eq!(out, json!({ "ok": true }));- }-- #[tokio::test]- async fn dispatch_rewrites_legacy_alias_before_lookup() {- // `openhuman.ping` is a legacy alias for `core.ping` in the shared- // alias table. Going through the dispatcher must rewrite it and- // route successfully to Tier 1 instead of falling through to the- // unknown-method error path.- let out = dispatch(test_state(), "openhuman.ping", json!({}))- .await- .expect("legacy alias openhuman.ping must resolve to core.ping");- assert_eq!(out, json!({ "ok": true }));- }-- #[tokio::test]- async fn dispatch_unknown_method_returns_error() {- let err = dispatch(test_state(), "does.not.exist", json!({}))- .await- .expect_err("unknown methods must error");- assert!(err.contains("unknown method"));- assert!(err.contains("does.not.exist"));- }-- #[tokio::test]- async fn dispatch_empty_method_returns_unknown_method_error() {- let err = dispatch(test_state(), "", json!({}))- .await- .expect_err("empty method must error");- assert!(err.contains("unknown method"));- }-- #[tokio::test]- async fn dispatch_delegates_to_tier2_for_domain_method() {- // Tier 2 dispatcher handles `openhuman.security_policy_info`, so- // it must succeed and return a policy object.- let workspace = tempfile::tempdir().expect("temporary workspace");- let _workspace_env = WorkspaceEnvGuard::set(workspace.path());- let out = dispatch(test_state(), "openhuman.security_policy_info", json!({}))- .await- .expect("security_policy_info should route via tier 2");- // With logs present, payload is wrapped as { result, logs }.- assert!(out.get("result").is_some() || out.get("autonomy").is_some());- }-- #[test]- fn try_core_dispatch_returns_none_for_non_core_namespace() {- let state = test_state();- assert!(try_core_dispatch(&state, "openhuman.memory_list_namespaces", json!({})).is_none());- assert!(try_core_dispatch(&state, "corez.ping", json!({})).is_none());- }-- #[test]- fn try_core_dispatch_matches_exact_ping_and_version() {- let state = test_state();- assert!(try_core_dispatch(&state, "core.ping", json!({})).is_some());- assert!(try_core_dispatch(&state, "core.version", json!({})).is_some());- // Prefix match alone must not count.- assert!(try_core_dispatch(&state, "core.pingz", json!({})).is_none());- assert!(try_core_dispatch(&state, "core", json!({})).is_none());- }-- #[test]- fn try_core_dispatch_version_reflects_appstate() {- let state = AppState {- core_version: "0.0.0-abc".into(),- };- let result = try_core_dispatch(&state, "core.version", json!({}))- .expect("core.version must be routed")- .expect("core.version must produce InvocationResult");- assert_eq!(result.value, json!({ "version": "0.0.0-abc" }));- assert!(result.logs.is_empty());- }-- #[tokio::test]- async fn dispatch_legacy_ping_rewrites_and_succeeds() {- let out = dispatch(test_state(), "openhuman.ping", json!({}))- .await- .expect("openhuman.ping should be rewritten to core.ping and succeed");- assert_eq!(out, json!({ "ok": true }));- }-- #[test]- fn is_known_probe_method_matches_allow_list_exactly() {- // Every allow-listed probe / legacy health name is recognised.- for m in [- "rpc.discover",- "list_methods",- "status",- "auth.status",- "config/get",- "openhuman.memory_tree_create_namespace",- "openhuman.harness_init_status",- ] {- assert!(- is_known_probe_method(m),- "{m} should be a debug-only known miss"- );- }- // Genuinely-unknown methods and near-misses are NOT allow-listed, so- // they stay on the warn-for-triage path rather than being silenced.- assert!(!is_known_probe_method("does.not.exist"));- assert!(!is_known_probe_method("core.not_a_real_method"));- assert!(!is_known_probe_method("Status")); // case-sensitive- assert!(!is_known_probe_method("rpc.discover.extra")); // exact match only- assert!(!is_known_probe_method("memory_tree_create_namespace"));- assert!(!is_known_probe_method(""));- }-- /// `openhuman.harness_init_status` is allow-listed as a debug-only miss so- /// client/core surface skew stops paging Sentry (#5157) — but it is a- /// **live** method, not a retired one. That allow-list entry means a- /// genuine regression (controller dropped from the registry) would go- /// completely silent: no error, no warn, no Sentry event. This test is the- /// replacement signal — if the method stops being served in a full build,- /// this fails instead of the regression shipping unnoticed.- #[test]- fn harness_init_status_is_registered_in_a_full_build() {- let served: Vec<String> = crate::core::all::all_controller_schemas()- .iter()- .map(crate::core::all::rpc_method_name)- .collect();- assert!(- served.iter().any(|m| m == "openhuman.harness_init_status"),- "harness_init_status must remain a registered controller — it is \- allow-listed in KNOWN_PROBE_METHODS for client/core skew only, so \- losing the real handler would be silently swallowed"- );- }-- #[tokio::test]- #[cfg(feature = "channels")]- async fn dispatch_dotted_channel_list_aliases_route_to_registry() {- for method in ["channels.list", "openhuman.channels.list"] {- let out = dispatch(test_state(), method, json!({}))- .await- .unwrap_or_else(|err| panic!("{method} should route via channels_list: {err}"));- assert!(- out.is_array() || out.get("result").is_some(),- "expected {method} to return the channels_list payload, got {out}"- );- }- }-- #[test]- fn unknown_method_name_extracts_from_error_string_only() {- // The classifier round-trips the exact string `dispatch` emits.- let err = format!("{UNKNOWN_METHOD_PREFIX}rpc.discover");- assert_eq!(unknown_method_name(&err), Some("rpc.discover"));- // Unrelated error strings are not misclassified as unknown-method.- assert_eq!(unknown_method_name("unknown param 'x' for ns.fn"), None);- assert_eq!(unknown_method_name("Session expired"), None);- }- #[tokio::test]- async fn dispatch_probe_method_still_returns_unknown_method_error() {- // Allow-listed probe names must not be silently "handled" — the caller- // still gets a method-not-found error. Only the Sentry severity (in the- // transport layer) changes; the dispatch contract is unchanged.- let err = dispatch(test_state(), "rpc.discover", json!({}))- .await- .expect_err("probe methods are still unknown to the dispatcher");- assert_eq!(unknown_method_name(&err), Some("rpc.discover"));- assert!(is_known_probe_method(- unknown_method_name(&err).expect("unknown-method error")- ));- }-- #[tokio::test]- async fn dispatch_legacy_alias_routes_to_registry() {- // This alias targets a controller registered in the domain registry.- // Do not invoke it here: its implementation can persist default config,- // which makes this routing test depend on a filesystem workspace.- let method =- crate::core::legacy_aliases::resolve_legacy("openhuman.get_analytics_settings");- assert!(- crate::core::all::schema_for_rpc_method(method).is_some(),- "legacy alias must resolve to a registered controller: {method}"- );- }-}+#[cfg(test)]+#[path = "dispatch_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/core/dispatch_tests.rs b/crates/openhuman-core/src/core/dispatch_tests.rsnew file mode 100644index 0000000000..1a8e14ae90--- /dev/null+++ b/crates/openhuman-core/src/core/dispatch_tests.rs@@ -0,0 +1,243 @@+use super::*;+use serde_json::json;+use std::ffi::OsString;++/// Holds the shared config-env lock while an RPC handler reads the active+/// workspace. The controller path loads and may initialize config, so it+/// cannot safely share another test's transient workspace.+struct WorkspaceEnvGuard {+ _lock: std::sync::MutexGuard<'static, ()>,+ previous: Option<OsString>,+}++impl WorkspaceEnvGuard {+ fn set(path: &std::path::Path) -> Self {+ let lock = crate::config::TEST_ENV_LOCK+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner());+ let previous = std::env::var_os("OPENHUMAN_WORKSPACE");+ std::env::set_var("OPENHUMAN_WORKSPACE", path);+ Self {+ _lock: lock,+ previous,+ }+ }+}++impl Drop for WorkspaceEnvGuard {+ fn drop(&mut self) {+ match self.previous.take() {+ Some(value) => std::env::set_var("OPENHUMAN_WORKSPACE", value),+ None => std::env::remove_var("OPENHUMAN_WORKSPACE"),+ }+ }+}++fn test_state() -> AppState {+ AppState {+ core_version: "9.9.9-test".to_string(),+ }+}++#[tokio::test]+async fn dispatch_core_ping_returns_ok_true() {+ let out = dispatch(test_state(), "core.ping", json!({}))+ .await+ .expect("core.ping should succeed");+ assert_eq!(out, json!({ "ok": true }));+}++#[tokio::test]+async fn dispatch_core_version_returns_state_version() {+ let out = dispatch(test_state(), "core.version", json!({}))+ .await+ .expect("core.version should succeed");+ assert_eq!(out, json!({ "version": "9.9.9-test" }));+}++#[tokio::test]+async fn dispatch_core_ignores_params() {+ // Params must be tolerated even when the method takes none.+ let out = dispatch(test_state(), "core.ping", json!({ "extra": 1 }))+ .await+ .expect("core.ping should ignore extra params");+ assert_eq!(out, json!({ "ok": true }));+}++#[tokio::test]+async fn dispatch_rewrites_legacy_alias_before_lookup() {+ // `openhuman.ping` is a legacy alias for `core.ping` in the shared+ // alias table. Going through the dispatcher must rewrite it and+ // route successfully to Tier 1 instead of falling through to the+ // unknown-method error path.+ let out = dispatch(test_state(), "openhuman.ping", json!({}))+ .await+ .expect("legacy alias openhuman.ping must resolve to core.ping");+ assert_eq!(out, json!({ "ok": true }));+}++#[tokio::test]+async fn dispatch_unknown_method_returns_error() {+ let err = dispatch(test_state(), "does.not.exist", json!({}))+ .await+ .expect_err("unknown methods must error");+ assert!(err.contains("unknown method"));+ assert!(err.contains("does.not.exist"));+}++#[tokio::test]+async fn dispatch_empty_method_returns_unknown_method_error() {+ let err = dispatch(test_state(), "", json!({}))+ .await+ .expect_err("empty method must error");+ assert!(err.contains("unknown method"));+}++#[tokio::test]+async fn dispatch_delegates_to_tier2_for_domain_method() {+ // Tier 2 dispatcher handles `openhuman.security_policy_info`, so+ // it must succeed and return a policy object.+ let workspace = tempfile::tempdir().expect("temporary workspace");+ let _workspace_env = WorkspaceEnvGuard::set(workspace.path());+ let out = dispatch(test_state(), "openhuman.security_policy_info", json!({}))+ .await+ .expect("security_policy_info should route via tier 2");+ // With logs present, payload is wrapped as { result, logs }.+ assert!(out.get("result").is_some() || out.get("autonomy").is_some());+}++#[test]+fn try_core_dispatch_returns_none_for_non_core_namespace() {+ let state = test_state();+ assert!(try_core_dispatch(&state, "openhuman.memory_list_namespaces", json!({})).is_none());+ assert!(try_core_dispatch(&state, "corez.ping", json!({})).is_none());+}++#[test]+fn try_core_dispatch_matches_exact_ping_and_version() {+ let state = test_state();+ assert!(try_core_dispatch(&state, "core.ping", json!({})).is_some());+ assert!(try_core_dispatch(&state, "core.version", json!({})).is_some());+ // Prefix match alone must not count.+ assert!(try_core_dispatch(&state, "core.pingz", json!({})).is_none());+ assert!(try_core_dispatch(&state, "core", json!({})).is_none());+}++#[test]+fn try_core_dispatch_version_reflects_appstate() {+ let state = AppState {+ core_version: "0.0.0-abc".into(),+ };+ let result = try_core_dispatch(&state, "core.version", json!({}))+ .expect("core.version must be routed")+ .expect("core.version must produce InvocationResult");+ assert_eq!(result.value, json!({ "version": "0.0.0-abc" }));+ assert!(result.logs.is_empty());+}++#[tokio::test]+async fn dispatch_legacy_ping_rewrites_and_succeeds() {+ let out = dispatch(test_state(), "openhuman.ping", json!({}))+ .await+ .expect("openhuman.ping should be rewritten to core.ping and succeed");+ assert_eq!(out, json!({ "ok": true }));+}++#[test]+fn is_known_probe_method_matches_allow_list_exactly() {+ // Every allow-listed probe / legacy health name is recognised.+ for m in [+ "rpc.discover",+ "list_methods",+ "status",+ "auth.status",+ "config/get",+ "openhuman.memory_tree_create_namespace",+ "openhuman.harness_init_status",+ ] {+ assert!(+ is_known_probe_method(m),+ "{m} should be a debug-only known miss"+ );+ }+ // Genuinely-unknown methods and near-misses are NOT allow-listed, so+ // they stay on the warn-for-triage path rather than being silenced.+ assert!(!is_known_probe_method("does.not.exist"));+ assert!(!is_known_probe_method("core.not_a_real_method"));+ assert!(!is_known_probe_method("Status")); // case-sensitive+ assert!(!is_known_probe_method("rpc.discover.extra")); // exact match only+ assert!(!is_known_probe_method("memory_tree_create_namespace"));+ assert!(!is_known_probe_method(""));+}++/// `openhuman.harness_init_status` is allow-listed as a debug-only miss so+/// client/core surface skew stops paging Sentry (#5157) — but it is a+/// **live** method, not a retired one. That allow-list entry means a+/// genuine regression (controller dropped from the registry) would go+/// completely silent: no error, no warn, no Sentry event. This test is the+/// replacement signal — if the method stops being served in a full build,+/// this fails instead of the regression shipping unnoticed.+#[test]+fn harness_init_status_is_registered_in_a_full_build() {+ let served: Vec<String> = crate::core::all::all_controller_schemas()+ .iter()+ .map(crate::core::all::rpc_method_name)+ .collect();+ assert!(+ served.iter().any(|m| m == "openhuman.harness_init_status"),+ "harness_init_status must remain a registered controller — it is \+ allow-listed in KNOWN_PROBE_METHODS for client/core skew only, so \+ losing the real handler would be silently swallowed"+ );+}++#[tokio::test]+#[cfg(feature = "channels")]+async fn dispatch_dotted_channel_list_aliases_route_to_registry() {+ for method in ["channels.list", "openhuman.channels.list"] {+ let out = dispatch(test_state(), method, json!({}))+ .await+ .unwrap_or_else(|err| panic!("{method} should route via channels_list: {err}"));+ assert!(+ out.is_array() || out.get("result").is_some(),+ "expected {method} to return the channels_list payload, got {out}"+ );+ }+}++#[test]+fn unknown_method_name_extracts_from_error_string_only() {+ // The classifier round-trips the exact string `dispatch` emits.+ let err = format!("{UNKNOWN_METHOD_PREFIX}rpc.discover");+ assert_eq!(unknown_method_name(&err), Some("rpc.discover"));+ // Unrelated error strings are not misclassified as unknown-method.+ assert_eq!(unknown_method_name("unknown param 'x' for ns.fn"), None);+ assert_eq!(unknown_method_name("Session expired"), None);+}++#[tokio::test]+async fn dispatch_probe_method_still_returns_unknown_method_error() {+ // Allow-listed probe names must not be silently "handled" — the caller+ // still gets a method-not-found error. Only the Sentry severity (in the+ // transport layer) changes; the dispatch contract is unchanged.+ let err = dispatch(test_state(), "rpc.discover", json!({}))+ .await+ .expect_err("probe methods are still unknown to the dispatcher");+ assert_eq!(unknown_method_name(&err), Some("rpc.discover"));+ assert!(is_known_probe_method(+ unknown_method_name(&err).expect("unknown-method error")+ ));+}++#[tokio::test]+async fn dispatch_legacy_alias_routes_to_registry() {+ // This alias targets a controller registered in the domain registry.+ // Do not invoke it here: its implementation can persist default config,+ // which makes this routing test depend on a filesystem workspace.+ let method =+ crate::core::legacy_aliases::resolve_legacy("openhuman.get_analytics_settings");+ assert!(+ crate::core::all::schema_for_rpc_method(method).is_some(),+ "legacy alias must resolve to a registered controller: {method}"+ );+}diff --git a/crates/openhuman-core/src/core/event_bind_tokens.rs b/crates/openhuman-core/src/core/event_bind_tokens.rsindex 313fed7d28..27fb5853e3 100644--- a/crates/openhuman-core/src/core/event_bind_tokens.rs+++ b/crates/openhuman-core/src/core/event_bind_tokens.rs@@ -141,65 +141,7 @@ fn generate_token() -> String {hex::encode(bytes)}-#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn issued_token_validates_for_matching_client_id() {- let issued = issue("cli-test-1", None).expect("issue");- assert!(consume("cli-test-1", &issued.token));- }-- #[test]- fn issued_token_rejects_wrong_client_id() {- let issued = issue("cli-test-2", None).expect("issue");- assert!(!consume("attacker-id", &issued.token));- }-- #[test]- fn wrong_client_id_does_not_consume_token() {- // Mismatched consume must leave the token intact so the legitimate- // subscriber can still validate after the failed probe — otherwise- // a wrong-id request becomes a one-shot DoS.- let issued = issue("cli-test-mismatch", None).expect("issue");- assert!(!consume("attacker-id", &issued.token));- assert!(- consume("cli-test-mismatch", &issued.token),- "legitimate consume must still succeed after a mismatched probe"- );- }-- #[test]- fn consumed_token_cannot_be_reused() {- let issued = issue("cli-test-3", None).expect("issue");- assert!(consume("cli-test-3", &issued.token));- assert!(- !consume("cli-test-3", &issued.token),- "tokens must be single-shot"- );- }- #[test]- fn expired_token_is_rejected() {- let issued = issue("cli-test-4", Some(Duration::from_millis(1))).expect("issue");- std::thread::sleep(Duration::from_millis(20));- assert!(!consume("cli-test-4", &issued.token));- }-- #[test]- fn unknown_token_is_rejected() {- assert!(!consume("any-id", "f00ba1"));- }-- #[test]- fn ttl_override_is_clamped_to_max() {- // Any caller asking for more than `MAX_TTL` collapses to the cap;- // confirm the issue path does not panic and the resulting token- // still validates.- let issued =- issue("cli-test-clamp", Some(Duration::from_secs(60 * 60 * 24))).expect("issue");- assert!(issued.valid_until <= Instant::now() + MAX_TTL + Duration::from_secs(1));- assert!(consume("cli-test-clamp", &issued.token));- }-}+#[cfg(test)]+#[path = "event_bind_tokens_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/core/event_bind_tokens_tests.rs b/crates/openhuman-core/src/core/event_bind_tokens_tests.rsnew file mode 100644index 0000000000..2d5fe9df9e--- /dev/null+++ b/crates/openhuman-core/src/core/event_bind_tokens_tests.rs@@ -0,0 +1,59 @@+use super::*;++#[test]+fn issued_token_validates_for_matching_client_id() {+ let issued = issue("cli-test-1", None).expect("issue");+ assert!(consume("cli-test-1", &issued.token));+}++#[test]+fn issued_token_rejects_wrong_client_id() {+ let issued = issue("cli-test-2", None).expect("issue");+ assert!(!consume("attacker-id", &issued.token));+}++#[test]+fn wrong_client_id_does_not_consume_token() {+ // Mismatched consume must leave the token intact so the legitimate+ // subscriber can still validate after the failed probe — otherwise+ // a wrong-id request becomes a one-shot DoS.+ let issued = issue("cli-test-mismatch", None).expect("issue");+ assert!(!consume("attacker-id", &issued.token));+ assert!(+ consume("cli-test-mismatch", &issued.token),+ "legitimate consume must still succeed after a mismatched probe"+ );+}++#[test]+fn consumed_token_cannot_be_reused() {+ let issued = issue("cli-test-3", None).expect("issue");+ assert!(consume("cli-test-3", &issued.token));+ assert!(+ !consume("cli-test-3", &issued.token),+ "tokens must be single-shot"+ );+}++#[test]+fn expired_token_is_rejected() {+ let issued = issue("cli-test-4", Some(Duration::from_millis(1))).expect("issue");+ std::thread::sleep(Duration::from_millis(20));+ assert!(!consume("cli-test-4", &issued.token));+}++#[test]+fn unknown_token_is_rejected() {+ assert!(!consume("any-id", "f00ba1"));+}++#[test]+fn ttl_override_is_clamped_to_max() {+ // Any caller asking for more than `MAX_TTL` collapses to the cap;+ // confirm the issue path does not panic and the resulting token+ // still validates.+ let issued =+ issue("cli-test-clamp", Some(Duration::from_secs(60 * 60 * 24))).expect("issue");+ assert!(issued.valid_until <= Instant::now() + MAX_TTL + Duration::from_secs(1));+ assert!(consume("cli-test-clamp", &issued.token));+}diff --git a/crates/openhuman-core/src/core/socketio.rs b/crates/openhuman-core/src/core/socketio.rsindex 4e59573ff6..5a9ebd764f 100644--- a/crates/openhuman-core/src/core/socketio.rs+++ b/crates/openhuman-core/src/core/socketio.rs@@ -1597,221 +1597,5 @@ fn emit_with_aliases(socket: &SocketRef, name: &str, payload: &serde_json::Value// Every test here names a gated fn (`channel_connection_update_payload`,// `event_alias`, `origin_is_allowed`), so the module gates in lockstep (#5048).#[cfg(all(test, feature = "http-server"))]-mod tests {- use super::{- channel_connection_update_payload, event_alias, origin_is_allowed_with_extra,- publish_companion_state_changed, subscribe_companion_state_changed,- };-- #[test]- fn companion_state_transport_delivers_payload_to_bridge() {- let mut rx = subscribe_companion_state_changed();- let payload = serde_json::json!({- "session_id": "session-1",- "state": "thinking",- "previous_state": "listening",- });- assert!(publish_companion_state_changed(payload.clone()) >= 1);- assert_eq!(rx.try_recv().expect("payload delivered"), payload);- }-- #[test]- fn channel_connection_update_payload_connected_omits_error() {- let payload = channel_connection_update_payload("discord", "connected", None);- assert_eq!(payload["channel"], "discord");- // Listener-backed channels always map to the bot_token auth mode.- assert_eq!(payload["auth_mode"], "bot_token");- assert_eq!(payload["status"], "connected");- assert!(- payload.get("last_error").is_none(),- "connected payload must not carry a last_error: {payload}"- );- }-- #[test]- fn channel_connection_update_payload_error_carries_reason() {- let payload =- channel_connection_update_payload("discord", "error", Some("gateway closed (4004)"));- assert_eq!(payload["channel"], "discord");- assert_eq!(payload["auth_mode"], "bot_token");- assert_eq!(payload["status"], "error");- assert_eq!(payload["last_error"], "gateway closed (4004)");- }-- #[test]- fn event_alias_translates_between_delimiters() {- assert_eq!(event_alias("chat_done").as_deref(), Some("chat:done"));- assert_eq!(event_alias("chat:error").as_deref(), Some("chat_error"));- assert_eq!(event_alias("ready"), None);- }-- #[test]- fn event_alias_suppressed_for_streaming_deltas() {- // Streaming deltas must NOT be aliased — doubling every token frame is- // the "double thinking-token streaming" bug. Discrete events still alias.- assert_eq!(event_alias("thinking_delta"), None);- assert_eq!(event_alias("text_delta"), None);- assert_eq!(event_alias("tool_args_delta"), None);- assert_eq!(event_alias("subagent_tool_args_delta"), None);- // A *discrete* event that merely ends in `_delta` is NOT a streaming- // token event and must keep its compat alias — this is what the explicit- // STREAMING_DELTA_EVENTS set guarantees over the old `*_delta` suffix.- assert_eq!(- event_alias("inventory_delta").as_deref(),- Some("inventory:delta")- );- // Sanity: a non-delta event in the same family still aliases.- assert_eq!(event_alias("tool_call").as_deref(), Some("tool:call"));- }-- #[test]- fn origin_allowlist_accepts_native_clients() {- assert!(origin_is_allowed_with_extra(None, None));- }-- #[test]- fn origin_allowlist_accepts_tauri_localhost_across_schemes() {- // The CEF-served app shell stamps a platform-dependent Origin:- // - macOS / iOS use the native `tauri://localhost` scheme- // - Windows uses the CEF custom HTTP protocol → `http://tauri.localhost`- // - Linux / older Windows builds use `https://tauri.localhost`- // All three flavours are the same trust tier (the bundled webview),- // so each must pass the handshake gate.- assert!(origin_is_allowed_with_extra(- Some("tauri://localhost"),- None- ));- assert!(origin_is_allowed_with_extra(- Some("https://tauri.localhost"),- None- ));- assert!(origin_is_allowed_with_extra(- Some("http://tauri.localhost"),- None- ));- }-- #[test]- fn origin_allowlist_accepts_local_dev_server() {- assert!(origin_is_allowed_with_extra(- Some("http://localhost:1420"),- None- ));- assert!(origin_is_allowed_with_extra(- Some("http://127.0.0.1:1420"),- None- ));- assert!(origin_is_allowed_with_extra(- Some("http://[::1]:1420"),- None- ));- // Loopback without an explicit port (some CEF builds stamp this- // shape when the shell runs on the default port).- assert!(origin_is_allowed_with_extra(Some("http://localhost"), None));- }-- #[test]- fn origin_allowlist_rejects_cross_origin_browser_pages() {- assert!(!origin_is_allowed_with_extra(- Some("https://attacker.example"),- None- ));- assert!(!origin_is_allowed_with_extra(- Some("http://evil.local"),- None- ));- assert!(!origin_is_allowed_with_extra(Some("null"), None));- assert!(!origin_is_allowed_with_extra(Some(""), None));- }-- #[test]- fn origin_allowlist_rejects_host_prefix_decoys() {- // Regression: `starts_with("localhost")` accepted these; the exact- // host match must not.- assert!(!origin_is_allowed_with_extra(- Some("http://localhost.attacker.example"),- None- ));- assert!(!origin_is_allowed_with_extra(- Some("http://127.0.0.1.attacker.example"),- None- ));- assert!(!origin_is_allowed_with_extra(- Some("https://localhost-evil"),- None- ));- // Same rule applies to the tauri.localhost host — must be exact.- assert!(!origin_is_allowed_with_extra(- Some("http://tauri.localhost.attacker.example"),- None- ));- assert!(!origin_is_allowed_with_extra(- Some("https://tauri.localhost.evil"),- None- ));- }-- #[test]- fn origin_allowlist_accepts_env_allowlisted_origin() {- // Regression: a non-loopback browser origin that the JSON-RPC CORS- // layer accepts must also pass the socket handshake, or chat (a- // socket-only transport) silently never connects.- let extra = Some("https://box.example.ts.net:9000");- assert!(origin_is_allowed_with_extra(- Some("https://box.example.ts.net:9000"),- extra- ));- }-- #[test]- fn origin_allowlist_env_handles_comma_list_and_whitespace() {- let extra = Some("https://a.example:9000 , https://b.example:8443");- assert!(origin_is_allowed_with_extra(- Some("https://a.example:9000"),- extra- ));- assert!(origin_is_allowed_with_extra(- Some("https://b.example:8443"),- extra- ));- assert!(!origin_is_allowed_with_extra(- Some("https://c.example"),- extra- ));- }-- #[test]- fn origin_allowlist_env_requires_exact_match() {- // Populating the allowlist must not loosen the decoy rules: no port- // wildcarding, no scheme swapping, no suffix matching.- let extra = Some("https://box.example.ts.net:9000");- assert!(!origin_is_allowed_with_extra(- Some("http://box.example.ts.net:9000"),- extra- ));- assert!(!origin_is_allowed_with_extra(- Some("https://box.example.ts.net:9001"),- extra- ));- assert!(!origin_is_allowed_with_extra(- Some("https://box.example.ts.net.attacker.example:9000"),- extra- ));- }-- #[test]- fn origin_allowlist_env_does_not_rescue_null_or_empty() {- let extra = Some("null,");- assert!(!origin_is_allowed_with_extra(Some("null"), extra));- assert!(!origin_is_allowed_with_extra(Some(""), extra));- }-- #[test]- fn origin_allowlist_rejects_unparseable_origin() {- assert!(!origin_is_allowed_with_extra(Some("not a url"), None));- assert!(!origin_is_allowed_with_extra(- Some("javascript:alert(1)"),- None- ));- }-}+#[path = "socketio_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/core/socketio_tests.rs b/crates/openhuman-core/src/core/socketio_tests.rsnew file mode 100644index 0000000000..cd6ae1d5e4--- /dev/null+++ b/crates/openhuman-core/src/core/socketio_tests.rs@@ -0,0 +1,216 @@+use super::{+ channel_connection_update_payload, event_alias, origin_is_allowed_with_extra,+ publish_companion_state_changed, subscribe_companion_state_changed,+};++#[test]+fn companion_state_transport_delivers_payload_to_bridge() {+ let mut rx = subscribe_companion_state_changed();+ let payload = serde_json::json!({+ "session_id": "session-1",+ "state": "thinking",+ "previous_state": "listening",+ });+ assert!(publish_companion_state_changed(payload.clone()) >= 1);+ assert_eq!(rx.try_recv().expect("payload delivered"), payload);+}++#[test]+fn channel_connection_update_payload_connected_omits_error() {+ let payload = channel_connection_update_payload("discord", "connected", None);+ assert_eq!(payload["channel"], "discord");+ // Listener-backed channels always map to the bot_token auth mode.+ assert_eq!(payload["auth_mode"], "bot_token");+ assert_eq!(payload["status"], "connected");+ assert!(+ payload.get("last_error").is_none(),+ "connected payload must not carry a last_error: {payload}"+ );+}++#[test]+fn channel_connection_update_payload_error_carries_reason() {+ let payload =+ channel_connection_update_payload("discord", "error", Some("gateway closed (4004)"));+ assert_eq!(payload["channel"], "discord");+ assert_eq!(payload["auth_mode"], "bot_token");+ assert_eq!(payload["status"], "error");+ assert_eq!(payload["last_error"], "gateway closed (4004)");+}++#[test]+fn event_alias_translates_between_delimiters() {+ assert_eq!(event_alias("chat_done").as_deref(), Some("chat:done"));+ assert_eq!(event_alias("chat:error").as_deref(), Some("chat_error"));+ assert_eq!(event_alias("ready"), None);+}++#[test]+fn event_alias_suppressed_for_streaming_deltas() {+ // Streaming deltas must NOT be aliased — doubling every token frame is+ // the "double thinking-token streaming" bug. Discrete events still alias.+ assert_eq!(event_alias("thinking_delta"), None);+ assert_eq!(event_alias("text_delta"), None);+ assert_eq!(event_alias("tool_args_delta"), None);+ assert_eq!(event_alias("subagent_tool_args_delta"), None);+ // A *discrete* event that merely ends in `_delta` is NOT a streaming+ // token event and must keep its compat alias — this is what the explicit+ // STREAMING_DELTA_EVENTS set guarantees over the old `*_delta` suffix.+ assert_eq!(+ event_alias("inventory_delta").as_deref(),+ Some("inventory:delta")+ );+ // Sanity: a non-delta event in the same family still aliases.+ assert_eq!(event_alias("tool_call").as_deref(), Some("tool:call"));+}++#[test]+fn origin_allowlist_accepts_native_clients() {+ assert!(origin_is_allowed_with_extra(None, None));+}++#[test]+fn origin_allowlist_accepts_tauri_localhost_across_schemes() {+ // The CEF-served app shell stamps a platform-dependent Origin:+ // - macOS / iOS use the native `tauri://localhost` scheme+ // - Windows uses the CEF custom HTTP protocol → `http://tauri.localhost`+ // - Linux / older Windows builds use `https://tauri.localhost`+ // All three flavours are the same trust tier (the bundled webview),+ // so each must pass the handshake gate.+ assert!(origin_is_allowed_with_extra(+ Some("tauri://localhost"),+ None+ ));+ assert!(origin_is_allowed_with_extra(+ Some("https://tauri.localhost"),+ None+ ));+ assert!(origin_is_allowed_with_extra(+ Some("http://tauri.localhost"),+ None+ ));+}++#[test]+fn origin_allowlist_accepts_local_dev_server() {+ assert!(origin_is_allowed_with_extra(+ Some("http://localhost:1420"),+ None+ ));+ assert!(origin_is_allowed_with_extra(+ Some("http://127.0.0.1:1420"),+ None+ ));+ assert!(origin_is_allowed_with_extra(+ Some("http://[::1]:1420"),+ None+ ));+ // Loopback without an explicit port (some CEF builds stamp this+ // shape when the shell runs on the default port).+ assert!(origin_is_allowed_with_extra(Some("http://localhost"), None));+}++#[test]+fn origin_allowlist_rejects_cross_origin_browser_pages() {+ assert!(!origin_is_allowed_with_extra(+ Some("https://attacker.example"),+ None+ ));+ assert!(!origin_is_allowed_with_extra(+ Some("http://evil.local"),+ None+ ));+ assert!(!origin_is_allowed_with_extra(Some("null"), None));+ assert!(!origin_is_allowed_with_extra(Some(""), None));+}++#[test]+fn origin_allowlist_rejects_host_prefix_decoys() {+ // Regression: `starts_with("localhost")` accepted these; the exact+ // host match must not.+ assert!(!origin_is_allowed_with_extra(+ Some("http://localhost.attacker.example"),+ None+ ));+ assert!(!origin_is_allowed_with_extra(+ Some("http://127.0.0.1.attacker.example"),+ None+ ));+ assert!(!origin_is_allowed_with_extra(+ Some("https://localhost-evil"),+ None+ ));+ // Same rule applies to the tauri.localhost host — must be exact.+ assert!(!origin_is_allowed_with_extra(+ Some("http://tauri.localhost.attacker.example"),+ None+ ));+ assert!(!origin_is_allowed_with_extra(+ Some("https://tauri.localhost.evil"),+ None+ ));+}++#[test]+fn origin_allowlist_accepts_env_allowlisted_origin() {+ // Regression: a non-loopback browser origin that the JSON-RPC CORS+ // layer accepts must also pass the socket handshake, or chat (a+ // socket-only transport) silently never connects.+ let extra = Some("https://box.example.ts.net:9000");+ assert!(origin_is_allowed_with_extra(+ Some("https://box.example.ts.net:9000"),+ extra+ ));+}++#[test]+fn origin_allowlist_env_handles_comma_list_and_whitespace() {+ let extra = Some("https://a.example:9000 , https://b.example:8443");+ assert!(origin_is_allowed_with_extra(+ Some("https://a.example:9000"),+ extra+ ));+ assert!(origin_is_allowed_with_extra(+ Some("https://b.example:8443"),+ extra+ ));+ assert!(!origin_is_allowed_with_extra(+ Some("https://c.example"),+ extra+ ));+}++#[test]+fn origin_allowlist_env_requires_exact_match() {+ // Populating the allowlist must not loosen the decoy rules: no port+ // wildcarding, no scheme swapping, no suffix matching.+ let extra = Some("https://box.example.ts.net:9000");+ assert!(!origin_is_allowed_with_extra(+ Some("http://box.example.ts.net:9000"),+ extra+ ));+ assert!(!origin_is_allowed_with_extra(+ Some("https://box.example.ts.net:9001"),+ extra+ ));+ assert!(!origin_is_allowed_with_extra(+ Some("https://box.example.ts.net.attacker.example:9000"),+ extra+ ));+}++#[test]+fn origin_allowlist_env_does_not_rescue_null_or_empty() {+ let extra = Some("null,");+ assert!(!origin_is_allowed_with_extra(Some("null"), extra));+ assert!(!origin_is_allowed_with_extra(Some(""), extra));+}++#[test]+fn origin_allowlist_rejects_unparseable_origin() {+ assert!(!origin_is_allowed_with_extra(Some("not a url"), None));+ assert!(!origin_is_allowed_with_extra(+ Some("javascript:alert(1)"),+ None+ ));+}diff --git a/scripts/ci/coverage-presence-allowlist.txt b/scripts/ci/coverage-presence-allowlist.txtindex b6b7796ced..acb3a8c584 100644--- a/scripts/ci/coverage-presence-allowlist.txt+++ b/scripts/ci/coverage-presence-allowlist.txt@@ -26,8 +26,13 @@# generic facade stub.crates/openhuman-core/src/runtime/client/disabled.rs-# `helper.rs` includes this fragment only to build the macOS Swift accessibility-# helper. The production feature set is compiled for Linux in this coverage lane,-# so the fragment's `#[cfg(target_os = "macos")]` definition is intentionally-# absent. It is exercised by the macOS desktop E2E matrix instead.-crates/openhuman-core/src/desktop/accessibility/helper_part_02.rs+# `helper/swift_source.rs` assembles these fragments only to build the macOS+# Swift accessibility helper. The production feature set is compiled for Linux+# in this coverage lane, so each fragment's `#[cfg(target_os = "macos")]`+# definition is intentionally absent. They are exercised by the macOS desktop+# E2E matrix instead.+crates/openhuman-core/src/desktop/accessibility/helper/swift_source.rs+crates/openhuman-core/src/desktop/accessibility/helper/swift_focus.rs+crates/openhuman-core/src/desktop/accessibility/helper/swift_paste.rs+crates/openhuman-core/src/desktop/accessibility/helper/swift_ax_actions.rs+crates/openhuman-core/src/desktop/accessibility/helper/swift_overlay.rs