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): harden browser scroll and endpoint proof

trycua-release[bot]7510ed9c1f82
diff --git a/docs/content/docs/how-to-guides/driver/drive-a-web-page.mdx b/docs/content/docs/how-to-guides/driver/drive-a-web-page.mdx
index ac2dd03ec0..b562dea087 100644
--- a/docs/content/docs/how-to-guides/driver/drive-a-web-page.mdx
+++ b/docs/content/docs/how-to-guides/driver/drive-a-web-page.mdx
@@ -280,6 +280,11 @@ browser_pointer({
})
```
+Hover, right-click, double-click, and drag require a ref whose `actions`
+contains `pointer`. Scroll accepts either `scroll` or `pointer`, so a plain
+overflow container can be scrollable without gaining broader pointer
+authority.
+
For drag, pass `destination_ref` from the same exact frame. The driver refuses
mixed-frame or stale destinations instead of translating them approximately.
@@ -351,7 +356,8 @@ and AX/PX actions for those surfaces.
The older `page` tool remains available for compatibility. Its read-only
`get_text` and `query_dom` actions are available by default. Legacy mutation
actions are disabled unless the daemon operator explicitly starts Cua Driver
-with `CUA_DRIVER_ENABLE_LEGACY_PAGE_MUTATIONS=1`.
+with `CUA_DRIVER_ENABLE_LEGACY_PAGE_MUTATIONS=1`. The flag is read when the
+daemon starts, so restart Cua Driver after changing it.
That flag is a temporary compatibility escape hatch, not an equivalent browser
grant: legacy CDP ports and URL hints do not receive the typed surface's exact
diff --git a/docs/content/docs/reference/cua-driver/mcp-tools.mdx b/docs/content/docs/reference/cua-driver/mcp-tools.mdx
index 23920fb6e6..4cd7af57ac 100644
--- a/docs/content/docs/reference/cua-driver/mcp-tools.mdx
+++ b/docs/content/docs/reference/cua-driver/mcp-tools.mdx
@@ -472,7 +472,7 @@ After a zoom, pass `from_zoom=true` to click/type_text to auto-translate coordin
### `page`
-Legacy browser compatibility tool. Prefer get_browser_state and the typed browser_* tools for exact targeting, endpoint ownership, and consent. Read-only get_text and query_dom remain available by default. Mutating actions require the daemon operator to set CUA_DRIVER_ENABLE_LEGACY_PAGE_MUTATIONS=1; this escape hatch does not provide the typed browser surface's exact binding or existing-profile grant guarantees. Supports Chrome, Brave, Edge, Safari (via AppleScript on macOS), Electron apps (via CDP), Chromium/Firefox on Windows (via UIA for read; CDP for execute_javascript when --remote-debugging-port is set), and WKWebView/Tauri/AT-SPI fallbacks.
+Legacy browser compatibility tool. Prefer get_browser_state and the typed browser_* tools for exact targeting, endpoint ownership, and consent. Read-only get_text and query_dom remain available by default. Mutating actions require the daemon operator to set CUA_DRIVER_ENABLE_LEGACY_PAGE_MUTATIONS=1 before daemon startup (restart the daemon after changing it); this escape hatch does not provide the typed browser surface's exact binding or existing-profile grant guarantees. Supports Chrome, Brave, Edge, Safari (via AppleScript on macOS), Electron apps (via CDP), Chromium/Firefox on Windows (via UIA for read; CDP for execute_javascript when --remote-debugging-port is set), and WKWebView/Tauri/AT-SPI fallbacks.
Actions:
- execute_javascript: Run JS and return the result.
@@ -886,7 +886,7 @@ Trigger one download through an exact live browser ref and save it inside an exp
### `browser_pointer`
-Perform hover, right-click, double-click, scroll, or drag in an exactly-bound browser tab. The trusted route uses CDP Input events and refuses if standalone background posture cannot be preserved. The explicit dom_event route requires a page ref and synthesizes full-background DOM events. Never activates or brings a tab to the foreground.
+Perform hover, right-click, double-click, scroll, or drag in an exactly-bound browser tab. Semantic refs must declare pointer for hover, right-click, double-click, and drag; scroll accepts a scroll or pointer capability. The trusted route uses CDP Input events and refuses if standalone background posture cannot be preserved. The explicit dom_event route requires a page ref and synthesizes full-background DOM events. Never activates or brings a tab to the foreground.
**Arguments:**
diff --git a/libs/cua-driver/rust/Skills/cua-driver/BROWSER.md b/libs/cua-driver/rust/Skills/cua-driver/BROWSER.md
index 42e4e57aaa..737ec7fb4b 100644
--- a/libs/cua-driver/rust/Skills/cua-driver/BROWSER.md
+++ b/libs/cua-driver/rust/Skills/cua-driver/BROWSER.md
@@ -254,9 +254,11 @@ task result.
Use `browser_pointer` for `hover`, `right_click`, `double_click`, `scroll`, and
`drag`. It uses the same `trusted` versus explicit `dom_event` distinction as
-`browser_click`. A ref used here must declare `pointer` in its `actions` array.
-The synthetic route requires a current ref; drag also requires
-`destination_ref` in the same proven frame. Coordinate origins and
+`browser_click`. Hover, right-click, double-click, and drag require a ref that
+declares `pointer`. Scroll accepts either `scroll` or `pointer`; a plain
+overflow container can therefore be scrollable without gaining click, hover,
+or drag authority. The synthetic route requires a current ref; drag also
+requires `destination_ref` in the same proven frame. Coordinate origins and
destinations are available only where the trusted route can preserve the
requested posture.
@@ -321,8 +323,9 @@ not start new browser workflows with it: its backend and trust semantics are
less precise than the typed browser tools, and it does not replace exact
window binding. Its mutations are disabled by default. Only a trusted daemon
operator can enable the temporary compatibility path with
-`CUA_DRIVER_ENABLE_LEGACY_PAGE_MUTATIONS=1`; that flag does not add typed
-endpoint ownership, capabilities, or existing-profile consent.
+`CUA_DRIVER_ENABLE_LEGACY_PAGE_MUTATIONS=1` before daemon startup. Restart Cua
+Driver after changing the flag. It does not add typed endpoint ownership,
+capabilities, or existing-profile consent.
## Support boundaries
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/pointer.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/pointer.rs
index 6058a47f09..22c8a6c101 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/pointer.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/pointer.rs
@@ -55,6 +55,15 @@ impl PointerAction {
}
}
+fn ref_declares_pointer_action(actions: &[BrowserActionKind], action: PointerAction) -> bool {
+ match action {
+ PointerAction::Scroll => actions
+ .iter()
+ .any(|kind| matches!(kind, BrowserActionKind::Scroll | BrowserActionKind::Pointer)),
+ _ => actions.contains(&BrowserActionKind::Pointer),
+ }
+}
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum InputRoute {
Trusted,
@@ -272,7 +281,7 @@ impl BrowserPointerTool {
Self {
def: ToolDef {
name: "browser_pointer".into(),
- description: "Perform hover, right-click, double-click, scroll, or drag in an exactly-bound browser tab. The trusted route uses CDP Input events and refuses if standalone background posture cannot be preserved. The explicit dom_event route requires a page ref and synthesizes full-background DOM events. Never activates or brings a tab to the foreground.".into(),
+ description: "Perform hover, right-click, double-click, scroll, or drag in an exactly-bound browser tab. Semantic refs must declare pointer for hover, right-click, double-click, and drag; scroll accepts a scroll or pointer capability. The trusted route uses CDP Input events and refuses if standalone background posture cannot be preserved. The explicit dom_event route requires a page ref and synthesizes full-background DOM events. Never activates or brings a tab to the foreground.".into(),
input_schema: json!({
"type": "object",
"properties": {
@@ -309,16 +318,23 @@ impl BrowserPointerTool {
tab_id: &str,
validated: &ValidatedTab,
external: &str,
+ action: PointerAction,
) -> Result<ResolvedRef, ToolResult> {
let entry = self
.engine
.store
.resolve_ref(session, target_id, tab_id, external)
.map_err(|refusal| refusal.to_tool_result())?;
- if entry.semantic && !entry.actions.contains(&BrowserActionKind::Pointer) {
+ let declared = ref_declares_pointer_action(&entry.actions, action);
+ if entry.semantic && !declared {
+ let required = if action == PointerAction::Scroll {
+ "scroll or pointer"
+ } else {
+ "pointer"
+ };
return Err(BrowserRefusal::new(
BrowserRefusalCode::BrowserActionUnavailable,
- format!("semantic ref {external} does not declare the pointer action"),
+ format!("semantic ref {external} does not declare the {required} action"),
)
.to_tool_result());
}
@@ -711,7 +727,14 @@ impl Tool for BrowserPointerTool {
let origin_ref = match &request.origin {
Location::Ref(external) => match self
- .resolve_ref(&session, &target_id, &tab_id, &validated, external)
+ .resolve_ref(
+ &session,
+ &target_id,
+ &tab_id,
+ &validated,
+ external,
+ request.action,
+ )
.await
{
Ok(reference) => Some(reference),
@@ -721,7 +744,14 @@ impl Tool for BrowserPointerTool {
};
let destination_ref = match &request.destination {
Some(Location::Ref(external)) => match self
- .resolve_ref(&session, &target_id, &tab_id, &validated, external)
+ .resolve_ref(
+ &session,
+ &target_id,
+ &tab_id,
+ &validated,
+ external,
+ request.action,
+ )
.await
{
Ok(reference) => Some(reference),
@@ -847,6 +877,30 @@ mod tests {
assert_eq!(parsed.delta_y, 240.0);
}
+ #[test]
+ fn scroll_capability_does_not_authorize_other_pointer_actions() {
+ let scroll_only = [BrowserActionKind::Scroll];
+ assert!(ref_declares_pointer_action(
+ &scroll_only,
+ PointerAction::Scroll
+ ));
+ for action in [
+ PointerAction::Hover,
+ PointerAction::RightClick,
+ PointerAction::DoubleClick,
+ PointerAction::Drag,
+ ] {
+ assert!(!ref_declares_pointer_action(&scroll_only, action));
+ }
+
+ let pointer = [BrowserActionKind::Pointer];
+ assert!(ref_declares_pointer_action(&pointer, PointerAction::Scroll));
+ assert!(ref_declares_pointer_action(
+ &pointer,
+ PointerAction::RightClick
+ ));
+ }
+
#[test]
fn quad_center_rejects_malformed_models() {
assert_eq!(
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/semantic.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/semantic.rs
index ec0b6de93f..5ac64a75a8 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/semantic.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/semantic.rs
@@ -20,6 +20,8 @@ pub(crate) const SEMANTIC_COMPUTED_STYLES: &[&str] = &[
"cursor",
"position",
"z-index",
+ "overflow-x",
+ "overflow-y",
];
pub(crate) const DEFAULT_SEMANTIC_NODE_BUDGET: usize = 300;
const NEAR_VIEWPORT_MARGIN: f64 = 1_000.0;
@@ -91,6 +93,8 @@ pub(crate) struct DomIndex {
#[derive(Debug, Clone, Default)]
struct LayoutMeta {
bounds: Option<Rect>,
+ client_rect: Option<Rect>,
+ scroll_rect: Option<Rect>,
styles: HashMap<String, String>,
paint_order: Option<i64>,
}
@@ -382,6 +386,16 @@ pub(crate) fn build_layout_index(snapshot: &Value) -> LayoutIndex {
.and_then(Value::as_array)
.cloned()
.unwrap_or_default();
+ let client_rects = layout
+ .get("clientRects")
+ .and_then(Value::as_array)
+ .cloned()
+ .unwrap_or_default();
+ let scroll_rects = layout
+ .get("scrollRects")
+ .and_then(Value::as_array)
+ .cloned()
+ .unwrap_or_default();
for (layout_idx, node_index) in node_indices.iter().enumerate() {
let Some(node_index) = node_index.as_u64().and_then(|v| usize::try_from(v).ok()) else {
@@ -405,6 +419,8 @@ pub(crate) fn build_layout_index(snapshot: &Value) -> LayoutIndex {
backend,
LayoutMeta {
bounds: bounds.get(layout_idx).and_then(Rect::from_value),
+ client_rect: client_rects.get(layout_idx).and_then(Rect::from_value),
+ scroll_rect: scroll_rects.get(layout_idx).and_then(Rect::from_value),
styles: computed,
paint_order: paint_orders.get(layout_idx).and_then(Value::as_i64),
},
@@ -810,20 +826,43 @@ fn action_kinds(
{
actions.push(BrowserActionKind::Click);
}
- if !actions.is_empty()
- && layout.is_some_and(|meta| {
- meta.bounds.is_some_and(Rect::has_area)
- && !meta
- .styles
- .get("pointer-events")
- .is_some_and(|value| value.eq_ignore_ascii_case("none"))
- })
- {
- actions.push(BrowserActionKind::Pointer);
+ if let Some(layout) = layout.filter(|meta| {
+ meta.bounds.is_some_and(Rect::has_area)
+ && !meta
+ .styles
+ .get("pointer-events")
+ .is_some_and(|value| value.eq_ignore_ascii_case("none"))
+ }) {
+ if !actions.is_empty() {
+ actions.push(BrowserActionKind::Pointer);
+ }
+ if layout_is_scrollable(layout) {
+ actions.push(BrowserActionKind::Scroll);
+ }
}
actions
}
+fn layout_is_scrollable(layout: &LayoutMeta) -> bool {
+ let (Some(client), Some(scroll)) = (layout.client_rect, layout.scroll_rect) else {
+ return false;
+ };
+ let scrollable_axis = |overflow: Option<&String>, scroll_extent: f64, client_extent: f64| {
+ overflow.is_some_and(|value| {
+ matches!(
+ value.to_ascii_lowercase().as_str(),
+ "auto" | "scroll" | "overlay"
+ )
+ }) && scroll_extent > client_extent + 0.5
+ };
+ scrollable_axis(layout.styles.get("overflow-x"), scroll.width, client.width)
+ || scrollable_axis(
+ layout.styles.get("overflow-y"),
+ scroll.height,
+ client.height,
+ )
+}
+
fn ax_states(node: &Value) -> BTreeMap<String, Value> {
const KEPT: &[&str] = &[
"checked",
@@ -1203,6 +1242,60 @@ mod tests {
.all(|node| node.name.as_deref() != Some("Static panel")));
}
+ #[test]
+ fn dom_supplement_exposes_scrollable_containers_without_click_authority() {
+ let dom = build_dom_index(&json!({
+ "nodeType": 9,
+ "frameId": "F_MAIN",
+ "children": [
+ {"nodeType": 1, "nodeName": "DIV", "backendNodeId": 1,
+ "attributes": ["aria-label", "Scrollable archive"]},
+ {"nodeType": 1, "nodeName": "DIV", "backendNodeId": 2,
+ "attributes": ["aria-label", "Overflow-visible panel"]}
+ ]
+ }));
+ let layout = build_layout_index(&json!({
+ "strings": ["block", "visible", "1", "auto", "default", "static", "0", "scroll"],
+ "documents": [{
+ "nodes": {"backendNodeId": [1, 2]},
+ "layout": {
+ "nodeIndex": [0, 1],
+ "bounds": [[10, 10, 100, 50], [10, 80, 100, 50]],
+ "clientRects": [[10, 10, 100, 50], [10, 80, 100, 50]],
+ "scrollRects": [[0, 0, 100, 250], [0, 0, 100, 250]],
+ "styles": [
+ [0, 1, 2, 3, 4, 5, 6, 3, 7],
+ [0, 1, 2, 3, 4, 5, 6, 1, 1]
+ ],
+ "paintOrders": [1, 2]
+ }
+ }]
+ }));
+ let viewport = parse_viewport(&json!({
+ "cssVisualViewport": {"pageX": 0.0, "pageY": 0.0,
+ "clientWidth": 800.0, "clientHeight": 600.0}
+ }));
+ let document = compose_accessibility_tree(
+ &json!({"nodes": [{"nodeId": "root", "ignored": false,
+ "role": {"value": "RootWebArea"}, "childIds": []}]}),
+ &dom,
+ &layout,
+ &viewport,
+ frame(),
+ );
+ let page = document.page(0, 300, None, None);
+ let scrollable = page
+ .selected
+ .iter()
+ .find(|node| node.name.as_deref() == Some("Scrollable archive"))
+ .expect("scrollable DOM supplement");
+ assert_eq!(scrollable.actions, vec![BrowserActionKind::Scroll]);
+ assert!(page
+ .selected
+ .iter()
+ .all(|node| node.name.as_deref() != Some("Overflow-visible panel")));
+ }
+
#[test]
fn layout_ranks_in_viewport_actions_before_offscreen_content() {
let dom = build_dom_index(&json!({
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/store.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/store.rs
index 98752e7dc4..2f856c30bd 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/store.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/store.rs
@@ -34,6 +34,7 @@ pub enum BrowserActionKind {
Type,
Upload,
Pointer,
+ Scroll,
}
impl BrowserActionKind {
@@ -43,6 +44,7 @@ impl BrowserActionKind {
Self::Type => "type",
Self::Upload => "upload",
Self::Pointer => "pointer",
+ Self::Scroll => "scroll",
}
}
}
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/page.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/page.rs
index 79b2f7a0c6..dc0cb0a6f7 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/page.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/page.rs
@@ -257,8 +257,9 @@ fn def() -> &'static ToolDef {
description: "Legacy browser compatibility tool. Prefer get_browser_state and the \
typed browser_* tools for exact targeting, endpoint ownership, and consent. \
Read-only get_text and query_dom remain available by default. Mutating actions \
- require the daemon operator to set CUA_DRIVER_ENABLE_LEGACY_PAGE_MUTATIONS=1; \
- this escape hatch does not provide the typed browser surface's exact binding or \
+ require the daemon operator to set CUA_DRIVER_ENABLE_LEGACY_PAGE_MUTATIONS=1 before \
+ daemon startup (restart the daemon after changing it); this escape hatch does not \
+ provide the typed browser surface's exact binding or \
existing-profile grant guarantees. Supports \
Chrome, Brave, Edge, Safari (via AppleScript on macOS), Electron apps (via CDP), \
Chromium/Firefox on Windows (via UIA for read; CDP for execute_javascript when \
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/protocol_schema_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/protocol_schema_test.rs
index 59eab39d6a..5b47d0ba9f 100644
--- a/libs/cua-driver/rust/crates/cua-driver/tests/protocol_schema_test.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/protocol_schema_test.rs
@@ -7,7 +7,7 @@
#![cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
-use cua_driver_testkit::RawDriver;
+use cua_driver_testkit::{Driver, McpDriver, RawDriver};
#[test]
fn tools_list_schema_shape() {
@@ -217,6 +217,47 @@ fn tools_list_schema_shape() {
}
}
+#[test]
+fn legacy_page_mutation_flag_is_read_by_the_spawned_daemon() {
+ let args = serde_json::json!({
+ "action": "enable_javascript_apple_events",
+ "user_has_confirmed_enabling": false
+ });
+
+ {
+ let mut driver = McpDriver::spawn().expect("spawn default source-built driver");
+ let response = driver.call("page", args.clone());
+ assert!(response.is_error(), "mutation must refuse by default");
+ assert!(
+ response
+ .text()
+ .contains("CUA_DRIVER_ENABLE_LEGACY_PAGE_MUTATIONS=1"),
+ "default refusal must name the operator gate: {}",
+ response.text()
+ );
+ }
+
+ let mut driver = McpDriver::spawn_with_env(&[("CUA_DRIVER_ENABLE_LEGACY_PAGE_MUTATIONS", "1")])
+ .expect("spawn source-built driver with daemon-scoped compatibility flag");
+ let response = driver.call("page", args);
+ assert!(
+ response.is_error(),
+ "unconfirmed mutation must still refuse"
+ );
+ assert!(
+ response
+ .text()
+ .contains("Set user_has_confirmed_enabling=true"),
+ "enabled daemon should reach the explicit confirmation gate: {}",
+ response.text()
+ );
+ assert!(
+ !response.text().contains("disabled by default"),
+ "the daemon did not observe its startup environment: {}",
+ response.text()
+ );
+}
+
#[test]
#[cfg(target_os = "linux")]
fn linux_cursor_motion_knobs_are_applied() {
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/standalone_browser_behavior_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/standalone_browser_behavior_test.rs
index 65607596e6..f0dbd19369 100644
--- a/libs/cua-driver/rust/crates/cua-driver/tests/standalone_browser_behavior_test.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/standalone_browser_behavior_test.rs
@@ -74,8 +74,6 @@ fn standalone_browser_completeness_html() -> String {
const names = Array.from(event.target.files).map(file => file.name).join(',');
document.getElementById('standalone-upload-state').textContent = `upload=${event.target.files.length}:${names}`;
});
- document.getElementById('scroll-tall').setAttribute('tabindex', '0');
- document.getElementById('scroll-tall').setAttribute('role', 'region');
document.getElementById('drag-source').setAttribute('tabindex', '0');
document.getElementById('drag-source').setAttribute('role', 'button');
document.getElementById('drag-source').setAttribute('draggable', 'true');
@@ -2623,7 +2621,7 @@ fn run_pointer_actions(spec: &BrowserSpec) {
serde_json::json!({
"target_id": target,
"tab_id": tab,
- "ref": semantic_ref_by_name(&snapshot, "scroll-tall", "pointer"),
+ "ref": semantic_ref_by_name(&snapshot, "scroll-tall", "scroll"),
"action": "scroll",
"input_route": "dom_event",
"delta_y": 240,
diff --git a/libs/cua-driver/rust/crates/platform-windows/src/browser_platform.rs b/libs/cua-driver/rust/crates/platform-windows/src/browser_platform.rs
index 1a872cb337..2b2a1062b3 100644
--- a/libs/cua-driver/rust/crates/platform-windows/src/browser_platform.rs
+++ b/libs/cua-driver/rust/crates/platform-windows/src/browser_platform.rs
@@ -68,15 +68,25 @@ fn browser_product(name: &str) -> BrowserProduct {
}
}
-fn loopback_websocket_port(url: &str) -> Option<u16> {
- ["ws://127.0.0.1:", "ws://localhost:", "ws://[::1]:"]
+fn websocket_port_and_suffix<'a>(url: &'a str, prefix: &str) -> Option<(u16, &'a str)> {
+ let remainder = url.strip_prefix(prefix)?;
+ let path_start = remainder.find('/')?;
+ let port = remainder[..path_start].parse::<u16>().ok()?;
+ Some((port, &remainder[path_start..]))
+}
+
+fn literal_loopback_websocket_port(url: &str) -> Option<u16> {
+ ["ws://127.0.0.1:", "ws://[::1]:"]
+ .iter()
+ .find_map(|prefix| websocket_port_and_suffix(url, prefix).map(|(port, _)| port))
+}
+
+fn canonical_discovered_websocket_url(url: &str, expected_port: u16) -> Option<String> {
+ ["ws://127.0.0.1:", "ws://[::1]:", "ws://localhost:"]
.iter()
- .find_map(|prefix| {
- url.strip_prefix(prefix)?
- .split('/')
- .next()?
- .parse::<u16>()
- .ok()
+ .find_map(|prefix| websocket_port_and_suffix(url, prefix))
+ .and_then(|(port, suffix)| {
+ (port == expected_port).then(|| format!("ws://127.0.0.1:{expected_port}{suffix}"))
})
}
@@ -217,8 +227,8 @@ async fn browser_websocket_url(port: u16) -> Option<String> {
}
let body_start = bytes.windows(4).position(|part| part == b"\r\n\r\n")? + 4;
let value: serde_json::Value = serde_json::from_slice(&bytes[body_start..]).ok()?;
- let url = value.get("webSocketDebuggerUrl")?.as_str()?.to_owned();
- (loopback_websocket_port(&url) == Some(port)).then_some(url)
+ let url = value.get("webSocketDebuggerUrl")?.as_str()?;
+ canonical_discovered_websocket_url(url, port)
})
.await
.ok()
@@ -271,12 +281,32 @@ async fn loopback_port_is_owned_with_retry(
pid: u32,
expected_port: u16,
) -> Result<bool, BrowserRefusal> {
- for attempt in 0..ENDPOINT_DISCOVERY_ATTEMPTS {
- if loopback_ports_for_pid(pid).await?.contains(&expected_port) {
+ retry_port_ownership(
+ ENDPOINT_DISCOVERY_ATTEMPTS,
+ ENDPOINT_DISCOVERY_RETRY_DELAY,
+ expected_port,
+ || loopback_ports_for_pid(pid),
+ )
+ .await
+}
+
+async fn retry_port_ownership<F, Fut>(
+ attempts: usize,
+ delay: Duration,
+ expected_port: u16,
+ mut probe: F,
+) -> Result<bool, BrowserRefusal>
+where
+ F: FnMut() -> Fut,
+ Fut: Future<Output = Result<Vec<u16>, BrowserRefusal>>,
+{
+ let attempts = attempts.max(1);
+ for attempt in 0..attempts {
+ if probe().await?.contains(&expected_port) {
return Ok(true);
}
- if attempt + 1 < ENDPOINT_DISCOVERY_ATTEMPTS {
- tokio::time::sleep(ENDPOINT_DISCOVERY_RETRY_DELAY).await;
+ if attempt + 1 < attempts {
+ tokio::time::sleep(delay).await;
}
}
Ok(false)
@@ -461,7 +491,7 @@ impl BrowserPlatform for WindowsBrowserPlatform {
format!("pid {pid} is outside the Windows process-id range"),
)
})?;
- let Some(port) = loopback_websocket_port(expected_ws_url) else {
+ let Some(port) = literal_loopback_websocket_port(expected_ws_url) else {
return Err(refusal(
BrowserRefusalCode::BrowserEndpointOwnerMismatch,
"the approved existing-profile endpoint is not loopback-only",
@@ -737,19 +767,57 @@ mod tests {
}
#[test]
- fn websocket_url_must_keep_the_attested_listener_port() {
+ fn discovered_websocket_url_is_canonical_and_keeps_the_attested_port() {
+ assert_eq!(
+ canonical_discovered_websocket_url("ws://localhost:9222/devtools/browser/id", 9222),
+ Some("ws://127.0.0.1:9222/devtools/browser/id".to_owned())
+ );
+ assert_eq!(
+ canonical_discovered_websocket_url("ws://[::1]:9222/devtools/browser/id", 9222),
+ Some("ws://127.0.0.1:9222/devtools/browser/id".to_owned())
+ );
assert_eq!(
- loopback_websocket_port("ws://[::1]:9222/devtools/browser/id"),
+ canonical_discovered_websocket_url(
+ "ws://127.0.0.1:9333/devtools/browser/foreign",
+ 9222
+ ),
+ None
+ );
+ assert_eq!(
+ canonical_discovered_websocket_url("wss://127.0.0.1:9222/devtools/browser/id", 9222),
+ None
+ );
+ assert_eq!(
+ canonical_discovered_websocket_url(
+ "ws://127.0.0.1.evil.test:9222/devtools/browser/id",
+ 9222
+ ),
+ None
+ );
+ assert_eq!(
+ canonical_discovered_websocket_url(
+ "ws://[email protected]:9222/devtools/browser/id",
+ 9222
+ ),
+ None
+ );
+ }
+
+ #[test]
+ fn endpoint_reproof_requires_a_literal_loopback_url() {
+ assert_eq!(
+ literal_loopback_websocket_port("ws://127.0.0.1:9222/devtools/browser/id"),
Some(9222)
);
- assert_ne!(
- loopback_websocket_port("ws://127.0.0.1:9333/devtools/browser/foreign"),
+ assert_eq!(
+ literal_loopback_websocket_port("ws://[::1]:9222/devtools/browser/id"),
Some(9222)
);
assert_eq!(
- loopback_websocket_port("wss://127.0.0.1:9222/devtools"),
+ literal_loopback_websocket_port("ws://localhost:9222/devtools/browser/id"),
None
);
+ assert_eq!(literal_loopback_websocket_port("ws://127.0.0.1:9222"), None);
}
#[tokio::test]
@@ -781,4 +849,54 @@ mod tests {
)]
);
}
+
+ #[tokio::test]
+ async fn endpoint_ownership_retries_transient_socket_snapshots() {
+ let calls = Arc::new(AtomicUsize::new(0));
+ let probe_calls = Arc::clone(&calls);
+ let owned = retry_port_ownership(4, Duration::ZERO, 9222, move || {
+ let call = probe_calls.fetch_add(1, Ordering::SeqCst);
+ async move {
+ if call < 2 {
+ Ok(Vec::new())
+ } else {
+ Ok(vec![9222])
+ }
+ }
+ })
+ .await
+ .expect("retry transient socket snapshots");
+
+ assert!(owned);
+ assert_eq!(calls.load(Ordering::SeqCst), 3);
+ }
+
+ #[tokio::test]
+ async fn endpoint_ownership_exhausts_wrong_ports_and_fails_fast_on_errors() {
+ let wrong_calls = Arc::new(AtomicUsize::new(0));
+ let probe_calls = Arc::clone(&wrong_calls);
+ let owned = retry_port_ownership(3, Duration::ZERO, 9222, move || {
+ probe_calls.fetch_add(1, Ordering::SeqCst);
+ async { Ok(vec![9333]) }
+ })
+ .await
+ .expect("wrong ports are a clean ownership miss");
+ assert!(!owned);
+ assert_eq!(wrong_calls.load(Ordering::SeqCst), 3);
+
+ let error_calls = Arc::new(AtomicUsize::new(0));
+ let probe_calls = Arc::clone(&error_calls);
+ let result = retry_port_ownership(3, Duration::ZERO, 9222, move || {
+ probe_calls.fetch_add(1, Ordering::SeqCst);
+ async {
+ Err(refusal(
+ BrowserRefusalCode::BrowserRouteUnavailable,
+ "socket inventory failed",
+ ))
+ }
+ })
+ .await;
+ assert!(result.is_err());
+ assert_eq!(error_calls.load(Ordering::SeqCst), 1);
+ }
}