diff --git a/crates/openhuman-cli/Cargo.toml b/crates/openhuman-cli/Cargo.toml index 85ad03e7840..d0f0c424856 100644 --- a/crates/openhuman-cli/Cargo.toml +++ b/crates/openhuman-cli/Cargo.toml @@ -87,6 +87,13 @@ name = "security_native_fixture" path = "../../tests/security_native_fixture.rs" required-features = ["security-module"] +[[test]] +# TinyComputer end to end with its staged release (TS-E2E-010); each test runs +# by exact name after scripts/ci/ts-e2e-stage-modules.sh. +name = "ts_e2e_tinycomputer" +path = "../../tests/ts_e2e_tinycomputer.rs" +required-features = ["security-module"] + [[test]] # TinySecurity from a pinned release (no local-file source) serves later loads. name = "security_release_reuse_fixture" diff --git a/crates/openhuman-core/src/modules/browser_egress_host.rs b/crates/openhuman-core/src/modules/browser_egress_host.rs index f972092b98a..af2c342888c 100644 --- a/crates/openhuman-core/src/modules/browser_egress_host.rs +++ b/crates/openhuman-core/src/modules/browser_egress_host.rs @@ -29,9 +29,32 @@ fn registered_scopes() -> &'static parking_lot::Mutex> { SCOPES.get_or_init(|| parking_lot::Mutex::new(Vec::new())) } -/// Register the browser's destination-only policy from the authenticated host -/// context and return the immutable id and generation for TinyComputer config. +/// The policy id and generation TinyComputer's config names. TinyBus fixes a +/// callback-bound module's config when it loads and refuses any change, while +/// the TinySecurity policy behind it is re-registered every +/// [`BROWSER_POLICY_REFRESH_AFTER`]. So the config carries this stable alias, +/// and each callback maps it to the current policy. +pub(crate) const BROWSER_POLICY_ALIAS: &str = "openhuman-browser-egress"; +pub(crate) const BROWSER_POLICY_ALIAS_GENERATION: u64 = 1; + +/// The `browser.egress` value TinyComputer is loaded and refreshed with. +pub(crate) fn browser_dial_alias() -> Value { + serde_json::json!({ + "policy_id": BROWSER_POLICY_ALIAS, + "generation": BROWSER_POLICY_ALIAS_GENERATION, + }) +} + +/// Make sure the browser's destination-only policy is registered for this +/// host context, then return the stable alias for TinyComputer config. pub(crate) async fn browser_dial_config(config: &crate::config::Config) -> Result { + current_browser_policy(config).await?; + Ok(browser_dial_alias()) +} + +/// The id and generation of the current browser policy, registering a new one +/// when the cached registration is stale. +async fn current_browser_policy(config: &crate::config::Config) -> Result<(String, u64), String> { let client = super::security::client(config) .await .map_err(|error| error.to_string())?; @@ -63,10 +86,7 @@ pub(crate) async fn browser_dial_config(config: &crate::config::Config) -> Resul &privacy_key, std::time::Instant::now(), ) { - return Ok(serde_json::json!({ - "policy_id": id, - "generation": generation, - })); + return Ok((id.to_owned(), generation)); } } let registered_at = std::time::Instant::now(); @@ -105,10 +125,7 @@ pub(crate) async fn browser_dial_config(config: &crate::config::Config) -> Resul if scopes.len() > 64 { scopes.remove(0); } - Ok(serde_json::json!({ - "policy_id": policy_id.0, - "generation": info.generation, - })) + Ok((policy_id.0, info.generation)) } fn find_reusable_policy<'a>( @@ -143,11 +160,8 @@ fn find_reusable_policy<'a>( .map(|(id, generation, ..)| (id.as_str(), *generation)) } -fn is_registered(policy_id: &str, generation: u64) -> bool { - registered_scopes() - .lock() - .iter() - .any(|(id, current, ..)| id == policy_id && *current == generation) +fn is_alias(policy_id: &str, generation: u64) -> bool { + policy_id == BROWSER_POLICY_ALIAS && generation == BROWSER_POLICY_ALIAS_GENERATION } #[derive(Clone)] @@ -193,20 +207,24 @@ impl ConsequenceReviewHost { #[tinybus::interface(name = "ai.tinyhumans.tinycomputer.BrowserEgressHost")] impl BrowserEgressHost { async fn authorize(&self, target: BrowserEgressTarget) -> tinybus::Result { - if !is_registered(&target.policy_id, target.expected_generation) { + if !is_alias(&target.policy_id, target.expected_generation) { return Err(refused()); } let config = crate::core::runtime::DispatchCtx::ambient() .load_config() .await .map_err(|_| refused())?; + let (policy_id, generation) = current_browser_policy(&config).await.map_err(|error| { + tracing::debug!(%error, "[computer] browser egress policy unavailable for a dial"); + refused() + })?; let client = super::security::client(&config) .await .map_err(|_| refused())?; let response = client .authorize_browser_dial(tinysecurity_bus::BrowserDialRequest { - policy_id: tinysecurity_bus::EgressPolicyId(target.policy_id), - expected_generation: target.expected_generation, + policy_id: tinysecurity_bus::EgressPolicyId(policy_id), + expected_generation: generation, session_id: target.session_id, scheme: target.scheme, hostname: target.hostname, @@ -214,7 +232,7 @@ impl BrowserEgressHost { }) .await .map_err(|_| refused())?; - if response.generation != target.expected_generation { + if response.generation != generation { return Err(refused()); } let authorization = response.authorization.ok_or_else(refused)?; @@ -227,8 +245,10 @@ impl BrowserEgressHost { .map(ToString::to_string) .collect(); let authorization = serde_json::to_string(&authorization).map_err(|_| refused())?; + // TinyComputer checks the grant against the generation its config + // names, which is the alias's. Ok(BrowserEgressGrant { - generation: response.generation, + generation: BROWSER_POLICY_ALIAS_GENERATION, authorization, addresses, }) @@ -241,9 +261,10 @@ impl BrowserEgressHost { let client = security_client().await?; let authorization = decode_browser_authorization(&request.authorization)?; let address = request.address.parse().map_err(|_| refused())?; + let request_target = browser_request(request.target, &authorization)?; let allowed = client .consume_browser_dial(tinysecurity_bus::ConsumeBrowserDialRequest { - request: browser_request(request.target), + request: request_target, address, authorization, }) @@ -276,15 +297,24 @@ async fn security_client() -> tinybus::Result { .map_err(|_| refused()) } -fn browser_request(target: BrowserEgressTarget) -> tinysecurity_bus::BrowserDialRequest { - tinysecurity_bus::BrowserDialRequest { - policy_id: tinysecurity_bus::EgressPolicyId(target.policy_id), - expected_generation: target.expected_generation, +/// The TinySecurity request for an aliased target: the policy the grant was +/// issued under, which the authorization records, since the current policy +/// may have rotated since. +fn browser_request( + target: BrowserEgressTarget, + authorization: &tinysecurity_bus::BrowserDialAuthorization, +) -> tinybus::Result { + if !is_alias(&target.policy_id, target.expected_generation) { + return Err(refused()); + } + Ok(tinysecurity_bus::BrowserDialRequest { + policy_id: authorization.policy_id.clone(), + expected_generation: authorization.generation, session_id: target.session_id, scheme: target.scheme, hostname: target.hostname, port: target.port, - } + }) } fn decode_browser_authorization( diff --git a/crates/openhuman-core/src/modules/browser_egress_host_tests.rs b/crates/openhuman-core/src/modules/browser_egress_host_tests.rs index d85e95cfdba..8307e4e3da2 100644 --- a/crates/openhuman-core/src/modules/browser_egress_host_tests.rs +++ b/crates/openhuman-core/src/modules/browser_egress_host_tests.rs @@ -138,3 +138,49 @@ async fn browser_egress_callback_refuses_unknown_host_registered_scope() { .await; assert!(result.is_err()); } + +fn authorization(policy_id: &str, generation: u64) -> tinysecurity_bus::BrowserDialAuthorization { + tinysecurity_bus::BrowserDialAuthorization { + authorization_id: "lease-1".into(), + session_id: "browser-session-test".into(), + scheme: "https".into(), + hostname: "8.8.8.8".into(), + port: 443, + addresses: vec!["8.8.8.8:443".parse().unwrap()], + subject: tinysecurity_bus::SubjectScope { + user: "user-1".into(), + workspace: "workspace-1".into(), + agent: "agent-1".into(), + }, + policy_id: tinysecurity_bus::EgressPolicyId(policy_id.into()), + generation, + expires_at_ms: 1, + } +} + +#[test] +fn the_config_names_a_stable_alias_not_the_rotating_policy() { + // TinyBus fixes TinyComputer's config at load; a policy id in it would + // change at the first re-registration and every refresh would be refused. + let alias = browser_dial_alias(); + assert_eq!(alias["policy_id"], BROWSER_POLICY_ALIAS); + assert_eq!(alias["generation"], BROWSER_POLICY_ALIAS_GENERATION); + assert_eq!(alias, browser_dial_alias()); +} + +#[test] +fn a_consumed_lease_is_checked_against_the_policy_it_was_issued_under() { + let mut aliased = target(BROWSER_POLICY_ALIAS); + aliased.expected_generation = BROWSER_POLICY_ALIAS_GENERATION; + let request = browser_request(aliased, &authorization("policy-real-7", 9)).unwrap(); + assert_eq!(request.policy_id.0, "policy-real-7"); + assert_eq!(request.expected_generation, 9); +} + +#[test] +fn a_target_that_does_not_name_the_alias_is_refused() { + assert!(browser_request(target("policy-real-7"), &authorization("policy-real-7", 9)).is_err()); + let mut stale = target(BROWSER_POLICY_ALIAS); + stale.expected_generation = BROWSER_POLICY_ALIAS_GENERATION + 1; + assert!(browser_request(stale, &authorization("policy-real-7", 9)).is_err()); +} diff --git a/crates/openhuman-core/src/modules/desktop.rs b/crates/openhuman-core/src/modules/desktop.rs index c504ed1e263..8f51f348dee 100644 --- a/crates/openhuman-core/src/modules/desktop.rs +++ b/crates/openhuman-core/src/modules/desktop.rs @@ -92,7 +92,10 @@ pub(crate) async fn proxy(config: &Config) -> Result { .map_err(|error| format!("TinyComputer module proxy unavailable: {error}")) } -fn inject_security_browser_config( +/// Add the security callbacks to TinyComputer's config. The callback-bound +/// load and every refresh in [`proxy`] go through here, so both produce the +/// same bytes and TinyBus accepts the refresh. +pub(super) fn inject_security_browser_config( configuration: &mut serde_json::Value, egress: serde_json::Value, callback_destination: &str, diff --git a/crates/openhuman-core/src/modules/desktop_tests.rs b/crates/openhuman-core/src/modules/desktop_tests.rs index 723475310d7..c4d883da727 100644 --- a/crates/openhuman-core/src/modules/desktop_tests.rs +++ b/crates/openhuman-core/src/modules/desktop_tests.rs @@ -192,3 +192,25 @@ fn registry_and_contract_address_agree() { assert_eq!(record.bus_name, names::INTERFACE); assert_eq!(record.object_path, names::OBJECT_PATH); } + +#[cfg(feature = "security-module")] +#[tokio::test] +async fn the_callback_bound_load_config_is_what_every_refresh_pushes() { + // TS-E2E-010: TinyBus fixes a callback-bound module's config at load and + // refuses a refresh with different bytes ("scoped callback configuration is + // immutable"), so the load config must already carry `browser.egress`. + let dir = tempfile::tempdir().expect("tempdir"); + let config = config_in(dir.path()); + let loaded = crate::modules::ops::computer_callback_config(&config, MODULE_ID, ":1.42").await; + + let mut refreshed = module_config(&config).await; + inject_security_browser_config( + &mut refreshed, + crate::modules::browser_egress_host::browser_dial_alias(), + ":1.42", + ); + + assert_eq!(loaded, refreshed); + assert_eq!(fingerprint(&loaded), fingerprint(&refreshed)); + assert!(loaded["browser"]["egress"].is_object()); +} diff --git a/crates/openhuman-core/src/modules/ops.rs b/crates/openhuman-core/src/modules/ops.rs index c86e3af6603..2aef576296b 100644 --- a/crates/openhuman-core/src/modules/ops.rs +++ b/crates/openhuman-core/src/modules/ops.rs @@ -358,10 +358,25 @@ async fn module_config_with_consequence_callback( config: &Config, id: &str, binding: &tinybus::module::HostCallbackBinding, +) -> serde_json::Value { + computer_callback_config(config, id, binding.unique_name().as_str()).await +} + +/// TinyComputer's config at its callback-bound load: exactly what +/// `desktop::proxy` pushes before each call, since TinyBus refuses a +/// callback-bound module any config that differs from the one it loaded with. +#[cfg(feature = "security-module")] +pub(super) async fn computer_callback_config( + config: &Config, + id: &str, + callback_destination: &str, ) -> serde_json::Value { let mut module_config = module_config(config, id).await; - module_config["consequence_host"] = - serde_json::json!({ "destination": binding.unique_name().as_str() }); + super::desktop::inject_security_browser_config( + &mut module_config, + super::browser_egress_host::browser_dial_alias(), + callback_destination, + ); module_config } diff --git a/scripts/ci/ts-e2e-stage-modules.sh b/scripts/ci/ts-e2e-stage-modules.sh new file mode 100755 index 00000000000..1752fe4a437 --- /dev/null +++ b/scripts/ci/ts-e2e-stage-modules.sh @@ -0,0 +1,101 @@ +#!/usr/bin/env bash +# Stage registry-pinned module releases for the TinySecurity E2E fixtures (TS-E2E X6). +# +# Usage: source scripts/ci/ts-e2e-stage-modules.sh [id,...] +# default ids: tinysecurity,tinycomputer,tinyconnectors,tinybox,tinyflows +# +# Each archive is downloaded from the URL the compiled registry pins, checked +# against its sha256, and laid out the way an installer bundle is +# (`////`, as security-native-fixture.sh does), so +# callback-bound modules load through the shipped release path. +# +# Exports: +# OPENHUMAN_BUNDLED_MODULES the bundle directory +# OPENHUMAN_TS_E2E_MODULES comma list of the ids that can load on this runner +# A Linux module linking a system library the runner lacks (TinyComputer needs +# libxdo and libasound) is left out of OPENHUMAN_TS_E2E_MODULES with a message; +# tests that need it fail with that reason instead of a dlopen error. +# +# Staging runs in a subshell with strict options, so sourcing leaves the +# caller's shell options alone; only the two exports come back. Any failure +# (an unresolvable module, a download or digest error) exports nothing and +# makes `source` return nonzero, with the reason on stderr. + +ts_e2e_stage() ( + set -euo pipefail + ids="${1:-tinysecurity,tinycomputer,tinyconnectors,tinybox,tinyflows}" + cache="${OPENHUMAN_TS_E2E_CACHE:-$HOME/.cache/openhuman-ts-e2e}" + bundled="$cache/bundled" + mkdir -p "$cache" + chmod 700 "$cache" + rm -rf "$bundled" + + host_key="${OH_MODULE_HOST_KEY:-}" + if [ -z "$host_key" ]; then + case "$(uname -s)-$(uname -m)" in + Linux-x86_64) host_key="ubuntu-24.04-x86_64" ;; + Linux-aarch64 | Linux-arm64) host_key="ubuntu-24.04-arm64" ;; + Darwin-arm64) host_key="macos-15-arm64" ;; + Darwin-*) host_key="macos-15-x86_64" ;; + *) echo "ts-e2e: unsupported host $(uname -s) $(uname -m)" >&2; exit 1 ;; + esac + fi + + if ! assets="$(node scripts/ci/self-hosted/test-module-assets.mjs "$host_key" "$ids")"; then + echo "ts-e2e: cannot resolve the release assets of $ids for $host_key" >&2 + exit 1 + fi + if [ -z "$assets" ]; then + echo "ts-e2e: no release assets for $ids on $host_key" >&2 + exit 1 + fi + + loadable="" + while IFS=$'\t' read -r id url archive sha; do + path="$cache/$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(`ts-e2e module digest mismatch for ${file}: expected ${expected}, got ${actual}`); +} +NODE + version="${archive#"$id"-module-}" + version="${version#"$id"-}" + version="${version%%-"$host_key"*}" + dir="$bundled/$id/$version/$host_key" + mkdir -p "$dir" + cp "$path" "$dir/$archive" + tar --no-same-owner -xzf "$dir/$archive" -C "$dir" + if [[ "$(uname -s)" == Linux ]]; then + if ! deps="$(find "$dir" -name '*.so' -exec ldd {} + 2>&1)"; then + echo "ts-e2e: $id $version staged but not loadable here; ldd failed: $deps" >&2 + continue + fi + missing="$(printf '%s\n' "$deps" | awk '/not found/ {print $1}' | sort -u | tr '\n' ' ')" + if [[ -n "$missing" ]]; then + echo "ts-e2e: $id $version staged but not loadable here; runner lacks: $missing" >&2 + continue + fi + fi + echo "ts-e2e: staged $id $version" >&2 + loadable="${loadable:+$loadable,}$id" + done <<< "$assets" + + printf 'export OPENHUMAN_BUNDLED_MODULES=%q\nexport OPENHUMAN_TS_E2E_MODULES=%q\n' "$bundled" "$loadable" +) + +if ts_e2e_exports="$(ts_e2e_stage "$@")"; then + eval "$ts_e2e_exports" + unset -f ts_e2e_stage + unset ts_e2e_exports + echo "ts-e2e: OPENHUMAN_BUNDLED_MODULES=$OPENHUMAN_BUNDLED_MODULES OPENHUMAN_TS_E2E_MODULES=$OPENHUMAN_TS_E2E_MODULES" >&2 +else + unset -f ts_e2e_stage + unset ts_e2e_exports + echo "ts-e2e: staging failed; nothing exported" >&2 + false +fi diff --git a/tests/support/ts_e2e_host.rs b/tests/support/ts_e2e_host.rs new file mode 100644 index 00000000000..d4042ee5739 --- /dev/null +++ b/tests/support/ts_e2e_host.rs @@ -0,0 +1,233 @@ +//! TS-E2E: a desktop core with TinySecurity and the modules the staging +//! script bundled (X6), over an isolated HOME. The same boot as +//! `security_native_fixture.rs#start_desktop_fixture`, kept here so the +//! sandbox and callback suites do not share a file with the H1 tests. + +use openhuman_core::config::Config; +use openhuman_rpc::{ + embed::ServiceSet, + host::{desktop_builder, serve_desktop, DesktopOptions, EmbeddedReadySignal}, +}; +use std::path::{Path, PathBuf}; +use tokio_util::sync::CancellationToken; + +/// Run `future` on a thread with the agent worker's stack, as the core does. +pub fn run_on_agent_stack(name: &str, future_factory: F) +where + F: FnOnce() -> Fut + Send + 'static, + Fut: std::future::Future + Send + 'static, +{ + std::thread::Builder::new() + .name(name.to_owned()) + .stack_size(openhuman_core::core::runtime::AGENT_WORKER_STACK_BYTES) + .spawn(move || { + tokio::runtime::Builder::new_multi_thread() + // Four, not two: CF-3's SB-43 stalled with no further logs, and + // two blocked workers would also stop the test's own timeouts. + .worker_threads(4) + .thread_stack_size(openhuman_core::core::runtime::AGENT_WORKER_STACK_BYTES) + .enable_all() + .build() + .expect("build TS-E2E runtime") + .block_on(future_factory()); + }) + .expect("spawn TS-E2E runtime") + .join() + .expect("TS-E2E test should not panic"); +} + +/// Core logs to stderr (shown with `--nocapture`), filtered by `TS_E2E_LOG`; +/// the sanitized RPC errors hide why a module call failed. +fn init_logging() { + let filter = std::env::var("TS_E2E_LOG") + .unwrap_or_else(|_| "info,openhuman=debug,tinybus=debug,tinybox=debug".to_owned()); + let _ = tracing_subscriber::fmt() + .with_env_filter(tracing_subscriber::EnvFilter::new(filter)) + .with_writer(std::io::stderr) + .try_init(); +} + +/// A served desktop core. Dropping it cancels the server. +pub struct Host { + pub port: u16, + pub home: PathBuf, + pub workspace: PathBuf, + pub action_dir: PathBuf, + pub config: Config, + shutdown: CancellationToken, + server: Option>>, +} + +impl Drop for Host { + fn drop(&mut self) { + self.shutdown.cancel(); + } +} + +impl Host { + /// Boot under `scratch` with modules from the staged bundle. `overlay` + /// edits the config before it is saved and booted. The sandbox follows the + /// config: `OPENHUMAN_SANDBOX` is cleared, unlike H1's `off`. + pub async fn start(scratch: &Path, overlay: impl FnOnce(&mut Config)) -> Self { + Self::start_with_backend(scratch, "http://127.0.0.1:9", overlay).await + } + + /// [`Self::start`] with the TinyHumans backend at `backend_url`, for rows + /// that count what reaches a mock backend. + pub async fn start_with_backend( + scratch: &Path, + backend_url: &str, + overlay: impl FnOnce(&mut Config), + ) -> Self { + super::ts_e2e_modules::use_bundled_modules(); + init_logging(); + let home = scratch.join("home"); + let workspace = scratch.join("workspace"); + let action_dir = scratch.join("action"); + for dir in [&home, &workspace, &action_dir] { + std::fs::create_dir_all(dir).expect("create fixture dir"); + } + std::env::set_var("HOME", &home); + std::env::set_var("OPENHUMAN_WORKSPACE", &workspace); + std::env::set_var("OPENHUMAN_ACTION_DIR", &action_dir); + std::env::set_var("OPENHUMAN_KEYRING_BACKEND", "file"); + // The file keyring and module storage grants need a master key, as + // security-native-fixture.sh gives the callback fixture (CF-2: without + // it tinymcp failed to initialize and auth_set_credential stalled). + // Approve the credential store's keyring prompts, as the renderer would; + // unanswered, a credential save waits on consent (CF-3: auth_set_credential). + if std::env::var_os("OPENHUMAN_TEST_KEYRING_CONSENT").is_none() { + std::env::set_var("OPENHUMAN_TEST_KEYRING_CONSENT", "approve"); + } + if std::env::var_os("OPENHUMAN_KEYRING_MASTER_KEY").is_none() { + std::env::set_var( + "OPENHUMAN_KEYRING_MASTER_KEY", + "7473652d6532652d6d61737465722d6b65792d666f722d746573742d6f6e6c79", + ); + } + std::env::set_var("BACKEND_URL", backend_url); + std::env::remove_var("OPENHUMAN_STORAGE_URL"); + std::env::remove_var("OPENHUMAN_SANDBOX"); + let mut config = Config::default(); + config.modules.enabled = true; + config.autonomy.enabled = false; + config.autonomy.forbidden_paths.clear(); + config.workspace_dir = workspace.clone(); + config.config_path = home.join(".openhuman/config.toml"); + config.action_dir = action_dir.clone(); + config.action_dir_override = Some(action_dir.clone()); + overlay(&mut config); + config.save().await.expect("save fixture config"); + openhuman_core::security::secret_storage::init_workspace(scratch); + + openhuman_rpc::host::prepare_cli_host(); + let port = std::net::TcpListener::bind("127.0.0.1:0") + .expect("reserve ephemeral port") + .local_addr() + .expect("ephemeral address") + .port(); + let options = DesktopOptions { + host: Some("127.0.0.1".into()), + port: Some(port), + socketio: false, + rpc_token: Some(std::sync::Arc::new(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.clone()) + .boot_mode(openhuman_tinyhumans::embed::CoreBootMode::Normal) + .services(services); + let mut server = tokio::spawn(serve_desktop(builder, shutdown.clone(), ready_tx)); + let ready = tokio::select! { + ready = tokio::time::timeout(std::time::Duration::from_secs(120), ready_rx) => match ready + .expect("desktop host ready signal") { + Ok(ready) => ready, + Err(error) => panic!("desktop host dropped ready channel: {error}; task result: {:?}", server.await), + }, + result = &mut server => panic!("desktop host exited before ready: {result:?}"), + }; + Self { + port: ready.port, + home, + workspace, + action_dir, + config, + shutdown, + server: Some(server), + } + } + + /// Shut the host down and wait for its runtime to drop. + pub async fn stop(mut self) { + self.shutdown.cancel(); + if let Some(server) = self.server.take() { + server + .await + .expect("desktop server task") + .expect("desktop server shuts down cleanly"); + } + } + + /// One authenticated JSON-RPC call; returns the whole envelope. + pub async fn rpc(&self, method: &str, params: serde_json::Value) -> serde_json::Value { + reqwest::Client::builder() + .no_proxy() + .timeout(std::time::Duration::from_secs(60)) + .build() + .expect("build RPC client") + .post(format!("http://127.0.0.1:{}/rpc", self.port)) + .bearer_auth(TOKEN) + .json(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":method,"params":params})) + .send() + .await + .unwrap_or_else(|error| panic!("POST {method}: {error}")) + .json() + .await + .expect("JSON-RPC envelope") + } + + /// The `result` of a JSON-RPC envelope, panicking on an error. + pub fn result(envelope: &serde_json::Value) -> &serde_json::Value { + assert!(envelope.get("error").is_none(), "{envelope}"); + let result = &envelope["result"]; + if result.get("logs").is_some() { + &result["result"] + } else { + result + } + } + + /// Every stored audit event name in this host's approval store. + pub async fn audit_events(&self) -> Vec { + let opened = openhuman_core::storage::local::open_async("approval::rows", &self.workspace) + .await + .expect("open the host approval store"); + let storage = opened.scoped().expect("scope the host approval store"); + storage + .documents() + .query("approval_events", &tinystoragedrivers::Query::all()) + .await + .expect("read audit events") + .items + .iter() + .filter_map(|event| event.doc["event"].as_str().map(str::to_owned)) + .collect() + } +} + +pub const TOKEN: &str = "ts-e2e-host-token"; diff --git a/tests/support/ts_e2e_modules.rs b/tests/support/ts_e2e_modules.rs new file mode 100644 index 00000000000..3bb98b4df04 --- /dev/null +++ b/tests/support/ts_e2e_modules.rs @@ -0,0 +1,33 @@ +//! TS-E2E X6: the modules `scripts/ci/ts-e2e-stage-modules.sh` staged as an +//! installer bundle, and the environment a fixture needs to load them the way +//! the shipped app does (bundled release, no local-file module path). + +/// The ids the staging script found loadable on this runner. +pub fn staged() -> Vec { + std::env::var("OPENHUMAN_TS_E2E_MODULES") + .unwrap_or_default() + .split(',') + .filter(|id| !id.is_empty()) + .map(str::to_owned) + .collect() +} + +/// Fail with the reason when `id` was not staged, instead of a later load error. +pub fn require_staged(id: &str) { + let staged = staged(); + assert!( + staged.iter().any(|staged| staged == id), + "TS-E2E: module {id} is not staged on this runner (staged: {staged:?}); \ + run under `source scripts/ci/ts-e2e-stage-modules.sh`" + ); +} + +/// Load modules from the staged bundle only: a local-file module path would +/// bypass the release source that callback-bound modules require. +pub fn use_bundled_modules() { + assert!( + std::env::var_os("OPENHUMAN_BUNDLED_MODULES").is_some(), + "TS-E2E: OPENHUMAN_BUNDLED_MODULES is unset; source scripts/ci/ts-e2e-stage-modules.sh" + ); + std::env::remove_var("OPENHUMAN_MODULE_PATH"); +} diff --git a/tests/ts_e2e_tinycomputer.rs b/tests/ts_e2e_tinycomputer.rs new file mode 100644 index 00000000000..531e2877650 --- /dev/null +++ b/tests/ts_e2e_tinycomputer.rs @@ -0,0 +1,66 @@ +//! TinyComputer end to end in a `security-module` build (TS-E2E-010): the +//! staged TinySecurity and TinyComputer releases, called through +//! `openhuman.modules_computer_status`. Run each test by exact name in its own +//! process after `source scripts/ci/ts-e2e-stage-modules.sh tinysecurity,tinycomputer`. + +#[allow(dead_code)] +#[path = "support/ts_e2e_host.rs"] +mod ts_e2e_host; +#[allow(dead_code)] +#[path = "support/ts_e2e_modules.rs"] +mod ts_e2e_modules; + +use ts_e2e_host::{run_on_agent_stack, Host}; + +/// One TinyComputer member call end to end: load the module and `Describe` +/// it through `desktop::proxy`, which pushes the browser egress config first. +async fn computer_status(host: &Host) -> serde_json::Value { + host.rpc( + "openhuman.modules_computer_status", + serde_json::json!({"load": true}), + ) + .await +} + +/// The status reports a failed load or `Describe` in its own `error` field +/// inside a successful envelope, so only capabilities prove TinyComputer answered. +fn assert_computer_answers(envelope: &serde_json::Value, when: &str) { + let status = Host::result(envelope); + assert!( + status["error"].is_null() && status["capabilities"].is_object(), + "TinyComputer must answer {when}: {envelope}" + ); +} + +/// CB-08: in a `security-module` build, a TinyComputer call succeeds. The +/// predicted gap: the module is loaded callback-bound without +/// `browser.egress`, and tinybus refuses `desktop::proxy`'s reinit with it +/// ("scoped callback configuration is immutable"). +#[test] +#[ignore = "needs the staged TinySecurity and TinyComputer releases (scripts/ci/ts-e2e-stage-modules.sh)"] +fn cb_08_tinycomputer_answers_in_a_security_module_build() { + run_on_agent_stack("cb_08", || async { + ts_e2e_modules::require_staged("tinycomputer"); + let scratch = tempfile::tempdir().expect("scratch"); + let host = Host::start(scratch.path(), |_| {}).await; + assert_computer_answers(&computer_status(&host).await, "a first call"); + assert_computer_answers(&computer_status(&host).await, "a second call"); + host.stop().await; + }); +} + +/// CB-11: TinyComputer keeps answering after its browser egress policy is +/// re-registered (every 25 s), which changes the pushed config again. +#[test] +#[ignore = "needs the staged TinySecurity and TinyComputer releases (scripts/ci/ts-e2e-stage-modules.sh)"] +fn cb_11_tinycomputer_answers_after_the_egress_policy_refreshes() { + run_on_agent_stack("cb_11", || async { + ts_e2e_modules::require_staged("tinycomputer"); + let scratch = tempfile::tempdir().expect("scratch"); + let host = Host::start(scratch.path(), |_| {}).await; + assert_computer_answers(&computer_status(&host).await, "before the refresh"); + tokio::time::sleep(std::time::Duration::from_secs(31)).await; + assert_computer_answers(&computer_status(&host).await, "after the refresh"); + host.stop().await; + }); +}