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 apps with a standard-user token from an elevated Windows Driver (#4282)
Francesco Bonacci002b93655576
diff --git a/.github/workflows/ci-rust-windows.yml b/.github/workflows/ci-rust-windows.ymlindex 881f42a460..d0792e8de3 100644--- a/.github/workflows/ci-rust-windows.yml+++ b/.github/workflows/ci-rust-windows.yml@@ -137,6 +137,11 @@ jobs:env:CUA_TEST_REQUIRE_DRIVER_BIN: "1"run: "cargo test -p cua-driver --test protocol_tools_call_test launch_edge_from_apps_folder_registration --locked -- --ignored --exact --nocapture"+ - name: Prove an elevated Driver launches apps with a standard-user token+ working-directory: libs/cua-driver/rust+ env:+ CUA_TEST_REQUIRE_DRIVER_BIN: "1"+ run: cargo test -p cua-driver --test launch_app_standard_user_test --locked -- --ignored --nocapture- name: Run transport-independent authorization and SDK testsworking-directory: libs/cua-driver/rustrun: |diff --git a/libs/cua-driver/rust/crates/cua-driver/src/main.rs b/libs/cua-driver/rust/crates/cua-driver/src/main.rsindex 858057022c..e1af27af99 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/main.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/main.rs@@ -901,6 +901,15 @@ fn main() {#[cfg(not(target_os = "macos"))]fn main() -> anyhow::Result<()> {+ // An elevated Driver runs shell launches through this executable with a+ // standard-user token (#3607). Checked first so the helper does no other+ // Driver work.+ #[cfg(target_os = "windows")]+ if let Some(code) =+ platform_windows::standard_user_launch::run_shell_launch_helper_if_requested()+ {+ std::process::exit(code);+ }cua_driver_sdk::configure_perception_client_resolver(extension_manager::perception_client_resolver(),);diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/launch_app_standard_user_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/launch_app_standard_user_test.rsnew file mode 100644index 0000000000..39b3e1e039--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver/tests/launch_app_standard_user_test.rs@@ -0,0 +1,161 @@+#![cfg(target_os = "windows")]++//! An elevated Windows Driver must not hand its administrator token to the+//! apps it launches (#3607). Both `launch_app` routes are covered: the shell+//! route (`ShellExecuteExW` in the standard-user helper) and the direct+//! `start_minimized` executable route. Each launched process must run at+//! Medium integrity when the Driver is elevated, and at the Driver's own+//! integrity level when it is not.+//!+//! GitHub-hosted Windows runners run tests elevated, so CI exercises the+//! standard-user path.++use std::ffi::c_void;+use std::path::PathBuf;++use cua_driver_testkit::{Driver, McpDriver};++type Handle = *mut c_void;++const PROCESS_TERMINATE: u32 = 0x0001;+const PROCESS_QUERY_LIMITED_INFORMATION: u32 = 0x1000;+const TOKEN_QUERY: u32 = 0x0008;+const TOKEN_INTEGRITY_LEVEL: u32 = 25;+const MEDIUM_INTEGRITY_RID: u32 = 0x2000;+const HIGH_INTEGRITY_RID: u32 = 0x3000;++#[link(name = "kernel32")]+extern "system" {+ fn GetCurrentProcess() -> Handle;+ fn OpenProcess(desired_access: u32, inherit_handle: i32, process_id: u32) -> Handle;+ fn TerminateProcess(process: Handle, exit_code: u32) -> i32;+ fn CloseHandle(handle: Handle) -> i32;+}++#[link(name = "advapi32")]+extern "system" {+ fn OpenProcessToken(process: Handle, desired_access: u32, token: *mut Handle) -> i32;+ fn GetTokenInformation(+ token: Handle,+ information_class: u32,+ information: *mut c_void,+ length: u32,+ return_length: *mut u32,+ ) -> i32;+ fn GetSidSubAuthorityCount(sid: *mut c_void) -> *mut u8;+ fn GetSidSubAuthority(sid: *mut c_void, index: u32) -> *mut u32;+}++/// Mandatory integrity RID of `process`.+fn integrity_rid(process: Handle) -> u32 {+ unsafe {+ let mut token: Handle = std::ptr::null_mut();+ assert!(+ OpenProcessToken(process, TOKEN_QUERY, &mut token) != 0,+ "OpenProcessToken failed: {}",+ std::io::Error::last_os_error()+ );+ let mut needed = 0u32;+ GetTokenInformation(+ token,+ TOKEN_INTEGRITY_LEVEL,+ std::ptr::null_mut(),+ 0,+ &mut needed,+ );+ let mut label = vec![0u64; (needed as usize).div_ceil(8)];+ let ok = GetTokenInformation(+ token,+ TOKEN_INTEGRITY_LEVEL,+ label.as_mut_ptr().cast(),+ (label.len() * 8) as u32,+ &mut needed,+ );+ CloseHandle(token);+ assert!(+ ok != 0,+ "GetTokenInformation(TokenIntegrityLevel) failed: {}",+ std::io::Error::last_os_error()+ );+ // TOKEN_MANDATORY_LABEL starts with the label SID pointer.+ let sid = *label.as_ptr().cast::<*mut c_void>();+ let count = *GetSidSubAuthorityCount(sid);+ *GetSidSubAuthority(sid, u32::from(count) - 1)+ }+}++fn ping() -> PathBuf {+ PathBuf::from(std::env::var_os("SystemRoot").expect("SystemRoot"))+ .join("System32")+ .join("PING.EXE")+}++#[test]+#[ignore = "launches a console process on the interactive desktop"]+fn elevated_driver_launches_apps_with_a_standard_user_token() {+ let driver_rid = integrity_rid(unsafe { GetCurrentProcess() });+ let mut driver = McpDriver::spawn_with_env(&[+ ("CUA_DRIVER_PERMISSION_MODE", "unrestricted"),+ ("CUA_DRIVER_DANGEROUSLY_BYPASS_APPROVALS", "1"),+ ])+ .expect("test Driver failed to start");+ let ping = ping();++ for (route, start_minimized) in [("shell", false), ("direct", true)] {+ let launch = driver.call(+ "launch_app",+ serde_json::json!({+ "path": ping,+ "additional_arguments": ["-n", "60", "127.0.0.1"],+ "start_minimized": start_minimized,+ }),+ );+ if start_minimized && launch.structured()["code"] == "background_unavailable" {+ eprintln!(+ "[launch_app_standard_user] direct route not exercised: {}",+ launch.text()+ );+ continue;+ }+ assert!(+ !launch.is_error(),+ "{route} launch failed: {}",+ launch.text()+ );+ let pid = launch.structured()["pid"].as_u64().unwrap_or(0) as u32;+ assert_ne!(pid, 0, "{route} launch reported no pid: {}", launch.text());++ let process = unsafe {+ OpenProcess(+ PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_TERMINATE,+ 0,+ pid,+ )+ };+ assert!(+ !process.is_null(),+ "could not open launched pid {pid}: {}",+ std::io::Error::last_os_error()+ );+ let launched_rid = integrity_rid(process);+ unsafe {+ TerminateProcess(process, 0);+ CloseHandle(process);+ }+ eprintln!(+ "[launch_app_standard_user] {route}: Driver 0x{driver_rid:04x}, launched pid {pid} \+ 0x{launched_rid:04x}"+ );+ if driver_rid >= HIGH_INTEGRITY_RID {+ assert!(+ launched_rid <= MEDIUM_INTEGRITY_RID,+ "{route} launch from an elevated Driver ran at integrity 0x{launched_rid:04x}"+ );+ } else {+ assert_eq!(+ launched_rid, driver_rid,+ "{route} launch from a non-elevated Driver changed integrity"+ );+ }+ }+}diff --git a/libs/cua-driver/rust/crates/platform-windows/Cargo.toml b/libs/cua-driver/rust/crates/platform-windows/Cargo.tomlindex 719f59d18d..935d1dc93c 100644--- a/libs/cua-driver/rust/crates/platform-windows/Cargo.toml+++ b/libs/cua-driver/rust/crates/platform-windows/Cargo.toml@@ -32,6 +32,8 @@ windows = { version = "0.58", features = ["Win32_UI_Accessibility","Win32_UI_WindowsAndMessaging","Win32_System_Threading",+ # CreatePipe: the result pipe of the standard-user shell launch helper.+ "Win32_System_Pipes","Win32_System_SystemInformation","Win32_System_Diagnostics_ToolHelp","Win32_Graphics_Gdi",diff --git a/libs/cua-driver/rust/crates/platform-windows/src/browser_standard_user.rs b/libs/cua-driver/rust/crates/platform-windows/src/browser_standard_user.rsindex cab7691ce3..b27e574f1d 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/browser_standard_user.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/browser_standard_user.rs@@ -75,9 +75,21 @@ unsafe impl Send for OwnedHandle {}unsafe impl Sync for OwnedHandle {}impl OwnedHandle {+ /// Take ownership of `handle`, which is closed on drop.+ pub(crate) fn new(handle: HANDLE) -> Self {+ Self(handle)+ }+pub(crate) fn raw(&self) -> HANDLE {self.0}++ /// Release ownership without closing the handle.+ pub(crate) fn into_raw(self) -> HANDLE {+ let handle = self.0;+ std::mem::forget(self);+ handle+ }}impl Drop for OwnedHandle {diff --git a/libs/cua-driver/rust/crates/platform-windows/src/input/keyboard.rs b/libs/cua-driver/rust/crates/platform-windows/src/input/keyboard.rsindex 6c13e1f64e..a814511960 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/input/keyboard.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/input/keyboard.rs@@ -421,11 +421,10 @@ pub fn post_key(hwnd: u64, key: &str, modifiers: &[&str]) -> Result<()> {/// which we mitigate by saving the previous foreground HWND and restoring it/// after the keystrokes are flushed.///-/// UIAccess constraint: `SetForegroundWindow` is restricted from non-UIAccess-/// processes when not driven by user input. The `cua-driver-uia` worker runs-/// at UIAccess integrity precisely so this restriction is lifted; outside the-/// worker, the foreground swap may silently fail and SendInput land on the-/// wrong window. Callers should funnel hotkey calls through the uia worker.+/// Windows may refuse the foreground swap (`SetForegroundWindow` is+/// restricted when not driven by user input), and UIPI drops input sent to a+/// higher-integrity target. Both are detected and reported as errors; no+/// input is sent to an unconfirmed window.pub fn send_key_synthesized(hwnd: u64, key: &str, modifiers: &[&str]) -> Result<()> {send_key_synthesized_after_focus(hwnd, key, modifiers, || Ok(()))}@@ -475,10 +474,11 @@ pub fn send_key_synthesized_after_focus(let sent = SendInput(&events, std::mem::size_of::<INPUT>() as i32);if sent as usize != events.len() {bail!(- "SendInput inserted only {sent} of {} events. Likely cause: \- the daemon is not at UIAccess integrity, so SetForegroundWindow \- was rejected and the events landed on the wrong window. Run \- hotkey through the cua-driver-uia worker.",+ "SendInput inserted only {sent} of {} events. Windows blocked the \+ rest: the target runs at a higher integrity level than the \+ Driver (UIPI), or the input desktop is locked or showing a \+ secure prompt. To drive an elevated app, run the Driver \+ elevated (the default autostart daemon is).",events.len());}@@ -493,7 +493,7 @@ pub fn send_key_synthesized_after_focus(/// foreground. This is only reached on the explicit `delivery_mode:"foreground"`/// rung (background never fronts); it does NOT silently fall back to/// PostMessage: if the foreground swap is rejected-/// (daemon not at UIAccess integrity) it bails with the same diagnostic+/// or the input is blocked, it bails with the same diagnostic/// `send_key_synthesized` returns, so the caller gets an honest error instead/// of a false success. Required for VCL/LibreOffice document grids and other/// targets where PostMessage WM_CHAR is silently dropped.@@ -552,9 +552,11 @@ pub fn send_text_synthesized_after_focus(let sent = SendInput(&events, std::mem::size_of::<INPUT>() as i32);if sent as usize != events.len() {bail!(- "SendInput inserted only {sent} of {} key events. Likely cause: \- the daemon is not at UIAccess integrity, so SetForegroundWindow \- was rejected and the events landed on the wrong window.",+ "SendInput inserted only {sent} of {} key events. Windows blocked \+ the rest: the target runs at a higher integrity level than the \+ Driver (UIPI), or the input desktop is locked or showing a \+ secure prompt. To drive an elevated app, run the Driver \+ elevated (the default autostart daemon is).",events.len());}@@ -596,8 +598,9 @@ fn with_confirmed_foreground<T>(}bail!("foreground_unavailable: Windows did not confirm exact target HWND {:?} for {operation} \- within 500 ms (actual foreground HWND {:?}). Route the request through the \- UIAccess-manifested cua-driver-uia worker; no input was sent.",+ within 500 ms (actual foreground HWND {:?}). Windows refused the foreground \+ change, usually because another window holds the foreground lock; no input \+ was sent. Retry, or use background delivery where the target accepts it.",target.0,actual.0);diff --git a/libs/cua-driver/rust/crates/platform-windows/src/lib.rs b/libs/cua-driver/rust/crates/platform-windows/src/lib.rsindex 8b1d223ebb..4e56ef643d 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/lib.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/lib.rs@@ -65,6 +65,10 @@ mod browser_launch_token;#[cfg(target_os = "windows")]mod browser_standard_user;+// De-elevated `launch_app` for an elevated Driver (#3607).+#[cfg(target_os = "windows")]+pub mod standard_user_launch;+#[cfg(target_os = "windows")]mod browser_consent_ui;#[cfg(target_os = "windows")]diff --git a/libs/cua-driver/rust/crates/platform-windows/src/standard_user_launch.rs b/libs/cua-driver/rust/crates/platform-windows/src/standard_user_launch.rsnew file mode 100644index 0000000000..e4989dea33--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-windows/src/standard_user_launch.rs@@ -0,0 +1,359 @@+//! Standard-user app launches for an elevated Windows Driver (#3607).+//!+//! A process inherits its creator's primary token. An elevated Driver (the+//! default autostart daemon runs at `RunLevel=Highest`) would therefore start+//! every `launch_app` target as an elevated administrator: the user's ordinary+//! tools could not close or automate the app, and it would behave differently+//! from the same app started from Explorer. An elevated Driver instead+//! launches apps with the verified standard-user token that already runs+//! isolated browsers (#4234): the same user and desktop, `BUILTIN\Administrators`+//! deny-only, and Medium integrity. The Driver keeps full control, because a+//! higher-integrity process may send input to and automate a lower one.+//!+//! Direct executable launches use `CreateProcessAsUserW` with that token.+//! `ShellExecuteExW` (PATH and App Paths lookup, file associations,+//! `shell:AppsFolder` registrations, URLs) always creates processes with its+//! caller's primary token, so shell launches run in a short-lived helper that+//! already holds the standard-user token: this Driver executable, started with+//! [`SHELL_LAUNCH_HELPER_FLAG`]. The helper performs one `ShellExecuteExW` call,+//! reports the launched process ID or the shell error on its standard output,+//! and exits. A process that embeds the Driver runtime without the Driver's+//! entry point (for example an SDK host) cannot run the helper, so an elevated+//! host of that kind refuses shell launches instead of starting them elevated.++use std::ffi::{c_void, OsStr, OsString};+use std::io::Read as _;+use std::os::windows::ffi::OsStrExt;+use std::os::windows::io::FromRawHandle as _;+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::Arc;+use std::time::Duration;++use windows::core::{PCWSTR, PWSTR};+use windows::Win32::Foundation::{+ SetHandleInformation, HANDLE, HANDLE_FLAG_INHERIT, WAIT_OBJECT_0, WAIT_TIMEOUT,+};+use windows::Win32::System::Pipes::CreatePipe;+use windows::Win32::System::Threading::{+ CreateProcessAsUserW, DeleteProcThreadAttributeList, GetExitCodeProcess,+ InitializeProcThreadAttributeList, TerminateProcess, UpdateProcThreadAttribute,+ WaitForSingleObject, CREATE_NO_WINDOW, EXTENDED_STARTUPINFO_PRESENT,+ LPPROC_THREAD_ATTRIBUTE_LIST, PROCESS_CREATION_FLAGS, PROCESS_INFORMATION,+ PROC_THREAD_ATTRIBUTE_HANDLE_LIST, STARTF_USESHOWWINDOW, STARTF_USESTDHANDLES, STARTUPINFOEXW,+ STARTUPINFOW,+};++use crate::browser_launch_token::windows_command_line;+use crate::browser_standard_user::{browser_launch_context, BrowserLaunchContext, OwnedHandle};++/// First argument that turns this Driver executable into the shell launch+/// helper. Never a public command.+pub const SHELL_LAUNCH_HELPER_FLAG: &str = "--cua-driver-standard-user-shell-launch";++/// Set once the Driver's own entry point has checked for the helper flag,+/// which proves this executable can serve as the helper.+static SHELL_LAUNCH_HELPER_AVAILABLE: AtomicBool = AtomicBool::new(false);++/// The token that runs apps started by `launch_app`.+#[derive(Clone)]+pub(crate) enum AppLaunchToken {+ /// The Driver is not elevated; apps start with the Driver's own token.+ Driver,+ /// A verified standard-user token derived from the elevated Driver token.+ StandardUser(Arc<OwnedHandle>),+}++/// Choose the launch token. An elevated Driver that cannot derive a verified+/// standard-user token refuses rather than starting the app elevated.+pub(crate) fn app_launch_token() -> Result<AppLaunchToken, String> {+ match browser_launch_context() {+ Ok(BrowserLaunchContext::Driver) => Ok(AppLaunchToken::Driver),+ Ok(BrowserLaunchContext::StandardUser(token)) => Ok(AppLaunchToken::StandardUser(token)),+ Err(refusal) => Err(format!(+ "The Driver is elevated and could not prepare the standard-user token it uses to \+ launch apps, so no app was started: {}",+ refusal.message+ )),+ }+}++fn wide(value: &OsStr) -> Vec<u16> {+ value.encode_wide().collect()+}++fn nul_terminated(mut value: Vec<u16>) -> Vec<u16> {+ value.push(0);+ value+}++/// Create `application` with `command_line` under `token`, showing its first+/// window with `n_show`. The child inherits no handles.+pub(crate) fn create_process(+ token: &OwnedHandle,+ application: &str,+ command_line: &str,+ n_show: i32,+) -> Result<u32, String> {+ let application = nul_terminated(wide(OsStr::new(application)));+ let mut command_line = nul_terminated(wide(OsStr::new(command_line)));+ let startup = STARTUPINFOW {+ cb: std::mem::size_of::<STARTUPINFOW>() as u32,+ dwFlags: STARTF_USESHOWWINDOW,+ wShowWindow: n_show as u16,+ ..Default::default()+ };+ let mut process = PROCESS_INFORMATION::default();+ unsafe {+ CreateProcessAsUserW(+ token.raw(),+ PCWSTR(application.as_ptr()),+ PWSTR(command_line.as_mut_ptr()),+ None,+ None,+ false,+ PROCESS_CREATION_FLAGS(0),+ None,+ PCWSTR::null(),+ &startup,+ &mut process,+ )+ }+ .map_err(|error| format!("CreateProcessAsUserW failed: {error}"))?;+ drop(OwnedHandle::new(process.hThread));+ drop(OwnedHandle::new(process.hProcess));+ Ok(process.dwProcessId)+}++/// Run `ShellExecuteExW` for `file` and `parameters` in a helper that holds+/// `token`. Returns the launched process ID, or 0 when the shell handed the+/// request to an existing process (for example a URL opened in a running+/// browser). The helper is terminated if it does not finish within `timeout`.+pub(crate) fn shell_execute(+ token: &OwnedHandle,+ file: &str,+ parameters: &str,+ n_show: i32,+ timeout: Duration,+) -> Result<u32, String> {+ if !SHELL_LAUNCH_HELPER_AVAILABLE.load(Ordering::Relaxed) {+ return Err(+ "The Driver is elevated and this process cannot start its standard-user shell launch \+ helper, so no app was started. Launch the app by executable path with \+ start_minimized, or run this host without elevation."+ .to_owned(),+ );+ }+ let helper = std::env::current_exe()+ .map_err(|error| format!("could not locate the Driver executable: {error}"))?;+ let program = wide(helper.as_os_str());+ let args = [+ wide(OsStr::new(SHELL_LAUNCH_HELPER_FLAG)),+ wide(OsStr::new(&n_show.to_string())),+ wide(OsStr::new(file)),+ wide(OsStr::new(parameters)),+ ];+ let mut command_line = nul_terminated(windows_command_line(&program, &args)?);+ let application = nul_terminated(program);++ // Only the write end of this pipe crosses into the helper.+ let mut read = HANDLE::default();+ let mut write = HANDLE::default();+ unsafe { CreatePipe(&mut read, &mut write, None, 0) }+ .map_err(|error| format!("could not create the helper result pipe: {error}"))?;+ let read = OwnedHandle::new(read);+ let write = OwnedHandle::new(write);+ unsafe { SetHandleInformation(write.raw(), HANDLE_FLAG_INHERIT.0, HANDLE_FLAG_INHERIT) }+ .map_err(|error| format!("could not share the helper result pipe: {error}"))?;++ let mut attribute_size = 0usize;+ let _ = unsafe {+ InitializeProcThreadAttributeList(+ LPPROC_THREAD_ATTRIBUTE_LIST(std::ptr::null_mut()),+ 1,+ 0,+ &mut attribute_size,+ )+ };+ let mut attribute_storage = vec![0u64; attribute_size.div_ceil(8)];+ let attributes = LPPROC_THREAD_ATTRIBUTE_LIST(attribute_storage.as_mut_ptr().cast());+ unsafe { InitializeProcThreadAttributeList(attributes, 1, 0, &mut attribute_size) }+ .map_err(|error| format!("could not prepare the helper handle list: {error}"))?;+ let inherited = [write.raw()];+ let updated = unsafe {+ UpdateProcThreadAttribute(+ attributes,+ 0,+ PROC_THREAD_ATTRIBUTE_HANDLE_LIST as usize,+ Some(inherited.as_ptr().cast::<c_void>()),+ std::mem::size_of_val(&inherited),+ None,+ None,+ )+ };+ let startup = STARTUPINFOEXW {+ StartupInfo: STARTUPINFOW {+ cb: std::mem::size_of::<STARTUPINFOEXW>() as u32,+ dwFlags: STARTF_USESTDHANDLES,+ hStdOutput: write.raw(),+ hStdError: write.raw(),+ ..Default::default()+ },+ lpAttributeList: attributes,+ };+ let mut process = PROCESS_INFORMATION::default();+ let created = updated.and_then(|()| unsafe {+ CreateProcessAsUserW(+ token.raw(),+ PCWSTR(application.as_ptr()),+ PWSTR(command_line.as_mut_ptr()),+ None,+ None,+ true,+ EXTENDED_STARTUPINFO_PRESENT | CREATE_NO_WINDOW,+ None,+ PCWSTR::null(),+ &startup.StartupInfo,+ &mut process,+ )+ });+ unsafe { DeleteProcThreadAttributeList(attributes) };+ created.map_err(|error| format!("could not start the standard-user launch helper: {error}"))?;+ drop(write);+ drop(OwnedHandle::new(process.hThread));+ let helper = OwnedHandle::new(process.hProcess);++ let timeout_ms = u32::try_from(timeout.as_millis()).unwrap_or(u32::MAX);+ let waited = unsafe { WaitForSingleObject(helper.raw(), timeout_ms) };+ if waited == WAIT_TIMEOUT {+ let _ = unsafe { TerminateProcess(helper.raw(), 1) };+ return Err(format!(+ "the standard-user launch helper did not finish within {}s; a blocking shell dialog \+ likely appeared on the session desktop",+ timeout.as_secs()+ ));+ }+ if waited != WAIT_OBJECT_0 {+ return Err(format!(+ "could not wait for the standard-user launch helper: {}",+ std::io::Error::last_os_error()+ ));+ }+ let mut exit_code = 0u32;+ let _ = unsafe { GetExitCodeProcess(helper.raw(), &mut exit_code) };++ // The helper has exited, so its end of the pipe is closed and the read+ // ends at the helper's last write.+ let mut output = String::new();+ let mut pipe = unsafe { std::fs::File::from_raw_handle(read.into_raw().0) };+ let _ = pipe.read_to_string(&mut output);+ parse_helper_output(&output, exit_code)+}++/// Interpret the helper's single result line.+fn parse_helper_output(output: &str, exit_code: u32) -> Result<u32, String> {+ let line = output.lines().next().unwrap_or("").trim();+ if let Some(pid) = line.strip_prefix("ok ") {+ return pid+ .trim()+ .parse::<u32>()+ .map_err(|_| format!("the standard-user launch helper reported {line:?}"));+ }+ if let Some(message) = line.strip_prefix("error ") {+ return Err(message.trim().to_owned());+ }+ Err(format!(+ "the standard-user launch helper exited with code {exit_code:#x} without a result"+ ))+}++/// Entry point for the helper. The Driver's `main` calls this first; it+/// returns `None` for every ordinary invocation.+pub fn run_shell_launch_helper_if_requested() -> Option<i32> {+ SHELL_LAUNCH_HELPER_AVAILABLE.store(true, Ordering::Relaxed);+ let mut args = std::env::args_os().skip(1);+ if args.next().as_deref() != Some(OsStr::new(SHELL_LAUNCH_HELPER_FLAG)) {+ return None;+ }+ let rest: Vec<OsString> = args.collect();+ let result = match rest.as_slice() {+ [n_show, file, parameters] => match n_show.to_str().and_then(|v| v.parse::<i32>().ok()) {+ Some(n_show) => helper_shell_execute(file, parameters, n_show),+ None => Err("the launch helper received an invalid show state".to_owned()),+ },+ _ => Err("the launch helper received malformed arguments".to_owned()),+ };+ match result {+ Ok(pid) => {+ println!("ok {pid}");+ Some(0)+ }+ Err(message) => {+ println!("error {message}");+ Some(1)+ }+ }+}++fn helper_shell_execute(file: &OsStr, parameters: &OsStr, n_show: i32) -> Result<u32, String> {+ use windows::Win32::Foundation::CloseHandle;+ use windows::Win32::System::Com::{+ CoInitializeEx, COINIT, COINIT_APARTMENTTHREADED, COINIT_DISABLE_OLE1DDE,+ };+ use windows::Win32::System::Threading::GetProcessId;+ use windows::Win32::UI::Shell::{+ ShellExecuteExW, SEE_MASK_FLAG_NO_UI, SEE_MASK_NOCLOSEPROCESS, SHELLEXECUTEINFOW,+ };++ // Shell verbs may be implemented by COM handlers.+ let _ = unsafe {+ CoInitializeEx(+ None,+ COINIT(COINIT_APARTMENTTHREADED.0 | COINIT_DISABLE_OLE1DDE.0),+ )+ };+ let verb = nul_terminated(wide(OsStr::new("open")));+ let file = nul_terminated(wide(file));+ let parameters_wide = nul_terminated(wide(parameters));+ let mut info = SHELLEXECUTEINFOW {+ cbSize: std::mem::size_of::<SHELLEXECUTEINFOW>() as u32,+ fMask: SEE_MASK_NOCLOSEPROCESS | SEE_MASK_FLAG_NO_UI,+ lpVerb: PCWSTR(verb.as_ptr()),+ lpFile: PCWSTR(file.as_ptr()),+ lpParameters: if parameters.is_empty() {+ PCWSTR::null()+ } else {+ PCWSTR(parameters_wide.as_ptr())+ },+ nShow: n_show,+ ..Default::default()+ };+ unsafe { ShellExecuteExW(&mut info) }.map_err(|error| error.to_string())?;+ if info.hProcess.is_invalid() {+ return Ok(0);+ }+ let pid = unsafe { GetProcessId(info.hProcess) };+ let _ = unsafe { CloseHandle(info.hProcess) };+ Ok(pid)+}++#[cfg(test)]+mod tests {+ use super::parse_helper_output;++ #[test]+ fn helper_output_reports_the_process_id_or_the_shell_error() {+ assert_eq!(parse_helper_output("ok 4242\r\n", 0), Ok(4242));+ assert_eq!(parse_helper_output("ok 0\n", 0), Ok(0));+ assert_eq!(+ parse_helper_output("error The system cannot find the file specified.\n", 1),+ Err("The system cannot find the file specified.".to_owned())+ );+ assert_eq!(+ parse_helper_output("", 0xc000_0005),+ Err(+ "the standard-user launch helper exited with code 0xc0000005 without a result"+ .to_owned()+ )+ );+ }+}diff --git a/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rsindex 483bd2cd98..453d2ee5d4 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs@@ -2024,6 +2024,11 @@ async fn restore_foreground_polling_best_effort(prior_foreground_addr: usize, sp}}+/// Bound on one standard-user shell launch helper. It stays inside the 15 s+/// launch deadline so a helper stuck on a shell dialog is terminated rather+/// than left behind.+const STANDARD_USER_SHELL_LAUNCH_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(12);+pub struct LaunchAppTool;static LAUNCH_DEF: std::sync::OnceLock<ToolDef> = std::sync::OnceLock::new();@@ -2396,9 +2401,14 @@ impl Tool for LaunchAppTool {Err(e) => return ToolResult::error(format!("Task error: {e}")),}} else {- // Legacy ShellExecuteExW path — unchanged behavior for plain- // Win32 apps and for callers passing an explicit `path` /- // `launch_path`.+ // Legacy ShellExecuteExW path for plain Win32 apps and for+ // callers passing an explicit `path` / `launch_path`. An elevated+ // Driver runs these launches with its standard-user token so the+ // app does not inherit administrator rights (#3607).+ let launch_token = match crate::standard_user_launch::app_launch_token() {+ Ok(token) => token,+ Err(message) => return ToolResult::error(message),+ };let urls_clone = urls.clone();let target_for_shell = target_file_opt.clone();let extra_for_shell = extra_joined.clone();@@ -2442,39 +2452,64 @@ impl Tool for LaunchAppTool {});let args_w = to_wide(&extra_for_shell);+ use crate::standard_user_launch::AppLaunchToken;let pid = if direct_minimized_exe {let target = target_for_shell.as_deref().expect("checked executable path");- let mut command_line = to_wide(&if extra_for_shell.is_empty() {+ let command_line_text = if extra_for_shell.is_empty() {format!(r#""{target}""#)} else {format!(r#""{target}" {extra_for_shell}"#)- });- let startup = STARTUPINFOW {- cb: std::mem::size_of::<STARTUPINFOW>() as u32,- dwFlags: STARTF_USESHOWWINDOW,- wShowWindow: n_show_for_shell as u16,- ..Default::default()};- let mut process = PROCESS_INFORMATION::default();- unsafe {- CreateProcessW(- PCWSTR(file_w.as_ptr()),- PWSTR(command_line.as_mut_ptr()),- None,- None,- false,- PROCESS_CREATION_FLAGS(0),- None,- PCWSTR::null(),- &startup,- &mut process,- )?;- let _ = CloseHandle(process.hThread);- let _ = CloseHandle(process.hProcess);+ if let AppLaunchToken::StandardUser(token) = &launch_token {+ crate::standard_user_launch::create_process(+ token,+ target,+ &command_line_text,+ n_show_for_shell,+ )+ .map_err(anyhow::Error::msg)?+ } else {+ let mut command_line = to_wide(&command_line_text);+ let startup = STARTUPINFOW {+ cb: std::mem::size_of::<STARTUPINFOW>() as u32,+ dwFlags: STARTF_USESHOWWINDOW,+ wShowWindow: n_show_for_shell as u16,+ ..Default::default()+ };+ let mut process = PROCESS_INFORMATION::default();+ unsafe {+ CreateProcessW(+ PCWSTR(file_w.as_ptr()),+ PWSTR(command_line.as_mut_ptr()),+ None,+ None,+ false,+ PROCESS_CREATION_FLAGS(0),+ None,+ PCWSTR::null(),+ &startup,+ &mut process,+ )?;+ let _ = CloseHandle(process.hThread);+ let _ = CloseHandle(process.hProcess);+ }+ process.dwProcessId}- process.dwProcessId+ } else if let AppLaunchToken::StandardUser(token) = &launch_token {+ let file = target_for_shell+ .as_deref()+ .or_else(|| urls_clone.first().map(String::as_str))+ .unwrap_or("");+ crate::standard_user_launch::shell_execute(+ token,+ file,+ &extra_for_shell,+ n_show_for_shell,+ STANDARD_USER_SHELL_LAUNCH_TIMEOUT,+ )+ .map_err(anyhow::Error::msg)?} else {let mut info = SHELLEXECUTEINFOW {cbSize: std::mem::size_of::<SHELLEXECUTEINFOW>() as u32,@@ -2511,6 +2546,16 @@ impl Tool for LaunchAppTool {// `lpFile`, so only their remaining URLs belong here.let first_unopened_url = first_unopened_shell_url_index(target_for_shell.is_some());for url in &urls_clone[first_unopened_url.min(urls_clone.len())..] {+ if let AppLaunchToken::StandardUser(token) = &launch_token {+ let _ = crate::standard_user_launch::shell_execute(+ token,+ url,+ "",+ n_show_for_shell,+ STANDARD_USER_SHELL_LAUNCH_TIMEOUT,+ );+ continue;+ }let file = to_wide(url);let mut url_info = SHELLEXECUTEINFOW {cbSize: std::mem::size_of::<SHELLEXECUTEINFOW>() as u32,