Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
3 changes: 3 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -118,3 +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
# 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
1 change: 1 addition & 0 deletions crates/tinycomputer/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ rust-version.workspace = true
license.workspace = true
repository.workspace = true
description = "Native desktop automation — accessibility-tree observation and interaction — as an installable TinyBus module."
build = "build.rs"
documentation = "https://docs.rs/tinycomputer"
readme = "../../README.md"
keywords = ["tinybus", "module", "accessibility", "automation", "desktop"]
Expand Down
9 changes: 9 additions & 0 deletions crates/tinycomputer/build.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
//! Declares the opt-in compile-time gate for local live Chromium tests.

fn main() {
println!("cargo:rustc-check-cfg=cfg(live_module_browser_egress_tests)");
println!("cargo:rerun-if-env-changed=TINYCOMPUTER_LIVE_BROWSER_EGRESS_TESTS");
if std::env::var_os("TINYCOMPUTER_LIVE_BROWSER_EGRESS_TESTS").is_some() {
Comment thread
senamakel marked this conversation as resolved.
Resolved
println!("cargo:rustc-cfg=live_module_browser_egress_tests");
}
}
253 changes: 253 additions & 0 deletions crates/tinycomputer/src/tinybus_module/browser_egress_live_tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,253 @@
//! 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,
};

#[derive(Clone)]
struct EgressHost {
allowed: Arc<AtomicBool>,
allowed_address: String,
observations: Arc<Mutex<Vec<String>>>,
}

#[tinybus::interface(name = "ai.tinyhumans.tinycomputer.BrowserEgressHost")]
impl EgressHost {
async fn authorize(&self, request: BrowserEgressTarget) -> tinybus::Result<BrowserEgressGrant> {
let allow = self.allowed.load(Ordering::SeqCst)
&& request.hostname == "fixture.test"
&& request.port
== self
.allowed_address
.rsplit(':')
.next()
.and_then(|port| port.parse::<u16>().ok())
.unwrap_or_default();
self.observations.lock().unwrap().push(format!(
"authorize:{}:{}:{}:{}",
request.policy_id, request.expected_generation, request.hostname, request.port
));
Ok(BrowserEgressGrant {
generation: 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<BrowserEgressDecision> {
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<BrowserEgressDecision> {
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<AtomicUsize>,
served: tokio::sync::oneshot::Sender<()>,
) {
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,
]
.concat();
let _ = tokio::io::AsyncWriteExt::write_all(&mut stream, &response).await;
let _ = served.send(());
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]
async fn live_chromium_module_dials_only_the_host_returned_socket_and_rejects_changed_policy()
-> tinybus::Result<()> {
Comment thread
senamakel marked this conversation as resolved.
Resolved
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,
));

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 = 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(),
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
);
tokio::time::timeout(Duration::from_secs(10), served_rx)
.await
.expect("authorized Chromium request reaches the fixture within ten seconds")
.expect("authorized fixture reports its response");

let authorizations_before_policy_change = 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.
allowed.store(false, Ordering::SeqCst);
let denied_url = format!("http://fixture.test:{port}/after-policy-change");
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_eq!(
extra_allowed_connections.load(Ordering::SeqCst),
extra_connections_before_policy_change,
"policy-denied navigation connected to the previously allowed socket"
);

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 socket was consumed: {calls:?}"
);
broker_task.abort();
allowed_server.abort();
Ok(())
}
4 changes: 4 additions & 0 deletions crates/tinycomputer/src/tinybus_module/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,5 +106,9 @@ tinybus_module::module_export_optional_static! {
#[path = "static_link_tests.rs"]
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)]
mod tinybus_module_tests;
Loading