Repository navigation
test(browser-egress): exercise host authorization through module #152
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
76832c7
chore(vendor): bump agent-browser, agent-desktop, tinybus and tinyinf…
senamakel 0d58f77
chore(vendor): bump agent-browser, agent-desktop, tinybus and tinyinf…
senamakel 66f4b0f
feat(tinycomputer): add live browser egress tests behind a build flag
senamakel 12100c9
test(tinycomputer): align live browser egress test with current bus API
senamakel f2170e0
test(tinybus): annotate port parse type in browser egress live tests
senamakel 9505180
test(browser_egress): assert session launch and drop headless flag
senamakel 2c04c85
test(browser_egress): tighten live chromium egress assertions
senamakel 7c3f6cc
style(tinycomputer): fix indentation in browser egress live test
senamakel af91ba0
docs(test): document live browser egress switch
senamakel 81d7390
test(browser_egress): assert denied navigation never dials the allowe…
senamakel 2201c9a
test(browser_egress): reflow an over-wrapped assertion binding
senamakel 2026946
docs(test): qualify live browser egress test filter
senamakel File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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() { | ||
| println!("cargo:rustc-cfg=live_module_browser_egress_tests"); | ||
| } | ||
| } | ||
253 changes: 253 additions & 0 deletions
253
crates/tinycomputer/src/tinybus_module/browser_egress_live_tests.rs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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<()> { | ||
|
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(()) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.