Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
8ac02a1
test(browser): cover worker egress authorization
senamakel Oct 22, 2026
ed424f2
style(tinycomputer): reformat browser egress live tests
senamakel Oct 22, 2026
10473e3
test(browser_egress): allow extra clippy lints in live tests
senamakel Oct 22, 2026
80b0975
test(tinycomputer): scope clippy allows to the items that need them
senamakel Oct 22, 2026
a942705
test(browser_egress): extract shared fixture host setup for live tests
senamakel Oct 22, 2026
4dee0d5
test(browser_egress): reuse fixture host helper in worker egress test
senamakel Oct 22, 2026
7060a52
test(browser_egress): align broker task handle type with tinybus result
senamakel Oct 22, 2026
ba7663f
test(browser): report observations when worker egress times out
senamakel Oct 22, 2026
a32341a
test(browser): distinguish bypass from unreached host authorization
senamakel Oct 22, 2026
b8fb10e
test(browser_egress): keep host connection and module host alive in l…
senamakel Oct 22, 2026
9080d6c
test(browser_egress): scope observation lock to assertion block
senamakel Oct 22, 2026
960447a
test(browser): wait for worker completion before asserting egress
senamakel Oct 22, 2026
c3f56dc
test(browser_egress): assert exact allowed connection count
senamakel Oct 22, 2026
eab0940
test(browser_egress): split live tests into a module directory
senamakel Oct 22, 2026
b9aa8d6
test(browser_egress): remove trailing blank line
senamakel Oct 22, 2026
37cc9f4
test(browser): document opt-in worker egress coverage
senamakel Oct 22, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -28,6 +30,7 @@ struct EgressHost {
#[tinybus::interface(name = "ai.tinyhumans.tinycomputer.BrowserEgressHost")]
impl EgressHost {
async fn authorize(&self, request: BrowserEgressTarget) -> tinybus::Result<BrowserEgressGrant> {
tokio::task::yield_now().await;
let allow = self.allowed.load(Ordering::SeqCst)
&& request.hostname == "fixture.test"
&& request.port
Expand Down Expand Up @@ -61,6 +64,7 @@ impl EgressHost {
&self,
request: BrowserEgressConsumeRequest,
) -> tinybus::Result<BrowserEgressDecision> {
tokio::task::yield_now().await;
self.observations
.lock()
.unwrap()
Expand All @@ -74,6 +78,7 @@ impl EgressHost {
&self,
request: BrowserEgressValidateRequest,
) -> tinybus::Result<BrowserEgressDecision> {
tokio::task::yield_now().await;
self.observations
.lock()
.unwrap()
Expand All @@ -87,9 +92,10 @@ impl EgressHost {

async fn serve_fixture(
listener: tokio::net::TcpListener,
expected: &'static [u8],
expected: Vec<u8>,
extra_connections: Arc<AtomicUsize>,
served: tokio::sync::oneshot::Sender<()>,
worker_done: Option<tokio::sync::oneshot::Sender<()>>,
) {
let (mut stream, _) = listener
.accept()
Expand All @@ -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(());
}
}
}
}

Expand All @@ -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"<!doctype html><link rel=\"icon\" href=\"data:,\"><title>allowed fixture</title>",
extra_allowed_connections.clone(),
served_tx,
));
struct LiveBrowser {
proxy: tinybus::Proxy,
session: serde_json::Value,
allowed: Arc<AtomicBool>,
observations: Arc<Mutex<Vec<String>>>,
broker_task: tokio::task::JoinHandle<tinybus::Result<()>>,
_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<LiveBrowser> {
let bus = MemoryBus::new();
let broker = Broker::new();
let broker_task = broker.spawn(bus.clone());
Expand All @@ -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(),
},
)
Expand Down Expand Up @@ -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,
Expand All @@ -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"<!doctype html><link rel=\"icon\" href=\"data:,\"><title>allowed fixture</title>"
.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()
Expand All @@ -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!(
Expand All @@ -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(())
}
Original file line number Diff line number Diff line change
@@ -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!(
"<!doctype html><link rel=\"icon\" href=\"data:,\"><script>\
const worker = new Worker(URL.createObjectURL(new Blob([\
\"fetch('http://127.0.0.2:{denied_port}/worker').catch(() => {{}}).finally(() => fetch('http://fixture.test:{page_port}/worker-done').catch(() => {{}}))\"\
], {{ type: 'text/javascript' }})));</script>"
)
.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(())
}
1 change: 0 additions & 1 deletion crates/tinycomputer/src/tinybus_module/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down
Loading