Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

fix(cua-driver): prefer the owned macOS browser profile endpoint (#4384)

injaneity9966c8bd8054
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/prepare.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/prepare.rs
index 813fee7b71..ad4309cb26 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/prepare.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/prepare.rs
@@ -1354,6 +1354,58 @@ impl BrowserEngine {
mod tests {
use super::*;
+ #[tokio::test]
+ async fn spawned_attestation_retries_absence_but_propagates_profile_errors() {
+ use super::super::types::EndpointTransport;
+ use super::super::v2_tests::fixture;
+ for case in ["missing", "wrong_url", "malformed", "unreadable"] {
+ let f = fixture().await;
+ let endpoint = OwnedEndpoint {
+ ws_url: "ws://127.0.0.1:9222/devtools/browser/expected".into(),
+ http_port: Some(9222),
+ transport: EndpointTransport::DevToolsActivePort,
+ ownership: EndpointOwnershipProof {
+ method: EndpointOwnershipMethod::DevtoolsActivePortsFile,
+ owner_pid: 1,
+ listener_pid: None,
+ detail: None,
+ },
+ };
+ let first = match case {
+ "missing" => Ok(None),
+ "wrong_url" => {
+ let mut wrong = endpoint.clone();
+ wrong.ws_url.push_str("-host");
+ Ok(Some(wrong))
+ }
+ "malformed" => Err(refusal(
+ BrowserRefusalCode::BrowserEndpointOwnerMismatch,
+ "malformed second read",
+ )),
+ _ => Err(refusal(
+ BrowserRefusalCode::BrowserRouteUnavailable,
+ "unreadable second read",
+ )),
+ };
+ f.state.lock().unwrap().endpoint_responses = [first, Ok(Some(endpoint.clone()))].into();
+ let result = attest_spawned_endpoint(&f.engine, 1, endpoint.clone()).await;
+ if matches!(case, "missing" | "wrong_url") {
+ assert_eq!(result.unwrap().ws_url, endpoint.ws_url);
+ assert_eq!(f.state.lock().unwrap().endpoint_discovery_count, 2);
+ } else {
+ assert_eq!(
+ result.unwrap_err().code,
+ if case == "malformed" {
+ BrowserRefusalCode::BrowserEndpointOwnerMismatch
+ } else {
+ BrowserRefusalCode::BrowserRouteUnavailable
+ }
+ );
+ assert_eq!(f.state.lock().unwrap().endpoint_discovery_count, 1);
+ }
+ }
+ }
+
struct DropSignal(Arc<std::sync::atomic::AtomicBool>);
impl Drop for DropSignal {
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/v2_tests.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/v2_tests.rs
index 52793d8060..42df4b0da1 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/v2_tests.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/v2_tests.rs
@@ -43,7 +43,10 @@ use super::types::{
/// test body. Tests flip loaders/capabilities mid-run to simulate
/// navigations, frame removal, and capability regression.
#[derive(Debug)]
-struct FixtureState {
+pub(super) struct FixtureState {
+ pub(super) endpoint_responses:
+ std::collections::VecDeque<Result<Option<OwnedEndpoint>, BrowserRefusal>>,
+ pub(super) endpoint_discovery_count: usize,
oopif_supported: bool,
oopif_present: bool,
emit_rogue_attach: bool,
@@ -78,6 +81,8 @@ struct FixtureState {
impl Default for FixtureState {
fn default() -> Self {
Self {
+ endpoint_responses: Default::default(),
+ endpoint_discovery_count: 0,
oopif_supported: true,
oopif_present: true,
emit_rogue_attach: false,
@@ -698,6 +703,7 @@ fn fixture_handler(state: SharedState) -> MockHandler {
/// Platform adapter pointing at the fixture endpoint: pid 1 is a
/// Chromium browser owning native window 7 at (0,0,800,600).
struct FixturePlatform {
+ endpoint_state: Option<SharedState>,
ws_url: String,
trusted_input_limited: bool,
managed_endpoint_visible: bool,
@@ -762,6 +768,16 @@ impl BrowserPlatform for FixturePlatform {
pid: i64,
) -> Result<Option<OwnedEndpoint>, BrowserRefusal> {
self.managed_discovery_invoked.store(true, Ordering::SeqCst);
+ if let Some(state) = &self.endpoint_state {
+ let mut state = state.lock().unwrap();
+ state.endpoint_discovery_count += 1;
+ if state.endpoint_responses.len() > 1 {
+ return state.endpoint_responses.pop_front().unwrap();
+ }
+ if let Some(response) = state.endpoint_responses.front() {
+ return response.clone();
+ }
+ }
if !self.managed_endpoint_visible {
return Ok(None);
}
@@ -891,11 +907,11 @@ impl BrowserPlatform for FixturePlatform {
// ── Scaffolding ──────────────────────────────────────────────────────────────
-struct Fixture {
- state: SharedState,
+pub(super) struct Fixture {
+ pub(super) state: SharedState,
// Kept alive for the test's duration; dropping it kills the endpoint.
_server: MockCdpServer,
- engine: Arc<BrowserEngine>,
+ pub(super) engine: Arc<BrowserEngine>,
setup_invoked: Arc<AtomicBool>,
}
@@ -913,6 +929,7 @@ async fn fixture_with_platform(
let server = MockCdpServer::start(fixture_handler(state.clone())).await;
let setup_invoked = Arc::new(AtomicBool::new(false));
let engine = BrowserEngine::new(Arc::new(FixturePlatform {
+ endpoint_state: Some(state.clone()),
ws_url: server.ws_url(),
trusted_input_limited,
managed_endpoint_visible: true,
@@ -931,7 +948,7 @@ async fn fixture_with_platform(
}
}
-async fn fixture() -> Fixture {
+pub(super) async fn fixture() -> Fixture {
fixture_with(|_| {}).await
}
@@ -966,6 +983,7 @@ async fn protected_existing_profile_fixture() -> (Fixture, Arc<FixtureProtectedP
});
let engine = BrowserEngine::new_with_protected_consent_provider(
Arc::new(FixturePlatform {
+ endpoint_state: None,
ws_url: server.ws_url(),
trusted_input_limited: false,
managed_endpoint_visible: false,
@@ -995,6 +1013,7 @@ async fn existing_profile_setup_fixture() -> (Fixture, Arc<AtomicBool>) {
let setup_invoked = Arc::new(AtomicBool::new(false));
let engine = BrowserEngine::new_with_protected_consent_provider(
Arc::new(FixturePlatform {
+ endpoint_state: None,
ws_url: server.ws_url(),
trusted_input_limited: false,
managed_endpoint_visible: false,
@@ -1049,6 +1068,7 @@ async fn standalone_consumer_bind_without_grant_refuses_before_endpoint_discover
let managed_discovery_invoked = Arc::new(AtomicBool::new(false));
let setup_invoked = Arc::new(AtomicBool::new(false));
let engine = BrowserEngine::new(Arc::new(FixturePlatform {
+ endpoint_state: None,
ws_url: server.ws_url(),
trusted_input_limited: false,
managed_endpoint_visible: true,
@@ -1295,6 +1315,7 @@ async fn refused_consent_cancels_stalled_claim_before_revoking_grant() {
});
let engine = BrowserEngine::new_with_protected_consent_provider(
Arc::new(FixturePlatform {
+ endpoint_state: None,
ws_url: format!("ws://{address}/devtools/browser"),
trusted_input_limited: false,
managed_endpoint_visible: false,
@@ -1339,6 +1360,7 @@ async fn cancelled_prepare_aborts_the_exact_pending_setup() {
let setup_aborted = Arc::new(AtomicBool::new(false));
let engine = BrowserEngine::new_with_protected_consent_provider(
Arc::new(FixturePlatform {
+ endpoint_state: None,
ws_url: format!("ws://{address}/devtools/browser"),
trusted_input_limited: false,
managed_endpoint_visible: false,
@@ -2034,6 +2056,136 @@ async fn rogue_attach_announcements_are_contained() {
);
}
+#[tokio::test]
+async fn stale_profile_path_redials_only_the_exact_endpoint() {
+ use tokio_tungstenite::tungstenite::handshake::server::{Request, Response};
+ let f = fixture().await;
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let port = listener.local_addr().unwrap().port();
+ let mut server = tokio::spawn(async move {
+ let mut paths = Vec::new();
+ for _ in 0..2 {
+ let (stream, _) = listener.accept().await.unwrap();
+ let result =
+ tokio_tungstenite::accept_hdr_async(stream, |request: &Request, _: Response| {
+ paths.push(request.uri().path().to_owned());
+ Err(tokio_tungstenite::tungstenite::http::Response::builder()
+ .status(404)
+ .body(Some("stale browser path".to_owned()))
+ .unwrap())
+ })
+ .await;
+ assert!(result.is_err());
+ }
+ paths
+ });
+ f.state
+ .lock()
+ .unwrap()
+ .endpoint_responses
+ .push_back(Ok(Some(OwnedEndpoint {
+ ws_url: format!("ws://127.0.0.1:{port}/devtools/browser/stale"),
+ http_port: Some(port),
+ transport: EndpointTransport::DevToolsActivePort,
+ ownership: EndpointOwnershipProof {
+ method: EndpointOwnershipMethod::DevtoolsActivePortsFile,
+ owner_pid: 1,
+ listener_pid: None,
+ detail: None,
+ },
+ })));
+ let exchange = tokio::time::timeout(std::time::Duration::from_secs(5), async {
+ let result = GetBrowserStateTool::new(f.engine.clone())
+ .invoke(json!({ "pid": 1, "window_id": 7, "session": SESSION }))
+ .await;
+ (result, (&mut server).await.unwrap())
+ })
+ .await;
+ server.abort();
+ let (result, paths) = exchange.expect("both exact-path attempts must finish");
+ assert_eq!(
+ structured(&result)["refusal"]["code"],
+ "browser_route_unavailable"
+ );
+ assert_eq!(paths, ["/devtools/browser/stale"; 2]);
+ assert!(f.state.lock().unwrap().calls.is_empty());
+}
+
+#[tokio::test]
+async fn owned_endpoint_transitions_refuse_before_dispatch() {
+ use super::refusal::BrowserRefusalCode;
+ for initial in [
+ EndpointTransport::LegacyJsonVersion,
+ EndpointTransport::DevToolsActivePort,
+ ] {
+ for change in ["transport", "url", "missing", "malformed", "unreadable"] {
+ let f = fixture().await;
+ let endpoint = OwnedEndpoint {
+ ws_url: f._server.ws_url(),
+ http_port: None,
+ transport: initial,
+ ownership: EndpointOwnershipProof {
+ method: EndpointOwnershipMethod::ListeningSocketPid,
+ owner_pid: 1,
+ listener_pid: None,
+ detail: None,
+ },
+ };
+ f.state
+ .lock()
+ .unwrap()
+ .endpoint_responses
+ .push_back(Ok(Some(endpoint.clone())));
+ let (target, tab) = bind(&f).await;
+ let snapshot = snapshot(&f, &target, &tab).await;
+ let reference = ref_of(&snapshot, "main", "main-btn");
+ let mut changed = endpoint;
+ let (response, code) = match change {
+ "transport" => {
+ changed.transport = if initial == EndpointTransport::LegacyJsonVersion {
+ EndpointTransport::DevToolsActivePort
+ } else {
+ EndpointTransport::LegacyJsonVersion
+ };
+ (Ok(Some(changed)), "browser_binding_stale")
+ }
+ "url" => {
+ changed.ws_url.push_str("-changed");
+ (Ok(Some(changed)), "browser_binding_stale")
+ }
+ "missing" => (Ok(None), "browser_requires_setup"),
+ "malformed" => (
+ Err(BrowserRefusal::new(
+ BrowserRefusalCode::BrowserEndpointOwnerMismatch,
+ "malformed profile",
+ )),
+ "browser_endpoint_owner_mismatch",
+ ),
+ _ => (
+ Err(BrowserRefusal::new(
+ BrowserRefusalCode::BrowserRouteUnavailable,
+ "unreadable profile",
+ )),
+ "browser_route_unavailable",
+ ),
+ };
+ f.state.lock().unwrap().endpoint_responses = [response].into();
+ let result = BrowserClickTool::new(f.engine.clone())
+ .invoke(json!({
+ "target_id": target, "tab_id": tab, "ref": reference, "session": SESSION
+ }))
+ .await;
+ assert_eq!(
+ structured(&result)["refusal"]["code"],
+ code,
+ "{initial:?} {change}: {}",
+ structured(&result)
+ );
+ assert!(recorded_calls(&f, "Input.dispatchMouseEvent").is_empty());
+ }
+ }
+}
+
// ── Mutation routing + frame identity revalidation ──────────────────────────
#[tokio::test]
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/browser/platform.rs b/libs/cua-driver/rust/crates/platform-macos/src/browser/platform.rs
index e60c0c0816..ce9ff48b7c 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/browser/platform.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/browser/platform.rs
@@ -221,6 +221,52 @@ impl MacOsBrowserPlatform {
browser_cursors: Arc::new(Mutex::new(BrowserCursorTracker::default())),
}
}
+
+ async fn discover_endpoint(
+ &self,
+ pid: i64,
+ existing_profile: bool,
+ ) -> Result<Option<OwnedEndpoint>, BrowserRefusal> {
+ // Profile evidence distinguishes the browser from an inherited host listener.
+ let classification = self.classify_browser(pid).await?;
+ if let Some(endpoint) = active_port_endpoint_with_relative_fallback(
+ pid,
+ classification.product_kind,
+ !existing_profile,
+ )
+ .await?
+ {
+ return Ok(Some(endpoint));
+ }
+ let mut discovered = None;
+ for port in loopback_ports_for_pid(pid).await? {
+ let Some(ws_url) = browser_websocket_url(port).await else {
+ continue;
+ };
+ if discovered.is_some() {
+ return Err(refusal(
+ BrowserRefusalCode::BrowserBindingAmbiguous,
+ "multiple browser-level DevTools endpoints are owned by the approved process",
+ ));
+ }
+ let endpoint = OwnedEndpoint {
+ ws_url,
+ http_port: Some(port),
+ transport: EndpointTransport::LegacyJsonVersion,
+ ownership: EndpointOwnershipProof {
+ method: EndpointOwnershipMethod::ListeningSocketPid,
+ owner_pid: pid,
+ listener_pid: None,
+ detail: Some("lsof loopback listener owner plus /json/version".to_owned()),
+ },
+ };
+ if !existing_profile {
+ return Ok(Some(endpoint));
+ }
+ discovered = Some(endpoint);
+ }
+ Ok(discovered)
+ }
}
impl Default for MacOsBrowserPlatform {
@@ -444,9 +490,10 @@ fn process_arguments(pid: i64) -> Result<Vec<Vec<u8>>, BrowserRefusal> {
Ok(args)
}
-fn user_data_dir_from_arguments(
+fn user_data_dir_from_arguments_with_relative_fallback(
args: &[Vec<u8>],
default: Option<PathBuf>,
+ allow_relative_fallback: bool,
) -> Result<Option<PathBuf>, BrowserRefusal> {
use std::os::unix::ffi::OsStringExt;
@@ -467,6 +514,7 @@ fn user_data_dir_from_arguments(
match directories.as_slice() {
[] => Ok(default),
[path] if path.is_absolute() => Ok(Some(path.clone())),
+ [_] if allow_relative_fallback => Ok(None),
[_] => Err(refusal(
BrowserRefusalCode::BrowserRouteUnavailable,
"the browser uses a relative --user-data-dir that cannot be attested without its launch working directory",
@@ -481,10 +529,15 @@ fn user_data_dir_from_arguments(
async fn user_data_dir_for_pid(
pid: i64,
product: BrowserProduct,
+ allow_relative_fallback: bool,
) -> Result<Option<PathBuf>, BrowserRefusal> {
tokio::task::spawn_blocking(move || {
let args = process_arguments(pid)?;
- user_data_dir_from_arguments(&args, default_user_data_dir(product))
+ user_data_dir_from_arguments_with_relative_fallback(
+ &args,
+ default_user_data_dir(product),
+ allow_relative_fallback,
+ )
})
.await
.map_err(|error| {
@@ -569,6 +622,8 @@ async fn loopback_ports_for_pid(pid: i64) -> Result<Vec<u16>, BrowserRefusal> {
let output = tokio::process::Command::new("lsof")
.args([
"-a",
+ // Numeric addresses: never block on DNS while enumerating listeners.
+ "-n",
"-p",
&pid.to_string(),
"-iTCP",
@@ -596,12 +651,21 @@ async fn loopback_ports_for_pid(pid: i64) -> Result<Vec<u16>, BrowserRefusal> {
async fn active_port_endpoint(
pid: i64,
product: BrowserProduct,
+) -> Result<Option<OwnedEndpoint>, BrowserRefusal> {
+ active_port_endpoint_with_relative_fallback(pid, product, false).await
+}
+
+async fn active_port_endpoint_with_relative_fallback(
+ pid: i64,
+ product: BrowserProduct,
+ allow_relative_fallback: bool,
) -> Result<Option<OwnedEndpoint>, BrowserRefusal> {
// The Chrome 144+ existing-profile bridge deliberately returns 404 for
// legacy /json discovery. Its exact browser WebSocket path is instead
// published in the exact user-data root's DevToolsActivePort file. argv
// comes from KERN_PROCARGS2 rather than lossy `ps` text.
- let Some(user_data_dir) = user_data_dir_for_pid(pid, product).await? else {
+ let Some(user_data_dir) = user_data_dir_for_pid(pid, product, allow_relative_fallback).await?
+ else {
return Ok(None);
};
let text = match tokio::fs::read_to_string(user_data_dir.join("DevToolsActivePort")).await {
@@ -929,64 +993,14 @@ impl BrowserPlatform for MacOsBrowserPlatform {
&self,
pid: i64,
) -> Result<Option<OwnedEndpoint>, BrowserRefusal> {
- for port in loopback_ports_for_pid(pid).await? {
- if let Some(ws_url) = browser_websocket_url(port).await {
- return Ok(Some(OwnedEndpoint {
- ws_url,
- http_port: Some(port),
- transport: EndpointTransport::LegacyJsonVersion,
- ownership: EndpointOwnershipProof {
- method: EndpointOwnershipMethod::ListeningSocketPid,
- owner_pid: pid,
- listener_pid: None,
- detail: Some("lsof loopback listener owner".to_owned()),
- },
- }));
- }
- }
- Ok(None)
+ self.discover_endpoint(pid, false).await
}
async fn discover_existing_profile_endpoint(
&self,
pid: i64,
) -> Result<Option<OwnedEndpoint>, BrowserRefusal> {
- let classification = self.classify_browser(pid).await?;
- if let Some(endpoint) = active_port_endpoint(pid, classification.product_kind).await? {
- return Ok(Some(endpoint));
- }
- let ports = loopback_ports_for_pid(pid).await?;
- let mut discovered = Vec::new();
- for port in &ports {
- if let Some(ws_url) = browser_websocket_url(*port).await {
- discovered.push((*port, ws_url));
- }
- }
- if discovered.len() == 1 {
- let (port, ws_url) = discovered.pop().expect("one discovered endpoint");
- return Ok(Some(OwnedEndpoint {
- ws_url,
- http_port: Some(port),
- transport: EndpointTransport::LegacyJsonVersion,
- ownership: EndpointOwnershipProof {
- method: EndpointOwnershipMethod::ListeningSocketPid,
- owner_pid: pid,
- listener_pid: None,
- detail: Some("lsof loopback listener owner plus /json/version".to_owned()),
- },
- }));
- }
- if discovered.len() > 1 {
- return Err(refusal(
- BrowserRefusalCode::BrowserBindingAmbiguous,
- "multiple browser-level DevTools endpoints are owned by the approved process",
- ));
- }
- // A bare listener is not enough to identify DevTools before approval:
- // Chromium can own unrelated loopback services. The setup path below
- // correlates a listener with the exact checkbox transition and the
- // pooled WebSocket claim proves the protocol before attachment.
- Ok(None)
+ self.discover_endpoint(pid, true).await
}
async fn reprove_existing_profile_endpoint(
@@ -1667,6 +1681,320 @@ mod tests {
assert_eq!(parse_loopback_lsof_ports(input), vec![9222, 9444]);
}
+ async fn assert_owned_discovery_profile_case(case: &str) {
+ use std::os::fd::AsRawFd;
+ use std::os::unix::process::CommandExt;
+ use std::sync::atomic::{AtomicUsize, Ordering};
+
+ struct ChildGuard(std::process::Child);
+ impl Drop for ChildGuard {
+ fn drop(&mut self) {
+ let _ = self.0.kill();
+ let _ = self.0.wait();
+ }
+ }
+ let mut listeners = (0..3)
+ .map(|_| std::net::TcpListener::bind("127.0.0.1:0").unwrap())
+ .collect::<Vec<_>>();
+ listeners.sort_by_key(|listener| listener.local_addr().unwrap().port());
+ let ports = listeners
+ .iter()
+ .map(|listener| listener.local_addr().unwrap().port())
+ .collect::<Vec<_>>();
+ let urls = ports
+ .iter()
+ .enumerate()
+ .map(|(index, port)| format!("ws://127.0.0.1:{port}/devtools/browser/endpoint-{index}"))
+ .collect::<Vec<_>>();
+ let profile = tempfile::tempdir().unwrap();
+ let active_port = profile.path().join("DevToolsActivePort");
+ std::fs::write(
+ &active_port,
+ format!("{}\n/devtools/browser/endpoint-1\n", ports[1]),
+ )
+ .unwrap();
+ let unrelated = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ match case {
+ "missing_file" | "non_loopback" | "wrong_port" | "multiple" | "one_valid"
+ | "no_valid" => std::fs::remove_file(&active_port).unwrap(),
+ "malformed" => std::fs::write(&active_port, "not-a-port\n").unwrap(),
+ "unreadable" => {
+ std::fs::remove_file(&active_port).unwrap();
+ std::fs::create_dir(&active_port).unwrap();
+ }
+ "uncorroborated" => std::fs::write(
+ &active_port,
+ format!(
+ "{}\n/devtools/browser/foreign\n",
+ unrelated.local_addr().unwrap().port()
+ ),
+ )
+ .unwrap(),
+ _ => {}
+ }
+ let descriptors = listeners.iter().map(AsRawFd::as_raw_fd).collect::<Vec<_>>();
+ let mut command = std::process::Command::new("/bin/sh");
+ command
+ .args(["-c", "read -r line", "endpoint-fixture"])
+ .stdin(Stdio::piped())
+ .stdout(Stdio::null())
+ .stderr(Stdio::null());
+ match case {
+ "relative" => {
+ command.arg("--user-data-dir=relative-profile");
+ }
+ "absent_profile" => {}
+ "conflicting" => {
+ command.args(["--user-data-dir=/tmp/one", "--user-data-dir=/tmp/two"]);
+ }
+ _ => {
+ command.arg(format!("--user-data-dir={}", profile.path().display()));
+ }
+ }
+ // Only the child's explicitly named listeners lose CLOEXEC.
+ unsafe {
+ command.pre_exec(move || {
+ for &fd in &descriptors {
+ if libc::fcntl(fd, libc::F_SETFD, 0) == -1 {
+ return Err(std::io::Error::last_os_error());
+ }
+ }
+ Ok(())
+ });
+ }
+ let child = ChildGuard(command.spawn().unwrap());
+ let pid = i64::from(child.0.id());
+ assert_eq!(loopback_ports_for_pid(pid).await.unwrap(), ports);
+ let counts = Arc::new([
+ AtomicUsize::new(0),
+ AtomicUsize::new(0),
+ AtomicUsize::new(0),
+ ]);
+ let mut servers = Vec::new();
+ for (index, listener) in listeners.into_iter().enumerate() {
+ listener.set_nonblocking(true).unwrap();
+ let listener = tokio::net::TcpListener::from_std(listener).unwrap();
+ let url = match case {
+ "non_loopback" => format!(
+ "ws://example.invalid:{}/devtools/browser/foreign",
+ ports[index]
+ ),
+ "wrong_port" => urls[(index + 1) % 3].clone(),
+ "one_valid" if index == 0 => urls[1].clone(),
+ "one_valid" if index == 2 => {
+ "ws://example.invalid:1/devtools/browser/foreign".into()
+ }
+ _ => urls[index].clone(),
+ };
+ let body = if case == "no_valid" {
+ "{}".to_owned()
+ } else {
+ serde_json::json!({"webSocketDebuggerUrl": url}).to_string()
+ };
+ let counts = counts.clone();
+ servers.push(tokio::spawn(async move {
+ while let Ok((mut stream, _)) = listener.accept().await {
+ let mut request = [0; 4096];
+ let _ = stream.read(&mut request).await;
+ counts[index].fetch_add(1, Ordering::SeqCst);
+ let response = format!(
+ "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
+ body.len()
+ );
+ let _ = stream.write_all(response.as_bytes()).await;
+ }
+ }));
+ }
+ let take_counts =
+ || std::array::from_fn::<_, 3, _>(|index| counts[index].swap(0, Ordering::SeqCst));
+ let platform = MacOsBrowserPlatform::new(Arc::new(crate::cursor::CursorRegistry::new()));
+ let endpoint = platform.discover_owned_endpoint(pid).await;
+ let expected_counts = match case {
+ "absolute" | "conflicting" | "malformed" | "unreadable" => [0, 0, 0],
+ "non_loopback" | "wrong_port" | "no_valid" => [1, 1, 1],
+ "one_valid" => [1, 1, 0],
+ _ => [1, 0, 0],
+ };
+ assert_eq!(take_counts(), expected_counts, "owned probes: {case}");
+ match case {
+ "conflicting" | "malformed" | "unreadable" => {
+ let code = match case {
+ "conflicting" => BrowserRefusalCode::BrowserBindingAmbiguous,
+ "malformed" => BrowserRefusalCode::BrowserEndpointOwnerMismatch,
+ _ => BrowserRefusalCode::BrowserRouteUnavailable,
+ };
+ assert_eq!(endpoint.unwrap_err().code, code);
+ assert_eq!(
+ platform
+ .discover_existing_profile_endpoint(pid)
+ .await
+ .unwrap_err()
+ .code,
+ code
+ );
+ assert_eq!(take_counts(), [0, 0, 0]);
+ }
+ "non_loopback" | "wrong_port" | "no_valid" => {
+ assert!(endpoint.unwrap().is_none());
+ assert!(platform
+ .discover_existing_profile_endpoint(pid)
+ .await
+ .unwrap()
+ .is_none());
+ assert_eq!(take_counts(), [1, 1, 1]);
+ }
+ _ => {
+ let endpoint = endpoint.unwrap().unwrap();
+ let index = usize::from(matches!(case, "absolute" | "one_valid"));
+ assert_eq!(endpoint.ws_url, urls[index]);
+ assert_eq!(endpoint.ownership.owner_pid, pid);
+ assert_eq!(
+ endpoint.transport,
+ if case == "absolute" {
+ EndpointTransport::DevToolsActivePort
+ } else {
+ EndpointTransport::LegacyJsonVersion
+ }
+ );
+ if case != "absolute" {
+ assert_eq!(
+ endpoint.ownership.detail.as_deref(),
+ Some("lsof loopback listener owner plus /json/version")
+ );
+ }
+ }
+ }
+ match case {
+ "absolute" => {
+ assert_eq!(
+ platform
+ .discover_existing_profile_endpoint(pid)
+ .await
+ .unwrap()
+ .unwrap()
+ .ws_url,
+ urls[1]
+ );
+ assert_eq!(
+ platform
+ .discover_spawned_endpoint(pid, &urls[1])
+ .await
+ .unwrap()
+ .unwrap()
+ .ws_url,
+ urls[1]
+ );
+ assert!(platform
+ .discover_spawned_endpoint(pid, &urls[0])
+ .await
+ .unwrap()
+ .is_none());
+ assert_eq!(
+ platform
+ .reprove_existing_profile_endpoint(pid, &urls[0])
+ .await
+ .unwrap_err()
+ .code,
+ BrowserRefusalCode::BrowserEndpointOwnerMismatch
+ );
+ assert_eq!(take_counts(), [0, 0, 0]);
+ }
+ "relative" => {
+ assert_eq!(
+ platform
+ .discover_existing_profile_endpoint(pid)
+ .await
+ .unwrap_err()
+ .code,
+ BrowserRefusalCode::BrowserRouteUnavailable
+ );
+ assert_eq!(
+ platform
+ .reprove_existing_profile_endpoint(pid, &urls[0])
+ .await
+ .unwrap_err()
+ .code,
+ BrowserRefusalCode::BrowserRouteUnavailable
+ );
+ assert_eq!(take_counts(), [0, 0, 0]);
+ }
+ "multiple" => {
+ assert_eq!(
+ platform
+ .discover_existing_profile_endpoint(pid)
+ .await
+ .unwrap_err()
+ .code,
+ BrowserRefusalCode::BrowserBindingAmbiguous
+ );
+ assert_eq!(take_counts(), [1, 1, 0]);
+ assert_eq!(
+ platform
+ .reprove_existing_profile_endpoint(pid, &urls[0])
+ .await
+ .unwrap()
+ .unwrap()
+ .ws_url,
+ urls[0]
+ );
+ assert_eq!(take_counts(), [0, 0, 0]);
+ }
+ "one_valid" => {
+ assert_eq!(
+ platform
+ .discover_existing_profile_endpoint(pid)
+ .await
+ .unwrap()
+ .unwrap()
+ .ws_url,
+ urls[1]
+ );
+ assert_eq!(take_counts(), [1, 1, 1]);
+ }
+ _ => {}
+ }
+ for server in servers {
+ server.abort();
+ }
+ }
+
+ #[tokio::test]
+ async fn owned_discovery_prefers_profile_endpoint_over_inherited_listener() {
+ assert_owned_discovery_profile_case("absolute").await;
+ }
+
+ #[tokio::test]
+ async fn owned_discovery_relative_profile_keeps_listener_fallback_and_consent_strict() {
+ assert_owned_discovery_profile_case("relative").await;
+ }
+
+ #[tokio::test]
+ async fn owned_discovery_missing_profile_or_file_keeps_listener_fallback() {
+ assert_owned_discovery_profile_case("absent_profile").await;
+ assert_owned_discovery_profile_case("missing_file").await;
+ assert_owned_discovery_profile_case("uncorroborated").await;
+ }
+
+ #[tokio::test]
+ async fn owned_discovery_rejects_conflicting_profiles_and_malformed_port_file() {
+ assert_owned_discovery_profile_case("conflicting").await;
+ assert_owned_discovery_profile_case("malformed").await;
+ assert_owned_discovery_profile_case("unreadable").await;
+ }
+
+ #[tokio::test]
+ async fn owned_discovery_rejects_non_loopback_fallback() {
+ assert_owned_discovery_profile_case("non_loopback").await;
+ assert_owned_discovery_profile_case("wrong_port").await;
+ }
+
+ #[tokio::test]
+ async fn existing_discovery_requires_one_endpoint_but_reproof_keeps_exact_approval() {
+ for case in ["multiple", "one_valid", "no_valid"] {
+ assert_owned_discovery_profile_case(case).await;
+ }
+ }
+
#[test]
fn browser_classifier_covers_embedded_and_standalone_chromium() {
assert!(is_chromium("Electron", "com.example.fixture"));
@@ -1681,8 +2009,12 @@ mod tests {
let custom = std::env::temp_dir().join("cua browser profile with spaces");
let arg = format!("--user-data-dir={}", custom.display()).into_bytes();
assert_eq!(
- user_data_dir_from_arguments(&[b"/Applications/Chrome".to_vec(), arg], None)
- .expect("one absolute custom profile"),
+ user_data_dir_from_arguments_with_relative_fallback(
+ &[b"/Applications/Chrome".to_vec(), arg],
+ None,
+ false
+ )
+ .expect("one absolute custom profile"),
Some(custom)
);
}
@@ -1691,20 +2023,22 @@ mod tests {
fn user_data_dir_parser_does_not_treat_a_path_as_authority() {
let default = PathBuf::from("/tmp/default-browser-data");
assert_eq!(
- user_data_dir_from_arguments(
+ user_data_dir_from_arguments_with_relative_fallback(
&[b"/Applications/Chrome".to_vec()],
- Some(default.clone())
+ Some(default.clone()),
+ false
)
.expect("default path"),
Some(default)
);
- assert!(user_data_dir_from_arguments(
+ assert!(user_data_dir_from_arguments_with_relative_fallback(
&[
b"/Applications/Chrome".to_vec(),
b"--user-data-dir=/tmp/one".to_vec(),
b"--user-data-dir=/tmp/two".to_vec(),
],
None,
+ false,
)
.is_err());
}