diff --git a/.env.example b/.env.example index afe5ebb28..8418d1b5a 100644 --- a/.env.example +++ b/.env.example @@ -118,6 +118,8 @@ TINYCOMPUTER_LAB_SELF_EMAIL= # TINYCOMPUTER_LIVE_BROWSER=1 # Compile and run the linked browser egress tests against installed Chromium. # TINYCOMPUTER_LIVE_BROWSER_TESTS=1 -# Compile and run TinyComputer's module-path egress test against installed Chromium +# Compile and run TinyComputer's module-path egress tests against installed Chromium # using only local fixture listeners: +# Run all module-path egress tests, or select the exact-socket test: +# TINYCOMPUTER_LIVE_BROWSER_EGRESS_TESTS=1 cargo test --manifest-path crates/tinycomputer/Cargo.toml -p tinycomputer --lib --features static-link tinybus_module::browser_egress_live_tests -- --nocapture # TINYCOMPUTER_LIVE_BROWSER_EGRESS_TESTS=1 cargo test --manifest-path crates/tinycomputer/Cargo.toml -p tinycomputer --lib --features static-link live_chromium_module_dials_only_the_host_returned_socket_and_rejects_changed_policy -- --nocapture diff --git a/Cargo.toml b/Cargo.toml index 5fbbdf347..fd1bd9a3f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -52,10 +52,11 @@ tinycomputer-accessibility = { path = "crates/tinycomputer-accessibility" } # crate of the vendored `vendor/tinyinference` submodule, pinned by its gitlink # so provider validation and retry behavior are reproducible. Only this crate # of TinyInference is linked into the module. -tinyinference-decisions = { path = "vendor/tinyinference/crates/tinyinference-decisions" } +tinyinference-decisions = { git = "https://github.com/tinyhumansai/tinyinference", rev = "02c01b72f70cd3747304b2a5a696b52a49fdd4fd" } # The optional LLM planner's model client (engine `planner` feature) and the -# lab's author. -tinyinference-llm = { path = "vendor/tinyinference/crates/tinyinference-llm" } +# lab's author. Naming the shared source lets a host workspace redirect it to +# its single TinyInference copy; standalone builds use the local patch below. +tinyinference-llm = { git = "https://github.com/tinyhumansai/tinyinference", rev = "02c01b72f70cd3747304b2a5a696b52a49fdd4fd" } # The browser automation engine, linked as a library: `execute_command` over a # `DaemonState`. Vendored from the tinyhumansai fork until # vercel-labs/agent-browser#2008 lands upstream. @@ -121,6 +122,12 @@ tinybus = { path = "vendor/tinybus/crates/tinybus" } tinybus-macros = { path = "vendor/tinybus/crates/tinybus-macros" } tinybus-module = { path = "vendor/tinybus/crates/tinybus-module" } +[patch."https://github.com/tinyhumansai/tinyinference"] +# Keep standalone TinyComputer builds on the pinned submodule while allowing +# an embedding workspace's top-level patch to provide its shared copy. +tinyinference-decisions = { path = "vendor/tinyinference/crates/tinyinference-decisions" } +tinyinference-llm = { path = "vendor/tinyinference/crates/tinyinference-llm" } + [workspace.lints.rust] unsafe_code = "forbid" missing_docs = "warn" diff --git a/MODULE.md b/MODULE.md index 5cc663bb4..918cba155 100644 --- a/MODULE.md +++ b/MODULE.md @@ -50,6 +50,9 @@ is optional: and requested task reports. Sink mode replaces local trace/session storage and does not fall back to `trace_path`; event errors follow `trace_strict`, and report write errors return a recoverable `TRACE_SINK_FAILED` response; +- `consequence_host`: an object containing only the unique destination prepared + for the confidential `ConsequenceHost` callback. When reviewing an approved + pending action, a missing object, interface, or failed callback declines it; - `jev`: the decision model and its API key, needed by the Jev-driven and task members. `provider` picks it: Jev through `type_safe` (the default), `open_router`, or `tiny_humans_open_router`; `open_jev` (OpenJEV's diff --git a/crates/tinycomputer-accessibility/src/helper.rs b/crates/tinycomputer-accessibility/src/helper.rs index 5f712b4fb..f45da9950 100644 --- a/crates/tinycomputer-accessibility/src/helper.rs +++ b/crates/tinycomputer-accessibility/src/helper.rs @@ -32,11 +32,20 @@ mod swift_source; #[cfg(target_os = "macos")] pub(crate) fn private_cache_dir(name: &str) -> Result { - use std::os::unix::fs::{MetadataExt, PermissionsExt}; - let temp_dir = std::fs::canonicalize(std::env::temp_dir()) .map_err(|error| format!("failed to resolve temporary directory: {error}"))?; - let temp_metadata = std::fs::symlink_metadata(&temp_dir) + private_cache_dir_in(&temp_dir, name) +} + +/// [`private_cache_dir`] under `temp_dir`, an already-resolved directory. +#[cfg(target_os = "macos")] +fn private_cache_dir_in( + temp_dir: &std::path::Path, + name: &str, +) -> Result { + use std::os::unix::fs::{MetadataExt, PermissionsExt}; + + let temp_metadata = std::fs::symlink_metadata(temp_dir) .map_err(|error| format!("failed to inspect temporary directory: {error}"))?; if !temp_metadata.is_dir() || temp_metadata.mode() & 0o077 != 0 diff --git a/crates/tinycomputer-accessibility/src/helper/process.rs b/crates/tinycomputer-accessibility/src/helper/process.rs index 77caef784..cf1d05476 100644 --- a/crates/tinycomputer-accessibility/src/helper/process.rs +++ b/crates/tinycomputer-accessibility/src/helper/process.rs @@ -105,18 +105,35 @@ pub(crate) fn helper_send_receive( } // UNIFIED_HELPER released here — fire-and-forget callers can proceed // Read until the line matches `id` (discards stale lines after a timeout or reordering). - let deadline = Instant::now() + HELPER_RECV_TIMEOUT; + match await_reply(&RESPONSE_RX, &id_str, HELPER_RECV_TIMEOUT)? { + Some(value) => Ok(value), + None => { + reset_helper_process(); + Err(format!( + "helper response timed out waiting for id {id_str} (stale lines may follow)" + )) + } + } +} + +/// Reads lines from the helper's reply channel until one carries `id_str`, +/// discarding blank, stale, and unnumbered lines. `None` when `timeout` +/// passes first. +#[cfg(target_os = "macos")] +fn await_reply( + rx_slot: &StdMutex>>, + id_str: &str, + timeout: Duration, +) -> Result, String> { + let deadline = Instant::now() + timeout; loop { let remaining = deadline.saturating_duration_since(Instant::now()); if remaining.is_zero() { - reset_helper_process(); - return Err(format!( - "helper response timed out waiting for id {id_str} (stale lines may follow)" - )); + return Ok(None); } let chunk = remaining.min(Duration::from_millis(500)); let response_line = { - let rx_guard = RESPONSE_RX + let rx_guard = rx_slot .lock() .map_err(|_| "response rx lock poisoned".to_string())?; let rx = rx_guard @@ -148,9 +165,9 @@ pub(crate) fn helper_send_receive( let matches = value .get("id") .and_then(|v| v.as_str()) - .is_some_and(|rid| rid == id_str.as_str()); + .is_some_and(|rid| rid == id_str); if matches { - return Ok(value); + return Ok(Some(value)); } log::debug!( "[accessibility] discarding helper response with mismatched or missing id (want id={id_str})" @@ -397,3 +414,7 @@ fn ensure_helper_binary() -> Result { Ok(binary_path) } + +#[cfg(test)] +#[path = "process_tests.rs"] +mod tests; diff --git a/crates/tinycomputer-accessibility/src/helper/process_tests.rs b/crates/tinycomputer-accessibility/src/helper/process_tests.rs new file mode 100644 index 000000000..ad11dc099 --- /dev/null +++ b/crates/tinycomputer-accessibility/src/helper/process_tests.rs @@ -0,0 +1,54 @@ +//! The helper reply wait: only the line carrying the request's id answers it. + +#![cfg(target_os = "macos")] +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::sync::{Mutex as StdMutex, mpsc}; +use std::time::Duration; + +use super::await_reply; + +/// A reply channel holding `lines`. Keep the sender alive so an empty +/// channel times out instead of disconnecting. +fn channel( + lines: &[&str], +) -> ( + mpsc::Sender, + StdMutex>>, +) { + let (tx, rx) = mpsc::channel(); + for line in lines { + tx.send((*line).to_owned()).unwrap(); + } + (tx, StdMutex::new(Some(rx))) +} + +#[test] +fn stale_blank_and_unnumbered_lines_are_skipped_until_the_id_matches() { + let (_tx, rx) = channel(&[ + r#"{"id":"6","ok":"stale"}"#, + " ", + r#"{"ok":"no id"}"#, + r#"{"id":"7","ok":"mine"}"#, + ]); + let reply = await_reply(&rx, "7", Duration::from_secs(1)) + .unwrap() + .unwrap(); + assert_eq!(reply["ok"], "mine"); +} + +#[test] +fn no_matching_reply_before_the_timeout_is_none() { + let (_tx, rx) = channel(&[r#"{"id":"6"}"#]); + assert!( + await_reply(&rx, "7", Duration::from_millis(50)) + .unwrap() + .is_none() + ); +} + +#[test] +fn a_reply_that_is_not_json_is_an_error() { + let (_tx, rx) = channel(&["not json"]); + assert!(await_reply(&rx, "7", Duration::from_secs(1)).is_err()); +} diff --git a/crates/tinycomputer-accessibility/src/helper_tests.rs b/crates/tinycomputer-accessibility/src/helper_tests.rs index 85556b863..05b050cc9 100644 --- a/crates/tinycomputer-accessibility/src/helper_tests.rs +++ b/crates/tinycomputer-accessibility/src/helper_tests.rs @@ -1,7 +1,64 @@ -//! Tests for the platform-independent entry points of the Swift helper module. +//! Tests for the platform-independent entry points of the Swift helper module, +//! and the macOS helper cache directory. #[cfg(not(target_os = "macos"))] #[test] fn precompile_entry_point_is_a_noop_off_macos() { super::precompile_helper_background(); } + +#[cfg(target_os = "macos")] +mod cache_dir { + #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + + use std::os::unix::fs::PermissionsExt; + + use super::super::private_cache_dir_in; + + /// A resolved temporary directory private to its owner. + fn private_temp() -> (tempfile::TempDir, std::path::PathBuf) { + let temp = tempfile::tempdir().unwrap(); + let path = std::fs::canonicalize(temp.path()).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o700)).unwrap(); + (temp, path) + } + + fn mode(path: &std::path::Path) -> u32 { + std::fs::metadata(path).unwrap().permissions().mode() & 0o777 + } + + #[test] + fn a_new_cache_dir_is_created_owner_only() { + let (_temp, root) = private_temp(); + let dir = private_cache_dir_in(&root, "helper").unwrap(); + assert_eq!(dir, root.join("helper")); + assert_eq!(mode(&dir), 0o700); + } + + #[test] + fn an_existing_own_cache_dir_is_reused_and_made_owner_only() { + let (_temp, root) = private_temp(); + let existing = root.join("helper"); + std::fs::create_dir(&existing).unwrap(); + std::fs::set_permissions(&existing, std::fs::Permissions::from_mode(0o755)).unwrap(); + assert_eq!(private_cache_dir_in(&root, "helper").unwrap(), existing); + assert_eq!(mode(&existing), 0o700); + } + + #[test] + fn a_symlinked_cache_dir_is_refused() { + let (_temp, root) = private_temp(); + let elsewhere = root.join("elsewhere"); + std::fs::create_dir(&elsewhere).unwrap(); + std::os::unix::fs::symlink(&elsewhere, root.join("helper")).unwrap(); + assert!(private_cache_dir_in(&root, "helper").is_err()); + } + + #[test] + fn a_temp_dir_others_can_write_is_refused() { + let (_temp, root) = private_temp(); + std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o770)).unwrap(); + assert!(private_cache_dir_in(&root, "helper").is_err()); + assert!(!root.join("helper").exists(), "nothing is created there"); + } +} diff --git a/crates/tinycomputer-browser/Cargo.toml b/crates/tinycomputer-browser/Cargo.toml index 92e2e9ef6..0ea198919 100644 --- a/crates/tinycomputer-browser/Cargo.toml +++ b/crates/tinycomputer-browser/Cargo.toml @@ -50,6 +50,9 @@ agent-browser = { workspace = true, optional = true } default = [] # Link agent-browser in-process and provide `AgentBrowser`, its `Launcher`. agent-browser = ["dep:agent-browser"] +# Lets host integration tests substitute the final TCP connector while keeping +# authorization, grant consumption, and proxy forwarding on the production path. +test-connector = [] [dev-dependencies] tokio = { workspace = true, features = ["test-util"] } diff --git a/crates/tinycomputer-browser/src/egress/README.md b/crates/tinycomputer-browser/src/egress/README.md index ecdb599b0..2b4d7e4b3 100644 --- a/crates/tinycomputer-browser/src/egress/README.md +++ b/crates/tinycomputer-browser/src/egress/README.md @@ -6,6 +6,32 @@ the engine adapter (`EgressAuthorizer`) small: the host authorizes the parsed destination, returns a one-use grant and exact socket addresses, consumes a grant before each dial, and revalidates active leases. +Host integration tests can enable the `test-connector` feature and provide +`EgressProxy::bind_with_test_connector` (or the corresponding +`EnforcedAgentBrowser` builder) to replace only the final TCP operation. The +connector receives the exact approved socket after grant consumption. The +TinyComputer module exposes a stricter module-config mapping for dynamic test +artifacts; it accepts one `8.8.8.8:port` to loopback `127.0.0.1:port` mapping +and denies all other sockets. Production builds do not parse that test-only +field. In a `test-connector` build, a host fixture supplies it at +`browser.egress.test_connector_map` as +`{"approved":"8.8.8.8:","fixture":"127.0.0.1:"}`. + +The loaded-module Chromium test is opt-in and is not part of hosted CI, whose +module-e2e lane packages and verifies the artifact without launching Chromium. +With Chromium installed, run the focused test locally with: + +```sh +TINYCOMPUTER_LIVE_BROWSER_EGRESS_TESTS=1 cargo test -p tinycomputer \ + --features static-link,test-connector \ + browser_egress_live_tests::public_connector_tests::loaded_module_consumes_public_socket_before_fixture_mapping \ + -- --nocapture +``` + +It uses a local HTTP listener and the TinyComputer fixture callback host; the +host's real TinySecurity policy composition is covered by the separate +OpenHuman fixture. + ## Structure - `mod.rs` defines the public `BrowserDialTarget`, `DialGrant`, diff --git a/crates/tinycomputer-browser/src/egress/mod.rs b/crates/tinycomputer-browser/src/egress/mod.rs index fc7760fb3..391c914f1 100644 --- a/crates/tinycomputer-browser/src/egress/mod.rs +++ b/crates/tinycomputer-browser/src/egress/mod.rs @@ -15,6 +15,15 @@ mod forward; mod request; mod serve; +/// Fixture-only replacement for the final TCP connect in host integration tests. +/// +/// The callback receives the exact socket selected by authorization and grant +/// consumption. Test connectors should map it to a local fixture only. +#[cfg(feature = "test-connector")] +pub type TestConnector = Arc< + dyn Fn(SocketAddr) -> Pin> + Send>> + Send + Sync, +>; + #[cfg(test)] pub(crate) use serve::connect_approved_addresses; @@ -95,6 +104,45 @@ impl EgressProxy { session_id: String, proxy_password: String, ) -> io::Result { + Self::bind_inner(authorizer, session_id, proxy_password, TcpStream::connect).await + } + + /// Bind the production proxy path with a fixture-only final socket connector. + /// + /// This feature-gated seam is for host integration tests that need to keep + /// policy authorization and one-use grant consumption real while mapping an + /// approved public socket operation onto a local fixture listener. The + /// connector receives the exact socket address after authorization and + /// consumption; it must not make public network connections. + /// + /// # Errors + /// + /// Returns an I/O error when the proxy listener cannot bind or its address + /// cannot be read. + #[cfg(feature = "test-connector")] + pub async fn bind_with_test_connector( + authorizer: Arc, + session_id: String, + proxy_password: String, + connector: C, + ) -> io::Result + where + C: Fn(SocketAddr) -> F + Clone + Send + Sync + 'static, + F: Future> + Send + 'static, + { + Self::bind_inner(authorizer, session_id, proxy_password, connector).await + } + + async fn bind_inner( + authorizer: Arc, + session_id: String, + proxy_password: String, + connector: C, + ) -> io::Result + where + C: Fn(SocketAddr) -> F + Clone + Send + Sync + 'static, + F: Future> + Send + 'static, + { let listener = TcpListener::bind(("127.0.0.1", 0)).await?; let address = listener.local_addr()?; let task = tokio::spawn(async move { @@ -106,8 +154,16 @@ impl EgressProxy { let auth = authorizer.clone(); let session = session_id.clone(); let password = proxy_password.clone(); + let connector = connector.clone(); connections.spawn(async move { - let _ = Box::pin(serve::serve(stream, auth, session, password)).await; + let _ = Box::pin(serve::serve_with_connector( + stream, + auth, + session, + password, + connector, + )) + .await; }); } _ = connections.join_next(), if !connections.is_empty() => {} diff --git a/crates/tinycomputer-browser/src/egress/serve.rs b/crates/tinycomputer-browser/src/egress/serve.rs index 21c718cac..9b33c83c9 100644 --- a/crates/tinycomputer-browser/src/egress/serve.rs +++ b/crates/tinycomputer-browser/src/egress/serve.rs @@ -13,22 +13,6 @@ use super::{ request::{has_valid_buffered_body, read_proxy_request}, }; -pub(super) async fn serve( - client: TcpStream, - auth: Arc, - session_id: String, - proxy_password: String, -) -> io::Result<()> { - Box::pin(serve_with_connector( - client, - auth, - session_id, - proxy_password, - TcpStream::connect, - )) - .await -} - pub(super) async fn serve_with_connector( mut client: TcpStream, auth: Arc, diff --git a/crates/tinycomputer-browser/src/lib.rs b/crates/tinycomputer-browser/src/lib.rs index 4786da69a..da43d7a3a 100644 --- a/crates/tinycomputer-browser/src/lib.rs +++ b/crates/tinycomputer-browser/src/lib.rs @@ -57,6 +57,8 @@ pub use action_gate::{ ActionContext, ActionGate, ActionRequest, ActionTarget, ActionVerdict, AllowAllActions, ObservationKind, }; +#[cfg(feature = "test-connector")] +pub use egress::TestConnector; pub use egress::{BrowserDialTarget, DialGrant, EgressAuthorizer, EgressProxy}; pub use engine::{Engine, Launcher, Reply}; pub use error::{Error, Result}; diff --git a/crates/tinycomputer-browser/src/linked/linked_tests.rs b/crates/tinycomputer-browser/src/linked/linked_tests.rs index f5197bde4..833f2b27f 100644 --- a/crates/tinycomputer-browser/src/linked/linked_tests.rs +++ b/crates/tinycomputer-browser/src/linked/linked_tests.rs @@ -75,6 +75,26 @@ async fn enforced_launcher_creates_a_private_session_without_implicit_launch() { ); } +#[tokio::test] +async fn enforced_launcher_binds_its_proxy_on_loopback_before_launch() { + let linked = Linked { + state: DaemonState::with_options(state_options("proxy-bind")), + egress_authorizer: Some(Arc::new(RejectAll)), + proxy: None, + proxy_session_id: "private-session-id".into(), + enforced_launch: false, + #[cfg(feature = "test-connector")] + test_connector: None, + }; + + let proxy = linked + .bind_egress_proxy(Arc::new(RejectAll)) + .await + .expect("the local egress proxy binds without opening a browser"); + + assert!(proxy.url().starts_with("http://127.0.0.1:")); +} + #[tokio::test] async fn enforced_browser_refuses_implicit_launch_before_any_request() { let mut engine = EnforcedAgentBrowser::new(Arc::new(RejectAll)).open("unit"); @@ -93,6 +113,8 @@ async fn a_closed_or_lost_browser_cannot_implicitly_launch_without_the_proxy() { proxy: None, proxy_session_id: "private-session-id".into(), enforced_launch: true, + #[cfg(feature = "test-connector")] + test_connector: None, }; let reply = engine .execute(json!({"id":"navigate","action":"navigate","url":"http://public.example/"})) @@ -114,6 +136,8 @@ async fn an_exited_enforced_browser_can_still_be_closed() { proxy: None, proxy_session_id: "private-session-id".into(), enforced_launch: true, + #[cfg(feature = "test-connector")] + test_connector: None, }; let reply = engine.execute(json!({"id":"close","action":"close"})).await; @@ -131,6 +155,8 @@ async fn enforced_browser_refuses_process_side_reads_with_a_url() { proxy: None, proxy_session_id: "private-session-id".into(), enforced_launch: true, + #[cfg(feature = "test-connector")] + test_connector: None, }; let reply = engine .execute(json!({ @@ -156,6 +182,8 @@ async fn enforced_browser_rechecks_liveness_after_waiting_for_engine_lock() { proxy: None, proxy_session_id: "private-session-id".into(), enforced_launch: true, + #[cfg(feature = "test-connector")] + test_connector: None, }; let serialized = ENGINE.lock().await; let pending = tokio::spawn(async move { diff --git a/crates/tinycomputer-browser/src/linked/linked_tests/live_tests.rs b/crates/tinycomputer-browser/src/linked/linked_tests/live_tests.rs index 6a43e4705..2a6d9d219 100644 --- a/crates/tinycomputer-browser/src/linked/linked_tests/live_tests.rs +++ b/crates/tinycomputer-browser/src/linked/linked_tests/live_tests.rs @@ -66,6 +66,51 @@ async fn live_chromium_loopback_navigation_uses_the_authenticated_session_proxy( server.await.unwrap(); } +#[tokio::test] +#[cfg(live_browser_tests)] +async fn live_chromium_dials_only_the_exact_host_authorized_socket() { + let allowed = TcpListener::bind("127.0.0.2:0").await.unwrap(); + let allowed_address = allowed.local_addr().unwrap(); + let denied = std::net::TcpListener::bind(("127.0.0.1", allowed_address.port())).unwrap(); + denied.set_nonblocking(true).unwrap(); + + let allowed_server = tokio::spawn(async move { + let (mut socket, _) = allowed.accept().await.unwrap(); + let mut request = [0; 4096]; + let _ = socket.read(&mut request).await.unwrap(); + socket + .write_all( + b"HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: 30\r\nConnection: close\r\n\r\n

pinned socket fixture

", + ) + .await + .unwrap(); + }); + let mut browser = EnforcedAgentBrowser::new(Arc::new(AuthorizeExactSocket(allowed_address))) + .open("live-egress-socket-pinning"); + let launch = browser + .execute(json!({"id":"launch","action":"launch","headless":true,"args":[]})) + .await; + assert_eq!(launch["success"], true, "{launch}"); + let navigation = browser + .execute(json!({ + "id":"navigate", + "action":"navigate", + "url":format!("http://127.0.0.1:{}/", allowed_address.port()) + })) + .await; + browser + .execute(json!({"id":"close","action":"close"})) + .await; + + assert_eq!(navigation["success"], true, "{navigation}"); + allowed_server.await.unwrap(); + assert_eq!( + denied.accept().unwrap_err().kind(), + io::ErrorKind::WouldBlock, + "Chromium must reach only the exact socket returned by the host grant" + ); +} + #[tokio::test] #[cfg(live_browser_tests)] async fn live_chromium_subresource_never_reaches_a_denied_destination() { @@ -474,6 +519,48 @@ struct RejectAllButFixture { denied_targets: Arc>>, } +#[cfg(live_browser_tests)] +#[derive(Debug)] +struct AuthorizeExactSocket(SocketAddr); + +#[cfg(live_browser_tests)] +impl EgressAuthorizer for AuthorizeExactSocket { + fn authorize( + &self, + _: BrowserDialTarget, + ) -> std::pin::Pin> + Send>> { + let address = self.0; + Box::pin(async move { + Ok(DialGrant { + lease: "live-pinned-socket-lease".into(), + addresses: vec![address], + }) + }) + } + + fn consume( + &self, + _: BrowserDialTarget, + grant: DialGrant, + address: SocketAddr, + ) -> std::pin::Pin> + Send>> { + Box::pin(async move { + if grant.addresses.contains(&address) { + Ok(()) + } else { + Err(io::Error::new(io::ErrorKind::PermissionDenied, "denied")) + } + }) + } + + fn validate( + &self, + _: String, + ) -> std::pin::Pin> + Send>> { + Box::pin(async { Ok(true) }) + } +} + #[cfg(live_browser_tests)] #[derive(Debug)] struct RebindingAuthorizer { diff --git a/crates/tinycomputer-browser/src/linked/mod.rs b/crates/tinycomputer-browser/src/linked/mod.rs index 191ec8419..9502fa2c5 100644 --- a/crates/tinycomputer-browser/src/linked/mod.rs +++ b/crates/tinycomputer-browser/src/linked/mod.rs @@ -30,6 +30,8 @@ pub struct AgentBrowser; #[derive(Clone)] pub struct EnforcedAgentBrowser { authorizer: Arc, + #[cfg(feature = "test-connector")] + test_connector: Option, } impl std::fmt::Debug for EnforcedAgentBrowser { @@ -42,7 +44,23 @@ impl EnforcedAgentBrowser { /// Use the authenticated host callback for every launched session. #[must_use] pub fn new(authorizer: Arc) -> Self { - Self { authorizer } + Self { + authorizer, + #[cfg(feature = "test-connector")] + test_connector: None, + } + } + + /// Replace only the final TCP connect for a fixture-backed host test. + /// + /// Authorization, grant consumption, and proxy forwarding remain on their + /// normal paths. The fixture connector receives the exact approved socket + /// and must map it to a local listener rather than public network access. + #[cfg(feature = "test-connector")] + #[must_use] + pub fn with_test_connector(mut self, connector: crate::egress::TestConnector) -> Self { + self.test_connector = Some(connector); + self } } @@ -54,6 +72,8 @@ impl Launcher for AgentBrowser { proxy: None, proxy_session_id: String::new(), enforced_launch: false, + #[cfg(feature = "test-connector")] + test_connector: None, }) } } @@ -66,6 +86,8 @@ impl Launcher for EnforcedAgentBrowser { proxy: None, proxy_session_id: private_session_id(), enforced_launch: false, + #[cfg(feature = "test-connector")] + test_connector: self.test_connector.clone(), }) } } @@ -76,6 +98,32 @@ struct Linked { proxy: Option, proxy_session_id: String, enforced_launch: bool, + #[cfg(feature = "test-connector")] + test_connector: Option, +} + +impl Linked { + async fn bind_egress_proxy( + &self, + authorizer: Arc, + ) -> std::io::Result { + #[cfg(feature = "test-connector")] + if let Some(connector) = self.test_connector.clone() { + return EgressProxy::bind_with_test_connector( + authorizer, + self.proxy_session_id.clone(), + self.proxy_session_id.clone(), + move |address| connector(address), + ) + .await; + } + EgressProxy::bind( + authorizer, + self.proxy_session_id.clone(), + self.proxy_session_id.clone(), + ) + .await + } } impl Engine for Linked { @@ -97,13 +145,7 @@ impl Engine for Linked { return failure_reply(&command, "network policy has no host authorizer"); }; if self.proxy.is_none() { - match EgressProxy::bind( - authorizer, - self.proxy_session_id.clone(), - self.proxy_session_id.clone(), - ) - .await - { + match self.bind_egress_proxy(authorizer).await { Ok(proxy) => self.proxy = Some(proxy), Err(_) => { return failure_reply(&command, "network policy proxy could not start"); diff --git a/crates/tinycomputer-browser/src/reply/mod.rs b/crates/tinycomputer-browser/src/reply/mod.rs index 2eaeb95c1..ba633429d 100644 --- a/crates/tinycomputer-browser/src/reply/mod.rs +++ b/crates/tinycomputer-browser/src/reply/mod.rs @@ -44,6 +44,11 @@ pub(crate) fn classify(message: &str) -> Error { reference: message.to_owned(), }; } + // A script error carries text the page controls, so it is classified + // before any keyword below can read that text as a timeout or a refusal. + if lower.starts_with("evaluation error") { + return Error::page(message); + } if lower.contains("is not in the allowed domains list") { return Error::BlockedByPolicy { url: quoted(message).unwrap_or(message).to_owned(), @@ -93,9 +98,6 @@ pub(crate) fn classify(message: &str) -> Error { if lower.contains("dialog is blocking the page") { return Error::not_actionable(message); } - if lower.starts_with("evaluation error") { - return Error::page(message); - } Error::failed(message) } diff --git a/crates/tinycomputer-browser/src/reply/reply_tests.rs b/crates/tinycomputer-browser/src/reply/reply_tests.rs index 60ee68164..acd6089b3 100644 --- a/crates/tinycomputer-browser/src/reply/reply_tests.rs +++ b/crates/tinycomputer-browser/src/reply/reply_tests.rs @@ -113,6 +113,23 @@ fn engine_messages_map_to_what_the_caller_should_do() { } } +#[test] +fn page_script_error_text_cannot_change_the_error_class() { + for message in [ + "Evaluation error: TimeoutError: slow", + "Evaluation error: Error: Domain 'x' is not in the allowed domains list", + "Evaluation error: Error: Element not found: #pay", + "Evaluation error: Error: Browser not launched", + "Evaluation error: Error: Invalid URL: nope", + ] { + let error = classify(message); + assert!( + matches!(error, Error::PageError { .. }), + "{message} became {error:?}" + ); + } +} + #[test] fn a_snapshot_lists_refs_in_document_order_and_caps_the_tree() { let reply = json!({ diff --git a/crates/tinycomputer-browser/tests/test_connector_tests.rs b/crates/tinycomputer-browser/tests/test_connector_tests.rs new file mode 100644 index 000000000..cbc83dd55 --- /dev/null +++ b/crates/tinycomputer-browser/tests/test_connector_tests.rs @@ -0,0 +1,156 @@ +//! Feature-gated integration tests for host-provided fixture connectors. +#![cfg(feature = "test-connector")] +#![allow(clippy::expect_used, clippy::panic, clippy::unwrap_used)] + +use std::{ + future::Future, + io, + net::SocketAddr, + pin::Pin, + sync::{Arc, Mutex}, +}; + +use base64::Engine as _; +use tinycomputer_browser::{BrowserDialTarget, DialGrant, EgressAuthorizer, EgressProxy}; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + net::{TcpListener, TcpStream}, +}; + +const SESSION: &str = "fixture-public-dial-session"; +const PASSWORD: &str = "fixture-proxy-secret"; + +struct ExactPublicGrant { + address: SocketAddr, + calls: Arc>>, +} + +impl EgressAuthorizer for ExactPublicGrant { + fn authorize( + &self, + target: BrowserDialTarget, + ) -> Pin> + Send>> { + let address = self.address; + let calls = self.calls.clone(); + Box::pin(async move { + assert_eq!(target.hostname, "8.8.8.8"); + assert_eq!(target.port, address.port()); + calls.lock().unwrap().push(format!("authorize:{address}")); + Ok(DialGrant { + lease: "fixture-only-lease".into(), + addresses: vec![address], + }) + }) + } + + fn consume( + &self, + target: BrowserDialTarget, + grant: DialGrant, + address: SocketAddr, + ) -> Pin> + Send>> { + let expected = self.address; + let calls = self.calls.clone(); + Box::pin(async move { + assert_eq!(target.hostname, "8.8.8.8"); + assert_eq!(address, expected); + assert_eq!(grant.addresses, [expected]); + calls.lock().unwrap().push(format!("consume:{address}")); + Ok(()) + }) + } + + fn validate(&self, lease: String) -> Pin> + Send>> { + Box::pin(async move { Ok(lease == "fixture-only-lease") }) + } +} + +#[tokio::test] +async fn proxy_consumes_the_exact_public_grant_before_fixture_connector_mapping() { + let fixture_listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let fixture_address = fixture_listener.local_addr().unwrap(); + let granted_address = SocketAddr::from(([8, 8, 8, 8], fixture_address.port())); + let calls = Arc::new(Mutex::new(Vec::new())); + let connector_calls = calls.clone(); + let auth: Arc = Arc::new(ExactPublicGrant { + address: granted_address, + calls: calls.clone(), + }); + + let proxy = EgressProxy::bind_with_test_connector( + auth, + SESSION.into(), + PASSWORD.into(), + move |address| { + let fixture_address = fixture_address; + let calls = connector_calls.clone(); + Box::pin(async move { + // The fixture mapper observes the authorized public socket but + // deliberately connects only to its local listener. + assert_eq!(address, granted_address); + calls.lock().unwrap().push(format!("connect:{address}")); + TcpStream::connect(fixture_address).await + }) + }, + ) + .await + .unwrap(); + + let fixture = tokio::spawn(async move { + let (mut stream, _) = + tokio::time::timeout(std::time::Duration::from_secs(5), fixture_listener.accept()) + .await + .expect("fixture connector reaches the local listener") + .unwrap(); + let mut request = vec![0; 2048]; + let read = stream.read(&mut request).await.unwrap(); + let request = String::from_utf8_lossy(&request[..read]); + assert!(request.starts_with("GET /control HTTP/1.1\r\n")); + assert!(request.contains(&format!("Host: 8.8.8.8:{}\r\n", fixture_address.port()))); + stream + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 7\r\nConnection: close\r\n\r\nfixture") + .await + .unwrap(); + }); + + let mut client = TcpStream::connect(proxy.url().replace("http://", "")) + .await + .unwrap(); + let auth = base64::engine::general_purpose::STANDARD.encode(format!("tinycomputer:{PASSWORD}")); + client + .write_all( + format!( + "GET http://8.8.8.8:{}/control HTTP/1.1\r\nHost: 8.8.8.8:{}\r\nProxy-Authorization: Basic {auth}\r\nConnection: close\r\n\r\n", + granted_address.port(), + granted_address.port(), + ) + .as_bytes(), + ) + .await + .unwrap(); + let mut response = Vec::new(); + tokio::time::timeout( + std::time::Duration::from_secs(5), + client.read_to_end(&mut response), + ) + .await + .expect("the proxy forwards and closes the fixture response") + .unwrap(); + let response = String::from_utf8_lossy(&response); + assert!( + response.starts_with("HTTP/1.1 200 OK\r\n"), + "unexpected proxy response {response:?}; calls {:?}", + calls.lock().unwrap() + ); + assert!(response.ends_with("fixture")); + fixture.await.unwrap(); + assert_eq!( + *calls.lock().unwrap(), + [ + format!("authorize:{granted_address}"), + format!("consume:{granted_address}"), + format!("connect:{granted_address}"), + ], + "authorization and one-use consumption must precede the fixture-only connector" + ); +} diff --git a/crates/tinycomputer-bus/README.md b/crates/tinycomputer-bus/README.md index 88bf0d96f..f97a3cc78 100644 --- a/crates/tinycomputer-bus/README.md +++ b/crates/tinycomputer-bus/README.md @@ -190,3 +190,9 @@ distinguish causal re-entry from unrelated concurrent work. Event and artifact acknowledgements are bounded by the engine's operation deadline; report calls have a ten-second transport timeout. A host that does not opt in keeps the existing desktop file/session trace behavior. + +Contract 2.27 adds an opaque host context to `ContinueTask` and relays it +unchanged to `ConsequenceHost.Review`. TinyComputer does not interpret the +context or grant it authority; hosts can use it to recover trusted caller +context while reviewing an approval. Hosts that depend on this relay must +reject modules older than 2.27. diff --git a/crates/tinycomputer-bus/src/agent/agent_tests.rs b/crates/tinycomputer-bus/src/agent/agent_tests.rs index fe2e40e21..a4d745c64 100644 --- a/crates/tinycomputer-bus/src/agent/agent_tests.rs +++ b/crates/tinycomputer-bus/src/agent/agent_tests.rs @@ -281,18 +281,57 @@ fn waiting_and_continuing_have_forgiving_defaults() { assert_eq!(resume.id.to_string(), "t-1"); assert_eq!(resume.inputs["date of birth"], "1990-04-02"); assert_eq!(resume.approve, None); + assert_eq!(resume.host_context, None); + assert!( + serde_json::to_value(&resume) + .unwrap() + .get("host_context") + .is_none() + ); let private: ContinueTaskRequest = serde_json::from_value(json!({ "id": "t-2", + "host_context": "opaque-context", "fact_handles": { "email": {"handle": "opaque-email", "mask": "‹email›", "kind": "asked_input"} } })) .unwrap(); assert_eq!(private.fact_handles["email"].handle, "opaque-email"); + assert_eq!( + private + .host_context + .as_ref() + .map(super::HostContext::as_str), + Some("opaque-context") + ); let wire = serde_json::to_value(private).unwrap(); assert_eq!(wire["fact_handles"]["email"]["mask"], "‹email›"); assert_eq!(wire["inputs"], json!({})); + assert_eq!(wire["host_context"], "opaque-context"); +} + +#[test] +fn host_context_debug_output_hides_the_opaque_value() { + let context = super::HostContext::new("secret-capability"); + assert!(!format!("{context:?}").contains("secret-capability")); +} + +#[test] +fn a_do_turn_limit_pins_its_wire_form() { + let request: StartTaskRequest = serde_json::from_value(json!({ + "task": "buy a pack of dried fruit", + "budget": {"max_do_turns": 16} + })) + .unwrap(); + assert_eq!(request.budget.max_do_turns, Some(16)); + assert_eq!( + serde_json::to_value(request.budget).unwrap()["max_do_turns"], + 16 + ); + let unset: StartTaskRequest = + serde_json::from_value(json!({"task": "buy a pack of dried fruit"})).unwrap(); + assert_eq!(unset.budget.max_do_turns, None); } #[test] diff --git a/crates/tinycomputer-bus/src/agent/mod.rs b/crates/tinycomputer-bus/src/agent/mod.rs index 30329d65e..ab8c2e5e2 100644 --- a/crates/tinycomputer-bus/src/agent/mod.rs +++ b/crates/tinycomputer-bus/src/agent/mod.rs @@ -52,8 +52,8 @@ mod types; pub use types::{ AgentError, AgentResponse, AwaitTaskRequest, Capabilities, ContinueTaskRequest, Example, - InputField, InputKind, LanguageModelConfiguration, LanguageModelProvider, MemberDoc, - ModelUsage, PaymentMode, PlanTaskRequest, Rescue, RescueOutcome, SecretHandle, + HostContext, InputField, InputKind, LanguageModelConfiguration, LanguageModelProvider, + MemberDoc, ModelUsage, PaymentMode, PlanTaskRequest, Rescue, RescueOutcome, SecretHandle, StartTaskRequest, StepView, SurfaceAvailability, SurfaceKind, TaskBudget, TaskConstraints, TaskId, TaskOutput, TaskPlan, TaskRef, TaskReport, TaskReportRequest, TaskStatus, TaskUsage, TaskView, diff --git a/crates/tinycomputer-bus/src/agent/types/mod.rs b/crates/tinycomputer-bus/src/agent/types/mod.rs index a3c8f70e3..bcb920f2d 100644 --- a/crates/tinycomputer-bus/src/agent/types/mod.rs +++ b/crates/tinycomputer-bus/src/agent/types/mod.rs @@ -13,7 +13,7 @@ pub use models::{LanguageModelConfiguration, LanguageModelProvider}; pub use reply::{AgentError, AgentResponse}; pub use report::{Rescue, RescueOutcome, TaskReport}; pub use request::{ - AwaitTaskRequest, ContinueTaskRequest, PaymentMode, PlanTaskRequest, SecretHandle, + AwaitTaskRequest, ContinueTaskRequest, HostContext, PaymentMode, PlanTaskRequest, SecretHandle, StartTaskRequest, SurfaceKind, TaskBudget, TaskConstraints, TaskId, TaskOutput, TaskPlan, TaskRef, TaskReportRequest, }; diff --git a/crates/tinycomputer-bus/src/agent/types/request.rs b/crates/tinycomputer-bus/src/agent/types/request.rs index 83cd9d4a8..5daac815c 100644 --- a/crates/tinycomputer-bus/src/agent/types/request.rs +++ b/crates/tinycomputer-bus/src/agent/types/request.rs @@ -120,6 +120,33 @@ impl std::fmt::Debug for SecretHandle { } } +/// Opaque, host-issued context carried from a task continuation to a +/// `ConsequenceHost` review. The module must relay it unchanged and never +/// treat it as authorization. Debug output deliberately hides the value. +#[derive(Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(transparent)] +pub struct HostContext(String); + +impl HostContext { + /// Wraps a host-issued opaque context value. + #[must_use] + pub fn new(value: impl Into) -> Self { + Self(value.into()) + } + + /// Returns the opaque value for host-side lookup. + #[must_use] + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl std::fmt::Debug for HostContext { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str("HostContext([opaque])") + } +} + /// What a finished task returns, beyond its raw records. /// /// The result is always a JSON object. `schema` is a JSON Schema it must @@ -206,6 +233,9 @@ pub struct TaskBudget { /// How many ways each decision is asked before its answers are averaged; /// the module's default when unset. pub votes: Option, + /// Turns each `do` step may spend before it fails as not accomplished; + /// the module's default (8) when unset, at most 32. + pub max_do_turns: Option, /// How each flow run asks its decisions; the narrow strategy when unset. pub strategy: Option, /// How much each flow run deliberates before acting; the deep level @@ -251,6 +281,10 @@ pub struct ContinueTaskRequest { /// The decision on a `needs_approval` pause, or `true` to go past a /// non-payment `checkpoint`. pub approve: Option, + /// Opaque host-issued context for reviewing this continuation. The module + /// carries it to `ConsequenceHost` without interpreting or authorizing it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub host_context: Option, /// A free-text answer, for a pause that asked a question — or, for /// `needs_human`, `"done"` once the person has finished. pub answer: Option, diff --git a/crates/tinycomputer-bus/src/consequence_host/consequence_host_tests.rs b/crates/tinycomputer-bus/src/consequence_host/consequence_host_tests.rs index 7a341a290..520cb819c 100644 --- a/crates/tinycomputer-bus/src/consequence_host/consequence_host_tests.rs +++ b/crates/tinycomputer-bus/src/consequence_host/consequence_host_tests.rs @@ -15,14 +15,29 @@ fn the_interface_is_its_own_not_the_desktop_or_site_memory_one() { #[test] fn a_review_request_keeps_its_wire_form() { let request: ReviewActionRequest = serde_json::from_value(serde_json::json!({ - "task": "t1", "action": "pay now", "target": "Pay", "kind": "payment" + "task": "t1", "action": "pay now", "target": "Pay", "kind": "payment", + "host_context": "opaque-context" })) .unwrap(); assert_eq!(request.kind, ConsequenceKind::Payment); + assert_eq!( + request + .host_context + .as_ref() + .map(crate::agent::HostContext::as_str), + Some("opaque-context") + ); let json = serde_json::to_value(&request).unwrap(); assert_eq!(json["kind"], "payment"); + assert_eq!(json["host_context"], "opaque-context"); let irreversible = serde_json::to_value(ConsequenceKind::Irreversible).unwrap(); assert_eq!(irreversible, "irreversible"); + + let legacy: ReviewActionRequest = serde_json::from_value(serde_json::json!({ + "task": "t2", "action": "send", "target": "Send", "kind": "irreversible" + })) + .unwrap(); + assert_eq!(legacy.host_context, None); } #[test] diff --git a/crates/tinycomputer-bus/src/consequence_host/mod.rs b/crates/tinycomputer-bus/src/consequence_host/mod.rs index ec2491e80..46aa9a6ef 100644 --- a/crates/tinycomputer-bus/src/consequence_host/mod.rs +++ b/crates/tinycomputer-bus/src/consequence_host/mod.rs @@ -21,6 +21,8 @@ use serde::{Deserialize, Serialize}; +use crate::agent::HostContext; + /// The interface the host serves consequence review on. pub const INTERFACE: &str = "ai.tinyhumans.tinycomputer.ConsequenceHost"; @@ -58,6 +60,10 @@ pub struct ReviewActionRequest { pub target: String, /// What the module classified the action as. pub kind: ConsequenceKind, + /// Opaque host-issued context from the `ContinueTask` request. The module + /// relays this value unchanged and grants it no authority. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub host_context: Option, } /// The reply to `Review`. diff --git a/crates/tinycomputer-bus/src/flow/flow_tests.rs b/crates/tinycomputer-bus/src/flow/flow_tests.rs index 4a13b3f19..a148f0603 100644 --- a/crates/tinycomputer-bus/src/flow/flow_tests.rs +++ b/crates/tinycomputer-bus/src/flow/flow_tests.rs @@ -204,6 +204,24 @@ fn a_brief_pins_its_wire_form_and_defaults_empty() { })) .unwrap(); assert_eq!((request.votes, request.brief.goal.as_str()), (3, "g")); + assert_eq!( + request.max_do_turns, None, + "unset keeps the module's default" + ); + assert!( + serde_json::to_value(&request) + .unwrap() + .get("max_do_turns") + .is_none(), + "an unset turn limit is left off the wire" + ); + let request: RunFlowRequest = serde_json::from_value(json!({ + "flow": {"app": "Mail", "steps": ["x"]}, + "max_do_turns": 12 + })) + .unwrap(); + assert_eq!(request.max_do_turns, Some(12)); + assert_eq!(serde_json::to_value(&request).unwrap()["max_do_turns"], 12); for (flow_loop, wire) in [ (FlowLoop::Vote, "vote"), (FlowLoop::PageKind, "page_kind"), diff --git a/crates/tinycomputer-bus/src/flow/types/request.rs b/crates/tinycomputer-bus/src/flow/types/request.rs index 2e24025ea..cfea954e1 100644 --- a/crates/tinycomputer-bus/src/flow/types/request.rs +++ b/crates/tinycomputer-bus/src/flow/types/request.rs @@ -196,6 +196,11 @@ pub struct RunFlowRequest { /// answers are averaged: 1 asks once. Jev calls are cheap, so accuracy /// is bought with more of them. Capped by the module at 9. pub votes: u32, + /// Turns a `do` step may spend before it fails as not accomplished; the + /// module's default (8) when unset, capped by the module at 32. A shop's + /// checkout can need more moves in one step than a desktop app does. + #[serde(skip_serializing_if = "Option::is_none")] + pub max_do_turns: Option, /// Who the run is for and what it is after, shown to Jev with every /// question so each small decision is made knowing the whole task. pub brief: FlowBrief, @@ -241,6 +246,7 @@ impl Default for RunFlowRequest { max_actions: 60, max_model_calls: 3000, votes: 7, + max_do_turns: None, brief: FlowBrief::default(), disabled_loops: Vec::new(), memory: Vec::new(), diff --git a/crates/tinycomputer-bus/src/version/mod.rs b/crates/tinycomputer-bus/src/version/mod.rs index 841c92b62..cf33c202b 100644 --- a/crates/tinycomputer-bus/src/version/mod.rs +++ b/crates/tinycomputer-bus/src/version/mod.rs @@ -8,7 +8,7 @@ //! release workflow bumps, which tracks the shipped artifact. /// The wire contract version this crate defines. -pub const CONTRACT_VERSION: (u32, u32) = (2, 26); +pub const CONTRACT_VERSION: (u32, u32) = (2, 28); /// Returns whether a host holding [`CONTRACT_VERSION`] can bind to a module /// reporting `module`. @@ -22,7 +22,7 @@ pub const CONTRACT_VERSION: (u32, u32) = (2, 26); /// ``` /// # use tinycomputer_bus::{is_compatible, CONTRACT_VERSION}; /// assert!(is_compatible(CONTRACT_VERSION)); -/// assert!(is_compatible((2, 26))); +/// assert!(is_compatible((2, 28))); /// assert!(!is_compatible((2, 11))); /// assert!(!is_compatible((1, 8))); /// ``` diff --git a/crates/tinycomputer-bus/src/version/version_tests.rs b/crates/tinycomputer-bus/src/version/version_tests.rs index e813ad574..e25ea5aca 100644 --- a/crates/tinycomputer-bus/src/version/version_tests.rs +++ b/crates/tinycomputer-bus/src/version/version_tests.rs @@ -6,7 +6,7 @@ use super::{CONTRACT_VERSION, binds, is_compatible}; #[test] fn the_shipped_contract_version_is_pinned() { - assert_eq!(CONTRACT_VERSION, (2, 26)); + assert_eq!(CONTRACT_VERSION, (2, 28)); } #[test] @@ -16,7 +16,7 @@ fn the_contract_binds_to_itself() { #[test] fn a_newer_minor_on_the_module_side_binds() { - assert!(is_compatible((2, 26))); + assert!(is_compatible((2, 28))); assert!(is_compatible((2, 97))); // 2.24 adds same-task flow-to-planner handoff to StartTask. // 2.22 adds optional host-held secret handles to StartTask and RunFlow. @@ -42,6 +42,12 @@ fn a_newer_minor_on_the_module_side_binds() { // 2.20 adds SessionOptions identity fields. // 2.25 adds BrowserEgressHost. // 2.26 adds TraceSinkHost, so a 2.25 module lacks that callback. + // 2.27 relays opaque host context to ConsequenceHost reviews. A 2.26 + // module would drop that context, so a host requiring it cannot bind. + // 2.28 adds `max_do_turns` to TaskBudget and RunFlowRequest. A 2.27 + // module ignores it and keeps every `do` step at 8 turns. + assert!(!is_compatible((2, 27))); + assert!(!is_compatible((2, 26))); assert!(!is_compatible((2, 25))); assert!(!is_compatible((2, 24))); assert!(!is_compatible((2, 23))); diff --git a/crates/tinycomputer-engine/src/agentic/flow/act/mod.rs b/crates/tinycomputer-engine/src/agentic/flow/act/mod.rs index 66e3db009..bbcf001d1 100644 --- a/crates/tinycomputer-engine/src/agentic/flow/act/mod.rs +++ b/crates/tinycomputer-engine/src/agentic/flow/act/mod.rs @@ -135,7 +135,9 @@ const MOVES: &[(&str, &str)] = &[ /// Standard macOS shortcuts that are safe to try: none sends, deletes, or /// quits. `confirm` (Return) commits text typed into a field; it is refused -/// while a sheet or alert is showing, where Return presses the default button. +/// while a sheet or alert is showing, where Return presses the default button, +/// and outside a search box in a flow with a `stop_before`, where Return may +/// send. pub(super) const SHORTCUTS: &[(&str, &str, &str)] = &[ ( "new_item", diff --git a/crates/tinycomputer-engine/src/agentic/flow/act/moves.rs b/crates/tinycomputer-engine/src/agentic/flow/act/moves.rs index 0ec2f604b..1f11d6d1f 100644 --- a/crates/tinycomputer-engine/src/agentic/flow/act/moves.rs +++ b/crates/tinycomputer-engine/src/agentic/flow/act/moves.rs @@ -85,6 +85,12 @@ impl FlowRun<'_, B> { )); return Ok(Move::Skipped); } + // In a composer Return sends: a flow that stops before an + // irreversible step must press a control, which is gated. + if combo == "return" && !searching && !self.stop_before.is_empty() { + self.history.push("refused return: this flow stops before an irreversible step, and Return may perform it; press the control instead".to_owned()); + return Ok(Move::Skipped); + } let app = self.app.clone(); let reply = self .act(log, &format!("press {combo}"), None, move |backend| { diff --git a/crates/tinycomputer-engine/src/agentic/flow/flow_tests/do_loop_tests.rs b/crates/tinycomputer-engine/src/agentic/flow/flow_tests/do_loop_tests.rs index ec7c33d29..5263d16aa 100644 --- a/crates/tinycomputer-engine/src/agentic/flow/flow_tests/do_loop_tests.rs +++ b/crates/tinycomputer-engine/src/agentic/flow/flow_tests/do_loop_tests.rs @@ -633,6 +633,43 @@ async fn an_action_judged_unhelpful_is_undone_and_not_tried_again() { assert_eq!(run.result.stop, FlowStopReason::Completed); } +#[tokio::test] +async fn a_do_step_spends_the_turns_its_run_allows() { + let ended_after = |max_do_turns: Option| async move { + let run = run_with( + App::quirky(Quirk::Frozen), + json!({"app": "Mail", "steps": ["open the search results"]}), + |request| { + request.max_do_turns = max_do_turns; + request.max_actions = 120; + }, + |id, question, _| (id == "move").then(|| pick(question, "wait", 0.9)), + ) + .await; + assert_eq!(run.result.stop, FlowStopReason::StepFailed); + let step = &run.result.steps[0]; + (step.turns, step.note.clone()) + }; + + let (turns, note) = ended_after(None).await; + assert_eq!(turns, 8, "the default is unchanged"); + assert!(note.contains("not accomplished after 8 turns"), "{note}"); + + let (turns, note) = ended_after(Some(3)).await; + assert_eq!(turns, 3); + assert!(note.contains("not accomplished after 3 turns"), "{note}"); + + let (turns, note) = ended_after(Some(12)).await; + assert_eq!(turns, 12); + assert!(note.contains("not accomplished after 12 turns"), "{note}"); + + let (_, note) = ended_after(Some(500)).await; + assert!( + note.contains("not accomplished after 32 turns"), + "capped by the module: {note}" + ); +} + #[tokio::test] async fn waits_that_change_nothing_are_not_a_stall_and_stop_being_offered() { let run = run_with( @@ -1260,3 +1297,24 @@ fn a_pressed_controls_copies_are_only_on_the_other_items_of_its_list() { "the bar's own has none" ); } + +#[tokio::test] +async fn return_is_not_pressed_when_the_flow_stops_before_sending() { + // In a message composer Return sends. The flow declared it stops before + // sending, so the "confirm" shortcut must not press Return unasked. + let run = run_with( + App::default(), + json!({"app": "Mail", "steps": [ + "confirm the message text", + {"stop_before": "sending the message"} + ]}), + |request| request.max_actions = 2, + |id, question, _| match id { + "shortcut" => Some(pick(question, "confirm", 0.9)), + _ => None, + }, + ) + .await; + let presses = run.app.sim().presses.clone(); + assert!(!presses.iter().any(|key| key == "return"), "{presses:?}"); +} diff --git a/crates/tinycomputer-engine/src/agentic/flow/mod.rs b/crates/tinycomputer-engine/src/agentic/flow/mod.rs index 96e4635d1..44a2579d8 100644 --- a/crates/tinycomputer-engine/src/agentic/flow/mod.rs +++ b/crates/tinycomputer-engine/src/agentic/flow/mod.rs @@ -97,6 +97,9 @@ const MAX_ACTIONS: u32 = 120; /// Upper bound on [`RunFlowRequest::max_model_calls`]. Jev is cheap, and /// every framing of a voted decision is one evaluation. const MAX_CALLS: u32 = 10_000; +/// Upper bound on [`RunFlowRequest::max_do_turns`]: a step stuck past this +/// many turns is better rescued than tried again. +const MAX_DO_TURNS: u32 = 32; /// Choices, picks, and entries remembered for the brief's `so_far`. const MAX_SO_FAR: usize = 12; /// Longest goal the brief carries, in characters. @@ -272,6 +275,8 @@ pub(super) struct FlowRun<'r, B> { pub(super) page: Option, /// How many ways each decision is asked. votes: u32, + /// Turns a `do` step may spend. + pub(super) do_turns: u32, /// The secret values, to mask every request with. secrets: Facts, /// Opaque host handles, never substituted into flow text. diff --git a/crates/tinycomputer-engine/src/agentic/flow/run.rs b/crates/tinycomputer-engine/src/agentic/flow/run.rs index 8f7db8cf3..f0583df80 100644 --- a/crates/tinycomputer-engine/src/agentic/flow/run.rs +++ b/crates/tinycomputer-engine/src/agentic/flow/run.rs @@ -16,7 +16,7 @@ use tinycomputer_bus::{ use tinycomputer_core::Facts; use super::{ - Ended, FlowRun, Halt, MAX_ACTIONS, MAX_CALLS, StepLog, + Ended, FlowRun, Halt, MAX_ACTIONS, MAX_CALLS, MAX_DO_TURNS, StepLog, backend::AgentBackend, front::Front, ledger, steps, @@ -106,6 +106,9 @@ impl<'r, B: AgentBackend + Sync> FlowRun<'r, B> { so_far: Vec::new(), page: None, votes: request.votes.clamp(1, vote::MAX_VOTES), + do_turns: request + .max_do_turns + .map_or(steps::DO_TURNS, |turns| turns.clamp(1, MAX_DO_TURNS)), secrets, fact_handles: request.fact_handles.clone(), secret_host, diff --git a/crates/tinycomputer-engine/src/agentic/flow/steps/mod.rs b/crates/tinycomputer-engine/src/agentic/flow/steps/mod.rs index d191a7d81..68806985b 100644 --- a/crates/tinycomputer-engine/src/agentic/flow/steps/mod.rs +++ b/crates/tinycomputer-engine/src/agentic/flow/steps/mod.rs @@ -44,8 +44,9 @@ use tinycomputer_bus::FlowAction; use super::{Ended, FlowRun, Halt, StepLog, backend::AgentBackend}; -/// Turns a `do` step may spend. -const DO_TURNS: u32 = 8; +/// Turns a `do` step may spend when the run does not set +/// `RunFlowRequest::max_do_turns`. +pub(super) const DO_TURNS: u32 = 8; /// Turns spent opening the thing a `choose` step picks from. pub(super) const REVEAL_TURNS: u32 = 3; /// Times `open` checks for a readable window, waiting between checks. @@ -99,7 +100,7 @@ pub(super) async fn run( // then be typed as the caller's card number. FlowAction::Do(intent) => match typing::typing(intent) { Some(slot) => run.enter(log, &[slot]).await, - None => run.accomplish(log, text, DO_TURNS).await, + None => run.accomplish(log, text, run.do_turns).await, }, FlowAction::Enter(slots) => run.enter(log, &slots.0).await, FlowAction::Choose(choose) => run.choose(log, choose).await, diff --git a/crates/tinycomputer-engine/src/agentic/flow/view/mod.rs b/crates/tinycomputer-engine/src/agentic/flow/view/mod.rs index 2c8224c88..cf79b3729 100644 --- a/crates/tinycomputer-engine/src/agentic/flow/view/mod.rs +++ b/crates/tinycomputer-engine/src/agentic/flow/view/mod.rs @@ -32,26 +32,51 @@ pub(in crate::agentic) fn is_banned( banned.contains(&signature(candidate)) || banned.contains(&press_key(candidate)) } +/// Words that commit to something wherever they sit in a label ("Post", +/// "Transfer $500", "Log out"). Matched as whole words, so "Postcode" and +/// "Design" stay pressable; "sign" counts unless it is signing in. +const COMMITTING_WORDS: &[&str] = &[ + "post", + "transfer", + "checkout", + "check out", + "log out", + "logout", + "sign", +]; + /// Whether a lower-cased label names an action that is hard to undo. A /// counter's minus button ("remove adult") is not: it only lowers a number. pub(in crate::agentic) fn destructive_label(evidence: &str) -> bool { + let words = format!( + " {} ", + evidence + .split(|character: char| !character.is_alphanumeric()) + .filter(|word| !word.is_empty()) + .collect::>() + .join(" ") + ) + .replace(" sign in ", " "); !tinycomputer_core::adjusts_a_count(evidence) - && [ - "delete", - "remove", - "send", - "purchase", - "buy", - "pay", - "submit", - "confirm", - "overwrite", - "quit without saving", - "empty trash", - "sign out", - ] - .iter() - .any(|term| evidence.contains(term)) + && (COMMITTING_WORDS + .iter() + .any(|word| words.contains(&format!(" {word} "))) + || [ + "delete", + "remove", + "send", + "purchase", + "buy", + "pay", + "submit", + "confirm", + "overwrite", + "quit without saving", + "empty trash", + "sign out", + ] + .iter() + .any(|term| evidence.contains(term))) } /// Whether `label` is named by a `stop_before` phrase the flow itself diff --git a/crates/tinycomputer-engine/src/agentic/flow/view/view_tests.rs b/crates/tinycomputer-engine/src/agentic/flow/view/view_tests.rs index 40d972850..379a0bc9c 100644 --- a/crates/tinycomputer-engine/src/agentic/flow/view/view_tests.rs +++ b/crates/tinycomputer-engine/src/agentic/flow/view/view_tests.rs @@ -224,3 +224,37 @@ fn the_elements_a_purpose_names_are_offered_first_in_their_own_order() { "filler names nothing" ); } + +#[test] +fn posting_transferring_checking_out_paying_deleting_logging_out_and_signing_are_destructive() { + let screen = clickable_screen(); + let pressable: Vec<&str> = [ + "Post", + "Transfer $500", + "Checkout", + "Check out", + "Pay", + "Delete", + "Log out", + "Sign", + "Sign up", + ] + .into_iter() + .filter(|name| !is_destructive(&button(name), &screen, &[])) + .collect(); + assert!( + pressable.is_empty(), + "pressed with no approval: {pressable:?}" + ); + // Signing in commits to nothing, and a word that only contains one of + // these is not one of them. + for name in [ + "Sign in", + "Sign-in with Google", + "Postcode", + "Design", + "Logo", + ] { + assert!(!is_destructive(&button(name), &screen, &[]), "{name}"); + } +} diff --git a/crates/tinycomputer-engine/src/task/budget.rs b/crates/tinycomputer-engine/src/task/budget.rs index b1755721e..094b08bb5 100644 --- a/crates/tinycomputer-engine/src/task/budget.rs +++ b/crates/tinycomputer-engine/src/task/budget.rs @@ -363,6 +363,7 @@ pub(super) fn run_request( max_actions, max_model_calls, votes: state.budget.votes.unwrap_or(DEFAULT_VOTES), + max_do_turns: state.budget.max_do_turns, strategy: state.budget.strategy.unwrap_or_default(), deliberation: state.budget.deliberation.unwrap_or_default(), brief: brief(&state), diff --git a/crates/tinycomputer-engine/src/task/describe.rs b/crates/tinycomputer-engine/src/task/describe.rs index 21e97c635..c6f5445aa 100644 --- a/crates/tinycomputer-engine/src/task/describe.rs +++ b/crates/tinycomputer-engine/src/task/describe.rs @@ -5,8 +5,8 @@ //! The schemas here are written by hand, so each field of a request type //! must be added here when it is added to the contract, save the host's //! own settings no model is offered (a task's browser binary and profile); -//! `task_tests/describe_tests.rs` checks the `StartTask` and `PlanTask` -//! schemas name every other field their types serialize. +//! `task_tests/describe_tests.rs` checks the request schemas name their +//! model-settable fields; host-only context is deliberately omitted. use serde_json::{Value, json}; use tinycomputer_bus::agent::names::{CONFIDENTIAL, methods}; @@ -115,6 +115,12 @@ fn start_task_input() -> Value { "max_actions": {"type": "integer"}, "max_model_calls": {"type": "integer"}, "votes": {"type": "integer"}, + "max_do_turns": { + "type": "integer", + "minimum": 1, + "maximum": 32, + "description": "turns each do step may spend before it fails as not accomplished; 8 when unset" + }, "strategy": {"enum": ["narrow", "wide"], "default": "narrow"}, "deliberation": {"enum": ["off", "standard", "deep"], "default": "deep"}, "max_elapsed_ms": {"type": "integer"}, diff --git a/crates/tinycomputer-engine/src/task/task_tests/describe_tests.rs b/crates/tinycomputer-engine/src/task/task_tests/describe_tests.rs index 6be80573c..82a06906e 100644 --- a/crates/tinycomputer-engine/src/task/task_tests/describe_tests.rs +++ b/crates/tinycomputer-engine/src/task/task_tests/describe_tests.rs @@ -15,6 +15,7 @@ fn continue_with_handle( id, approve: Some(true), answer: Some(String::new()), + host_context: Some(tinycomputer_bus::agent::HostContext::new("opaque-context")), fact_handles: std::collections::BTreeMap::from([( "email".to_owned(), tinycomputer_bus::agent::SecretHandle { @@ -240,6 +241,7 @@ async fn describe_schemas_name_every_request_field() { max_actions: Some(1), max_model_calls: Some(1), votes: Some(1), + max_do_turns: Some(1), strategy: Some(tinycomputer_bus::FlowStrategy::default()), deliberation: Some(tinycomputer_bus::Deliberation::default()), max_elapsed_ms: Some(1), @@ -256,7 +258,20 @@ async fn describe_schemas_name_every_request_field() { let plan = serde_json::to_value(tinycomputer_bus::agent::PlanTaskRequest::default()).unwrap(); assert_eq!(documented(&schema("PlanTask")), fields(&plan)); +} +#[tokio::test] +async fn describe_schemas_name_continuation_request_fields() { + let (tasks, _) = controller(Vec::new()); + let described = capabilities(Vec::new(), Some(&jev()), &tasks); + let schema = |name: &str| { + described + .members + .iter() + .find(|member| member.name == name) + .map(|member| member.input.clone()) + .expect("the member is documented") + }; let id = tinycomputer_bus::agent::TaskId::new("t-1"); let others = [ ( @@ -282,10 +297,23 @@ async fn describe_schemas_name_every_request_field() { for (member, request) in others { assert_eq!( documented(&schema(member)), - fields(&request.unwrap()), + if member == "ContinueTask" { + fields(&request.unwrap()) + .into_iter() + .filter(|field| field != "host_context") + .collect() + } else { + fields(&request.unwrap()) + }, "{member}" ); } + assert!( + schema("ContinueTask")["properties"] + .get("host_context") + .is_none(), + "host context is injected by the trusted host, not exposed to agents" + ); // Every member with a request object is compared above; the rest take // no argument. for member in &described.members { diff --git a/crates/tinycomputer-engine/src/task/task_tests/start_tests.rs b/crates/tinycomputer-engine/src/task/task_tests/start_tests.rs index a18de9c1e..e92ba1fbb 100644 --- a/crates/tinycomputer-engine/src/task/task_tests/start_tests.rs +++ b/crates/tinycomputer-engine/src/task/task_tests/start_tests.rs @@ -66,6 +66,7 @@ async fn a_finished_flow_is_done_with_its_reads_and_no_fact_values() { (request.max_actions, request.max_model_calls, request.votes), (120, 6000, 7) ); + assert_eq!(request.max_do_turns, None, "the module's own default"); assert!(request.facts.is_empty(), "an email is shared, not secret"); assert_eq!(request.brief.details["email"], "asha@example.com"); assert!( @@ -630,3 +631,29 @@ async fn a_run_gets_the_callers_values_and_the_flow_keeps_its_own_definitions() ); assert_eq!(request.flow.vars["first_name"], "${first name}"); } + +#[tokio::test] +async fn a_budget_turn_limit_reaches_every_run() { + let (tasks, script) = controller(vec![finished_run( + FlowStopReason::Completed, + vec![step("1", "do", "add it to the cart", StepOutcome::Done, "")], + &[], + None, + )]); + let view = tasks + .start(&StartTaskRequest { + flow: Some( + serde_json::from_value(json!({"app": "browser", "steps": ["add it to the cart"]})) + .unwrap(), + ), + budget: tinycomputer_bus::agent::TaskBudget { + max_do_turns: Some(16), + ..tinycomputer_bus::agent::TaskBudget::default() + }, + ..StartTaskRequest::default() + }) + .data + .unwrap(); + settle(&tasks, &view.id).await; + assert_eq!(script.requests.lock().unwrap()[0].max_do_turns, Some(16)); +} diff --git a/crates/tinycomputer-skills/schemas/start_task.schema.json b/crates/tinycomputer-skills/schemas/start_task.schema.json index f399c8905..d649e8c2d 100644 --- a/crates/tinycomputer-skills/schemas/start_task.schema.json +++ b/crates/tinycomputer-skills/schemas/start_task.schema.json @@ -34,6 +34,7 @@ "max_model_calls": {"type": "integer"}, "max_elapsed_ms": {"type": "integer"}, "votes": {"type": "integer", "description": "How many ways each decision is asked before its answers are averaged."}, + "max_do_turns": {"type": "integer", "minimum": 1, "maximum": 32, "description": "How many turns each do step may spend before it fails as not accomplished (default 8, at most 32)."}, "strategy": {"type": "string", "enum": ["narrow", "wide"], "description": "How each decision is asked: many small requests (narrow, the default), or one request per turn over a digest of the screen with a working memory (wide)."}, "deliberation": {"type": "string", "enum": ["off", "standard", "deep"], "description": "How much each decision is deliberated before acting: deep (the default) escalates close calls with more framings, pairwise duels, and contrasting questions, checks every action's effect, and undoes and retries mistakes; standard does less; off uses single thresholds."}, "max_rescues": {"type": "integer", "minimum": 0, "maximum": 5, "description": "How many failed steps a reasoning model may rescue with guidance before the task fails (default and most 5; 0 turns rescues off). Needs the module's planner configuration."} diff --git a/crates/tinycomputer/Cargo.toml b/crates/tinycomputer/Cargo.toml index 10aefe96b..fa836aca8 100644 --- a/crates/tinycomputer/Cargo.toml +++ b/crates/tinycomputer/Cargo.toml @@ -64,6 +64,8 @@ default = [] # process and is only touched on macOS/Windows, so co-linking is safe. static-link = [] linked = ["static-link"] +# Exposes a fixture-only TCP connector override for host/module integration tests. +test-connector = ["tinycomputer-browser/test-connector"] [lints] workspace = true diff --git a/crates/tinycomputer/src/tinybus_module/README.md b/crates/tinycomputer/src/tinybus_module/README.md index a2af54e06..480af3ea0 100644 --- a/crates/tinycomputer/src/tinybus_module/README.md +++ b/crates/tinycomputer/src/tinybus_module/README.md @@ -75,6 +75,14 @@ TinyBus treats initial and replacement module configuration as sensitive host-control traffic. An unreadable configuration fails before replacing the served object rather than falling back to defaults. +Setting `consequence_host` to an object with the unique `destination` supplied +by `ModuleHost::prepare_host_callbacks` enables confidential consequence +reviews. When `ContinueTask` approves a pending action for host review, the +module declines it if the configured callback is absent or cannot answer. A +declined approval, an unanswered pause, or a continuation with no pending +action does not fail solely because this callback is absent. Without host +context, the legacy well-known host interface remains available. + ## The manifest `tinybus_module::module_export_optional_static!` emits (C exports by default; `linked_module()` under `static-link`) the descriptor, embedded manifest, and diff --git a/crates/tinycomputer/src/tinybus_module/browser_egress_live_tests.rs b/crates/tinycomputer/src/tinybus_module/browser_egress_live_tests.rs deleted file mode 100644 index db6701b0d..000000000 --- a/crates/tinycomputer/src/tinybus_module/browser_egress_live_tests.rs +++ /dev/null @@ -1,517 +0,0 @@ -//! Opt-in real-Chromium coverage through the loaded `TinyComputer` module. -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] - -use std::sync::{ - Arc, Mutex, - atomic::{AtomicBool, AtomicUsize, Ordering}, -}; -use std::time::Duration; - -use tinybus::{Connection, broker::Broker, module::ModuleHost, transport::memory::MemoryBus}; -use tinycomputer_bus::{ - DesktopResponse, - browser::names as browser_names, - browser_egress::{ - self, BrowserEgressConsumeRequest, BrowserEgressDecision, BrowserEgressGrant, - BrowserEgressTarget, BrowserEgressValidateRequest, - }, - names, -}; - -static LIVE_TEST_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); - -#[derive(Clone)] -struct EgressHost { - allowed: Arc, - allowed_address: String, - grant_generation: Option, - authorize_delay: Duration, - resolved_address: Arc>, - observations: Arc>>, -} - -#[tinybus::interface(name = "ai.tinyhumans.tinycomputer.BrowserEgressHost")] -impl EgressHost { - async fn authorize(&self, request: BrowserEgressTarget) -> tinybus::Result { - self.observations.lock().unwrap().push(format!( - "authorize:{}:{}:{}:{}", - request.policy_id, request.expected_generation, request.hostname, request.port - )); - self.observations.lock().unwrap().push(format!( - "resolve:{}:{}:{}", - request.hostname, - request.port, - self.resolved_address.lock().unwrap() - )); - tokio::time::sleep(self.authorize_delay).await; - let allow = self.allowed.load(Ordering::SeqCst) - && request.hostname == "fixture.test" - && *self.resolved_address.lock().unwrap() == self.allowed_address - && request.port - == self - .allowed_address - .rsplit(':') - .next() - .and_then(|port| port.parse::().ok()) - .unwrap_or_default(); - Ok(BrowserEgressGrant { - generation: self.grant_generation.unwrap_or(request.expected_generation), - authorization: if allow { - "fixture-lease" - } else { - "denied-after-policy-change" - } - .into(), - addresses: if allow { - vec![self.allowed_address.clone()] - } else { - Vec::new() - }, - }) - } - - async fn consume( - &self, - request: BrowserEgressConsumeRequest, - ) -> tinybus::Result { - tokio::task::yield_now().await; - self.observations - .lock() - .unwrap() - .push(format!("consume:{}", request.address)); - Ok(BrowserEgressDecision { - allowed: self.allowed.load(Ordering::SeqCst) && request.address == self.allowed_address, - }) - } - - async fn validate( - &self, - request: BrowserEgressValidateRequest, - ) -> tinybus::Result { - tokio::task::yield_now().await; - self.observations - .lock() - .unwrap() - .push(format!("validate:{}", request.authorization)); - Ok(BrowserEgressDecision { - allowed: self.allowed.load(Ordering::SeqCst) - && request.authorization == "fixture-lease", - }) - } -} - -async fn serve_fixture( - listener: tokio::net::TcpListener, - expected: &'static [u8], - extra_connections: Arc, -) { - let (mut stream, _) = tokio::time::timeout(Duration::from_secs(10), listener.accept()) - .await - .expect("authorized Chromium socket arrives before the deadline") - .expect("fixture listener accepts the authorized socket"); - let mut request = [0_u8; 4096]; - let _ = tokio::io::AsyncReadExt::read(&mut stream, &mut request).await; - assert!(String::from_utf8_lossy(&request).contains("GET /")); - let response = [ - b"HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: ".as_slice(), - expected.len().to_string().as_bytes(), - b"\r\nConnection: close\r\n\r\n".as_slice(), - expected, - ] - .concat(); - let _ = tokio::io::AsyncWriteExt::write_all(&mut stream, &response).await; - drop(stream); - - while let Ok((stream, _)) = listener.accept().await { - extra_connections.fetch_add(1, Ordering::SeqCst); - drop(stream); - } -} - -fn successful_data(reply: &DesktopResponse) -> &serde_json::Value { - assert!(reply.ok, "{} failed: {:?}", reply.command, reply.error); - reply.data.as_ref().expect("successful response has data") -} - -#[tokio::test] -#[allow(clippy::too_many_lines)] -async fn live_chromium_module_dials_only_the_host_returned_socket_and_rejects_changed_policy() --> tinybus::Result<()> { - let _guard = LIVE_TEST_LOCK.lock().await; - let allowed_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?; - let port = allowed_listener.local_addr()?.port(); - // Use a distinct loopback address that does not require an interface alias - // (macOS only binds 127.0.0.1 by default). - let denied_listener = - tokio::net::TcpListener::bind((std::net::Ipv6Addr::LOCALHOST, port)).await?; - let allowed_address = allowed_listener.local_addr()?.to_string(); - let rebound_address = denied_listener.local_addr()?.to_string(); - let extra_allowed_connections = Arc::new(AtomicUsize::new(0)); - let allowed_server = tokio::spawn(serve_fixture( - allowed_listener, - b"allowed fixture", - extra_allowed_connections.clone(), - )); - - let bus = MemoryBus::new(); - let broker = Broker::new(); - let broker_task = broker.spawn(bus.clone()); - let host_connection = Connection::connect(bus.connect().await?).await?; - let allowed = Arc::new(AtomicBool::new(true)); - let resolved_address = Arc::new(Mutex::new(allowed_address.clone())); - let observations = Arc::new(Mutex::new(Vec::new())); - host_connection - .serve_at( - browser_egress::OBJECT_PATH.try_into()?, - EgressHost { - allowed: allowed.clone(), - allowed_address: allowed_address.clone(), - grant_generation: None, - authorize_delay: Duration::ZERO, - resolved_address: resolved_address.clone(), - observations: observations.clone(), - }, - ) - .await?; - host_connection - .request_name(browser_egress::INTERFACE) - .await?; - - let module_host = ModuleHost::new(broker); - let module = crate::linked_module().expect("linked module manifest is valid"); - module_host - .attach_linked_with_config( - module, - serde_json::json!({ - "browser": {"egress": {"policy_id": "fixture-policy", "generation": 41}} - }), - ) - .expect("TinyComputer module loads through ModuleHost"); - let client = Connection::connect(bus.connect().await?).await?; - let proxy = client.proxy(names::INTERFACE, names::OBJECT_PATH, names::INTERFACE)?; - - let opened: DesktopResponse = proxy - .call( - browser_names::methods::OPEN_SESSION, - (serde_json::json!({}),), - ) - .await?; - let session = successful_data(&opened)["id"].clone(); - assert_eq!(successful_data(&opened)["launched"], true); - let url = format!("http://fixture.test:{port}/allowed"); - let navigated: DesktopResponse = proxy - .call( - browser_names::methods::NAVIGATE, - (serde_json::json!({"session": session, "url": url}),), - ) - .await?; - assert!( - navigated.ok, - "authorized navigation failed: {:?}", - navigated.error - ); - let authorizations_before_policy_change = observations - .lock() - .unwrap() - .iter() - .filter(|call| call.starts_with("authorize:fixture-policy:41:fixture.test:")) - .count(); - // Rebind the same test hostname to a private fixture socket and revoke the - // old grant. The loopback fixtures model the host resolver's two answers; - // Chromium itself never resolves or dials the hostname directly. - *resolved_address.lock().unwrap() = rebound_address.clone(); - allowed.store(false, Ordering::SeqCst); - let previously_allowed_connections = extra_allowed_connections.load(Ordering::SeqCst); - let denied_url = format!("http://fixture.test:{port}/after-dns-rebind"); - let denied: DesktopResponse = proxy - .call( - browser_names::methods::NAVIGATE, - (serde_json::json!({"session": session, "url": denied_url}),), - ) - .await?; - assert!( - !denied.ok, - "navigation after host policy denial unexpectedly succeeded" - ); - assert!( - tokio::time::timeout(Duration::from_millis(500), denied_listener.accept()) - .await - .is_err(), - "denied policy-change socket received a connection" - ); - assert!( - tokio::time::timeout(Duration::from_millis(500), async { - while extra_allowed_connections.load(Ordering::SeqCst) == previously_allowed_connections - { - tokio::task::yield_now().await; - } - }) - .await - .is_err(), - "denied rebound request reached the previously allowed socket" - ); - - allowed_server.abort(); - let _ = allowed_server.await; - broker_task.abort(); - let _ = broker_task.await; - - let calls = observations.lock().unwrap(); - assert!( - calls - .iter() - .any(|call| call == &format!("consume:{allowed_address}")), - "host did not consume the exact returned socket: {calls:?}" - ); - let authorizations_after_policy_change = calls - .iter() - .filter(|call| call.starts_with("authorize:fixture-policy:41:fixture.test:")) - .count(); - assert!( - authorizations_after_policy_change > authorizations_before_policy_change, - "the post-change request did not reach the host authorizer: {calls:?}" - ); - let denied_address = denied_listener.local_addr()?.to_string(); - assert!( - !calls - .iter() - .any(|call| call == &format!("consume:{denied_address}")), - "denied rebound socket was consumed: {calls:?}" - ); - assert!( - calls - .iter() - .any(|call| call == &format!("resolve:fixture.test:{port}:{rebound_address}")), - "the controlled resolver did not provide the private rebound answer: {calls:?}" - ); - Ok(()) -} - -#[tokio::test] -async fn live_chromium_module_denies_loopback_when_egress_authority_is_missing() --> tinybus::Result<()> { - let _guard = LIVE_TEST_LOCK.lock().await; - let denied_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?; - let port = denied_listener.local_addr()?.port(); - - let bus = MemoryBus::new(); - let broker = Broker::new(); - let broker_task = broker.spawn(bus.clone()); - let module_host = ModuleHost::new(broker); - let module = crate::linked_module().expect("linked module manifest is valid"); - module_host - .attach_linked_with_config( - module, - serde_json::json!({ - "browser": {"egress": {"policy_id": "missing-authority", "generation": 7}} - }), - ) - .expect("TinyComputer module loads through ModuleHost"); - let client = Connection::connect(bus.connect().await?).await?; - let proxy = client.proxy(names::INTERFACE, names::OBJECT_PATH, names::INTERFACE)?; - - let opened: DesktopResponse = proxy - .call( - browser_names::methods::OPEN_SESSION, - (serde_json::json!({}),), - ) - .await?; - let session = successful_data(&opened)["id"].clone(); - let url = format!("http://127.0.0.1:{port}/must-not-connect"); - let denied: DesktopResponse = proxy - .call( - browser_names::methods::NAVIGATE, - (serde_json::json!({"session": session, "url": url}),), - ) - .await?; - - assert!( - !denied.ok, - "navigation without an egress authority unexpectedly succeeded" - ); - assert!( - tokio::time::timeout(Duration::from_millis(500), denied_listener.accept()) - .await - .is_err(), - "loopback destination received a connection without an egress authority" - ); - - broker_task.abort(); - let _ = broker_task.await; - Ok(()) -} - -#[tokio::test] -async fn live_chromium_module_denies_a_stale_egress_generation_before_dialing() --> tinybus::Result<()> { - let _guard = LIVE_TEST_LOCK.lock().await; - let denied_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?; - let allowed_address = denied_listener.local_addr()?.to_string(); - let port = denied_listener.local_addr()?.port(); - - let bus = MemoryBus::new(); - let broker = Broker::new(); - let broker_task = broker.spawn(bus.clone()); - let host_connection = Connection::connect(bus.connect().await?).await?; - let observations = Arc::new(Mutex::new(Vec::new())); - host_connection - .serve_at( - browser_egress::OBJECT_PATH.try_into()?, - EgressHost { - allowed: Arc::new(AtomicBool::new(true)), - allowed_address: allowed_address.clone(), - grant_generation: Some(40), - authorize_delay: Duration::ZERO, - resolved_address: Arc::new(Mutex::new(allowed_address.clone())), - observations: observations.clone(), - }, - ) - .await?; - host_connection - .request_name(browser_egress::INTERFACE) - .await?; - - let module_host = ModuleHost::new(broker); - let module = crate::linked_module().expect("linked module manifest is valid"); - module_host - .attach_linked_with_config( - module, - serde_json::json!({ - "browser": {"egress": {"policy_id": "stale-generation", "generation": 41}} - }), - ) - .expect("TinyComputer module loads through ModuleHost"); - let client = Connection::connect(bus.connect().await?).await?; - let proxy = client.proxy(names::INTERFACE, names::OBJECT_PATH, names::INTERFACE)?; - - let opened: DesktopResponse = proxy - .call( - browser_names::methods::OPEN_SESSION, - (serde_json::json!({}),), - ) - .await?; - let session = successful_data(&opened)["id"].clone(); - let url = format!("http://fixture.test:{port}/stale-generation"); - let denied: DesktopResponse = proxy - .call( - browser_names::methods::NAVIGATE, - (serde_json::json!({"session": session, "url": url}),), - ) - .await?; - - assert!( - !denied.ok, - "navigation with a stale egress generation unexpectedly succeeded" - ); - assert!( - tokio::time::timeout(Duration::from_millis(500), denied_listener.accept()) - .await - .is_err(), - "stale-generation socket received a connection" - ); - broker_task.abort(); - let _ = broker_task.await; - - let calls = observations.lock().unwrap(); - assert!( - calls - .iter() - .any(|call| call.starts_with("authorize:stale-generation:41:fixture.test:")), - "the live module did not ask the host for an authorization: {calls:?}" - ); - assert!( - !calls.iter().any(|call| call.starts_with("consume:")), - "stale grant reached socket consumption: {calls:?}" - ); - Ok(()) -} - -#[tokio::test] -async fn live_chromium_module_denies_when_host_authorization_times_out() -> tinybus::Result<()> { - let _guard = LIVE_TEST_LOCK.lock().await; - let denied_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?; - let denied_address = denied_listener.local_addr()?.to_string(); - let port = denied_listener.local_addr()?.port(); - - let bus = MemoryBus::new(); - let broker = Broker::new(); - let broker_task = broker.spawn(bus.clone()); - let host_connection = Connection::connect(bus.connect().await?).await?; - let observations = Arc::new(Mutex::new(Vec::new())); - host_connection - .serve_at( - browser_egress::OBJECT_PATH.try_into()?, - EgressHost { - allowed: Arc::new(AtomicBool::new(true)), - allowed_address: denied_address.clone(), - grant_generation: None, - authorize_delay: Duration::from_secs(6), - resolved_address: Arc::new(Mutex::new(denied_address.clone())), - observations: observations.clone(), - }, - ) - .await?; - host_connection - .request_name(browser_egress::INTERFACE) - .await?; - - let module_host = ModuleHost::new(broker); - let module = crate::linked_module().expect("linked module manifest is valid"); - module_host - .attach_linked_with_config( - module, - serde_json::json!({ - "browser": {"egress": {"policy_id": "slow-authority", "generation": 12}} - }), - ) - .expect("TinyComputer module loads through ModuleHost"); - let client = Connection::connect(bus.connect().await?).await?; - let proxy = client.proxy(names::INTERFACE, names::OBJECT_PATH, names::INTERFACE)?; - - let opened: DesktopResponse = proxy - .call( - browser_names::methods::OPEN_SESSION, - (serde_json::json!({}),), - ) - .await?; - let session = successful_data(&opened)["id"].clone(); - let url = format!("http://fixture.test:{port}/slow-authority"); - let denied: DesktopResponse = proxy - .call( - browser_names::methods::NAVIGATE, - (serde_json::json!({"session": session, "url": url}),), - ) - .await?; - - assert!( - !denied.ok, - "navigation unexpectedly succeeded when host authorization exceeded its deadline" - ); - assert!( - tokio::time::timeout(Duration::from_millis(500), denied_listener.accept()) - .await - .is_err(), - "destination received a connection while host authorization was pending" - ); - broker_task.abort(); - let _ = broker_task.await; - - let calls = observations.lock().unwrap(); - assert!( - calls - .iter() - .any(|call| call.starts_with("authorize:slow-authority:12:fixture.test:")), - "the live module did not reach the deliberately slow host authorization: {calls:?}" - ); - assert!( - !calls.iter().any(|call| call.starts_with("consume:")), - "timed-out authorization reached socket consumption: {calls:?}" - ); - assert!( - !calls - .iter() - .any(|call| call.starts_with(&format!("consume:{denied_address}"))), - "timed-out destination was consumed: {calls:?}" - ); - Ok(()) -} diff --git a/crates/tinycomputer/src/tinybus_module/browser_egress_live_tests/authority_denial_tests.rs b/crates/tinycomputer/src/tinybus_module/browser_egress_live_tests/authority_denial_tests.rs new file mode 100644 index 000000000..aff977399 --- /dev/null +++ b/crates/tinycomputer/src/tinybus_module/browser_egress_live_tests/authority_denial_tests.rs @@ -0,0 +1,218 @@ +//! Live Chromium checks that missing and stale host authority denies dialing. + +use super::*; + +struct DenialBrowser { + proxy: tinybus::Proxy, + session: serde_json::Value, + broker_task: tokio::task::JoinHandle>, + _host_connection: Option, + _module_host: ModuleHost, +} + +async fn start_denial_browser( + host: Option, + policy_id: &str, + generation: u64, +) -> tinybus::Result { + let bus = MemoryBus::new(); + let broker = Broker::new(); + let broker_task = broker.spawn(bus.clone()); + let host_connection = if let Some(host) = host { + let connection = Connection::connect(bus.connect().await?).await?; + connection + .serve_at(browser_egress::OBJECT_PATH.try_into()?, host) + .await?; + connection.request_name(browser_egress::INTERFACE).await?; + Some(connection) + } else { + None + }; + + let module_host = ModuleHost::new(broker); + let module = crate::linked_module().expect("linked module manifest is valid"); + module_host + .attach_linked_with_config( + module, + serde_json::json!({ + "browser": {"egress": {"policy_id": policy_id, "generation": generation}} + }), + ) + .expect("TinyComputer module loads through ModuleHost"); + let client = Connection::connect(bus.connect().await?).await?; + let proxy = client.proxy(names::INTERFACE, names::OBJECT_PATH, names::INTERFACE)?; + let opened: DesktopResponse = proxy + .call( + browser_names::methods::OPEN_SESSION, + (serde_json::json!({}),), + ) + .await?; + let session = successful_data(&opened)["id"].clone(); + assert_eq!(successful_data(&opened)["launched"], true); + + Ok(DenialBrowser { + proxy, + session, + broker_task, + _host_connection: host_connection, + _module_host: module_host, + }) +} + +async fn close_denial_browser(browser: DenialBrowser) -> tinybus::Result<()> { + let closed: DesktopResponse = browser + .proxy + .call( + browser_names::methods::CLOSE_SESSION, + (serde_json::json!({"session": browser.session}),), + ) + .await?; + assert!( + closed.ok, + "browser session did not close: {:?}", + closed.error + ); + browser.broker_task.abort(); + let _ = browser.broker_task.await; + Ok(()) +} + +#[tokio::test] +async fn live_chromium_denies_loopback_when_egress_authority_is_missing() -> tinybus::Result<()> { + let denied_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?; + let port = denied_listener.local_addr()?.port(); + let browser = start_denial_browser(None, "missing-authority", 7).await?; + let url = format!("http://127.0.0.1:{port}/must-not-connect"); + let denied: DesktopResponse = browser + .proxy + .call( + browser_names::methods::NAVIGATE, + (serde_json::json!({"session": browser.session, "url": url}),), + ) + .await?; + + assert!( + !denied.ok, + "navigation without an egress authority unexpectedly succeeded" + ); + assert!( + tokio::time::timeout(Duration::from_millis(500), denied_listener.accept()) + .await + .is_err(), + "loopback destination received a connection without an egress authority" + ); + close_denial_browser(browser).await?; + Ok(()) +} + +#[tokio::test] +async fn live_chromium_denies_stale_egress_generation_before_dialing() -> tinybus::Result<()> { + let denied_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?; + let allowed_address = denied_listener.local_addr()?.to_string(); + let port = denied_listener.local_addr()?.port(); + let observations = Arc::new(Mutex::new(Vec::new())); + let browser = start_denial_browser( + Some(EgressHost { + allowed: Arc::new(AtomicBool::new(true)), + allowed_addresses: vec![allowed_address], + grant_generation: Some(40), + authorize_delay: Duration::ZERO, + observations: observations.clone(), + }), + "stale-generation", + 41, + ) + .await?; + let url = format!("http://fixture.test:{port}/stale-generation"); + let denied: DesktopResponse = browser + .proxy + .call( + browser_names::methods::NAVIGATE, + (serde_json::json!({"session": browser.session, "url": url}),), + ) + .await?; + + assert!( + !denied.ok, + "navigation with a stale egress generation unexpectedly succeeded" + ); + assert!( + tokio::time::timeout(Duration::from_millis(500), denied_listener.accept()) + .await + .is_err(), + "stale-generation socket received a connection" + ); + close_denial_browser(browser).await?; + + let calls = observations.lock().unwrap(); + assert!( + calls + .iter() + .any(|call| call.starts_with("authorize:stale-generation:41:fixture.test:")), + "the live module did not ask the host for authorization: {calls:?}" + ); + assert!( + !calls.iter().any(|call| call.starts_with("consume:")), + "stale grant reached socket consumption: {calls:?}" + ); + Ok(()) +} + +#[tokio::test] +async fn live_chromium_denies_when_host_authorization_times_out() -> tinybus::Result<()> { + let denied_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?; + let denied_address = denied_listener.local_addr()?.to_string(); + let port = denied_listener.local_addr()?.port(); + let observations = Arc::new(Mutex::new(Vec::new())); + let browser = start_denial_browser( + Some(EgressHost { + allowed: Arc::new(AtomicBool::new(true)), + allowed_addresses: vec![denied_address.clone()], + grant_generation: None, + authorize_delay: Duration::from_secs(6), + observations: observations.clone(), + }), + "slow-authority", + 12, + ) + .await?; + let url = format!("http://fixture.test:{port}/slow-authority"); + let denied: DesktopResponse = browser + .proxy + .call( + browser_names::methods::NAVIGATE, + (serde_json::json!({"session": browser.session, "url": url}),), + ) + .await?; + + assert!( + !denied.ok, + "navigation unexpectedly succeeded when host authorization exceeded its deadline" + ); + assert!( + tokio::time::timeout(Duration::from_millis(500), denied_listener.accept()) + .await + .is_err(), + "destination received a connection while host authorization was pending" + ); + close_denial_browser(browser).await?; + + let calls = observations.lock().unwrap(); + assert!( + calls + .iter() + .any(|call| call.starts_with("authorize:slow-authority:12:fixture.test:")), + "the live module did not reach the deliberately slow host authorization: {calls:?}" + ); + assert!( + !calls.iter().any(|call| call.starts_with("consume:")), + "timed-out authorization reached socket consumption: {calls:?}" + ); + assert!( + !calls + .iter() + .any(|call| call.starts_with(&format!("consume:{denied_address}"))), + "timed-out destination was consumed: {calls:?}" + ); + Ok(()) +} diff --git a/crates/tinycomputer/src/tinybus_module/browser_egress_live_tests/mod.rs b/crates/tinycomputer/src/tinybus_module/browser_egress_live_tests/mod.rs new file mode 100644 index 000000000..7be104ba9 --- /dev/null +++ b/crates/tinycomputer/src/tinybus_module/browser_egress_live_tests/mod.rs @@ -0,0 +1,381 @@ +//! Opt-in real-Chromium coverage through the loaded `TinyComputer` module. +#![allow(clippy::expect_used, clippy::panic, clippy::unwrap_used)] + +mod authority_denial_tests; +#[cfg(feature = "test-connector")] +mod public_connector_tests; +mod transport_classes_tests; +mod worker; + +use std::sync::{ + Arc, Mutex, + atomic::{AtomicBool, AtomicUsize, Ordering}, +}; +use std::time::Duration; + +use tinybus::{Connection, broker::Broker, module::ModuleHost, transport::memory::MemoryBus}; +use tinycomputer_bus::{ + DesktopResponse, + browser::names as browser_names, + browser_egress::{ + self, BrowserEgressConsumeRequest, BrowserEgressDecision, BrowserEgressGrant, + BrowserEgressTarget, BrowserEgressValidateRequest, + }, + names, +}; + +#[derive(Clone)] +struct EgressHost { + allowed: Arc, + allowed_addresses: Vec, + grant_generation: Option, + authorize_delay: Duration, + observations: Arc>>, +} + +#[tinybus::interface(name = "ai.tinyhumans.tinycomputer.BrowserEgressHost")] +impl EgressHost { + async fn authorize(&self, request: BrowserEgressTarget) -> tinybus::Result { + self.observations.lock().unwrap().push(format!( + "authorize:{}:{}:{}:{}", + request.policy_id, request.expected_generation, request.hostname, request.port + )); + tokio::time::sleep(self.authorize_delay).await; + tokio::task::yield_now().await; + let allowed_address = self.allowed_addresses.iter().find(|address| { + address + .rsplit(':') + .next() + .and_then(|port| port.parse::().ok()) + == Some(request.port) + }); + let allow = self.allowed.load(Ordering::SeqCst) + && request.hostname == "fixture.test" + && allowed_address.is_some(); + Ok(BrowserEgressGrant { + generation: self.grant_generation.unwrap_or(request.expected_generation), + authorization: if allow { + "fixture-lease" + } else { + "denied-after-policy-change" + } + .into(), + addresses: if allow { + allowed_address.cloned().into_iter().collect() + } else { + Vec::new() + }, + }) + } + + async fn consume( + &self, + request: BrowserEgressConsumeRequest, + ) -> tinybus::Result { + tokio::task::yield_now().await; + self.observations + .lock() + .unwrap() + .push(format!("consume:{}", request.address)); + Ok(BrowserEgressDecision { + allowed: self.allowed.load(Ordering::SeqCst) + && self.allowed_addresses.contains(&request.address), + }) + } + + async fn validate( + &self, + request: BrowserEgressValidateRequest, + ) -> tinybus::Result { + tokio::task::yield_now().await; + self.observations + .lock() + .unwrap() + .push(format!("validate:{}", request.authorization)); + Ok(BrowserEgressDecision { + allowed: self.allowed.load(Ordering::SeqCst) + && request.authorization == "fixture-lease", + }) + } +} + +async fn serve_fixture( + listener: tokio::net::TcpListener, + expected: Vec, + extra_connections: Arc, + served: tokio::sync::oneshot::Sender<()>, + worker_done: Option>, +) { + let (mut stream, _) = listener + .accept() + .await + .expect("authorized Chromium socket arrives"); + let mut request = [0_u8; 4096]; + let _ = tokio::io::AsyncReadExt::read(&mut stream, &mut request).await; + assert!(String::from_utf8_lossy(&request).contains("GET /")); + let response = [ + b"HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: ".as_slice(), + expected.len().to_string().as_bytes(), + b"\r\nConnection: close\r\n\r\n".as_slice(), + expected.as_slice(), + ] + .concat(); + let _ = tokio::io::AsyncWriteExt::write_all(&mut stream, &response).await; + let _ = served.send(()); + drop(stream); + let mut worker_done = worker_done; + while let Ok((mut stream, _)) = listener.accept().await { + extra_connections.fetch_add(1, Ordering::SeqCst); + let mut request = [0_u8; 4096]; + let _ = tokio::io::AsyncReadExt::read(&mut stream, &mut request).await; + if String::from_utf8_lossy(&request).contains("GET /worker-done ") { + let _ = tokio::io::AsyncWriteExt::write_all( + &mut stream, + b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", + ) + .await; + if let Some(done) = worker_done.take() { + let _ = done.send(()); + } + } + } +} + +fn successful_data(reply: &DesktopResponse) -> &serde_json::Value { + assert!(reply.ok, "{} failed: {:?}", reply.command, reply.error); + reply.data.as_ref().expect("successful response has data") +} + +struct LiveBrowser { + proxy: tinybus::Proxy, + session: serde_json::Value, + navigation: serde_json::Value, + allowed: Arc, + observations: Arc>>, + broker_task: tokio::task::JoinHandle>, + _host_connection: Connection, + _module_host: ModuleHost, +} + +async fn start_browser_with_fixture_host( + allowed_address: String, + page_port: u16, + page_path: &str, + served: tokio::sync::oneshot::Receiver<()>, +) -> tinybus::Result { + start_browser_with_fixture_hosts_for_policy( + vec![allowed_address], + page_port, + page_path, + served, + "fixture-policy", + 41, + None, + None, + ) + .await +} + +async fn start_browser_with_fixture_hosts( + allowed_addresses: Vec, + page_port: u16, + page_path: &str, + served: tokio::sync::oneshot::Receiver<()>, +) -> tinybus::Result { + start_browser_with_fixture_hosts_for_policy( + allowed_addresses, + page_port, + page_path, + served, + "fixture-policy", + 41, + None, + None, + ) + .await +} + +async fn start_browser_with_fixture_hosts_for_policy( + allowed_addresses: Vec, + page_port: u16, + page_path: &str, + served: tokio::sync::oneshot::Receiver<()>, + policy_id: &str, + generation: u64, + shared_observations: Option>>>, + test_connector_map: Option<(String, String)>, +) -> tinybus::Result { + let bus = MemoryBus::new(); + let broker = Broker::new(); + let broker_task = broker.spawn(bus.clone()); + let host_connection = Connection::connect(bus.connect().await?).await?; + let allowed = Arc::new(AtomicBool::new(true)); + let observations = shared_observations.unwrap_or_else(|| Arc::new(Mutex::new(Vec::new()))); + host_connection + .serve_at( + browser_egress::OBJECT_PATH.try_into()?, + EgressHost { + allowed: allowed.clone(), + allowed_addresses, + grant_generation: None, + authorize_delay: Duration::ZERO, + observations: observations.clone(), + }, + ) + .await?; + host_connection + .request_name(browser_egress::INTERFACE) + .await?; + + let module_host = ModuleHost::new(broker); + let module = crate::linked_module().expect("linked module manifest is valid"); + let mut module_config = serde_json::json!({ + "browser": {"egress": {"policy_id": policy_id, "generation": generation}} + }); + if let Some((approved, fixture)) = test_connector_map { + module_config["browser"]["egress"]["test_connector_map"] = serde_json::json!({ + "approved": approved, + "fixture": fixture, + }); + } + module_host + .attach_linked_with_config(module, module_config) + .expect("TinyComputer module loads through ModuleHost"); + let client = Connection::connect(bus.connect().await?).await?; + let proxy = client.proxy(names::INTERFACE, names::OBJECT_PATH, names::INTERFACE)?; + + let opened: DesktopResponse = proxy + .call( + browser_names::methods::OPEN_SESSION, + (serde_json::json!({}),), + ) + .await?; + let session = successful_data(&opened)["id"].clone(); + assert_eq!(successful_data(&opened)["launched"], true); + let url = format!("http://fixture.test:{page_port}{page_path}"); + let navigated: DesktopResponse = proxy + .call( + browser_names::methods::NAVIGATE, + (serde_json::json!({"session": session, "url": url}),), + ) + .await?; + assert!( + navigated.ok, + "authorized fixture navigation failed: {:?}", + navigated.error + ); + let navigation = successful_data(&navigated).clone(); + tokio::time::timeout(Duration::from_secs(10), served) + .await + .expect("fixture page is served") + .expect("fixture server reports the response"); + + Ok(LiveBrowser { + proxy, + session, + navigation, + allowed, + observations, + broker_task, + _host_connection: host_connection, + _module_host: module_host, + }) +} + +#[tokio::test] +async fn live_chromium_module_dials_only_the_host_returned_socket_and_rejects_changed_policy() +-> tinybus::Result<()> { + let allowed_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?; + let port = allowed_listener.local_addr()?.port(); + let denied_listener = tokio::net::TcpListener::bind(("127.0.0.2", port)).await?; + let allowed_address = allowed_listener.local_addr()?.to_string(); + let extra_allowed_connections = Arc::new(AtomicUsize::new(0)); + let (served_tx, served_rx) = tokio::sync::oneshot::channel(); + let allowed_server = tokio::spawn(serve_fixture( + allowed_listener, + b"allowed fixture" + .to_vec(), + extra_allowed_connections.clone(), + served_tx, + None, + )); + + let browser = + start_browser_with_fixture_host(allowed_address.clone(), port, "/allowed", served_rx) + .await?; + + let authorizations_before_policy_change = browser + .observations + .lock() + .unwrap() + .iter() + .filter(|call| call.starts_with("authorize:fixture-policy:41:fixture.test:")) + .count(); + let extra_connections_before_policy_change = extra_allowed_connections.load(Ordering::SeqCst); + // Simulate a policy refresh: the host changes from granting the fixture + // socket to denying requests for the same hostname. + browser.allowed.store(false, Ordering::SeqCst); + let denied_url = format!("http://fixture.test:{port}/after-policy-change"); + let denied: DesktopResponse = browser + .proxy + .call( + browser_names::methods::NAVIGATE, + (serde_json::json!({"session": browser.session, "url": denied_url}),), + ) + .await?; + assert!( + !denied.ok, + "navigation after host policy denial unexpectedly succeeded" + ); + assert!( + tokio::time::timeout(Duration::from_millis(500), denied_listener.accept()) + .await + .is_err(), + "denied policy-change socket received a connection" + ); + assert_eq!( + extra_allowed_connections.load(Ordering::SeqCst), + extra_connections_before_policy_change, + "policy-denied navigation connected to the previously allowed socket" + ); + + { + let calls = browser.observations.lock().unwrap(); + assert!( + calls + .iter() + .any(|call| call == &format!("consume:{allowed_address}")), + "host did not consume the exact returned socket: {calls:?}" + ); + let authorizations_after_policy_change = calls + .iter() + .filter(|call| call.starts_with("authorize:fixture-policy:41:fixture.test:")) + .count(); + assert!( + authorizations_after_policy_change > authorizations_before_policy_change, + "the post-change request did not reach the host authorizer: {calls:?}" + ); + let denied_address = denied_listener.local_addr()?.to_string(); + assert!( + !calls + .iter() + .any(|call| call == &format!("consume:{denied_address}")), + "denied socket was consumed: {calls:?}" + ); + } + let closed: DesktopResponse = browser + .proxy + .call( + browser_names::methods::CLOSE_SESSION, + (serde_json::json!({"session": browser.session}),), + ) + .await?; + assert!( + closed.ok, + "browser session did not close: {:?}", + closed.error + ); + browser.broker_task.abort(); + allowed_server.abort(); + Ok(()) +} diff --git a/crates/tinycomputer/src/tinybus_module/browser_egress_live_tests/public_connector_tests.rs b/crates/tinycomputer/src/tinybus_module/browser_egress_live_tests/public_connector_tests.rs new file mode 100644 index 000000000..979aee4e1 --- /dev/null +++ b/crates/tinycomputer/src/tinybus_module/browser_egress_live_tests/public_connector_tests.rs @@ -0,0 +1,73 @@ +//! Live module test for the fixture-only public-address connector override. +#![allow(clippy::expect_used, clippy::panic, clippy::unwrap_used)] + +use super::*; +use std::net::SocketAddr; + +#[tokio::test] +async fn loaded_module_consumes_public_socket_before_fixture_mapping() -> tinybus::Result<()> { + let local_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?; + let page_port = local_listener.local_addr()?.port(); + let public_socket = SocketAddr::from(([8, 8, 8, 8], page_port)); + let fixture_address = local_listener.local_addr()?; + let policy_id = "fixture-public-control"; + let generation = 973; + + let body = b"public fixture"; + let extra_connections = Arc::new(AtomicUsize::new(0)); + let (served_tx, served_rx) = tokio::sync::oneshot::channel(); + let fixture = tokio::spawn(serve_fixture( + local_listener, + body.to_vec(), + extra_connections, + served_tx, + None, + )); + let browser = start_browser_with_fixture_hosts_for_policy( + vec![public_socket.to_string()], + page_port, + "/public-control", + served_rx, + policy_id, + generation, + None, + Some((public_socket.to_string(), fixture_address.to_string())), + ) + .await?; + + assert_eq!(browser.navigation["title"], "public fixture"); + let expected_authorize = format!("authorize:{policy_id}:{generation}:fixture.test:{page_port}"); + let expected_consume = format!("consume:{public_socket}"); + let observed = browser.observations.lock().unwrap().clone(); + assert_eq!( + &observed[..3], + [ + expected_authorize, + expected_consume, + "validate:fixture-lease".into() + ], + "TinyComputer's BusAuthorizer consumes exactly the granted public socket before forwarding" + ); + assert!( + observed[3..] + .iter() + .all(|call| call.starts_with("authorize:") && call.contains(":www.google.com:443")), + "background public requests must stop at authorization without a grant or connector: {observed:?}" + ); + + let closed: DesktopResponse = browser + .proxy + .call( + browser_names::methods::CLOSE_SESSION, + (serde_json::json!({"session": browser.session}),), + ) + .await?; + assert!( + closed.ok, + "browser session did not close: {:?}", + closed.error + ); + browser.broker_task.abort(); + fixture.abort(); + Ok(()) +} diff --git a/crates/tinycomputer/src/tinybus_module/browser_egress_live_tests/transport_classes_tests.rs b/crates/tinycomputer/src/tinybus_module/browser_egress_live_tests/transport_classes_tests.rs new file mode 100644 index 000000000..94c83eb86 --- /dev/null +++ b/crates/tinycomputer/src/tinybus_module/browser_egress_live_tests/transport_classes_tests.rs @@ -0,0 +1,207 @@ +//! Live Chromium checks that browser transport classes use host authorization. + +use super::*; + +async fn serve_once( + listener: tokio::net::TcpListener, + expected_path: &'static str, + response: String, + served: Option>, + completed: tokio::sync::mpsc::Sender<&'static str>, +) { + let (mut stream, _) = listener + .accept() + .await + .expect("authorized Chromium socket arrives"); + let mut request = Vec::new(); + let mut chunk = [0_u8; 1024]; + loop { + let Ok(Ok(read)) = tokio::time::timeout( + Duration::from_secs(5), + tokio::io::AsyncReadExt::read(&mut stream, &mut chunk), + ) + .await + else { + panic!("browser request timed out"); + }; + assert!( + read != 0, + "browser closed before sending a complete request" + ); + request.extend_from_slice(&chunk[..read]); + if request.windows(4).any(|window| window == b"\r\n\r\n") { + break; + } + } + let request = String::from_utf8_lossy(&request); + let target = request + .lines() + .next() + .and_then(|line| line.split_ascii_whitespace().nth(1)) + .expect("browser request has a target"); + let path = + url::Url::parse(target).map_or_else(|_| target.to_owned(), |url| url.path().to_owned()); + assert_eq!(path, expected_path); + if expected_path == "/socket" { + let header = |name: &str| { + request.lines().find_map(|line| { + let (key, value) = line.split_once(':')?; + key.eq_ignore_ascii_case(name).then(|| value.trim()) + }) + }; + assert_eq!( + header("Upgrade").map(str::to_ascii_lowercase).as_deref(), + Some("websocket"), + "socket fixture only accepts a WebSocket upgrade request: {request}" + ); + assert!( + header("Connection").is_some_and(|value| { + value + .split(',') + .any(|token| token.trim().eq_ignore_ascii_case("upgrade")) + }), + "socket fixture only accepts Connection: Upgrade: {request}" + ); + assert!( + header("Sec-WebSocket-Key").is_some_and(|value| !value.is_empty()), + "socket fixture only accepts a request with Sec-WebSocket-Key: {request}" + ); + } + tokio::io::AsyncWriteExt::write_all(&mut stream, response.as_bytes()) + .await + .expect("fixture response is written"); + if let Some(served) = served { + let _ = served.send(()); + } + let _ = completed.send(expected_path).await; +} + +fn fixture_response(status: &str, headers: &str, body: &str) -> String { + format!( + "HTTP/1.1 {status}\r\n{headers}Connection: close\r\nContent-Length: {}\r\n\r\n{body}", + body.len() + ) +} + +#[tokio::test] +#[allow(clippy::too_many_lines)] +async fn live_chromium_redirect_subresource_and_websocket_requests_use_host_authorization() +-> tinybus::Result<()> { + let redirect_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?; + let page_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?; + let pixel_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?; + let socket_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?; + let redirect_address = redirect_listener.local_addr()?.to_string(); + let page_address = page_listener.local_addr()?.to_string(); + let pixel_address = pixel_listener.local_addr()?.to_string(); + let socket_address = socket_listener.local_addr()?.to_string(); + let redirect_port = redirect_listener.local_addr()?.port(); + let page_port = page_listener.local_addr()?.port(); + let pixel_port = pixel_listener.local_addr()?.port(); + let socket_port = socket_listener.local_addr()?.port(); + + let (served_tx, served_rx) = tokio::sync::oneshot::channel(); + let (completed_tx, mut completed_rx) = tokio::sync::mpsc::channel(4); + let redirect = tokio::spawn(serve_once( + redirect_listener, + "/redirect", + fixture_response( + "302 Found", + &format!("Location: http://fixture.test:{page_port}/page\r\n"), + "", + ), + None, + completed_tx.clone(), + )); + let html = format!( + "" + ); + let page = tokio::spawn(serve_once( + page_listener, + "/page", + fixture_response("200 OK", "Content-Type: text/html\r\n", &html), + Some(served_tx), + completed_tx.clone(), + )); + let pixel = tokio::spawn(serve_once( + pixel_listener, + "/pixel", + fixture_response("204 No Content", "", ""), + None, + completed_tx.clone(), + )); + let socket = tokio::spawn(serve_once( + socket_listener, + "/socket", + fixture_response("403 Forbidden", "", ""), + None, + completed_tx.clone(), + )); + drop(completed_tx); + + let browser = start_browser_with_fixture_hosts( + vec![ + redirect_address.clone(), + page_address.clone(), + pixel_address.clone(), + socket_address.clone(), + ], + redirect_port, + "/redirect", + served_rx, + ) + .await?; + let mut paths = Vec::new(); + for _ in 0..4 { + paths.push( + tokio::time::timeout(Duration::from_secs(10), completed_rx.recv()) + .await + .expect("each transport request reaches its fixture listener") + .expect("fixture reports every observed request"), + ); + } + paths.sort_unstable(); + assert_eq!(paths, ["/page", "/pixel", "/redirect", "/socket"]); + + { + let observations = browser.observations.lock().unwrap(); + for port in [redirect_port, page_port, pixel_port, socket_port] { + let authorization = format!("authorize:fixture-policy:41:fixture.test:{port}"); + assert!( + observations.iter().any(|call| call == &authorization), + "transport destination on port {port} did not reach host authorization: {observations:?}" + ); + } + for address in [ + &redirect_address, + &page_address, + &pixel_address, + &socket_address, + ] { + let consumption = format!("consume:{address}"); + assert!( + observations.iter().any(|call| call == &consumption), + "transport destination {address} did not consume its one-use grant: {observations:?}" + ); + } + } + + let closed: DesktopResponse = browser + .proxy + .call( + browser_names::methods::CLOSE_SESSION, + (serde_json::json!({"session": browser.session}),), + ) + .await?; + assert!( + closed.ok, + "browser session did not close: {:?}", + closed.error + ); + browser.broker_task.abort(); + redirect.abort(); + page.abort(); + pixel.abort(); + socket.abort(); + Ok(()) +} diff --git a/crates/tinycomputer/src/tinybus_module/browser_egress_live_tests/worker.rs b/crates/tinycomputer/src/tinybus_module/browser_egress_live_tests/worker.rs new file mode 100644 index 000000000..4d77c63e1 --- /dev/null +++ b/crates/tinycomputer/src/tinybus_module/browser_egress_live_tests/worker.rs @@ -0,0 +1,99 @@ +use super::*; + +#[tokio::test] +async fn live_chromium_module_routes_worker_egress_through_host_authorization() +-> tinybus::Result<()> { + let allowed_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?; + let page_port = allowed_listener.local_addr()?.port(); + let denied_listener = tokio::net::TcpListener::bind("127.0.0.2:0").await?; + let denied_port = denied_listener.local_addr()?.port(); + let html = format!( + "" + ) + .into_bytes(); + let (served_tx, served_rx) = tokio::sync::oneshot::channel(); + let (worker_done_tx, worker_done_rx) = tokio::sync::oneshot::channel(); + let extra_allowed_connections = Arc::new(AtomicUsize::new(0)); + let allowed_server = tokio::spawn(serve_fixture( + allowed_listener, + html, + extra_allowed_connections.clone(), + served_tx, + Some(worker_done_tx), + )); + + let allowed_address = format!("127.0.0.1:{page_port}"); + let browser = + start_browser_with_fixture_host(allowed_address, page_port, "/worker-fixture", served_rx) + .await?; + + let worker_authorization = format!("authorize:fixture-policy:41:127.0.0.2:{denied_port}"); + let worker_authorized = tokio::time::timeout(Duration::from_secs(10), async { + loop { + if browser + .observations + .lock() + .unwrap() + .iter() + .any(|call| call == &worker_authorization) + { + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await; + if worker_authorized.is_err() { + assert!( + tokio::time::timeout(Duration::from_millis(500), denied_listener.accept()) + .await + .is_err(), + "worker request bypassed host authorization and connected directly" + ); + panic!( + "worker request did not reach host authorization: {:?}", + browser.observations.lock().unwrap() + ); + } + tokio::select! { + done = tokio::time::timeout(Duration::from_secs(10), worker_done_rx) => { + done.expect("worker request completes within ten seconds") + .expect("worker completion fixture receives the done request"); + } + accepted = denied_listener.accept() => { + let (stream, _) = accepted.expect("denied listener remains open"); + drop(stream); + panic!("worker request connected directly to the denied private listener"); + } + } + assert_eq!( + extra_allowed_connections.load(Ordering::SeqCst), + 1, + "only the worker completion request reached the allowed fixture after navigation" + ); + assert!( + tokio::time::timeout(Duration::from_millis(500), denied_listener.accept()) + .await + .is_err(), + "worker request connected directly to the denied private listener after completion" + ); + + let closed: DesktopResponse = browser + .proxy + .call( + browser_names::methods::CLOSE_SESSION, + (serde_json::json!({"session": browser.session}),), + ) + .await?; + assert!( + closed.ok, + "browser session did not close: {:?}", + closed.error + ); + browser.broker_task.abort(); + allowed_server.abort(); + Ok(()) +} diff --git a/crates/tinycomputer/src/tinybus_module/config.rs b/crates/tinycomputer/src/tinybus_module/config.rs index 5521ae9f5..588c72d49 100644 --- a/crates/tinycomputer/src/tinybus_module/config.rs +++ b/crates/tinycomputer/src/tinybus_module/config.rs @@ -6,6 +6,8 @@ //! a desktop `user_agent` and launch `args` once here rather than on every //! request. +#[cfg(feature = "test-connector")] +use std::{future::Future, io, net::SocketAddr, pin::Pin, sync::Arc}; use tinycomputer_browser::{CursorPace, Perception, ScreenCursor, SessionOptions, Settle}; use crate::Result; @@ -31,6 +33,9 @@ pub(crate) struct BrowserDefaults { pub(crate) prelaunch: bool, /// Immutable `TinySecurity` scope captured from host-private configuration. pub(crate) egress: Option, + /// Exact public-to-local mapping available only in test-connector builds. + #[cfg(feature = "test-connector")] + pub(crate) test_connector_map: Option, } /// Host-selected policy identity and generation; never an agent argument. @@ -40,6 +45,34 @@ pub(crate) struct BrowserEgressConfig { pub(crate) generation: u64, } +/// A single exact public socket mapped to a loopback fixture by test builds. +#[cfg(feature = "test-connector")] +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct TestConnectorMap { + pub(crate) approved: SocketAddr, + pub(crate) fixture: SocketAddr, +} + +#[cfg(feature = "test-connector")] +impl TestConnectorMap { + pub(crate) fn connector(&self) -> tinycomputer_browser::TestConnector { + let approved = self.approved; + let fixture = self.fixture; + Arc::new(move |address| { + Box::pin(async move { + if address != approved { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "test connector refused an address outside its exact mapping", + )); + } + tokio::net::TcpStream::connect(fixture).await + }) + as Pin> + Send>> + }) + } +} + impl std::fmt::Debug for BrowserEgressConfig { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("BrowserEgressConfig([REDACTED])") @@ -56,6 +89,8 @@ impl Default for BrowserDefaults { settle: Settle::default(), prelaunch: true, egress: None, + #[cfg(feature = "test-connector")] + test_connector_map: None, } } } @@ -128,7 +163,15 @@ impl BrowserDefaults { .and_then(serde_json::Value::as_u64) .filter(|generation| *generation > 0) .ok_or_else(invalid)?; - if egress.len() != 2 + #[cfg(feature = "test-connector")] + { + defaults.test_connector_map = + test_connector_map(egress.get("test_connector_map"), &invalid)?; + } + let expected_egress_keys = 2 + usize::from( + cfg!(feature = "test-connector") && egress.contains_key("test_connector_map"), + ); + if egress.len() != expected_egress_keys || browser.contains_key("args") || browser.contains_key("executable") { @@ -177,6 +220,39 @@ impl BrowserDefaults { } } +#[cfg(feature = "test-connector")] +fn test_connector_map( + value: Option<&serde_json::Value>, + invalid: &impl Fn() -> crate::Error, +) -> Result> { + let Some(value) = value else { + return Ok(None); + }; + let object = value.as_object().ok_or_else(invalid)?; + if object.len() != 2 { + return Err(invalid()); + } + let parse = |name: &str| -> Result { + object + .get(name) + .and_then(serde_json::Value::as_str) + .and_then(|value| value.parse().ok()) + .ok_or_else(invalid) + }; + let approved = parse("approved")?; + let fixture = parse("fixture")?; + if approved.ip().to_string() != "8.8.8.8" + || !fixture.ip().is_loopback() + || approved.port() != fixture.port() + || object + .keys() + .any(|key| !["approved", "fixture"].contains(&key.as_str())) + { + return Err(invalid()); + } + Ok(Some(TestConnectorMap { approved, fixture })) +} + /// Whether the host explicitly selected the trace/report callback. pub(crate) fn trace_sink_destination( config: &serde_json::Value, @@ -225,6 +301,44 @@ pub(crate) fn trace_sink_destination( } } +/// Whether the host prepared a confidential consequence-review callback. +pub(crate) fn consequence_host_destination( + config: &serde_json::Value, +) -> Result> { + match config + .as_object() + .and_then(|object| object.get("consequence_host")) + { + None | Some(serde_json::Value::Bool(false)) => Ok(None), + Some(serde_json::Value::Object(options)) if options.len() == 1 => { + let destination = options + .get("destination") + .and_then(serde_json::Value::as_str) + .ok_or(crate::Error::ConfigFieldType { + field: "consequence_host.destination", + expected: "the unique name of the host callback prepared for this module", + })?; + tinybus::BusName::new(destination.to_owned()) + .map_err(|_| crate::Error::ConfigFieldType { + field: "consequence_host.destination", + expected: "the unique name of the host callback prepared for this module", + }) + .and_then(|name| { + name.is_unique() + .then_some(Some(name)) + .ok_or(crate::Error::ConfigFieldType { + field: "consequence_host.destination", + expected: "the unique name of the host callback prepared for this module", + }) + }) + } + Some(_) => Err(crate::Error::ConfigFieldType { + field: "consequence_host", + expected: "false or an object containing only the host callback `destination`", + }), + } +} + /// The `cursor` configuration: the agent's one on-screen cursor, shared by /// the desktop and every task's browser. Either a pace name, or an object /// with an optional `pace` and an optional `overlay` path to the diff --git a/crates/tinycomputer/src/tinybus_module/consequence_gate/consequence_gate_tests.rs b/crates/tinycomputer/src/tinybus_module/consequence_gate/consequence_gate_tests.rs index 32089e4b8..efb5806bd 100644 --- a/crates/tinycomputer/src/tinybus_module/consequence_gate/consequence_gate_tests.rs +++ b/crates/tinycomputer/src/tinybus_module/consequence_gate/consequence_gate_tests.rs @@ -6,7 +6,7 @@ use std::sync::{Arc, Mutex}; use tinybus::Connection; -use tinycomputer_bus::agent::{ContinueTaskRequest, TaskId}; +use tinycomputer_bus::agent::{ContinueTaskRequest, HostContext, TaskId}; use super::*; @@ -61,6 +61,7 @@ fn approval(approve: Option) -> ContinueTaskRequest { fact_handles: std::collections::BTreeMap::new(), approve, answer: None, + host_context: Some(HostContext::new("opaque-context")), } } @@ -103,6 +104,10 @@ async fn an_allowed_approval_goes_through() { assert_eq!(seen[0].task, "t1"); assert_eq!(seen[0].target, "Send"); assert_eq!(seen[0].kind, ConsequenceKind::Irreversible); + assert_eq!( + seen[0].host_context.as_ref().map(HostContext::as_str), + Some("opaque-context") + ); } #[tokio::test] @@ -174,13 +179,43 @@ async fn the_bus_port_reaches_the_hosts_interface() -> tinybus::Result<()> { host_connection.request_name(INTERFACE).await?; let module = Connection::connect(bus.connect().await?).await?; - let link = ConsequenceLink::new(Box::new(BusPort::new(module))); - let verdict = link.review("t1", "pay now", "Pay").await; + let link = ConsequenceLink::new(Box::new(BusPort::new(module, None))); + let verdict = link.review("t1", "pay now", "Pay", None).await; assert_eq!(verdict, Verdict::Denied("no".to_owned())); assert_eq!(fake.seen.lock().unwrap()[0].kind, ConsequenceKind::Payment); Ok(()) } +#[tokio::test] +async fn the_bus_port_never_sends_host_context_to_an_unconfidential_host() -> tinybus::Result<()> { + use tinybus::broker::Broker; + use tinybus::transport::memory::MemoryBus; + + let bus = MemoryBus::new(); + Broker::new().spawn(bus.clone()); + let host_connection = Connection::connect(bus.connect().await?).await?; + let fake = FakeHost::new(Answer::Allow); + host_connection + .serve_at(OBJECT_PATH.try_into()?, BusHost(fake.clone())) + .await?; + host_connection.request_name(INTERFACE).await?; + let module = Connection::connect(bus.connect().await?).await?; + + let link = ConsequenceLink::new(Box::new(BusPort::new(module, None))); + let verdict = link + .review( + "t1", + "send", + "Send", + Some(HostContext::new("opaque-context")), + ) + .await; + + assert!(matches!(verdict, Verdict::Denied(ref reason) if reason.contains("confidential"))); + assert!(fake.seen.lock().unwrap().is_empty()); + Ok(()) +} + #[tokio::test] async fn the_bus_port_treats_a_host_that_serves_nothing_as_unreviewed() -> tinybus::Result<()> { use tinybus::broker::Broker; @@ -189,7 +224,55 @@ async fn the_bus_port_treats_a_host_that_serves_nothing_as_unreviewed() -> tinyb let bus = MemoryBus::new(); Broker::new().spawn(bus.clone()); let module = Connection::connect(bus.connect().await?).await?; - let link = ConsequenceLink::new(Box::new(BusPort::new(module))); - assert_eq!(link.review("t1", "send", "Send").await, Verdict::Unreviewed); + let link = ConsequenceLink::new(Box::new(BusPort::new(module, None))); + assert_eq!( + link.review("t1", "send", "Send", None).await, + Verdict::Unreviewed + ); + Ok(()) +} + +#[tokio::test] +async fn a_missing_configured_callback_is_a_failure_not_an_unreviewed_action() -> tinybus::Result<()> +{ + use tinybus::broker::Broker; + use tinybus::transport::memory::MemoryBus; + + let bus = MemoryBus::new(); + Broker::new().spawn(bus.clone()); + let host = Connection::connect(bus.connect().await?).await?; + let destination = host + .unique_name() + .expect("connected host has a unique name"); + host.serve_at(OBJECT_PATH.try_into()?, UnrelatedObject) + .await?; + let module = Connection::connect(bus.connect().await?).await?; + let link = ConsequenceLink::new(Box::new(BusPort::new(module, Some(destination)))); + + assert!(matches!( + link.review("t1", "send", "Send", None).await, + Verdict::Denied(_) + )); Ok(()) } + +struct UnrelatedObject; + +#[tinybus::interface(name = "org.example.Unrelated")] +impl UnrelatedObject { + async fn ping(&self) -> tinybus::Result<()> { + std::future::ready(Ok(())).await + } +} + +#[test] +fn a_configured_callback_that_is_not_served_is_a_failure() { + let error = tinybus::Error::UnknownInterface { + path: OBJECT_PATH.parse().unwrap(), + interface: INTERFACE.parse().unwrap(), + }; + assert!(matches!( + BusPort::classify_error(true, &error), + PortError::Failed(_) + )); +} diff --git a/crates/tinycomputer/src/tinybus_module/consequence_gate/mod.rs b/crates/tinycomputer/src/tinybus_module/consequence_gate/mod.rs index 93dd0e777..01ee55650 100644 --- a/crates/tinycomputer/src/tinybus_module/consequence_gate/mod.rs +++ b/crates/tinycomputer/src/tinybus_module/consequence_gate/mod.rs @@ -17,7 +17,7 @@ use std::future::Future; use std::pin::Pin; use tinybus::Connection; -use tinycomputer_bus::agent::ContinueTaskRequest; +use tinycomputer_bus::agent::{ContinueTaskRequest, HostContext}; use tinycomputer_bus::consequence_host::{ ConsequenceKind, INTERFACE, OBJECT_PATH, ReviewActionRequest, ReviewActionResponse, methods, }; @@ -26,8 +26,9 @@ use tinycomputer_core::{Consequence, consequence}; /// The deadline for one call to the host. const CALL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30); -/// The bus errors that mean the host does not serve the interface at all, -/// rather than serving it and failing. +/// The bus errors that identify a missing service on the legacy well-known +/// lookup. An explicitly configured destination is expected to be served and +/// every failure from it denies the action. const NOT_SERVED: [&str; 3] = [ "ai.tinyhumans.tinybus.Error.NameHasNoOwner", "ai.tinyhumans.tinybus.Error.UnknownObject", @@ -56,6 +57,7 @@ pub(crate) trait ConsequencePort: Send + Sync + std::fmt::Debug { #[derive(Clone)] pub(crate) struct BusPort { connection: Connection, + destination: Option, } impl std::fmt::Debug for BusPort { @@ -65,31 +67,49 @@ impl std::fmt::Debug for BusPort { } impl BusPort { - pub(crate) fn new(connection: Connection) -> Self { - Self { connection } + pub(crate) fn new(connection: Connection, destination: Option) -> Self { + Self { + connection, + destination, + } + } + + fn classify_error(configured_destination: bool, error: &tinybus::Error) -> PortError { + if !configured_destination && NOT_SERVED.contains(&error.wire_name()) { + PortError::NotServed + } else { + PortError::Failed(error.to_string()) + } } } impl ConsequencePort for BusPort { fn review(&self, request: ReviewActionRequest) -> PortFuture<'_, ReviewActionResponse> { + if request.host_context.is_some() && self.destination.is_none() { + return Box::pin(async { + Err(PortError::Failed( + "host context requires a confidential host callback".to_owned(), + )) + }); + } Box::pin(async move { let proxy = self .connection - .proxy(INTERFACE, OBJECT_PATH, INTERFACE) + .proxy( + self.destination + .as_ref() + .map_or(INTERFACE, tinybus::BusName::as_str), + OBJECT_PATH, + INTERFACE, + ) .map(|proxy| proxy.with_timeout(CALL_TIMEOUT)) .map_err(|error| PortError::Failed(error.to_string()))?; - proxy - .call(methods::REVIEW, (request,)) - .await - .map_err(|error| { - // Across the bus an error keeps its dotted name, not its - // variant, so the name is what says nobody serves this. - if NOT_SERVED.contains(&error.wire_name()) { - PortError::NotServed - } else { - PortError::Failed(error.to_string()) - } - }) + let reply = if self.destination.is_some() { + proxy.call_confidential(methods::REVIEW, (request,)).await + } else { + proxy.call(methods::REVIEW, (request,)).await + }; + reply.map_err(|error| Self::classify_error(self.destination.is_some(), &error)) }) } } @@ -129,13 +149,20 @@ impl ConsequenceLink { /// Asks the host whether task `task` may go ahead with `action` on /// `target`. - pub(crate) async fn review(&self, task: &str, action: &str, target: &str) -> Verdict { + pub(crate) async fn review( + &self, + task: &str, + action: &str, + target: &str, + host_context: Option, + ) -> Verdict { let kind = kind_of(action, target); let request = ReviewActionRequest { task: task.to_owned(), action: action.to_owned(), target: target.to_owned(), kind, + host_context, }; match self.port.review(request).await { Ok(reply) if reply.allow => Verdict::Allowed, @@ -169,7 +196,15 @@ impl ConsequenceLink { let Some((action, target)) = paused else { return; }; - if let Verdict::Denied(_) = self.review(&request.id.to_string(), &action, &target).await { + if let Verdict::Denied(_) = self + .review( + &request.id.to_string(), + &action, + &target, + request.host_context.clone(), + ) + .await + { request.approve = Some(false); } } diff --git a/crates/tinycomputer/src/tinybus_module/dispatch/service.rs b/crates/tinycomputer/src/tinybus_module/dispatch/service.rs index 4385e3081..64081bf70 100644 --- a/crates/tinycomputer/src/tinybus_module/dispatch/service.rs +++ b/crates/tinycomputer/src/tinybus_module/dispatch/service.rs @@ -42,9 +42,19 @@ impl DesktopService { let defaults = BrowserDefaults::from_config(config) .map_err(|error| TinyBusError::failed(error.to_string()))?; let browser = if let Some(egress) = defaults.egress { - Arc::new(Browser::new(Arc::new(EnforcedAgentBrowser::new(Arc::new( - BusAuthorizer::new(connection.clone(), egress.policy_id, egress.generation), - ))))) + let launcher = EnforcedAgentBrowser::new(Arc::new(BusAuthorizer::new( + connection.clone(), + egress.policy_id, + egress.generation, + ))); + #[cfg(feature = "test-connector")] + let launcher = defaults + .test_connector_map + .as_ref() + .map_or(launcher.clone(), |mapping| { + launcher.with_test_connector(mapping.connector()) + }); + Arc::new(Browser::new(Arc::new(launcher))) } else { Arc::new(Browser::new(Arc::new(AgentBrowser))) }; @@ -73,6 +83,12 @@ impl DesktopService { expected: "a module set up with its host callback connection", }); } + if super::super::config::consequence_host_destination(config)?.is_some() { + return Err(crate::Error::ConfigFieldType { + field: "consequence_host", + expected: "a module set up with its confidential host callback connection", + }); + } Self::with_browser_and_trace_sink(config, browser, None) } diff --git a/crates/tinycomputer/src/tinybus_module/mod.rs b/crates/tinycomputer/src/tinybus_module/mod.rs index 2fe7786a3..d38baacd2 100644 --- a/crates/tinycomputer/src/tinybus_module/mod.rs +++ b/crates/tinycomputer/src/tinybus_module/mod.rs @@ -40,6 +40,8 @@ pub(crate) use dispatch::DesktopService; /// silently ignoring the session it was told to join would allocate refs /// nothing else can spend. async fn setup(connection: Connection, config: Value) -> TinyBusResult<()> { + let consequence_host = config::consequence_host_destination(&config) + .map_err(|error| tinybus::Error::failed(error.to_string()))?; let service = DesktopService::from_config_with_connection(&config, connection.clone()) .map_err(|error| tinybus::Error::failed(error.to_string()))?; // The host's per-site memory; a host that does not serve it only costs @@ -47,8 +49,10 @@ async fn setup(connection: Connection, config: Value) -> TinyBusResult<()> { let service = service.with_site_memory(Box::new(site_memory::BusPort::new(connection.clone()))); // The host's consequence review; a host that does not serve it leaves a // task's own approval pause as the only gate. - let service = service - .with_consequence_review(Box::new(consequence_gate::BusPort::new(connection.clone()))); + let service = service.with_consequence_review(Box::new(consequence_gate::BusPort::new( + connection.clone(), + consequence_host, + ))); #[cfg(test)] let service = service.with_native_fixture(); service.sweep_outputs(); @@ -107,7 +111,6 @@ tinybus_module::module_export_optional_static! { mod static_link_tests; #[cfg(all(test, feature = "static-link", live_module_browser_egress_tests))] -#[path = "browser_egress_live_tests.rs"] mod browser_egress_live_tests; #[cfg(test)] diff --git a/crates/tinycomputer/src/tinybus_module/tinybus_module_tests.rs b/crates/tinycomputer/src/tinybus_module/tinybus_module_tests.rs index a59f84a71..b2d4fda1b 100644 --- a/crates/tinycomputer/src/tinybus_module/tinybus_module_tests.rs +++ b/crates/tinycomputer/src/tinybus_module/tinybus_module_tests.rs @@ -12,6 +12,7 @@ use serde_json::json; mod browser_tests; mod config_tests; +mod consequence_review_tests; mod manifest_tests; mod tasks_tests; mod wire_tests; diff --git a/crates/tinycomputer/src/tinybus_module/tinybus_module_tests/config_tests.rs b/crates/tinycomputer/src/tinybus_module/tinybus_module_tests/config_tests.rs index c81d44495..ce57f7910 100644 --- a/crates/tinycomputer/src/tinybus_module/tinybus_module_tests/config_tests.rs +++ b/crates/tinycomputer/src/tinybus_module/tinybus_module_tests/config_tests.rs @@ -211,6 +211,50 @@ fn the_browser_configuration_is_read_or_refused() { } } +#[test] +fn browser_test_connector_map_is_available_only_in_test_connector_builds() { + use crate::tinybus_module::config::BrowserDefaults; + + let config = json!({"browser": {"egress": { + "policy_id": "host-policy", + "generation": 7, + "test_connector_map": { + "approved": "8.8.8.8:443", + "fixture": "127.0.0.1:443" + } + }}}); + #[cfg(feature = "test-connector")] + { + let defaults = BrowserDefaults::from_config(&config).unwrap(); + let mapping = defaults.test_connector_map.unwrap(); + assert_eq!(mapping.approved.to_string(), "8.8.8.8:443"); + assert_eq!(mapping.fixture.to_string(), "127.0.0.1:443"); + + for invalid in [ + json!({"browser": {"egress": { + "policy_id": "p", "generation": 1, + "test_connector_map": {"approved": "8.8.4.4:443", "fixture": "127.0.0.1:443"} + }}}), + json!({"browser": {"egress": { + "policy_id": "p", "generation": 1, + "test_connector_map": {"approved": "8.8.8.8:443", "fixture": "192.168.1.1:443"} + }}}), + json!({"browser": {"egress": { + "policy_id": "p", "generation": 1, + "test_connector_map": {"approved": "8.8.8.8:443", "fixture": "127.0.0.1:80"} + }}}), + json!({"browser": {"egress": { + "policy_id": "p", "generation": 1, + "test_connector_map": {"approved": "8.8.8.8:443", "fixture": "127.0.0.1:443", "extra": true} + }}}), + ] { + assert!(BrowserDefaults::from_config(&invalid).is_err(), "{invalid}"); + } + } + #[cfg(not(feature = "test-connector"))] + assert!(BrowserDefaults::from_config(&config).is_err()); +} + #[test] fn browser_defaults_fill_only_what_the_caller_left_unset() { use crate::tinybus_module::config::BrowserDefaults; @@ -308,6 +352,45 @@ fn trace_sink_requires_the_host_prepared_unique_destination() { ); } +#[test] +fn consequence_host_requires_the_host_prepared_unique_destination() { + use crate::tinybus_module::config::consequence_host_destination; + + assert!(consequence_host_destination(&json!({})).unwrap().is_none()); + assert!( + consequence_host_destination(&json!({"consequence_host": false})) + .unwrap() + .is_none() + ); + for invalid in [ + json!({"consequence_host": true}), + json!({"consequence_host": {}}), + json!({"consequence_host": {"destination": "ai.tinyhumans.host"}}), + json!({"consequence_host": {"destination": ":1.42", "scope": "model"}}), + ] { + assert!(consequence_host_destination(&invalid).is_err(), "{invalid}"); + } + assert_eq!( + consequence_host_destination(&json!({ + "consequence_host": {"destination": ":1.42"} + })) + .unwrap() + .unwrap() + .as_str(), + ":1.42" + ); +} + +#[test] +fn connectionless_service_construction_rejects_consequence_host_configuration() { + let error = DesktopService::from_config(&json!({ + "consequence_host": {"destination": ":1.42"} + })) + .expect_err("a host callback needs the module's bus connection"); + + assert!(error.to_string().contains("consequence_host")); +} + #[test] fn connectionless_service_construction_rejects_trace_sink_configuration() { let error = DesktopService::from_config(&json!({ diff --git a/crates/tinycomputer/src/tinybus_module/tinybus_module_tests/consequence_review_tests.rs b/crates/tinycomputer/src/tinybus_module/tinybus_module_tests/consequence_review_tests.rs new file mode 100644 index 000000000..d73214524 --- /dev/null +++ b/crates/tinycomputer/src/tinybus_module/tinybus_module_tests/consequence_review_tests.rs @@ -0,0 +1,157 @@ +//! The host's consequence review, at the service: an approval the host +//! denies reaches the task as a decline. + +use std::collections::VecDeque; +use std::sync::{Arc, Mutex}; + +use serde_json::json; +use tinybus::Interface; +use tinycomputer_bus::agent::{AgentResponse, TaskConstraints, TaskId, TaskStatus, TaskView}; +use tinycomputer_bus::consequence_host::{ReviewActionRequest, ReviewActionResponse}; +use tinycomputer_bus::{ + DesktopResponse, FlowRunResult, FlowStopReason, JevMetrics, JevTarget, RunFlowRequest, + StepOutcome, StepReport, names, +}; +use tinycomputer_engine::{FlowFuture, FlowRunner, Tasks}; + +use super::service; +use crate::tinybus_module::consequence_gate::{ConsequencePort, PortFuture}; + +/// A runner whose first flow stops before pressing "Send", and every later +/// one completes. It records whether each run was allowed to act. +#[derive(Default)] +struct GatedOnce { + replies: Mutex>, + allowed: Mutex>, +} + +fn run(stop: FlowStopReason, steps: Vec, pending: Option<&str>) -> FlowRunResult { + FlowRunResult { + stop, + steps, + vars: std::collections::BTreeMap::new(), + pending: pending.map(|name| JevTarget { + ref_id: "e9".to_owned(), + role: "button".to_owned(), + name: Some(name.to_owned()), + }), + learned: Vec::new(), + actions: 1, + metrics: JevMetrics::default(), + trace: Vec::new(), + dialog_left_open: false, + } +} + +impl FlowRunner for GatedOnce { + fn run(&self, _: &TaskId, _: &TaskConstraints, request: RunFlowRequest) -> FlowFuture { + self.allowed.lock().unwrap().push(request.allow_destructive); + let result = self + .replies + .lock() + .unwrap() + .pop_front() + .unwrap_or_else(|| run(FlowStopReason::Completed, Vec::new(), None)); + let reply = DesktopResponse::ok("run-flow", serde_json::to_value(result).unwrap()); + Box::pin(async move { reply }) + } +} + +#[derive(Debug, Default)] +struct DenyingHost { + seen: Mutex>, +} + +impl ConsequencePort for Arc { + fn review(&self, request: ReviewActionRequest) -> PortFuture<'_, ReviewActionResponse> { + self.seen.lock().unwrap().push(request); + Box::pin(async { + Ok(ReviewActionResponse { + allow: false, + reason: Some("not today".to_owned()), + }) + }) + } +} + +async fn awaited(service: &crate::tinybus_module::DesktopService, id: &TaskId) -> TaskView { + let settled = service + .call( + &names::methods::AWAIT_TASK.try_into().unwrap(), + json!([{"id": id, "timeout_ms": 5_000}]), + ) + .await + .unwrap(); + serde_json::from_value::>(settled) + .unwrap() + .data + .unwrap() +} + +#[tokio::test] +async fn a_host_denial_turns_an_approval_into_a_decline() { + let runner = Arc::new(GatedOnce::default()); + runner.replies.lock().unwrap().push_back(run( + FlowStopReason::StoppedBeforeDestructive, + vec![StepReport { + path: "1".to_owned(), + kind: "stop_before".to_owned(), + text: "sending the email".to_owned(), + outcome: StepOutcome::Gated, + turns: 1, + jev_calls: 1, + actions: Vec::new(), + loops: Vec::new(), + confidence: None, + note: "found it".to_owned(), + }], + Some("Send"), + )); + let host = Arc::new(DenyingHost::default()); + let mut service = service().with_consequence_review(Box::new(host.clone())); + service.tasks = Arc::new(Tasks::new(runner.clone())); + + let started = service + .call( + &names::methods::START_TASK.try_into().unwrap(), + json!([{"flow": {"app": "Mail", "steps": [ + {"stop_before": "sending the email"}, + "start another email message" + ]}}]), + ) + .await + .unwrap(); + let id = serde_json::from_value::>(started) + .unwrap() + .data + .unwrap() + .id; + let paused = awaited(&service, &id).await; + assert!( + matches!(paused.status, TaskStatus::NeedsApproval { ref target, .. } if target == "Send"), + "{:?}", + paused.status + ); + + service + .call( + &names::methods::CONTINUE_TASK.try_into().unwrap(), + json!([{"id": id, "approve": true}]), + ) + .await + .unwrap(); + + assert_eq!(awaited(&service, &id).await.status, TaskStatus::Cancelled); + let seen = host.seen.lock().unwrap(); + assert_eq!(seen.len(), 1, "the host is asked once"); + assert_eq!(seen[0].target, "Send"); + assert!( + !runner + .allowed + .lock() + .unwrap() + .iter() + .any(|allowed| *allowed), + "no run was allowed to take the denied action" + ); +} diff --git a/crates/tinycomputer/tests/public_api_tests.rs b/crates/tinycomputer/tests/public_api_tests.rs index 9497a15c0..b63bb8ddc 100644 --- a/crates/tinycomputer/tests/public_api_tests.rs +++ b/crates/tinycomputer/tests/public_api_tests.rs @@ -34,7 +34,7 @@ fn the_crate_re_exports_the_contract_rather_than_redefining_it() { #[test] fn the_shipped_contract_binds_to_itself() { assert!(is_compatible(CONTRACT_VERSION)); - assert_eq!(CONTRACT_VERSION, (2, 26)); + assert_eq!(CONTRACT_VERSION, (2, 28)); assert!(!is_compatible((2, 25))); } diff --git a/docs/crates/tinycomputer-bus/agent-and-tasks.md b/docs/crates/tinycomputer-bus/agent-and-tasks.md index 45648e410..2ef98445d 100644 --- a/docs/crates/tinycomputer-bus/agent-and-tasks.md +++ b/docs/crates/tinycomputer-bus/agent-and-tasks.md @@ -108,7 +108,8 @@ for the fuller picture of what does and does not get automated here. `TaskBudget` mirrors the levers `RunFlowRequest` exposes (see [Writing flows](flows.md)) but every field is `Option`, so an unset one takes the module's own default rather than the crate baking one in twice: -`max_actions`, `max_model_calls`, `votes`, `strategy`, `deliberation`, +`max_actions`, `max_model_calls`, `votes`, `max_do_turns` (turns each `do` +step may spend, 8 when unset, at most 32), `strategy`, `deliberation`, `max_elapsed_ms` (excludes time spent waiting on the caller), and `max_rescues`, how many times a failed step may be handed to a reasoning model for guidance before the task gives up on it. Absent means the module's diff --git a/docs/crates/tinycomputer-bus/versioning.md b/docs/crates/tinycomputer-bus/versioning.md index b4767f549..edf255cf1 100644 --- a/docs/crates/tinycomputer-bus/versioning.md +++ b/docs/crates/tinycomputer-bus/versioning.md @@ -9,7 +9,7 @@ code, so this page exists mostly to keep them apart. ## `CONTRACT_VERSION`: does this host understand this module ```rust,ignore -pub const CONTRACT_VERSION: (u32, u32) = (2, 26); +pub const CONTRACT_VERSION: (u32, u32) = (2, 27); ``` This describes the *vocabulary*: the member set and the payload shapes, @@ -45,17 +45,19 @@ Two conditions, both necessary: relies on changed shape or disappeared, so a mismatched major is refused outright, in either direction. 2. **The module must be at least as new, minor-wise, as the host.** A host - built against `(2, 26)` expects at least the members and fields that - existed at `(2, 26)`. A module reporting `(2, 25)` predates the + built against `(2, 27)` expects at least the members and fields that + existed at `(2, 27)`. A module reporting `(2, 26)` lacks host-context relay + for `ConsequenceHost`, so a 2.27 host rejects it. A module reporting + `(2, 25)` predates the `TraceSinkHost` callback added in 2.26, so a 2.26 host rejects it. It does include `BrowserEgressHost`, which was added in 2.25. A newer module with the same major is accepted. ```rust,ignore -assert!(is_compatible(CONTRACT_VERSION)); // (2, 26), the exact version this crate ships -assert!(is_compatible((2, 27))); // a newer, still-compatible module +assert!(is_compatible(CONTRACT_VERSION)); // (2, 27), the exact version this crate ships +assert!(is_compatible((2, 28))); // a newer, still-compatible module assert!(!is_compatible((2, 11))); // an older module, missing something -assert!(!is_compatible((2, 25))); // predates TraceSinkHost; includes BrowserEgressHost from 2.25 +assert!(!is_compatible((2, 26))); // predates ConsequenceHost host-context relay assert!(!is_compatible((1, 10))); // a different major, all bets off ``` diff --git a/docs/crates/tinycomputer/configuration.md b/docs/crates/tinycomputer/configuration.md index 51717dbf1..561cd88cf 100644 --- a/docs/crates/tinycomputer/configuration.md +++ b/docs/crates/tinycomputer/configuration.md @@ -66,6 +66,26 @@ can retry `TaskReport`. Without this key, or with `false`, the existing `trace_path` behavior remains in effect. `true`, malformed objects, and well-known bus names are rejected. +## `consequence_host` + +```json +{ + "consequence_host": { + "destination": ":1.42" + } +} +``` + +Set `consequence_host` to an object containing only the unique callback +destination prepared for this module by `ModuleHost::prepare_host_callbacks`. +The module sends consequence reviews to the host through that confidential +callback. When a `ContinueTask` approves a pending action for host review, +failure to reach the configured callback declines the action. A declined +approval, unanswered pause, or continuation without a pending action does not +fail solely because this callback is absent. Without this key, or with +`false`, calls without host context keep using the legacy well-known host +interface. `true`, malformed objects, and well-known bus names are rejected. + ## `jev` ```json diff --git a/docs/technical/architecture.md b/docs/technical/architecture.md index 1f0ef1317..5036b776a 100644 --- a/docs/technical/architecture.md +++ b/docs/technical/architecture.md @@ -222,6 +222,7 @@ configuration validates. | `trace_path` | string | where agent-desktop writes its trace | | `trace_strict` | bool | fail a call when its trace cannot be written | | `trace_sink` | object | optional host-owned persistence at the unique destination prepared by `ModuleHost::prepare_host_callbacks`; replaces local trace and session persistence | +| `consequence_host` | object | optional confidential consequence review callback at the unique destination prepared by `ModuleHost::prepare_host_callbacks`; a missing callback denies an approved pending action under host review | | `headed` | bool | use real input instead of accessibility actions | | `jev` | object | decision provider (`type_safe`, `open_router`, `tiny_humans_open_router`, `open_jev`, `sage`), API key, optional model, approved endpoint, timeout, retries, `sdk_name` for the TinyHumans proxy, and `fast` for Sage | | `planner` | object | `api_key`, `provider` (`open_router` or `tiny_humans`), approved `endpoint_url`, `sdk_name`, and optional `model` for the planner, optional `rescue_route` giving the rescuer its own route and key, optional `rescue_model` for rescuing failed steps (`docs/technical/specs/task-rescue.md`), and optional `output_model` for shaping a finished task's answer (`docs/technical/specs/task-output.md`); absent means no planner, no rescues, and no output shapes | diff --git a/docs/technical/decision-thresholds.md b/docs/technical/decision-thresholds.md index c65e94e10..b050e3d64 100644 --- a/docs/technical/decision-thresholds.md +++ b/docs/technical/decision-thresholds.md @@ -32,7 +32,7 @@ Change a constant and its row together. | `CAP` | 20 | `ask/mod.rs` | most options in one Choice | | `HEDGED` | 0.10 | `ask/answers.rs` | distance from an even chance within which a condition's calibrated yes/no says nothing either way, and defers to a crisp coverage | | `CRISP_TOP` | 0.85 | `ask/answers.rs` | probability on a condition's top coverage level at which it stands alone for a hedged yes/no | -| `DO_TURNS` | 8 | `steps/mod.rs` | turns a `do` step may spend | +| `DO_TURNS` / `MAX_DO_TURNS` | 8 / 32 | `steps/mod.rs`, `mod.rs` | turns a `do` step may spend when `max_do_turns` is unset, and the most a run may set | | `REFLECT_FLOOR` | 0.50 | `reflect.rs` | belief that a pressed `choose` left its choice, below which it is repaired, and failed if the repair does not take | | `REPAIR_TURNS` | 4 | `reflect.rs` | turns one reflection repair may spend | | `MAX_ACTIONS` / `MAX_CALLS` | 120 / 10000 | `mod.rs` | per-run caps on actions and Jev calls | diff --git a/docs/technical/specs/desktop-module-contract.md b/docs/technical/specs/desktop-module-contract.md index 79d556918..098e16284 100644 --- a/docs/technical/specs/desktop-module-contract.md +++ b/docs/technical/specs/desktop-module-contract.md @@ -89,6 +89,20 @@ serves the interface and fails to answer, turns the approval into a decline, so the task never takes the action. A host that serves nothing leaves the pause as the only gate. A payment checkpoint is never continuable and needs no review. +Do-step turns (2.28): `TaskBudget` and `RunFlowRequest` take an optional +`max_do_turns`, the turns each `do` step may spend before it fails as not +accomplished. Unset keeps the module's default of 8; the module caps it at +32. A 2.27 module ignores the field. + +Host context relay (2.27): `ContinueTaskRequest` takes an optional opaque +`host_context`. When the module requests consequence review, it copies that +value unchanged into `ReviewActionRequest.host_context`; the module does not +interpret it or grant it authority. The bus type redacts the value from its +`Debug` output. Hosts that use the relay must validate the context themselves +and bind it to the task and action under review. Omitting the field preserves +the earlier continuation and consequence-review behavior; hosts that depend on +the relay require a compatible 2.27 module. + Browser egress (2.25): a host may serve the optional `ai.tinyhumans.tinycomputer.BrowserEgressHost` interface (`tinycomputer_bus::browser_egress`) with `Authorize`, `Consume`, and diff --git a/docs/technical/tasks.md b/docs/technical/tasks.md index 134f3b4ee..b46f5b074 100644 --- a/docs/technical/tasks.md +++ b/docs/technical/tasks.md @@ -163,6 +163,9 @@ is acted on: `deep` (the default), `standard`, or `off` ([`specs/jev-deliberation.md`](specs/jev-deliberation.md)). Deliberation spends calls only where the evidence is thin, and degrades rung by rung when the budget runs short rather than failing the run. +`budget.max_do_turns` sets how many turns each `do` step may spend before it +fails as not accomplished: 8 when unset, at most 32. A long step on a busy +page, such as a shop's cart or checkout, may need more than 8 moves. `budget.max_rescues` caps how many failed steps are rescued (below). The flow runtime has no clock, so `max_elapsed_ms` is enforced by the controller, which times out a run that would go past what is left. Time