diff --git a/.env.example b/.env.example index ae778e276..bb65b9c98 100644 --- a/.env.example +++ b/.env.example @@ -118,6 +118,6 @@ 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: -# 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::live_chromium_module_dials_only_the_host_returned_socket_and_rejects_changed_policy -- --exact --nocapture +# 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 diff --git a/crates/tinycomputer/src/tinybus_module/browser_egress_live_tests.rs b/crates/tinycomputer/src/tinybus_module/browser_egress_live_tests/mod.rs similarity index 66% rename from crates/tinycomputer/src/tinybus_module/browser_egress_live_tests.rs rename to crates/tinycomputer/src/tinybus_module/browser_egress_live_tests/mod.rs index e466eebbe..f6732792e 100644 --- a/crates/tinycomputer/src/tinybus_module/browser_egress_live_tests.rs +++ b/crates/tinycomputer/src/tinybus_module/browser_egress_live_tests/mod.rs @@ -1,5 +1,7 @@ -//! Opt-in real-Chromium coverage through the loaded TinyComputer module. -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +//! Opt-in real-Chromium coverage through the loaded `TinyComputer` module. +#![allow(clippy::expect_used, clippy::panic, clippy::unwrap_used)] + +mod worker; use std::sync::{ Arc, Mutex, @@ -28,6 +30,7 @@ struct EgressHost { #[tinybus::interface(name = "ai.tinyhumans.tinycomputer.BrowserEgressHost")] impl EgressHost { async fn authorize(&self, request: BrowserEgressTarget) -> tinybus::Result { + tokio::task::yield_now().await; let allow = self.allowed.load(Ordering::SeqCst) && request.hostname == "fixture.test" && request.port @@ -61,6 +64,7 @@ impl EgressHost { &self, request: BrowserEgressConsumeRequest, ) -> tinybus::Result { + tokio::task::yield_now().await; self.observations .lock() .unwrap() @@ -74,6 +78,7 @@ impl EgressHost { &self, request: BrowserEgressValidateRequest, ) -> tinybus::Result { + tokio::task::yield_now().await; self.observations .lock() .unwrap() @@ -87,9 +92,10 @@ impl EgressHost { async fn serve_fixture( listener: tokio::net::TcpListener, - expected: &'static [u8], + expected: Vec, extra_connections: Arc, served: tokio::sync::oneshot::Sender<()>, + worker_done: Option>, ) { let (mut stream, _) = listener .accept() @@ -102,14 +108,27 @@ async fn serve_fixture( 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, + expected.as_slice(), ] .concat(); let _ = tokio::io::AsyncWriteExt::write_all(&mut stream, &response).await; let _ = served.send(()); - while let Ok((stream, _)) = listener.accept().await { + drop(stream); + let mut worker_done = worker_done; + while let Ok((mut stream, _)) = listener.accept().await { extra_connections.fetch_add(1, Ordering::SeqCst); - drop(stream); + 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(()); + } + } } } @@ -118,22 +137,22 @@ fn successful_data(reply: &DesktopResponse) -> &serde_json::Value { reply.data.as_ref().expect("successful response has data") } -#[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", - extra_allowed_connections.clone(), - served_tx, - )); +struct LiveBrowser { + proxy: tinybus::Proxy, + session: 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 { let bus = MemoryBus::new(); let broker = Broker::new(); let broker_task = broker.spawn(bus.clone()); @@ -145,7 +164,7 @@ async fn live_chromium_module_dials_only_the_host_returned_socket_and_rejects_ch browser_egress::OBJECT_PATH.try_into()?, EgressHost { allowed: allowed.clone(), - allowed_address: allowed_address.clone(), + allowed_address, observations: observations.clone(), }, ) @@ -175,7 +194,7 @@ async fn live_chromium_module_dials_only_the_host_returned_socket_and_rejects_ch .await?; let session = successful_data(&opened)["id"].clone(); assert_eq!(successful_data(&opened)["launched"], true); - let url = format!("http://fixture.test:{port}/allowed"); + let url = format!("http://fixture.test:{page_port}{page_path}"); let navigated: DesktopResponse = proxy .call( browser_names::methods::NAVIGATE, @@ -184,15 +203,49 @@ async fn live_chromium_module_dials_only_the_host_returned_socket_and_rejects_ch .await?; assert!( navigated.ok, - "authorized navigation failed: {:?}", + "authorized fixture navigation failed: {:?}", navigated.error ); - tokio::time::timeout(Duration::from_secs(10), served_rx) + tokio::time::timeout(Duration::from_secs(10), served) .await - .expect("authorized Chromium request reaches the fixture within ten seconds") - .expect("authorized fixture reports its response"); + .expect("fixture page is served") + .expect("fixture server reports the response"); + + Ok(LiveBrowser { + proxy, + session, + 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 = observations + let authorizations_before_policy_change = browser + .observations .lock() .unwrap() .iter() @@ -201,12 +254,13 @@ async fn live_chromium_module_dials_only_the_host_returned_socket_and_rejects_ch 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. - allowed.store(false, Ordering::SeqCst); + browser.allowed.store(false, Ordering::SeqCst); let denied_url = format!("http://fixture.test:{port}/after-policy-change"); - let denied: DesktopResponse = proxy + let denied: DesktopResponse = browser + .proxy .call( browser_names::methods::NAVIGATE, - (serde_json::json!({"session": session, "url": denied_url}),), + (serde_json::json!({"session": browser.session, "url": denied_url}),), ) .await?; assert!( @@ -225,29 +279,43 @@ async fn live_chromium_module_dials_only_the_host_returned_socket_and_rejects_ch "policy-denied navigation connected to the previously allowed socket" ); - let calls = observations.lock().unwrap(); - assert!( - calls + { + 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() - .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(); + .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!( - !calls - .iter() - .any(|call| call == &format!("consume:{denied_address}")), - "denied socket was consumed: {calls:?}" + closed.ok, + "browser session did not close: {:?}", + closed.error ); - broker_task.abort(); + browser.broker_task.abort(); allowed_server.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/mod.rs b/crates/tinycomputer/src/tinybus_module/mod.rs index e7e3c93f6..d38baacd2 100644 --- a/crates/tinycomputer/src/tinybus_module/mod.rs +++ b/crates/tinycomputer/src/tinybus_module/mod.rs @@ -111,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)]