diff --git a/desktop/src-tauri/src/docker_desktop_update.rs b/desktop/src-tauri/src/docker_desktop_update.rs index e9bafa05fe..4b03a62f7c 100644 --- a/desktop/src-tauri/src/docker_desktop_update.rs +++ b/desktop/src-tauri/src/docker_desktop_update.rs @@ -254,33 +254,33 @@ pub fn powershell_with_path(script: &str, variable: &str, path: &Path) -> std::p command } +/// The environment variable the all-users install reads the installer's command line from. +pub const INSTALLER_ARGUMENTS: &str = "OPENBOT_INSTALLER_ARGUMENTS"; + /// The exit code that means the person said no to Windows' approval prompt: `ERROR_CANCELLED`, as -/// the WSL fix reads it (`windows::DECLINED`). -const ERROR_CANCELLED: i32 = 1223; +/// the WSL fix reads it. +const ERROR_CANCELLED: i32 = crate::windows::DECLINED; /// The all-users install: Windows' approval prompt, then Docker's installer as an administrator, -/// waited for, its exit code PowerShell's. The installer's path is `INSTALLER_PATH`. +/// waited for, its exit code PowerShell's, and `ERROR_CANCELLED` for a No (`windows::runas_script`). +/// The installer's path is `INSTALLER_PATH` and its command line `INSTALLER_ARGUMENTS`. pub fn elevated_install(installer: &Path, arguments: &[String]) -> std::process::Command { - let quoted: Vec = arguments - .iter() - .map(|argument| format!("'{}'", argument.replace('\'', "''"))) - .collect(); - let start = format!( - "$p = Start-Process -FilePath $env:{INSTALLER_PATH} -ArgumentList {} -Verb RunAs -Wait \ - -PassThru", - quoted.join(",") + let mut command = powershell_with_path( + &install_script(crate::windows::PROCESS_START), + INSTALLER_PATH, + installer, ); - powershell_with_path(&elevated_script(&start), INSTALLER_PATH, installer) + command.env(INSTALLER_ARGUMENTS, crate::windows::command_line(arguments)); + command } -/// `start`, which raises Windows' approval prompt and sets `$p`, exiting with `$p`'s exit code. A -/// no to the prompt exits `ERROR_CANCELLED`, found by its Win32 code in the error, never by its -/// words, which are in Windows' own language. -fn elevated_script(start: &str) -> String { - format!( - "$ErrorActionPreference = 'Stop'; try {{ {start}; exit $p.ExitCode }} catch {{ \ - $e = $_.Exception; while ($e) {{ if ($e.NativeErrorCode -eq {ERROR_CANCELLED}) \ - {{ exit {ERROR_CANCELLED} }}; $e = $e.InnerException }}; throw }}" +/// The script `elevated_install` runs, with `starting` raising the prompt (`windows::runas_script`). +fn install_script(starting: &str) -> String { + crate::windows::runas_script( + &format!("$env:{INSTALLER_PATH}"), + &format!("$env:{INSTALLER_ARGUMENTS}"), + false, + starting, ) } @@ -792,7 +792,7 @@ fn run_installer(mounted: &Mounted) -> Installed { } /// Whether `elevated_install` stopped because the person said no to Windows' approval prompt: it -/// then exits `ERROR_CANCELLED` (`elevated_script`). What PowerShell said is in Windows' own +/// then exits `ERROR_CANCELLED` (`windows::runas_script`). What PowerShell said is in Windows' own /// language, so it is never read for this. #[cfg_attr(not(target_os = "windows"), allow(dead_code))] fn closed_the_prompt(code: Option) -> bool { @@ -1497,9 +1497,15 @@ Internal requirements count=1 size=180 .to_string_lossy() .into_owned(); assert!( - script.contains("-ArgumentList 'install','--quiet' -Verb RunAs"), + script.contains("$start.Arguments = $env:OPENBOT_INSTALLER_ARGUMENTS"), "{script}" ); + assert!(script.contains("$start.Verb = 'runas'"), "{script}"); + let envs: Vec<_> = install.get_envs().collect(); + assert!(envs.contains(&( + std::ffi::OsStr::new(INSTALLER_ARGUMENTS), + Some(std::ffi::OsStr::new("install --quiet")) + ))); } /* @@ -1746,8 +1752,9 @@ Internal requirements count=1 size=180 assert!(!closed_the_prompt(Some(1))); assert!(!closed_the_prompt(Some(0))); assert!(!closed_the_prompt(None)); - // The script reads the Win32 code, never the words. - let script = elevated_script("$p = Start-Process x -Verb RunAs -Wait -PassThru"); + // The script reads the Win32 code, never the words, and asks through the call that keeps + // the code (`windows::PROCESS_START`), not Start-Process, which loses it. + let script = install_script(crate::windows::PROCESS_START); assert!(script.contains("NativeErrorCode -eq 1223"), "{script}"); assert!(script.contains("exit 1223"), "{script}"); assert!( @@ -1755,32 +1762,74 @@ Internal requirements count=1 size=180 "{script}" ); assert!(!script.contains("canceled"), "{script}"); + assert!(!script.contains("Start-Process"), "{script}"); } - /// The script `elevated_install` runs, in real Windows PowerShell, with `Start-Process` standing - /// in for by the error it throws when the person says no: a Win32 `ERROR_CANCELLED` inside the - /// `InvalidOperationException`, worded in German. It exits 1223. Any other error exits 1. + /// The script `elevated_install` runs, in real Windows PowerShell, answered No as Windows + /// answers it. With `Start-Process -Verb RunAs`, a No on Windows Server 2022 (PowerShell + /// 5.1.20348) came as an `InvalidOperationException` (HResult 0x80131509) with no inner + /// exception and no Win32 code, so the script exited 1 and the update went on to open Docker's + /// installer. It now asks through `Process.Start`, whose No carries `ERROR_CANCELLED`. #[test] #[cfg(windows)] - fn the_elevated_install_script_exits_1223_on_a_no_in_any_language() { - let run = |native: i32| { - let start = format!( - "throw [System.InvalidOperationException]::new('Dieser Befehl kann aufgrund des \ - folgenden Fehlers nicht ausgeführt werden.', \ - [System.ComponentModel.Win32Exception]::new({native}))" + fn the_elevated_install_script_exits_1223_on_a_no_as_windows_says_it() { + let script = format!( + "{}{}", + crate::windows::SAYS_NO_TYPE, + install_script(crate::windows::SAYS_NO) + ); + let code = crate::windows::powershell_exit_for_test( + &script, + &[ + (INSTALLER_PATH, r"C:\nowhere\Docker Desktop Installer.exe"), + (INSTALLER_ARGUMENTS, "install --quiet"), + ], + ); + assert_eq!(code, Some(ERROR_CANCELLED)); + assert!(closed_the_prompt(code)); + } + + /// The real install command on real Windows, with `Start-Process` answering No as it did on + /// Windows Server 2022: the install never asks through it. The runner's Windows asks nobody, + /// so the program runs elevated and its exit code comes back; one that isn't there is a + /// failure, not a No. + #[test] + #[cfg(windows)] + fn the_elevated_install_runs_the_installer_and_hands_back_its_exit_code() { + let cmd = std::path::PathBuf::from(std::env::var("ComSpec").unwrap()); + let ran = |program: &Path, arguments: &[&str]| { + let command = elevated_install( + program, + &arguments.iter().map(|a| a.to_string()).collect::>(), ); - let output = powershell_with_path( - &elevated_script(&start), - INSTALLER_PATH, - Path::new(r"C:\nowhere\Docker Desktop Installer.exe"), + let script = command + .get_args() + .nth(3) + .unwrap() + .to_string_lossy() + .into_owned(); + let envs: Vec<(String, String)> = command + .get_envs() + .filter_map(|(name, value)| { + Some(( + name.to_string_lossy().into_owned(), + value?.to_string_lossy().into_owned(), + )) + }) + .collect(); + let envs: Vec<(&str, &str)> = + envs.iter().map(|(n, v)| (n.as_str(), v.as_str())).collect(); + crate::windows::powershell_exit_for_test( + &format!("{}{script}", crate::windows::START_PROCESS_SAID_NO), + &envs, ) - .output() - .unwrap(); - output.status.code() }; - assert_eq!(run(ERROR_CANCELLED), Some(ERROR_CANCELLED)); - let other = run(2); - assert_ne!(other, Some(ERROR_CANCELLED)); - assert_ne!(other, Some(0)); + assert_eq!(ran(cmd.as_path(), &["/c", "exit 7"]), Some(7)); + let missing = ran( + Path::new(r"C:\nowhere\Docker Desktop Installer.exe"), + &["install"], + ); + assert_ne!(missing, Some(0)); + assert!(!closed_the_prompt(missing), "{missing:?}"); } } diff --git a/desktop/src-tauri/src/windows.rs b/desktop/src-tauri/src/windows.rs index b7393f514f..34dcf0873e 100644 --- a/desktop/src-tauri/src/windows.rs +++ b/desktop/src-tauri/src/windows.rs @@ -906,9 +906,132 @@ impl Blocker { } } +/// For tests: `Process.Start` as it answers when the person says No to Windows' prompt, a +/// `Win32Exception` with `ERROR_CANCELLED` and no inner exception, called from PowerShell as +/// `PROCESS_START` is. Prefix the script with `SAYS_NO_TYPE` and pass `SAYS_NO` as `starting`. +#[cfg(all(test, windows))] +pub(crate) const SAYS_NO_TYPE: &str = "Add-Type -TypeDefinition 'namespace OpenBotTest { public static class Prompt { public static System.Diagnostics.Process Start(System.Diagnostics.ProcessStartInfo info) { throw new System.ComponentModel.Win32Exception(1223); } } }'\n"; +#[cfg(all(test, windows))] +pub(crate) const SAYS_NO: &str = "[OpenBotTest.Prompt]::Start($start)"; + +/// For tests: `Start-Process` as it answered a No on Windows Server 2022 (PowerShell 5.1.20348): +/// an `InvalidOperationException`, HResult 0x80131509, no inner exception, no Win32 code. +#[cfg(all(test, windows))] +pub(crate) const START_PROCESS_SAID_NO: &str = "function Start-Process { throw [System.InvalidOperationException]::new('This command cannot be run due to the error: The operation was canceled by the user.') }\n"; + +/// For tests: run `script` in Windows PowerShell with `envs`, and its exit code. Fails the test +/// rather than hang when it runs past two minutes, as a prompt nobody answers would. +#[cfg(all(test, windows))] +pub(crate) fn powershell_exit_for_test(script: &str, envs: &[(&str, &str)]) -> Option { + let mut command = crate::quiet::command("powershell"); + command + .args([ + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", + "Bypass", + "-EncodedCommand", + ]) + .arg(encoded(script)) + .env_remove("PSModulePath"); + for (name, value) in envs { + command.env(name, value); + } + let mut child = command.spawn().unwrap(); + let until = std::time::Instant::now() + std::time::Duration::from_secs(120); + loop { + if let Some(status) = child.try_wait().unwrap() { + return status.code(); + } + if std::time::Instant::now() >= until { + let _ = child.kill(); + panic!("the script ran past two minutes: a prompt nobody answered?"); + } + std::thread::sleep(std::time::Duration::from_millis(100)); + } +} + /// The exit code that means the person said no to the administrator prompt: `ERROR_CANCELLED`. #[cfg_attr(not(target_os = "windows"), allow(dead_code))] -const DECLINED: i32 = 1223; +pub(crate) const DECLINED: i32 = 1223; + +/// What raises Windows' approval prompt in `runas_script`: .NET's `Process.Start` with the `runas` +/// verb, which throws the `Win32Exception` itself, `ERROR_CANCELLED` on a No. PowerShell hands it +/// on as the inner exception of a `MethodInvocationException`. +/// +/// Not `Start-Process -Verb RunAs`, which wraps that same call: on Windows Server 2022 (PowerShell +/// 5.1.20348) a No made it throw an `InvalidOperationException` (HResult 0x80131509) with no inner +/// exception and no Win32 code, so only its words, in Windows' own language, said it was a No. The +/// Docker update then opened Docker's installer and Windows asked a second time; the WSL fix said +/// it hadn't finished. +pub(crate) const PROCESS_START: &str = "[System.Diagnostics.Process]::Start($start)"; + +/// A PowerShell script that raises Windows' approval prompt for `file` with `arguments` (each a +/// PowerShell expression; `arguments` one command line, as `command_line` quotes it), waits for it +/// and exits with its exit code: `DECLINED` when the person says no, whatever Windows' language. +/// Any other failure is thrown, so PowerShell exits 1 and prints it. `starting` is the call that +/// raises the prompt with the `ProcessStartInfo` in `$start`: `PROCESS_START`, or a test's. +pub(crate) fn runas_script(file: &str, arguments: &str, hidden: bool, starting: &str) -> String { + let window = if hidden { + "\n $start.WindowStyle = 'Hidden'" + } else { + "" + }; + format!( + r#"$ErrorActionPreference = 'Stop' +try {{ + $start = New-Object System.Diagnostics.ProcessStartInfo + $start.FileName = {file} + $start.Arguments = {arguments} + $start.Verb = 'runas' + $start.UseShellExecute = $true{window} + $process = {starting} + $process.WaitForExit() + exit $process.ExitCode +}} catch {{ + $error_ = $_.Exception + while ($error_) {{ if ($error_.NativeErrorCode -eq {DECLINED}) {{ exit {DECLINED} }}; $error_ = $error_.InnerException }} + throw +}}"# + ) +} + +/// `arguments` as one Windows command line, each quoted as Windows reads it back +/// (`CommandLineToArgvW`): bare when it has no space, tab or quote, quoted otherwise, with the +/// backslashes before a quote doubled. +pub fn command_line(arguments: &[String]) -> String { + arguments + .iter() + .map(|argument| quote_argument(argument)) + .collect::>() + .join(" ") +} + +fn quote_argument(argument: &str) -> String { + if !argument.is_empty() && !argument.contains([' ', '\t', '\n', '\u{b}', '"']) { + return argument.to_string(); + } + let mut quoted = String::from("\""); + let mut backslashes = 0; + for c in argument.chars() { + match c { + '\\' => backslashes += 1, + '"' => { + quoted.push_str(&"\\".repeat(backslashes * 2 + 1)); + quoted.push('"'); + backslashes = 0; + } + _ => { + quoted.push_str(&"\\".repeat(backslashes)); + quoted.push(c); + backslashes = 0; + } + } + } + quoted.push_str(&"\\".repeat(backslashes * 2)); + quoted.push('"'); + quoted +} /// The script as PowerShell's `-EncodedCommand` takes it: UTF-16LE, base64. Nothing in it is /// quoted twice, which is what passing a script through `Start-Process` otherwise comes to. @@ -923,21 +1046,25 @@ fn encoded(script: &str) -> String { /// has one, comes back through `log` because an elevated process cannot write to our pipes. #[cfg_attr(not(target_os = "windows"), allow(dead_code))] fn elevated_launcher(script: &str, log: &Path) -> String { + elevated_launcher_starting(script, log, PROCESS_START) +} + +/// `elevated_launcher`, with `starting` raising the prompt (`runas_script`). +#[cfg_attr(not(target_os = "windows"), allow(dead_code))] +fn elevated_launcher_starting(script: &str, log: &Path, starting: &str) -> String { let log = log.display().to_string().replace('\'', "''"); let inner = format!( "try {{\n{script}\n}} catch {{ $_ | Out-String | Set-Content -LiteralPath '{log}' -Encoding UTF8; exit 1 }}" ); - format!( - r#"$ErrorActionPreference = 'Stop' -try {{ - $process = Start-Process -FilePath powershell.exe -Verb RunAs -Wait -PassThru -WindowStyle Hidden -ArgumentList '-NoProfile','-NonInteractive','-ExecutionPolicy','Bypass','-EncodedCommand','{}' - exit $process.ExitCode -}} catch {{ - $error_ = $_.Exception - while ($error_) {{ if ($error_.NativeErrorCode -eq {DECLINED}) {{ exit {DECLINED} }}; $error_ = $error_.InnerException }} - throw -}}"#, - encoded(&inner) + // Base64 has no quote or space in it, so the command line needs no quoting. + runas_script( + "'powershell.exe'", + &format!( + "'-NoProfile -NonInteractive -ExecutionPolicy Bypass -EncodedCommand {}'", + encoded(&inner) + ), + true, + starting, ) } @@ -3144,12 +3271,16 @@ mod tests { #[test] fn the_elevated_launcher_asks_through_runas_and_reports_a_refusal() { let launcher = elevated_launcher("exit 0", Path::new(r"C:\Users\o'brien\fix.txt")); - assert!(launcher.contains("-Verb RunAs")); - assert!(launcher.contains("-Wait -PassThru")); + assert!(launcher.contains("$start.Verb = 'runas'")); + assert!(launcher.contains("$start.WindowStyle = 'Hidden'")); + assert!(launcher.contains("$process.WaitForExit()")); + assert!(launcher.contains("NativeErrorCode -eq 1223")); assert!(launcher.contains("exit 1223")); + // Start-Process loses the code a No carries (`PROCESS_START`). + assert!(!launcher.contains("Start-Process"), "{launcher}"); // The log path is inside the encoded inner script, quoted for PowerShell there. let encoded_inner = launcher - .split("'-EncodedCommand','") + .split("-EncodedCommand ") .nth(1) .and_then(|rest| rest.split('\'').next()) .unwrap(); @@ -3165,6 +3296,61 @@ mod tests { assert!(inner.contains(r"'C:\Users\o''brien\fix.txt'"), "{inner}"); } + /// The WSL fix's launcher, in real Windows PowerShell, answered No as Windows answers it. With + /// `Start-Process -Verb RunAs`, a No on Windows Server 2022 came as an `InvalidOperationException` + /// with no inner exception and no Win32 code, and the window said "That didn't finish". The + /// launcher now asks through `Process.Start`, whose No carries `ERROR_CANCELLED`. + #[test] + #[cfg(windows)] + fn the_elevated_launcher_exits_1223_on_a_no_as_windows_says_it() { + let log = std::env::temp_dir().join(format!("openbot-runas-no-{}.txt", std::process::id())); + let script = format!( + "{SAYS_NO_TYPE}{}", + elevated_launcher_starting("exit 0", &log, SAYS_NO) + ); + assert_eq!(powershell_exit_for_test(&script, &[]), Some(DECLINED)); + } + + /// The real launcher on real Windows, with `Start-Process` answering No as it did on Windows + /// Server 2022: the launcher never asks through it. The runner's Windows asks nobody, so the + /// fix runs elevated, hidden, and its exit code comes back. + #[test] + #[cfg(windows)] + fn the_elevated_launcher_runs_the_fix_and_hands_back_its_exit_code() { + let log = + std::env::temp_dir().join(format!("openbot-runas-run-{}.txt", std::process::id())); + let script = format!( + "{START_PROCESS_SAID_NO}{}", + elevated_launcher("exit 5", &log) + ); + assert_eq!(powershell_exit_for_test(&script, &[]), Some(5)); + } + + #[test] + fn a_command_line_reads_back_as_the_arguments_it_was_made_from() { + let line = |arguments: &[&str]| { + command_line( + &arguments + .iter() + .map(|argument| argument.to_string()) + .collect::>(), + ) + }; + assert_eq!(line(&["install", "--quiet"]), "install --quiet"); + assert_eq!( + line(&["install", "--quiet", "--user"]), + "install --quiet --user" + ); + assert_eq!(line(&[""]), "\"\""); + assert_eq!( + line(&[r"C:\Program Files\Docker"]), + r#""C:\Program Files\Docker""# + ); + assert_eq!(line(&[r"C:\a b\"]), r#""C:\a b\\""#); + assert_eq!(line(&[r#"say "hi""#]), r#""say \"hi\"""#); + assert_eq!(line(&[r#"a\"b"#]), r#""a\\\"b""#); + } + #[test] fn a_fix_says_restart_done_declined_or_failed_with_its_log() { let enable = Blocker::WslAbsent.fix().unwrap();