Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
fix(cua-driver): launch isolated browser without pid (#3208)
Francesco Bonaccieaf5a34ea780
diff --git a/docs/content/docs/reference/cua-driver/mcp-tools.mdx b/docs/content/docs/reference/cua-driver/mcp-tools.mdxindex 18eb76d6af..ff2573b5a8 100644--- a/docs/content/docs/reference/cua-driver/mcp-tools.mdx+++ b/docs/content/docs/reference/cua-driver/mcp-tools.mdx@@ -879,21 +879,17 @@ Read-only browser inspection. Mode 1 (bind): pass pid + window_id of a native br### `browser_prepare`-Explicitly prepare an owned DevTools endpoint for a browser pid. Existing endpoints are detected without side effects. Acting setup for an isolated profile follows the runtime permission mode and optional capability manifest. It requires allow_launch=true, launches a separate browser, and never copies, modifies, or terminates the requested user profile. Existing-profile attachment is explicit and follows the runtime's immutable permission mode: standard requires an explicit --grant existing-profile launch grant or an embedding authorization host, bounded requires a launch-approved exact resource manifest, and unrestricted requires explicit trusted startup risk acceptance. Ordinary MCP transport approval never proves profile authorization. On proven platforms, an authorized request also permits one bounded exact-window setup: open the recognized browser product's fixed remote-debugging page, toggle its uniquely matched per-instance checkbox, prove the PID-owned loopback endpoint, and close the temporary tab. Every visible effect is reported; ambiguity is refused.+Explicitly prepare an owned DevTools endpoint for a browser. pid is required for an existing process or existing-profile attachment, and optional only for allow_launch=true with an isolated profile. Existing endpoints are detected without side effects. Acting setup for an isolated profile follows the runtime permission mode and optional capability manifest. It requires allow_launch=true, launches a separate browser, and never copies, modifies, or terminates the requested user profile. Without pid, only a platform-attested system Chrome/Edge installation (or a root-owned package payload on Linux) is eligible; redirects and user-controlled locations fail closed. Existing-profile attachment is explicit and follows the runtime's immutable permission mode: standard requires an explicit --grant existing-profile launch grant or an embedding authorization host, bounded requires a launch-approved exact resource manifest, and unrestricted requires explicit trusted startup risk acceptance. Ordinary MCP transport approval never proves profile authorization. On proven platforms, an authorized request also permits one bounded exact-window setup: open the recognized browser product's fixed remote-debugging page, toggle its uniquely matched per-instance checkbox, prove the PID-owned loopback endpoint, and close the temporary tab. Every visible effect is reported; ambiguity is refused.**Arguments:**- `allow_launch` (boolean, optional): Allow a separate driver-owned isolated Chromium process to be launched (default false).-- `pid` (integer, required): Browser process id to prepare.+- `pid` (integer, optional): Browser process id to prepare. Required except for a driver-owned isolated_new/isolated_named launch with allow_launch=true.- `profile` (object, optional)- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session. Browser targets, tabs, and refs belong to the resolved lifecycle session.- `strategy` (object, optional)- `window_id` (integer, optional): Exact native window approval anchor; required for strategy.kind=existing_profile.-```json-{"pid":844}-```-### `browser_navigate`Navigate one tab of an exactly-bound browser target to a new URL (http/https/about only). Refused for heuristic bindings. Navigation invalidates all p<snapshot>:<index> refs for the tab.diff --git a/libs/cua-driver/rust/Cargo.lock b/libs/cua-driver/rust/Cargo.lockindex 9ea9ebe6b1..e6a27645d6 100644--- a/libs/cua-driver/rust/Cargo.lock+++ b/libs/cua-driver/rust/Cargo.lock@@ -3234,6 +3234,7 @@ dependencies = ["reis","serde","serde_json",+ "tempfile","thiserror 1.0.69","tiny-skia","tokio",@@ -3309,6 +3310,7 @@ dependencies = ["pip-preview","serde","serde_json",+ "tempfile","thiserror 1.0.69","tiny-skia","tokio",diff --git a/libs/cua-driver/rust/Skills/cua-driver/BROWSER.md b/libs/cua-driver/rust/Skills/cua-driver/BROWSER.mdindex 97903b313b..47599485da 100644--- a/libs/cua-driver/rust/Skills/cua-driver/BROWSER.md+++ b/libs/cua-driver/rust/Skills/cua-driver/BROWSER.md@@ -108,7 +108,7 @@ cookies or login state:```bashcua-driver browser_prepare \- '{"pid":4242,"session":"browser-run-1","allow_launch":true,+ '{"session":"browser-run-1","allow_launch":true,"profile":{"mode":"isolated_new"}}'```@@ -118,9 +118,19 @@ a matching manifest, and unrestricted mode requires the launcher's dangerousacknowledgement. `allow_launch: true` states that this call may create theseparate process; it does not widen runtime authorization.+When `pid` is omitted, the driver uses only a platform-attested installation.+On macOS and Windows it accepts vendor-signed system installations in this+order: Google Chrome, then Microsoft Edge. On Linux it accepts exact+root-owned, non-group/world-writable package payloads in this order: Google+Chrome, Chromium, then Microsoft Edge. User application directories, `PATH`+entries, redirected paths, and unsigned or mismatched products fail closed.+Supply a Chromium-family browser pid when the isolated launch must use that+process's exact executable, including Chromium on macOS or Windows. The pid+remains required for existing-profile attachment.+Use `isolated_named` with a path-safe `name` for a reusable driver-managedprofile. Preparation launches a separate browser and never copies, modifies,-or terminates the requested personal profile. The result returns a+or terminates an existing personal profile. The result returns a`prepared_pid`; list that process's windows and bind the new `(pid,window_id)`.diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/platform.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/platform.rsindex 8e071f8ae7..387958eb8c 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/platform.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/platform.rs@@ -10,12 +10,64 @@use async_trait::async_trait;use serde::{Deserialize, Serialize};+use std::path::PathBuf;use super::refusal::BrowserRefusal;use super::types::{BrowserClassification, BrowserProduct, NativeWindowInfo, OwnedEndpoint, ProcessFingerprint,};+/// Select the first installed, non-redirected candidate and return its+/// canonical path. Native adapters must supply only trusted installation+/// locations in public product-preference order. Rejecting redirects prevents+/// a known browser path from becoming an arbitrary executable through a+/// symlink or junction controlled outside the trusted installation.+pub fn select_isolated_browser_executable(+ candidates: impl IntoIterator<Item = PathBuf>,+) -> Result<String, BrowserRefusal> {+ for candidate in candidates {+ if !candidate.is_file() {+ continue;+ }+ let canonical = std::fs::canonicalize(&candidate).map_err(|error| {+ BrowserRefusal::new(+ super::refusal::BrowserRefusalCode::BrowserRouteUnavailable,+ format!(+ "could not canonicalize installed browser executable {}: {error}",+ candidate.display()+ ),+ )+ })?;+ if !same_installation_path(&candidate, &canonical) {+ continue;+ }+ return Ok(canonical.to_string_lossy().into_owned());+ }+ Err(BrowserRefusal::new(+ super::refusal::BrowserRefusalCode::BrowserRouteUnavailable,+ "no supported installed Chromium executable is available for isolated launch",+ ))+}++fn same_installation_path(candidate: &std::path::Path, canonical: &std::path::Path) -> bool {+ #[cfg(windows)]+ {+ let normalize = |path: &std::path::Path| {+ let value = path.to_string_lossy();+ value+ .strip_prefix(r"\\?\")+ .unwrap_or(&value)+ .replace('/', "\\")+ .to_ascii_lowercase()+ };+ normalize(candidate) == normalize(canonical)+ }+ #[cfg(not(windows))]+ {+ candidate == canonical+ }+}+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub enum PrepareProfileMode {@@ -42,7 +94,10 @@ pub enum PrepareStrategy {/// implicit: `get_browser_state` must not trigger it.#[derive(Debug, Clone)]pub struct PrepareRequest {- pub pid: i64,+ /// Existing browser process used to select and attest the launch executable.+ /// Omitted only for a driver-owned isolated launch, where the platform+ /// resolves a supported installed Chromium executable instead.+ pub pid: Option<i64>,/// Exact native window used as the visible approval and ownership anchor/// for existing-profile attachment.pub window_id: Option<u64>,@@ -213,6 +268,17 @@ pub struct PrepareSideEffects {/// `browser_route_unavailable`).#[async_trait]pub trait BrowserPlatform: Send + Sync {+ /// Resolve a canonical installed Chromium-family executable for a+ /// driver-owned isolated launch that did not name an existing process.+ /// Native adapters use deterministic product priority and fail closed when+ /// no supported executable can be proven.+ fn isolated_browser_executable(&self) -> Result<String, BrowserRefusal> {+ Err(BrowserRefusal::new(+ super::refusal::BrowserRefusalCode::BrowserRouteUnavailable,+ "no supported installed Chromium executable is available for isolated launch",+ ))+ }+/// Explain why a trusted CDP Input route cannot preserve background/// posture for a standalone browser on this platform. Embedded Chromium/// routes are independently proven and do not consult this capability.@@ -361,3 +427,50 @@ pub trait BrowserPlatform: Send + Sync {request: PrepareRequest,) -> Result<PrepareOutcome, BrowserRefusal>;}++#[cfg(test)]+mod tests {+ use super::select_isolated_browser_executable;++ #[test]+ fn isolated_browser_selection_uses_first_installed_canonical_candidate() {+ let root = tempfile::tempdir().expect("temporary browser candidates");+ let canonical_root = std::fs::canonicalize(root.path()).expect("canonical temp root");+ let first = canonical_root.join("chrome");+ let second = canonical_root.join("chromium");+ std::fs::write(&first, b"first").expect("first candidate");+ std::fs::write(&second, b"second").expect("second candidate");++ let selected = select_isolated_browser_executable([+ canonical_root.join("missing"),+ first.clone(),+ second,+ ])+ .expect("select installed browser");++ assert_eq!(+ std::path::PathBuf::from(selected),+ std::fs::canonicalize(first).expect("canonical first candidate")+ );+ }++ #[cfg(unix)]+ #[test]+ fn isolated_browser_selection_rejects_symlinked_candidate() {+ use std::os::unix::fs::symlink;++ let root = tempfile::tempdir().expect("temporary browser candidates");+ let canonical_root = std::fs::canonicalize(root.path()).expect("canonical temp root");+ let arbitrary = canonical_root.join("arbitrary");+ let redirected = canonical_root.join("chrome");+ std::fs::write(&arbitrary, b"not a browser").expect("arbitrary executable fixture");+ symlink(&arbitrary, &redirected).expect("redirected browser fixture");++ let error = select_isolated_browser_executable([redirected])+ .expect_err("redirected browser path must fail closed");+ assert_eq!(+ error.code,+ super::super::refusal::BrowserRefusalCode::BrowserRouteUnavailable+ );+ }+}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.rsindex bfde6d2417..07702a0f97 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@@ -670,20 +670,22 @@ impl BrowserEngine {));}- match self.platform.prepare_endpoint(request.clone()).await {- Ok(mut outcome) => {- if outcome.prepared_pid.is_none() {- outcome.prepared_pid = outcome- .endpoint- .as_ref()- .map(|endpoint| endpoint.ownership.owner_pid);+ if request.pid.is_some() {+ match self.platform.prepare_endpoint(request.clone()).await {+ Ok(mut outcome) => {+ if outcome.prepared_pid.is_none() {+ outcome.prepared_pid = outcome+ .endpoint+ .as_ref()+ .map(|endpoint| endpoint.ownership.owner_pid);+ }+ return Ok(outcome);}- return Ok(outcome);- }- Err(error) if error.code != BrowserRefusalCode::BrowserRequiresSetup => {- return Err(error)+ Err(error) if error.code != BrowserRefusalCode::BrowserRequiresSetup => {+ return Err(error)+ }+ Err(_) => {}}- Err(_) => {}}if !request.allow_launch {@@ -699,20 +701,29 @@ impl BrowserEngine {)})?;validate_profile(profile_request)?;- let classification = self.platform.classify_browser(request.pid).await?;- if !classification.supports_cdp || classification.engine != BrowserEngineFamily::Chromium {- return Err(unsupported_engine_refusal(- &classification,- "prepare_isolated_profile",- ));- }- let fingerprint = self.platform.process_fingerprint(request.pid).await?;- let executable = fingerprint.executable.ok_or_else(|| {- refusal(- BrowserRefusalCode::BrowserRouteUnavailable,- "could not prove the requested browser executable for isolated launch",- )- })?;+ let executable = if let Some(pid) = request.pid {+ let classification = self.platform.classify_browser(pid).await?;+ if !classification.supports_cdp+ || classification.engine != BrowserEngineFamily::Chromium+ {+ return Err(unsupported_engine_refusal(+ &classification,+ "prepare_isolated_profile",+ ));+ }+ self.platform+ .process_fingerprint(pid)+ .await?+ .executable+ .ok_or_else(|| {+ refusal(+ BrowserRefusalCode::BrowserRouteUnavailable,+ "could not prove the requested browser executable for isolated launch",+ )+ })?+ } else {+ self.platform.isolated_browser_executable()?+ };let prepared_profile = prepare_profile(profile_request)?;let mut command = isolated_browser_command(&executable, &prepared_profile.path);let mut child = command.spawn().map_err(|error| {@@ -765,7 +776,7 @@ impl BrowserEngine {Ok(PrepareOutcome {action: PrepareAction::LaunchedIsolatedBrowser,endpoint: Some(endpoint),- message: "Launched a separate driver-owned isolated Chromium process; the requested browser process was not modified or terminated.".to_owned(),+ message: "Launched a separate driver-owned isolated Chromium process; no existing browser process was modified or terminated.".to_owned(),prepared_pid: Some(prepared_pid),side_effects: PrepareSideEffects {launched_browser: true,@@ -788,6 +799,12 @@ impl BrowserEngine {Unrestricted,}+ let pid = request.pid.ok_or_else(|| {+ refusal(+ BrowserRefusalCode::BrowserConsentRequired,+ "strategy=existing_profile requires an exact pid approval anchor",+ )+ })?;let window_id = request.window_id.ok_or_else(|| {refusal(BrowserRefusalCode::BrowserConsentRequired,@@ -823,7 +840,7 @@ impl BrowserEngine {.authorize_call("browser_prepare",&serde_json::json!({- "pid": request.pid,+ "pid": pid,"window_id": window_id,"strategy": {"kind": "existing_profile"},}),@@ -852,18 +869,18 @@ impl BrowserEngine {));}- let classification = self.platform.classify_browser(request.pid).await?;+ let classification = self.platform.classify_browser(pid).await?;if !classification.supports_cdp || classification.engine != BrowserEngineFamily::Chromium {return Err(unsupported_engine_refusal(&classification,"attach_existing_profile",));}- self.native_window_checked(request.pid, window_id).await?;- let fingerprint = self.platform.process_fingerprint(request.pid).await?;+ self.native_window_checked(pid, window_id).await?;+ let fingerprint = self.platform.process_fingerprint(pid).await?;let mut setup = ExistingProfileSetupOutcome::default();let setup_request = ExistingProfileSetupRequest {- pid: request.pid,+ pid,window_id,browser: classification.product_kind,};@@ -871,7 +888,7 @@ impl BrowserEngine {let mut setup_guard = None;let mut endpoint = self.platform- .discover_existing_profile_endpoint(request.pid)+ .discover_existing_profile_endpoint(pid).await?;if endpoint.is_none() {setup = self@@ -887,14 +904,14 @@ impl BrowserEngine {// Setup is allowed to interact only with the already-approved// process/window generation. Re-prove both before accepting the// newly exposed listener.- if let Err(error) = self.native_window_checked(request.pid, window_id).await {+ if let Err(error) = self.native_window_checked(pid, window_id).await {return Err(setup_guard.as_mut().expect("setup guard exists while setup is pending").abort(with_setup_side_effects(error, &setup)).await);}- let current_fingerprint = match self.platform.process_fingerprint(request.pid).await {+ let current_fingerprint = match self.platform.process_fingerprint(pid).await {Ok(fingerprint) => fingerprint,Err(error) => {return Err(setup_guard@@ -920,11 +937,7 @@ impl BrowserEngine {}endpoint = setup.endpoint.clone();if endpoint.is_none() {- endpoint = match self- .platform- .discover_existing_profile_endpoint(request.pid)- .await- {+ endpoint = match self.platform.discover_existing_profile_endpoint(pid).await {Ok(endpoint) => endpoint,Err(error) => {return Err(setup_guard@@ -953,7 +966,7 @@ impl BrowserEngine {return Err(error);}};- if endpoint.ownership.owner_pid != request.pid {+ if endpoint.ownership.owner_pid != pid {let error = with_setup_side_effects(refusal(BrowserRefusalCode::BrowserEndpointOwnerMismatch,@@ -987,7 +1000,7 @@ impl BrowserEngine {request.session.clone(),transport_session.to_owned(),serde_json::json!({- "pid": request.pid,+ "pid": pid,"window_id": window_id,"process_fingerprint": fingerprint.clone(),"browser_product": classification.product_kind,@@ -1020,11 +1033,7 @@ impl BrowserEngine {};let previous_grant = self- .existing_profile_grant(- &request.session,- request.transport_session.as_deref(),- request.pid,- )+ .existing_profile_grant(&request.session, request.transport_session.as_deref(), pid).await;let previous_grant = match previous_grant {Ok(grant) => grant,@@ -1047,7 +1056,7 @@ impl BrowserEngine {let grant = self.existing_profile_grants.mint(&request.session,request.transport_session.as_deref(),- request.pid,+ pid,window_id,fingerprint,"chromium".to_owned(),@@ -1079,7 +1088,7 @@ impl BrowserEngine {&mut claim,self.platform.handle_existing_profile_consent(BrowserConsentRequest {- pid: request.pid,+ pid,window_id,attempt: 1,}),@@ -1095,7 +1104,7 @@ impl BrowserEngine {self.revoke_existing_profile_grant(&request.session,request.transport_session.as_deref(),- request.pid,+ pid,).await;let error = with_setup_side_effects(error, &setup);@@ -1127,7 +1136,7 @@ impl BrowserEngine {self.revoke_existing_profile_grant(&request.session,request.transport_session.as_deref(),- request.pid,+ pid,).await;let error = with_prepare_side_effects(@@ -1163,7 +1172,7 @@ impl BrowserEngine {self.revoke_existing_profile_grant(&request.session,request.transport_session.as_deref(),- request.pid,+ pid,).await;return Err(with_prepare_side_effects(@@ -1175,13 +1184,13 @@ impl BrowserEngine {}}self.store- .invalidate_endpoint_generation(request.pid, previous_generation);+ .invalidate_endpoint_generation(pid, previous_generation);Ok(PrepareOutcome {action: PrepareAction::AttachedExistingProfile,endpoint: Some(endpoint),message: "Attached to the approved existing Chromium profile. Bind the native window again before using browser capabilities.".to_owned(),- prepared_pid: Some(request.pid),+ prepared_pid: Some(pid),side_effects: PrepareSideEffects {displayed_consent_prompt,changed_preferences: setup.enabled_remote_debugging,diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/tools.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/tools.rsindex b787a24d76..a5da89a19a 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/tools.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/tools.rs@@ -581,11 +581,15 @@ impl BrowserPrepareTool {pub fn new(engine: Arc<BrowserEngine>) -> Self {let def = ToolDef {name: "browser_prepare".into(),- description: "Explicitly prepare an owned DevTools endpoint for a browser \- pid. Existing endpoints are detected without side effects. Acting setup \+ description: "Explicitly prepare an owned DevTools endpoint for a browser. \+ pid is required for an existing process or existing-profile attachment, \+ and optional only for allow_launch=true with an isolated profile. Existing \+ endpoints are detected without side effects. Acting setup \for an isolated profile follows the runtime permission mode and optional \capability manifest. It requires allow_launch=true, launches a separate browser, and never \- copies, modifies, or terminates the requested user profile. Existing-profile \+ copies, modifies, or terminates the requested user profile. Without pid, only a \+ platform-attested system Chrome/Edge installation (or a root-owned package \+ payload on Linux) is eligible; redirects and user-controlled locations fail closed. Existing-profile \attachment is explicit and follows the runtime's immutable permission mode: \standard requires an explicit --grant existing-profile launch grant or an \embedding authorization host, bounded requires a launch-approved exact resource \@@ -600,7 +604,7 @@ impl BrowserPrepareTool {input_schema: json!({"type": "object","properties": {- "pid": { "type": "integer", "description": "Browser process id to prepare." },+ "pid": { "type": "integer", "description": "Browser process id to prepare. Required except for a driver-owned isolated_new/isolated_named launch with allow_launch=true." },"window_id": { "type": "integer", "description": "Exact native window approval anchor; required for strategy.kind=existing_profile." },"allow_launch": {"type": "boolean",@@ -625,7 +629,22 @@ impl BrowserPrepareTool {},"session": schema_session(),},- "required": ["pid"],+ "required": [],+ "anyOf": [+ { "required": ["pid"] },+ {+ "required": ["allow_launch", "profile"],+ "properties": {+ "allow_launch": { "const": true },+ "profile": {+ "required": ["mode"],+ "properties": {+ "mode": { "enum": ["isolated_new", "isolated_named"] }+ }+ }+ }+ }+ ],"additionalProperties": true}),read_only: false,@@ -644,10 +663,6 @@ impl Tool for BrowserPrepareTool {}async fn invoke(&self, args: Value) -> ToolResult {- let pid = match args.require_i64("pid") {- Ok(v) => v,- Err(e) => return e,- };let session = match require_explicit_session(&args) {Ok(session) => session,Err(error) => return error,@@ -672,6 +687,21 @@ impl Tool for BrowserPrepareTool {}},};+ let allow_launch = args.opt_bool("allow_launch").unwrap_or(false);+ let pid = match args.get("pid") {+ None => None,+ Some(_) => match args.require_i64("pid") {+ Ok(pid) => Some(pid),+ Err(error) => return error,+ },+ };+ let pid_optional = strategy.is_none() && profile.is_some() && allow_launch;+ if pid.is_none() && !pid_optional {+ return match args.require_i64("pid") {+ Ok(_) => unreachable!("pid was already parsed"),+ Err(error) => error,+ };+ }let request = PrepareRequest {pid,window_id: args.opt_u64("window_id"),@@ -679,7 +709,7 @@ impl Tool for BrowserPrepareTool {transport_session: args.opt_str("_transport_session_id"),strategy,profile,- allow_launch: args.opt_bool("allow_launch").unwrap_or(false),+ allow_launch,};match self.engine.prepare_browser(request).await {Ok(outcome) => {@@ -2822,6 +2852,40 @@ mod tests {);}+ #[tokio::test]+ async fn isolated_launch_accepts_omitted_pid() {+ let tool = BrowserPrepareTool::new(engine());+ let result = tool+ .invoke(json!({+ "allow_launch": true,+ "profile": { "mode": "isolated_new" },+ "session": "pid-free-isolated-run"+ }))+ .await;+ assert_eq!(+ structured(&result)["refusal"]["code"],+ "browser_route_unavailable"+ );+ }++ #[tokio::test]+ async fn existing_profile_still_requires_pid() {+ let tool = BrowserPrepareTool::new(engine());+ let result = tool+ .invoke(json!({+ "window_id": 7,+ "strategy": { "kind": "existing_profile" },+ "session": "existing-profile-without-pid"+ }))+ .await;+ assert_eq!(result.is_error, Some(true));+ let body = serde_json::to_string(&result.content).expect("serialize tool error");+ assert!(+ body.contains("Missing required integer field: pid"),+ "{body}"+ );+ }+#[tokio::test]async fn existing_profile_requires_runtime_authorization() {let tool = BrowserPrepareTool::new(engine());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.rsindex a2ee5c604b..25bc6dd8bd 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@@ -82,7 +82,7 @@ fn tools_list_schema_shape() {"get_browser_state should advertise opt-in exact-tab capture");for (name, required) in [- ("browser_prepare", &["pid"][..]),+ ("browser_prepare", &[][..]),("browser_navigate", &["target_id", "tab_id", "url"][..]),("browser_click", &["target_id", "tab_id"][..]),("browser_type", &["target_id", "tab_id", "ref", "text"][..]),@@ -109,6 +109,20 @@ fn tools_list_schema_shape() {);}}+ let prepare = tools+ .iter()+ .find(|tool| tool["name"] == "browser_prepare")+ .expect("browser_prepare not found in tools/list");+ assert!(+ prepare["inputSchema"]["anyOf"]+ .as_array()+ .is_some_and(|alternatives| alternatives.iter().any(|alternative| {+ alternative["required"]+ .as_array()+ .is_some_and(|required| required.iter().any(|field| field == "pid"))+ })),+ "browser_prepare schema must retain a pid-required alternative"+ );const DELIVERY_MODE_TOOLS: &[&str] = &["click",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.rsindex f06effb428..a47940c8cf 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@@ -24,7 +24,9 @@ use cua_driver_testkit::e2e::{};use cua_driver_testkit::observer::TargetWindow;use cua_driver_testkit::sentinel::ForegroundSentinel;-use cua_driver_testkit::{spawn_in_job, BrowserFixtureServer, Driver, McpDriver, ToolResponse};+use cua_driver_testkit::{+ spawn_in_job, BrowserFixtureServer, Driver, McpDriver, RawDriver, ToolResponse,+};use futures_util::{SinkExt, StreamExt};use tokio_tungstenite::tungstenite::Message;@@ -2196,44 +2198,18 @@ fn run_prepare_isolated_launch(spec: &BrowserSpec) {case(&spec.name, "browser_prepare_isolated_launch"),|evidence| {let target_server = BrowserFixtureServer::start(&standalone_fixture_html());- let source_profile = tempfile::Builder::new()- .prefix("cua-e2e-user-browser-")- .tempdir()- .expect("create ordinary browser profile");let driver_profiles = driver_profile_root();let profiles_before = profile_entries(&driver_profiles);let mut driver = spawn_driver(&scenario);*evidence = recording_evidence(driver.recording_dir());- let before = window_ids(&mut driver);- let mut source_command = command_for_unprepared_browser(- spec,- source_profile.path(),- "about:blank",- TEST_BROWSER_INITIAL_POSITION,- );- let source_child = spawn_in_job(&mut source_command).expect("launch ordinary browser");- let launched_pid = source_child.id();- eprintln!(- "[standalone-browser] spawned ordinary {} pid={} profile={}",- spec.name,- source_child.id(),- source_profile.path().display()- );- driver.reaper().push(source_child);- let (source_pid, source_window_id) =- wait_for_new_browser_window(&mut driver, &before, spec, launched_pid)- .expect("ordinary browser native window");- driver.reaper().track_pid(source_pid);-- let session = format!("standalone-prepare-{source_pid}");+ let session = format!("standalone-prepare-{}", spec.name);let started = driver.call("start_session", serde_json::json!({ "session": session }));assert!(!started.is_error(), "start_session failed: {}", started.raw);driver.start_behavior_recording();let prepared = driver.call("browser_prepare",serde_json::json!({- "pid": source_pid as i64,"session": session,"allow_launch": true,"profile": {"mode": "isolated_new"},@@ -2264,7 +2240,6 @@ fn run_prepare_isolated_launch(spec: &BrowserSpec) {let prepared_pid = prepared.structured()["prepared_pid"].as_u64().expect("prepared browser pid") as u32;- assert_ne!(prepared_pid, source_pid);let (prepared_window_id, state) =wait_for_exact_browser_binding(&mut driver, prepared_pid, &session).expect("isolated browser did not expose an exactly bindable window");@@ -2329,17 +2304,6 @@ fn run_prepare_isolated_launch(spec: &BrowserSpec) {clicked.raw);wait_for_text(&target_server, "lbl-counter", "counter=1");- let source_windows =- driver.call("list_windows", serde_json::json!({"pid": source_pid}));- assert!(- source_windows.structured()["windows"]- .as_array()- .is_some_and(|windows| windows.iter().any(|window| {- window["window_id"].as_u64() == Some(source_window_id)- })),- "ordinary browser was modified or terminated: {}",- source_windows.raw- );Observation::delivered(vec![OracleKind::FixtureState], Evidence::default())}).expect("observe isolated browser desktop effects");@@ -2364,6 +2328,79 @@ fn run_prepare_isolated_launch(spec: &BrowserSpec) {);}+#[test]+#[ignore = "requires an installed standalone Chromium browser"]+fn standalone_browser_prepare_isolated_source_smoke() {+ let _guard = STANDALONE_BROWSER_TEST_LOCK+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner());+ let driver_profiles = driver_profile_root();+ let profiles_before = profile_entries(&driver_profiles);+ let mut driver = RawDriver::spawn_with_env(&[+ ("CUA_DRIVER_PERMISSION_MODE", "unrestricted"),+ ("CUA_DRIVER_DANGEROUSLY_BYPASS_APPROVALS", "1"),+ ])+ .expect("source-built driver daemon");++ driver.send(&serde_json::json!({+ "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}+ }));+ driver.recv();+ driver.send(&serde_json::json!({+ "jsonrpc": "2.0", "id": 2, "method": "tools/call",+ "params": {"name": "start_session", "arguments": {"session": "pid-free-source-smoke"}}+ }));+ let started = driver.recv();+ assert_eq!(+ started["result"]["isError"],+ serde_json::Value::Null,+ "{started}"+ );++ driver.send(&serde_json::json!({+ "jsonrpc": "2.0", "id": 3, "method": "tools/call",+ "params": {+ "name": "browser_prepare",+ "arguments": {+ "session": "pid-free-source-smoke",+ "allow_launch": true,+ "profile": {"mode": "isolated_new"}+ }+ }+ }));+ let prepared = driver.recv();+ assert_eq!(+ prepared["result"]["structuredContent"]["action"], "launched_isolated_browser",+ "{prepared}"+ );+ assert!(+ prepared["result"]["structuredContent"]["prepared_pid"]+ .as_i64()+ .is_some_and(|pid| pid > 0),+ "{prepared}"+ );++ driver.send(&serde_json::json!({+ "jsonrpc": "2.0", "id": 4, "method": "tools/call",+ "params": {"name": "end_session", "arguments": {"session": "pid-free-source-smoke"}}+ }));+ let ended = driver.recv();+ assert_eq!(+ ended["result"]["isError"],+ serde_json::Value::Null,+ "{ended}"+ );++ let deadline = Instant::now() + Duration::from_secs(5);+ while profile_entries(&driver_profiles) != profiles_before {+ assert!(+ Instant::now() < deadline,+ "isolated_new profile remained after source-daemon end_session"+ );+ thread::sleep(Duration::from_millis(100));+ }+}+#[cfg(not(target_os = "macos"))]fn run_existing_profile_standard_refusal(spec: &BrowserSpec) {let scenario = format!(diff --git a/libs/cua-driver/rust/crates/platform-linux/Cargo.toml b/libs/cua-driver/rust/crates/platform-linux/Cargo.tomlindex 83eb4f6911..5a54b732aa 100644--- a/libs/cua-driver/rust/crates/platform-linux/Cargo.toml+++ b/libs/cua-driver/rust/crates/platform-linux/Cargo.toml@@ -139,6 +139,7 @@ portal-libei = ["portal-input", "portal-capture"][dev-dependencies]tokio = { workspace = true, features = ["test-util"] }uuid = { workspace = true }+tempfile = "3"# Used by the `screenshot_cascade` example to surface the# `tracing::debug!` lines emitted by each tier of the dispatch as it# falls through.diff --git a/libs/cua-driver/rust/crates/platform-linux/src/browser_platform.rs b/libs/cua-driver/rust/crates/platform-linux/src/browser_platform.rsindex 6808992d6f..67a7f84d5c 100644--- a/libs/cua-driver/rust/crates/platform-linux/src/browser_platform.rs+++ b/libs/cua-driver/rust/crates/platform-linux/src/browser_platform.rs@@ -1,14 +1,16 @@//! Linux identity and endpoint evidence for the first-class browser tools.use std::collections::{HashMap, HashSet, VecDeque};+use std::os::unix::fs::MetadataExt;use std::path::PathBuf;use std::time::Duration;use async_trait::async_trait;use cua_driver_core::browser::existing_profile_setup_descriptor;use cua_driver_core::browser::platform::{- BrowserConsentOutcome, BrowserConsentRequest, BrowserPlatform, ExistingProfileSetupOutcome,- ExistingProfileSetupRequest, PrepareAction, PrepareOutcome, PrepareRequest,+ select_isolated_browser_executable, BrowserConsentOutcome, BrowserConsentRequest,+ BrowserPlatform, ExistingProfileSetupOutcome, ExistingProfileSetupRequest, PrepareAction,+ PrepareOutcome, PrepareRequest,};use cua_driver_core::browser::refusal::{BrowserRefusal, BrowserRefusalCode};use cua_driver_core::browser::types::{@@ -74,6 +76,40 @@ fn browser_product(identity: &str) -> BrowserProduct {}}+fn isolated_browser_candidates() -> Vec<PathBuf> {+ // These are the root-managed payload locations of supported Linux+ // packages, not PATH shims. Core additionally rejects symlinked paths, so+ // an isolated-launch grant cannot be redirected to a user-controlled file.+ [+ "/opt/google/chrome/google-chrome",+ "/usr/lib/chromium/chromium",+ "/usr/lib/chromium-browser/chromium-browser",+ "/opt/microsoft/msedge/msedge",+ ]+ .into_iter()+ .map(PathBuf::from)+ .collect()+}++fn trusted_root_owned_installation(executable: &std::path::Path) -> bool {+ if !executable.is_absolute() {+ return false;+ }+ let mut current = Some(executable);+ while let Some(path) = current {+ let Ok(metadata) = std::fs::symlink_metadata(path) else {+ return false;+ };+ if metadata.file_type().is_symlink() || metadata.uid() != 0 || metadata.mode() & 0o022 != 0+ {+ return false;+ }+ current = path.parent();+ }+ std::fs::metadata(executable)+ .is_ok_and(|metadata| metadata.is_file() && metadata.mode() & 0o111 != 0)+}+fn loopback_websocket_port(url: &str) -> Option<u16> {["ws://127.0.0.1:", "ws://localhost:", "ws://[::1]:"].iter()@@ -388,6 +424,21 @@ async fn browser_websocket_url(port: u16) -> Option<String> {#[async_trait]impl BrowserPlatform for LinuxBrowserPlatform {+ fn isolated_browser_executable(&self) -> Result<String, BrowserRefusal> {+ for candidate in isolated_browser_candidates() {+ let Ok(executable) = select_isolated_browser_executable([candidate]) else {+ continue;+ };+ if trusted_root_owned_installation(std::path::Path::new(&executable)) {+ return Ok(executable);+ }+ }+ Err(refusal(+ BrowserRefusalCode::BrowserRouteUnavailable,+ "no root-owned, non-writable system Chromium executable is available for isolated launch",+ ))+ }+fn standalone_trusted_input_background_limitation(&self) -> Option<&'static str> {Some("Chromium's trusted CDP Input route activates its standalone browser window on Linux")}@@ -1035,7 +1086,13 @@ impl BrowserPlatform for LinuxBrowserPlatform {&self,request: PrepareRequest,) -> Result<PrepareOutcome, BrowserRefusal> {- if let Some(endpoint) = self.discover_owned_endpoint(request.pid).await? {+ let Some(pid) = request.pid else {+ return Err(refusal(+ BrowserRefusalCode::BrowserRequiresSetup,+ "pid-free isolated launch is handled by shared core",+ ));+ };+ if let Some(endpoint) = self.discover_owned_endpoint(pid).await? {return Ok(PrepareOutcome {action: PrepareAction::AlreadyPrepared,prepared_pid: Some(endpoint.ownership.owner_pid),@@ -1056,6 +1113,30 @@ impl BrowserPlatform for LinuxBrowserPlatform {mod tests {use super::*;+ #[test]+ fn isolated_browser_candidates_use_only_root_managed_payloads() {+ let candidates = isolated_browser_candidates();+ assert!(candidates.iter().all(|candidate| candidate.is_absolute()));+ assert_eq!(+ candidates,+ [+ "/opt/google/chrome/google-chrome",+ "/usr/lib/chromium/chromium",+ "/usr/lib/chromium-browser/chromium-browser",+ "/opt/microsoft/msedge/msedge",+ ]+ .map(PathBuf::from)+ );+ }++ #[test]+ fn user_owned_writable_candidate_is_not_a_trusted_installation() {+ let root = tempfile::tempdir().expect("temporary untrusted installation");+ let executable = root.path().join("google-chrome");+ std::fs::write(&executable, b"not a browser").expect("untrusted executable fixture");+ assert!(!trusted_root_owned_installation(&executable));+ }+#[test]fn proc_net_parser_returns_only_loopback_listeners() {let input = " sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\n\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.rsindex 0ba27cea87..79c8aa10f4 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@@ -10,9 +10,9 @@ use std::time::Duration;use async_trait::async_trait;use cua_driver_core::browser::existing_profile_setup_descriptor;use cua_driver_core::browser::platform::{- BrowserConsentOutcome, BrowserConsentRequest, BrowserPlatform, BrowserVisualAction,- BrowserVisualActionKind, ExistingProfileSetupOutcome, ExistingProfileSetupRequest,- PrepareAction, PrepareOutcome, PrepareRequest,+ select_isolated_browser_executable, BrowserConsentOutcome, BrowserConsentRequest,+ BrowserPlatform, BrowserVisualAction, BrowserVisualActionKind, ExistingProfileSetupOutcome,+ ExistingProfileSetupRequest, PrepareAction, PrepareOutcome, PrepareRequest,};use cua_driver_core::browser::refusal::{BrowserRefusal, BrowserRefusalCode};use cua_driver_core::browser::types::{@@ -141,6 +141,72 @@ fn browser_product(name: &str, bundle_id: &str) -> BrowserProduct {}}+fn isolated_browser_candidates() -> Vec<(PathBuf, &'static str, &'static str)> {+ // pid-free launch deliberately supports only vendor-signed system-wide+ // installations. Chromium builds have no stable vendor team identity, so+ // callers can still select one by supplying its already-running pid.+ vec![+ (+ PathBuf::from("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"),+ "com.google.Chrome",+ "EQHXZ8M8AV",+ ),+ (+ PathBuf::from("/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"),+ "com.microsoft.edgemac",+ "UBF8T346G9",+ ),+ ]+}++fn codesign_identity_matches(details: &str, identifier: &str, team_identifier: &str) -> bool {+ let mut observed_identifier = None;+ let mut observed_team = None;+ for line in details.lines() {+ if let Some(value) = line.strip_prefix("Identifier=") {+ observed_identifier = Some(value.trim());+ } else if let Some(value) = line.strip_prefix("TeamIdentifier=") {+ observed_team = Some(value.trim());+ }+ }+ observed_identifier == Some(identifier) && observed_team == Some(team_identifier)+}++fn has_trusted_codesign_identity(+ executable: &std::path::Path,+ identifier: &str,+ team_identifier: &str,+) -> bool {+ let requirement = format!(+ "=anchor apple generic and certificate leaf[subject.OU] = \"{team_identifier}\" and identifier \"{identifier}\""+ );+ let verified = std::process::Command::new("/usr/bin/codesign")+ .args(["--verify", "--strict", "--test-requirement", &requirement])+ .arg(executable)+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .status()+ .is_ok_and(|status| status.success());+ if !verified {+ return false;+ }+ let Ok(details) = std::process::Command::new("/usr/bin/codesign")+ .args(["-dv", "--verbose=4"])+ .arg(executable)+ .stdin(Stdio::null())+ .output()+ else {+ return false;+ };+ details.status.success()+ && codesign_identity_matches(+ &String::from_utf8_lossy(&details.stderr),+ identifier,+ team_identifier,+ )+}+fn loopback_websocket_port(url: &str) -> Option<u16> {["ws://127.0.0.1:", "ws://localhost:", "ws://[::1]:"].iter()@@ -396,6 +462,25 @@ async fn browser_websocket_url(port: u16) -> Option<String> {#[async_trait]impl BrowserPlatform for MacOsBrowserPlatform {+ fn isolated_browser_executable(&self) -> Result<String, BrowserRefusal> {+ for (candidate, identifier, team_identifier) in isolated_browser_candidates() {+ let Ok(executable) = select_isolated_browser_executable([candidate]) else {+ continue;+ };+ if has_trusted_codesign_identity(+ std::path::Path::new(&executable),+ identifier,+ team_identifier,+ ) {+ return Ok(executable);+ }+ }+ Err(refusal(+ BrowserRefusalCode::BrowserRouteUnavailable,+ "no vendor-signed system Chromium executable is available for isolated launch",+ ))+ }+fn standalone_trusted_input_background_limitation(&self) -> Option<&'static str> {Some("Chromium's trusted CDP Input route activates its standalone browser window on macOS")}@@ -903,7 +988,13 @@ impl BrowserPlatform for MacOsBrowserPlatform {&self,request: PrepareRequest,) -> Result<PrepareOutcome, BrowserRefusal> {- if let Some(endpoint) = self.discover_owned_endpoint(request.pid).await? {+ let Some(pid) = request.pid else {+ return Err(refusal(+ BrowserRefusalCode::BrowserRequiresSetup,+ "pid-free isolated launch is handled by shared core",+ ));+ };+ if let Some(endpoint) = self.discover_owned_endpoint(pid).await? {return Ok(PrepareOutcome {action: PrepareAction::AlreadyPrepared,prepared_pid: Some(endpoint.ownership.owner_pid),@@ -924,6 +1015,45 @@ impl BrowserPlatform for MacOsBrowserPlatform {mod tests {use super::*;+ #[test]+ fn isolated_browser_candidates_are_vendor_attested_system_installs() {+ let candidates = isolated_browser_candidates();+ assert_eq!(candidates.len(), 2);+ assert_eq!(candidates[0].1, "com.google.Chrome");+ assert_eq!(candidates[0].2, "EQHXZ8M8AV");+ assert!(candidates[0]+ .0+ .ends_with("Google Chrome.app/Contents/MacOS/Google Chrome"));+ assert_eq!(candidates[1].1, "com.microsoft.edgemac");+ assert_eq!(candidates[1].2, "UBF8T346G9");+ assert!(candidates[1]+ .0+ .ends_with("Microsoft Edge.app/Contents/MacOS/Microsoft Edge"));+ assert!(candidates+ .iter()+ .all(|(candidate, _, _)| candidate.is_absolute()));+ }++ #[test]+ fn codesign_identity_requires_exact_identifier_and_team() {+ let details = "Identifier=com.google.Chrome\nTeamIdentifier=EQHXZ8M8AV\n";+ assert!(codesign_identity_matches(+ details,+ "com.google.Chrome",+ "EQHXZ8M8AV"+ ));+ assert!(!codesign_identity_matches(+ details,+ "com.google.Chrome",+ "ATTACKER00"+ ));+ assert!(!codesign_identity_matches(+ "Identifier=com.google.Chrome\nTeamIdentifier=\n",+ "com.google.Chrome",+ "EQHXZ8M8AV"+ ));+ }+fn window(window_id: u32, pid: i32, title: &str) -> crate::windows::WindowInfo {crate::windows::WindowInfo {window_id,diff --git a/libs/cua-driver/rust/crates/platform-windows/Cargo.toml b/libs/cua-driver/rust/crates/platform-windows/Cargo.tomlindex 1479c4f338..e7caf40998 100644--- a/libs/cua-driver/rust/crates/platform-windows/Cargo.toml+++ b/libs/cua-driver/rust/crates/platform-windows/Cargo.toml@@ -87,3 +87,4 @@ base64 = { workspace = true }[dev-dependencies]uuid = { workspace = true }+tempfile = "3"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.rsindex 6783e52be4..4831efc409 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@@ -10,9 +10,9 @@ use std::time::Duration;use async_trait::async_trait;use cua_driver_core::browser::existing_profile_setup_descriptor;use cua_driver_core::browser::platform::{- BrowserConsentOutcome, BrowserConsentRequest, BrowserPlatform, BrowserVisualAction,- BrowserVisualActionKind, ExistingProfileSetupOutcome, ExistingProfileSetupRequest,- PrepareAction, PrepareOutcome, PrepareRequest,+ select_isolated_browser_executable, BrowserConsentOutcome, BrowserConsentRequest,+ BrowserPlatform, BrowserVisualAction, BrowserVisualActionKind, ExistingProfileSetupOutcome,+ ExistingProfileSetupRequest, PrepareAction, PrepareOutcome, PrepareRequest,};use cua_driver_core::browser::refusal::{BrowserRefusal, BrowserRefusalCode};use cua_driver_core::browser::types::{@@ -21,13 +21,24 @@ use cua_driver_core::browser::types::{OwnedEndpoint, ProcessFingerprint, Rect,};use tokio::io::{AsyncReadExt, AsyncWriteExt};-use windows::Win32::Foundation::{CloseHandle, FILETIME, HWND, RECT};+use windows::core::PCWSTR;+use windows::Win32::Foundation::{CloseHandle, E_ACCESSDENIED, FILETIME, HWND, RECT};+use windows::Win32::Storage::FileSystem::{+ CreateFileW, DELETE, FILE_ADD_FILE, FILE_ADD_SUBDIRECTORY, FILE_APPEND_DATA, FILE_DELETE_CHILD,+ FILE_FLAGS_AND_ATTRIBUTES, FILE_FLAG_BACKUP_SEMANTICS, FILE_SHARE_DELETE, FILE_SHARE_READ,+ FILE_SHARE_WRITE, FILE_WRITE_ATTRIBUTES, FILE_WRITE_DATA, FILE_WRITE_EA, OPEN_EXISTING,+ WRITE_DAC, WRITE_OWNER,+};+use windows::Win32::System::Com::CoTaskMemFree;use windows::Win32::System::SystemInformation::GetSystemDirectoryW;use windows::Win32::System::Threading::{GetProcessTimes, OpenProcess, QueryFullProcessImageNameW, PROCESS_NAME_FORMAT,PROCESS_QUERY_LIMITED_INFORMATION,};use windows::Win32::UI::HiDpi::GetDpiForWindow;+use windows::Win32::UI::Shell::{+ FOLDERID_ProgramFiles, FOLDERID_ProgramFilesX86, SHGetKnownFolderPath, KF_FLAG_DEFAULT,+};use windows::Win32::UI::WindowsAndMessaging::{GetAncestor, GetWindowRect, GA_ROOT};#[derive(Clone)]@@ -135,6 +146,209 @@ fn browser_product(name: &str) -> BrowserProduct {}}+fn isolated_browser_candidates_from_roots(+ program_files: &std::path::Path,+ program_files_x86: &std::path::Path,+) -> Vec<(PathBuf, PathBuf, &'static str, &'static str)> {+ vec![+ (+ program_files.join(r"Google\Chrome\Application\chrome.exe"),+ program_files.to_owned(),+ "CN=Google LLC",+ "O=Google LLC",+ ),+ (+ program_files_x86.join(r"Google\Chrome\Application\chrome.exe"),+ program_files_x86.to_owned(),+ "CN=Google LLC",+ "O=Google LLC",+ ),+ (+ program_files.join(r"Microsoft\Edge\Application\msedge.exe"),+ program_files.to_owned(),+ "CN=Microsoft Corporation",+ "O=Microsoft Corporation",+ ),+ (+ program_files_x86.join(r"Microsoft\Edge\Application\msedge.exe"),+ program_files_x86.to_owned(),+ "CN=Microsoft Corporation",+ "O=Microsoft Corporation",+ ),+ ]+}++fn known_folder_path(id: &windows::core::GUID) -> Result<PathBuf, BrowserRefusal> {+ let raw = unsafe { SHGetKnownFolderPath(id, KF_FLAG_DEFAULT, None) }.map_err(|error| {+ refusal(+ BrowserRefusalCode::BrowserRouteUnavailable,+ format!("could not resolve trusted Windows installation root: {error}"),+ )+ })?;+ let decoded = unsafe { raw.to_string() };+ unsafe { CoTaskMemFree(Some(raw.0.cast())) };+ decoded.map(PathBuf::from).map_err(|error| {+ refusal(+ BrowserRefusalCode::BrowserRouteUnavailable,+ format!("trusted Windows installation root was not valid Unicode: {error}"),+ )+ })+}++fn isolated_browser_candidates(+) -> Result<Vec<(PathBuf, PathBuf, &'static str, &'static str)>, BrowserRefusal> {+ let program_files = known_folder_path(&FOLDERID_ProgramFiles)?;+ let program_files_x86 = known_folder_path(&FOLDERID_ProgramFilesX86)?;+ Ok(isolated_browser_candidates_from_roots(+ &program_files,+ &program_files_x86,+ ))+}++fn authenticode_identity_matches(details: &str, expected_cn: &str, expected_org: &str) -> bool {+ let mut lines = details.lines();+ if lines.next().map(str::trim) != Some("Valid") {+ return false;+ }+ let Some(subject) = lines.next() else {+ return false;+ };+ let fields = subject.split(',').map(str::trim).collect::<Vec<_>>();+ fields.contains(&expected_cn) && fields.contains(&expected_org)+}++fn has_trusted_authenticode_identity(+ executable: &std::path::Path,+ expected_cn: &str,+ expected_org: &str,+) -> bool {+ let Ok(output) = authenticode_output(executable) else {+ return false;+ };+ output.status.success()+ && authenticode_identity_matches(+ &String::from_utf8_lossy(&output.stdout),+ expected_cn,+ expected_org,+ )+}++fn authenticode_output(executable: &std::path::Path) -> std::io::Result<std::process::Output> {+ let Ok(system32) = system_directory_path() else {+ return Err(std::io::Error::other(+ "could not resolve the Windows system directory",+ ));+ };+ let powershell = system32.join(r"WindowsPowerShell\v1.0\powershell.exe");+ std::process::Command::new(powershell)+ .args([+ "-NoLogo",+ "-NoProfile",+ "-NonInteractive",+ "-Command",+ r#"$ErrorActionPreference = 'Stop'; $utf8 = [System.Text.UTF8Encoding]::new($false); [Console]::OutputEncoding = $utf8; $module = Join-Path $PSHOME 'Modules\Microsoft.PowerShell.Security\Microsoft.PowerShell.Security.psd1'; Import-Module -Name $module -Force -ErrorAction Stop; $path = [Environment]::GetEnvironmentVariable('CUA_BROWSER_ATTEST_PATH'); $signature = Microsoft.PowerShell.Security\Get-AuthenticodeSignature -LiteralPath $path; Write-Output $signature.Status; Write-Output $signature.SignerCertificate.Subject"#,+ ])+ // The static command imports Security beside the trusted System32+ // PowerShell, ignoring an incompatible inherited PSModulePath. Pass the+ // browser path as data so PowerShell never parses it as command text.+ .env("CUA_BROWSER_ATTEST_PATH", executable)+ .stdin(Stdio::null())+ .output()+}++fn current_token_write_denial_reason(path: &std::path::Path, directory: bool) -> Option<String> {+ use std::os::windows::ffi::OsStrExt;++ // This launch boundary protects the current agent token from executing a+ // browser tree that it can modify. Other principals that can replace an+ // installed browser are outside this runtime authorization boundary.+ let wide = path+ .as_os_str()+ .encode_wide()+ .chain(std::iter::once(0))+ .collect::<Vec<_>>();+ let rights: &[(&str, u32)] = if directory {+ &[+ ("add_file", FILE_ADD_FILE.0),+ ("add_subdirectory", FILE_ADD_SUBDIRECTORY.0),+ ("delete_child", FILE_DELETE_CHILD.0),+ ("write_ea", FILE_WRITE_EA.0),+ ("write_attributes", FILE_WRITE_ATTRIBUTES.0),+ ("delete", DELETE.0),+ ("write_dac", WRITE_DAC.0),+ ("write_owner", WRITE_OWNER.0),+ ]+ } else {+ &[+ ("write_data", FILE_WRITE_DATA.0),+ ("append_data", FILE_APPEND_DATA.0),+ ("write_ea", FILE_WRITE_EA.0),+ ("write_attributes", FILE_WRITE_ATTRIBUTES.0),+ ("delete", DELETE.0),+ ("write_dac", WRITE_DAC.0),+ ("write_owner", WRITE_OWNER.0),+ ]+ };+ let flags = if directory {+ FILE_FLAG_BACKUP_SEMANTICS+ } else {+ FILE_FLAGS_AND_ATTRIBUTES(0)+ };+ for &(name, right) in rights {+ match unsafe {+ CreateFileW(+ PCWSTR(wide.as_ptr()),+ right,+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,+ None,+ OPEN_EXISTING,+ flags,+ None,+ )+ } {+ Ok(handle) => {+ let _ = unsafe { CloseHandle(handle) };+ return Some(format!("current token was granted {name}"));+ }+ Err(error) if error.code() == E_ACCESSDENIED => {}+ Err(error) => return Some(format!("{name} probe failed closed: {error}")),+ }+ }+ None+}++fn current_token_cannot_write(path: &std::path::Path, directory: bool) -> bool {+ current_token_write_denial_reason(path, directory).is_none()+}++fn trusted_windows_installation(+ executable: &std::path::Path,+ trusted_root: &std::path::Path,+) -> bool {+ trusted_windows_installation_with_probe(executable, trusted_root, current_token_cannot_write)+}++fn trusted_windows_installation_with_probe(+ executable: &std::path::Path,+ trusted_root: &std::path::Path,+ mut cannot_write: impl FnMut(&std::path::Path, bool) -> bool,+) -> bool {+ if !executable.starts_with(trusted_root) || !cannot_write(executable, false) {+ return false;+ }+ let mut current = executable.parent();+ while let Some(directory) = current {+ if !cannot_write(directory, true) {+ return false;+ }+ if directory == trusted_root {+ return true;+ }+ current = directory.parent();+ }+ false+}+fn allows_embedded_descendant_endpoint(executable_path: &str) -> bool {let executable = executable_path.rsplit(['/', '\\'])@@ -346,7 +560,7 @@ fn parse_netstat_loopback_ports(text: &str, allowed_pids: &[u32]) -> Vec<u16> {ports}-fn system_netstat_path() -> Result<PathBuf, BrowserRefusal> {+fn system_directory_path() -> Result<PathBuf, BrowserRefusal> {let mut buffer = [0u16; 32768];let length = unsafe { GetSystemDirectoryW(Some(&mut buffer)) } as usize;if length == 0 || length >= buffer.len() {@@ -355,7 +569,11 @@ fn system_netstat_path() -> Result<PathBuf, BrowserRefusal> {"could not resolve the trusted Windows system directory",));}- Ok(PathBuf::from(String::from_utf16_lossy(&buffer[..length])).join("netstat.exe"))+ Ok(PathBuf::from(String::from_utf16_lossy(&buffer[..length])))+}++fn system_netstat_path() -> Result<PathBuf, BrowserRefusal> {+ Ok(system_directory_path()?.join("netstat.exe"))}async fn netstat_loopback_listeners(@@ -811,6 +1029,27 @@ where#[async_trait]impl BrowserPlatform for WindowsBrowserPlatform {+ fn isolated_browser_executable(&self) -> Result<String, BrowserRefusal> {+ for (candidate, trusted_root, expected_cn, expected_org) in isolated_browser_candidates()? {+ let Ok(executable) = select_isolated_browser_executable([candidate.clone()]) else {+ continue;+ };+ if trusted_windows_installation(&candidate, &trusted_root)+ && has_trusted_authenticode_identity(+ std::path::Path::new(&executable),+ expected_cn,+ expected_org,+ )+ {+ return Ok(executable);+ }+ }+ Err(refusal(+ BrowserRefusalCode::BrowserRouteUnavailable,+ "no vendor-signed protected Chromium executable is available for isolated launch",+ ))+ }+async fn visualize_browser_action(&self, action: BrowserVisualAction) {if action.session.is_empty()|| action.cdp_target_id.is_empty()@@ -1291,7 +1530,13 @@ impl BrowserPlatform for WindowsBrowserPlatform {&self,request: PrepareRequest,) -> Result<PrepareOutcome, BrowserRefusal> {- if let Some(endpoint) = self.discover_owned_endpoint(request.pid).await? {+ let Some(pid) = request.pid else {+ return Err(refusal(+ BrowserRefusalCode::BrowserRequiresSetup,+ "pid-free isolated launch is handled by shared core",+ ));+ };+ if let Some(endpoint) = self.discover_owned_endpoint(pid).await? {return Ok(PrepareOutcome {action: PrepareAction::AlreadyPrepared,prepared_pid: Some(endpoint.ownership.owner_pid),@@ -1311,6 +1556,154 @@ impl BrowserPlatform for WindowsBrowserPlatform {#[cfg(test)]mod tests {use super::*;++ #[test]+ fn isolated_browser_candidates_are_vendor_attested_protected_installs() {+ let candidates = isolated_browser_candidates_from_roots(+ std::path::Path::new(r"D:\Apps"),+ std::path::Path::new(r"E:\Apps32"),+ );+ assert_eq!(candidates.len(), 4);+ assert_eq!(+ candidates[0].0,+ PathBuf::from(r"D:\Apps\Google\Chrome\Application\chrome.exe")+ );+ assert_eq!(+ candidates[1].0,+ PathBuf::from(r"E:\Apps32\Google\Chrome\Application\chrome.exe")+ );+ assert_eq!(+ candidates[2].0,+ PathBuf::from(r"D:\Apps\Microsoft\Edge\Application\msedge.exe")+ );+ }++ #[test]+ fn authenticode_identity_requires_valid_exact_publisher_fields() {+ let details = "Valid\r\nCN=Google LLC, O=Google LLC, L=Mountain View\r\n";+ assert!(authenticode_identity_matches(+ details,+ "CN=Google LLC",+ "O=Google LLC"+ ));+ assert!(!authenticode_identity_matches(+ "NotSigned\r\nCN=Google LLC, O=Google LLC\r\n",+ "CN=Google LLC",+ "O=Google LLC"+ ));+ assert!(!authenticode_identity_matches(+ "Valid\r\nCN=Google LLC, O=Google LLC Evil\r\n",+ "CN=Google LLC",+ "O=Google LLC"+ ));+ }++ #[test]+ fn writable_installation_tree_is_rejected() {+ let root = tempfile::tempdir().expect("writable product root");+ let product = root.path().join(r"Google\Chrome\Application");+ std::fs::create_dir_all(&product).expect("writable product directories");+ let executable = product.join("chrome.exe");+ std::fs::write(&executable, b"not a browser").expect("writable executable");++ assert!(!trusted_windows_installation(&executable, root.path()));+ }++ #[test]+ fn installation_trust_walk_requires_every_probe_to_deny_write() {+ let root = std::path::Path::new(r"C:\Program Files");+ let executable = root.join(r"Google\Chrome\Application\chrome.exe");++ assert!(trusted_windows_installation_with_probe(+ &executable,+ root,+ |_, _| true,+ ));+ assert!(!trusted_windows_installation_with_probe(+ &executable,+ root,+ |path, directory| !(directory && path.ends_with(r"Google\Chrome")),+ ));+ assert!(!trusted_windows_installation_with_probe(+ &std::path::PathBuf::from(r"D:\UserControlled\chrome.exe"),+ root,+ |_, _| true,+ ));+ }++ #[test]+ fn installed_vendor_browser_tree_is_accepted_only_for_a_nonwritable_token() {+ let candidates = isolated_browser_candidates().expect("trusted Known Folder roots");+ let installed = candidates+ .iter()+ .find(|(candidate, _, expected_cn, expected_org)| {+ candidate.is_file()+ && has_trusted_authenticode_identity(candidate, expected_cn, expected_org)+ });+ let Some(installed) = installed else {+ let diagnostics = candidates+ .iter()+ .map(|(candidate, _, _, _)| {+ let name = candidate+ .file_name()+ .and_then(|value| value.to_str())+ .unwrap_or("unknown.exe");+ if !candidate.is_file() {+ return format!("{name}: missing");+ }+ match authenticode_output(candidate) {+ Ok(output) => format!(+ "{name}: exit={:?}, stdout_utf8={:?}, stdout_bytes={:?}, stderr_utf8={:?}",+ output.status.code(),+ String::from_utf8_lossy(&output.stdout),+ output.stdout,+ String::from_utf8_lossy(&output.stderr),+ ),+ Err(error) => format!("{name}: invocation_error={error}"),+ }+ })+ .collect::<Vec<_>>();+ panic!(+ "Windows CI image must provide signed Chrome or Edge; diagnostics: {diagnostics:?}"+ );+ };++ if !trusted_windows_installation(&installed.0, &installed.1) {+ let mut diagnostics = vec![(+ "executable".to_string(),+ current_token_write_denial_reason(&installed.0, false),+ )];+ let mut current = installed.0.parent();+ let mut index = 0;+ while let Some(directory) = current {+ diagnostics.push((+ format!("ancestor_{index}"),+ current_token_write_denial_reason(directory, true),+ ));+ if directory == installed.1 {+ break;+ }+ current = directory.parent();+ index += 1;+ }+ for (location, reason) in &diagnostics {+ if let Some(reason) = reason {+ assert!(+ reason.starts_with("current token was granted "),+ "{location} refusal must prove write-capable token posture, not an unexpected probe failure: {reason}"+ );+ }+ }+ assert!(+ diagnostics.iter().any(|(_, reason)| reason.is_some()),+ "a refused installation must identify an explicitly granted write right: {diagnostics:?}"+ );+ eprintln!(+ "installed browser correctly refused for this write-capable runner token: {diagnostics:?}"+ );+ return;+ }+ }use std::sync::atomic::{AtomicUsize, Ordering};use std::sync::Arc;