diff --git a/crates/automation/src/security.rs b/crates/automation/src/security.rs index 0932374526..8e75f07ecd 100644 --- a/crates/automation/src/security.rs +++ b/crates/automation/src/security.rs @@ -322,9 +322,12 @@ fn read_token_file(path: &Path) -> Result { Ok(token) } -fn create_token_file(path: &Path, token: &str) -> Result<(), AutomationError> { +/// Create the token file `path` holding `token` and a newline. An error keeps the kind of the one +/// that caused it, with the path in its message. +fn create_token_file(path: &Path, token: &str) -> std::io::Result<()> { + let at = |p: &Path, e: std::io::Error| std::io::Error::new(e.kind(), format!("{}: {e}", p.display())); if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) { - std::fs::create_dir_all(parent).map_err(|e| AutomationError::Io(format!("{}: {e}", parent.display())))?; + std::fs::create_dir_all(parent).map_err(|e| at(parent, e))?; } // On Windows the file is created with an access list of its user and SYSTEM only, so it never has its folder's // access list, and the token is written through the handle that created it. @@ -333,7 +336,7 @@ fn create_token_file(path: &Path, token: &str) -> Result<(), AutomationError> { use craft_platform::owner_only; owner_only::current_user_sid() .and_then(|me| owner_only::create_private_file(path, &me, format!("{token}\n").as_bytes())) - .map_err(|e| AutomationError::Io(format!("{}: cannot create the control token file for its owner only: {e}", path.display()))) + .map_err(|e| std::io::Error::new(e.kind(), format!("{}: cannot create the control token file for its owner only: {e}", path.display()))) } #[cfg(not(windows))] { @@ -344,8 +347,8 @@ fn create_token_file(path: &Path, token: &str) -> Result<(), AutomationError> { use std::os::unix::fs::OpenOptionsExt; options.mode(0o600); } - let mut file = options.open(path).map_err(|e| AutomationError::Io(format!("{}: {e}", path.display())))?; - writeln!(file, "{token}").map_err(|e| AutomationError::Io(format!("{}: {e}", path.display()))) + let mut file = options.open(path).map_err(|e| at(path, e))?; + writeln!(file, "{token}").map_err(|e| at(path, e)) } } @@ -359,8 +362,19 @@ fn create_token_file(path: &Path, token: &str) -> Result<(), AutomationError> { /// file can be reached by others: ; restrict it to its owner`), and its trimmed content is /// validated. A missing one is created with a generated token (parent directories created, /// `create_new`, mode 0600 on Unix, the user and SYSTEM only on Windows, the token and a -/// newline); losing that create race to another process reads the winner's file instead. +/// newline); losing that create race to another process reads the winner's file instead. On +/// Windows a create that does not finish in time fails (`I/O: : cannot create the control +/// token file for its owner only: `), and a file it left at the path is not read as a winner's. pub fn server_token(supplied: Option<&str>, token_file: Option<&Path>) -> Result { + server_token_with(supplied, token_file, create_token_file) +} + +/// [`server_token`], with `create` making a missing token file. +fn server_token_with( + supplied: Option<&str>, + token_file: Option<&Path>, + create: impl FnOnce(&Path, &str) -> std::io::Result<()>, +) -> Result { if supplied.is_some() && token_file.is_some() { return Err(token_conflict()); } @@ -374,11 +388,11 @@ pub fn server_token(supplied: Option<&str>, token_file: Option<&Path>) -> Result }; match read_token_file(path) { Ok(existing) => Ok(existing.to_ascii_lowercase()), - Err(AutomationError::Io(_)) if !path.exists() => match create_token_file(path, &token) { + Err(AutomationError::Io(_)) if !path.exists() => match create(path, &token) { Ok(()) => Ok(token), - // Another process won the create-new race. - Err(AutomationError::Io(_)) if path.exists() => read_token_file(path).map(|v| v.to_ascii_lowercase()), - Err(e) => Err(e), + // Another process won the create-new race. A file left by a create that ran out of time is this one's. + Err(e) if e.kind() != std::io::ErrorKind::TimedOut && path.exists() => read_token_file(path).map(|v| v.to_ascii_lowercase()), + Err(e) => Err(AutomationError::Io(e.to_string())), }, Err(e) => Err(e), } diff --git a/crates/automation/src/security_tests.rs b/crates/automation/src/security_tests.rs index bba93f3c94..2716fc24c2 100644 --- a/crates/automation/src/security_tests.rs +++ b/crates/automation/src/security_tests.rs @@ -169,3 +169,25 @@ fn server_token_sources_and_validation() { "bridge mode needs --control-token, --control-token-file, PHOTOCRAFT_CONTROL_TOKEN, or PHOTOCRAFT_CONTROL_TOKEN_FILE" ); } + +// A token file create that runs out of time fails with its own error, even when it left a file at +// the path: that file is not read as another process's. A create that another process beat to the +// path reads that process's token. +#[trial] +fn a_token_file_create_that_runs_out_of_time_is_an_error() { + let dir = scratch_dir("token-limit"); + let file = dir.join("token"); + let late = |p: &Path, _: &str| { + std::fs::write(p, "partial").unwrap(); + Err(std::io::Error::new(std::io::ErrorKind::TimedOut, format!("{}: powershell.exe did not finish within 10 s and was ended", p.display()))) + }; + let err = server_token_with(None, Some(&file), late).unwrap_err().to_string(); + assert!(err.starts_with("I/O: ") && err.ends_with("did not finish within 10 s and was ended"), "{err}"); + std::fs::remove_file(&file).unwrap(); + let beaten = |p: &Path, _: &str| { + create_token_file(p, TOKEN).unwrap(); + Err(std::io::Error::new(std::io::ErrorKind::AlreadyExists, "the file already exists")) + }; + assert_eq!(server_token_with(None, Some(&file), beaten).unwrap(), TOKEN); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/platform/README.md b/crates/platform/README.md index b6d8e949a8..a8377d927d 100644 --- a/crates/platform/README.md +++ b/crates/platform/README.md @@ -23,7 +23,7 @@ pull in heavier dependencies. | always | `watch::FileWatch` and `Changed`: open files that changed on disk. One worker thread (`craft-file-watch`) compares each file's metadata (`FileStamp`) every 250 ms and sleeps while nothing is watched; a changed file is reported once it has settled and, with `ReadPolicy::Whole`, looks complete. The app's own saves are recognised by `known_now`; `disk_differs` answers at Save time; `take_changes` runs on the frame the worker's `Wake` asks for. | | always (native) | `default_app::make_default`: the Preferences button that makes the app the system default for its file types. Windows opens Settings › Default apps (`SettingsOpened`), Linux and BSD run `xdg-mime default` (`MadeDefault`, refused inside Flatpak or without an installed desktop entry), macOS answers `Unsupported`. `path_from_arg` and `rejoin_split_paths` read the paths a launcher hands the app. Only a button may call it. | | always (native) | `temp::TempDir` and `TempFiles`: private temporary folders created exclusively with owner-only permissions (`0700`, files `0600`, `create_new`), named with the process id and a counter, removed on drop. | -| always (native) | `owner_only`: files only their user can read on Windows, as mode `0600` makes them on Unix. `restrict_to_owner` and `create_private_dir` give a file or new folder an access list of the user and SYSTEM only, `create_private_file` creates a file with that access list from the start, `read_with_sddl` reads a file with its security descriptor through one handle, and `foreign_access` says why a descriptor is not the user's alone. They run the tools Windows ships (`whoami`, PowerShell, `icacls`, from System32) because the security API would need `unsafe`. | +| always (native) | `owner_only`: files only their user can read on Windows, as mode `0600` makes them on Unix. `restrict_to_owner` and `create_private_dir` give a file or new folder an access list of the user and SYSTEM only, `create_private_file` creates a file with that access list from the start, `read_with_sddl` reads a file with its security descriptor through one handle, and `foreign_access` says why a descriptor is not the user's alone. They run the tools Windows ships (`whoami`, PowerShell, `icacls`, from System32) because the security API would need `unsafe`. A run of a tool that takes longer than `TOOL_LIMIT` (10 s) is ended, and the call fails with `ErrorKind::TimedOut`. | | always | `PlatformText`: a user-visible message of a platform service (id, English text with `{name}` placeholders) that the app looks up in its own catalog. The open, clipboard, watch, default-app and temp services and craft-dialogs' save flow use it. No words table lists them yet, so the missing-translation list does not show them. | | `screen` | Screen capture for the screen colour picker (`craft_platform::screen`). | | `apple-events` | Apple Events requests on macOS (`open::apple_events`), through `fmv-macos-events`. | diff --git a/crates/platform/src/owner_only.rs b/crates/platform/src/owner_only.rs index b60709b4af..6f18c9a798 100644 --- a/crates/platform/src/owner_only.rs +++ b/crates/platform/src/owner_only.rs @@ -9,7 +9,9 @@ //! through one handle. [`foreign_access`] reads the descriptor in SDDL form, which names accounts //! by SID and so reads the same in every Windows language, and says why another user could have //! written or could read the file. They run the tools Windows ships rather than calling the -//! security API directly, which would need `unsafe`. +//! security API directly, which would need `unsafe`. A run of a tool that takes longer than +//! `TOOL_LIMIT` (10 s) is ended, and the function fails with an error of kind +//! [`std::io::ErrorKind::TimedOut`]. /// Why the file whose security descriptor is `sddl` (`O:` owner and `D:` access list, in SDDL or /// as `read_with_sddl` writes it) can't be trusted as user `me`'s own: it is owned by someone else, it has no @@ -146,11 +148,129 @@ fn system_tool(relative: &str) -> std::process::Command { command } +/// How long one run of a tool may take before it is ended. Each tool finishes in a second or two. +/// On some computers a new process is left suspended (security software holding it), and without +/// a limit the caller would wait on it for as long as it stays that way. +#[cfg(windows)] +pub const TOOL_LIMIT: std::time::Duration = std::time::Duration::from_secs(10); + +/// How often [`run_until`] checks whether the tool has exited. +#[cfg(any(test, windows))] +const POLL: std::time::Duration = std::time::Duration::from_millis(20); + +/// How many more checks [`run_until`] makes for a tool it has ended to exit before it stops +/// waiting on it. +#[cfg(any(test, windows))] +const EXIT_POLLS: u32 = 50; + +/// How a run of [`run_until`] ended. +#[cfg(any(test, windows))] +enum Ran { + /// The tool exited by itself: its status and output, and how writing its standard input went. + Exited(std::process::Output, std::io::Result<()>), + /// The time was up first and the tool was ended. `exited` is whether it was then seen to exit. + Ended { exited: bool }, +} + +/// Start `command` with its standard input, output and error piped, hand its standard input to +/// `feed` on a thread of its own, and wait for it to exit. Between checks, `expired` gets what +/// the tool has written to its standard output so far; when it answers `true` first, the tool is +/// ended ([`std::process::Child::kill`]). Standard output and error are read on threads of their +/// own, so a tool that writes more than a pipe holds is not stopped by it. +#[cfg(any(test, windows))] +fn run_until( + mut command: std::process::Command, + feed: impl FnOnce(std::process::ChildStdin) -> std::io::Result<()> + Send + 'static, + mut expired: impl FnMut(&[u8]) -> bool, +) -> std::io::Result { + use std::io::Read as _; + use std::process::Stdio; + let mut child = command.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn()?; + let fed = child.stdin.take().map(|stdin| std::thread::spawn(move || feed(stdin))); + let (chunks, received) = std::sync::mpsc::channel::>(); + if let Some(mut out) = child.stdout.take() { + std::thread::spawn(move || { + let mut buf = [0u8; 4096]; + while let Ok(n @ 1..) = out.read(&mut buf) { + if chunks.send(buf.get(..n).unwrap_or_default().to_vec()).is_err() { + break; + } + } + }); + } + let errors = child.stderr.take().map(|mut err| { + std::thread::spawn(move || { + let mut text = Vec::new(); + let _ = err.read_to_end(&mut text); + text + }) + }); + let mut stdout = Vec::new(); + loop { + stdout.extend(received.try_iter().flatten()); + if let Some(status) = child.try_wait()? { + // The pipes close when the tool exits, which ends both readers. + stdout.extend(received.iter().flatten()); + let stderr = errors.and_then(|e| e.join().ok()).unwrap_or_default(); + let sent = match fed.map(std::thread::JoinHandle::join) { + Some(Ok(sent)) => sent, + Some(Err(_)) => Err(std::io::Error::other("the thread writing the standard input stopped")), + None => Err(std::io::Error::other("the standard input could not be opened")), + }; + return Ok(Ran::Exited(std::process::Output { status, stdout, stderr }, sent)); + } + if expired(&stdout) { + let _ = child.kill(); + let mut exited = false; + for _ in 0..EXIT_POLLS { + if child.try_wait().ok().flatten().is_some() { + exited = true; + break; + } + std::thread::sleep(POLL); + } + return Ok(Ran::Ended { exited }); + } + std::thread::sleep(POLL); + } +} + +/// Run `command`, with nothing on its standard input, for at most [`TOOL_LIMIT`]: its status and +/// output, or an error of kind [`std::io::ErrorKind::TimedOut`] when it was ended. +#[cfg(windows)] +fn run(command: std::process::Command) -> std::io::Result { + let deadline = std::time::Instant::now() + TOOL_LIMIT; + let program = tool_name(&command); + let close = |stdin: std::process::ChildStdin| { + drop(stdin); + Ok(()) + }; + match run_until(command, close, |_| std::time::Instant::now() >= deadline)? { + Ran::Exited(out, _) => Ok(out), + Ran::Ended { .. } => Err(timed_out(&program)), + } +} + +/// The file name of the program `command` starts, for messages. +#[cfg(windows)] +fn tool_name(command: &std::process::Command) -> String { + let program = std::path::Path::new(command.get_program()); + program.file_name().unwrap_or(program.as_os_str()).to_string_lossy().into_owned() +} + +/// The error for a run of `program` that [`run_until`] ended. +#[cfg(windows)] +fn timed_out(program: &str) -> std::io::Error { + std::io::Error::new(std::io::ErrorKind::TimedOut, format!("{program} did not finish within {} s and was ended", TOOL_LIMIT.as_secs())) +} + /// The current user's SID (`whoami /user`). It starts a process, so a caller that needs it for /// several steps reads it once and passes it to each. #[cfg(windows)] pub fn current_user_sid() -> std::io::Result { - let out = system_tool(WHOAMI).args(["/user", "/fo", "csv", "/nh"]).output()?; + let mut whoami = system_tool(WHOAMI); + whoami.args(["/user", "/fo", "csv", "/nh"]); + let out = run(whoami)?; if !out.status.success() { return Err(std::io::Error::other("whoami /user failed")); } @@ -208,51 +328,86 @@ pub fn create_private_dir(dir: &std::path::Path, me: &str) -> std::io::Result<() /// Create the file `path`, which must not exist yet, with user `me` (as for [`restrict_to_owner`]) /// as its owner and an access list of that user and SYSTEM only, given to Windows in the call that /// creates the file, so the file never has its folder's access list, and write `contents` through -/// that handle, opened unshared. Then check the file's descriptor as [`restrict_to_owner`] does. -/// An existing `path` is an error of kind [`std::io::ErrorKind::AlreadyExists`] and is left as it -/// is. A file that was created but could not be written or checked is removed again. `contents` -/// reach PowerShell through its standard input, never as script text or an environment variable. +/// that handle, opened unshared. The file is created beside `path` under a name of its own +/// (`....tmp`) and takes the name `path` only once `contents` are +/// written, so `path` never holds a partly written file. Then check the file's descriptor as +/// [`restrict_to_owner`] does. An existing `path` is an error of kind +/// [`std::io::ErrorKind::AlreadyExists`] and is left as it is. A file that was created but could +/// not be written or checked is removed again. `contents` reach PowerShell through its standard +/// input, never as script text or an environment variable. +/// +/// PowerShell is ended when it takes longer than [`TOOL_LIMIT`], and the call fails with an error +/// of kind [`std::io::ErrorKind::TimedOut`]. The file under its own name is then removed. If +/// PowerShell is not seen to exit after being ended, that file may stay; it still has the access +/// list given when it was created. #[cfg(windows)] pub fn create_private_file(path: &std::path::Path, me: &str, contents: &[u8]) -> std::io::Result<()> { use std::io::Write as _; + let deadline = std::time::Instant::now() + TOOL_LIMIT; + let contents = contents.to_vec(); + create_private_file_until(path, me, move |mut stdin| stdin.write_all(&contents), |_| std::time::Instant::now() >= deadline) +} + +/// [`create_private_file`], with `feed` writing the contents to PowerShell's standard input and +/// `expired` saying when to end it, as [`run_until`] takes them. +#[cfg(windows)] +fn create_private_file_until( + path: &std::path::Path, + me: &str, + feed: impl FnOnce(std::process::ChildStdin) -> std::io::Result<()> + Send + 'static, + expired: impl FnMut(&[u8]) -> bool, +) -> std::io::Result<()> { + use std::sync::atomic::{AtomicU64, Ordering}; /// The exit code the script ends with when the file already exists. const EXISTS: i32 = 3; + /// Numbers the staged files of this process. + static COUNT: AtomicU64 = AtomicU64::new(0); // No double quotes: the command line would strip them. -2147024816 and -2147024713 are the - // HRESULTs of ERROR_FILE_EXISTS and ERROR_ALREADY_EXISTS. + // HRESULTs of ERROR_FILE_EXISTS and ERROR_ALREADY_EXISTS. `File.Move` fails when the + // destination exists. const SCRIPT: &str = "$ErrorActionPreference = 'Stop'; \ + if (Test-Path -LiteralPath $env:CRAFT_ACL_PATH) { exit 3 }; \ $s = New-Object Security.AccessControl.FileSecurity; \ $s.SetSecurityDescriptorSddlForm('O:' + $env:CRAFT_ACL_USER + 'D:P(A;;FA;;;' + $env:CRAFT_ACL_USER + ')(A;;FA;;;SY)'); \ - try { $fs = New-Object IO.FileStream -ArgumentList @($env:CRAFT_ACL_PATH, [IO.FileMode]::CreateNew, \ - [Security.AccessControl.FileSystemRights]::Write, [IO.FileShare]::None, 4096, [IO.FileOptions]::None, $s) } \ - catch { $e = $_.Exception; while ($e.InnerException) { $e = $e.InnerException }; \ - if ($e.HResult -eq -2147024816 -or $e.HResult -eq -2147024713) { exit 3 }; throw }; \ + $fs = New-Object IO.FileStream -ArgumentList @($env:CRAFT_ACL_STAGED, [IO.FileMode]::CreateNew, \ + [Security.AccessControl.FileSystemRights]::Write, [IO.FileShare]::None, 4096, [IO.FileOptions]::None, $s); \ try { [Console]::OpenStandardInput().CopyTo($fs); $fs.Flush($true); $fs.Dispose() } \ - catch { $fs.Dispose(); [IO.File]::Delete($env:CRAFT_ACL_PATH); throw }"; - let mut child = system_tool(POWERSHELL) + catch { $fs.Dispose(); [IO.File]::Delete($env:CRAFT_ACL_STAGED); throw }; \ + try { [IO.File]::Move($env:CRAFT_ACL_STAGED, $env:CRAFT_ACL_PATH) } \ + catch { [IO.File]::Delete($env:CRAFT_ACL_STAGED); $e = $_.Exception; while ($e.InnerException) { $e = $e.InnerException }; \ + if ($e.HResult -eq -2147024816 -or $e.HResult -eq -2147024713) { exit 3 }; throw }"; + let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + let staged = path.with_file_name(format!(".{name}.{}.{}.tmp", std::process::id(), COUNT.fetch_add(1, Ordering::Relaxed))); + let mut powershell = system_tool(POWERSHELL); + powershell .args(["-NoProfile", "-NonInteractive", "-Command", SCRIPT]) .env("CRAFT_ACL_PATH", path) - .env("CRAFT_ACL_USER", me) - .stdin(std::process::Stdio::piped()) - .stdout(std::process::Stdio::piped()) - .stderr(std::process::Stdio::piped()) - .spawn()?; + .env("CRAFT_ACL_STAGED", &staged) + .env("CRAFT_ACL_USER", me); // A script that stops before reading (the file exists) closes the pipe; its exit code says why. - let sent = child.stdin.take().map(|mut stdin| stdin.write_all(contents)); - let out = child.wait_with_output()?; + let ran = run_until(powershell, feed, expired); + // The staged name is this call's own, so removing it never removes another process's file. + // PowerShell holds the staged file open unshared until it exits. + let (out, sent) = match ran? { + Ran::Exited(out, sent) => (out, sent), + Ran::Ended { exited } => { + if exited { + let _ = std::fs::remove_file(&staged); + } + return Err(timed_out("powershell.exe")); + } + }; if out.status.code() == Some(EXISTS) { return Err(std::io::Error::new(std::io::ErrorKind::AlreadyExists, "the file already exists")); } if !out.status.success() { + let _ = std::fs::remove_file(&staged); return Err(std::io::Error::other(format!( "PowerShell could not create the file for its owner only: {}", String::from_utf8_lossy(&out.stderr).trim() ))); } - let checked = match sent { - Some(Ok(())) => sddl_of(path).and_then(|sddl| still_foreign(&sddl, me)), - Some(Err(e)) => Err(e), - None => Err(std::io::Error::other("PowerShell's standard input could not be opened")), - }; + let checked = sent.and_then(|()| sddl_of(path)).and_then(|sddl| still_foreign(&sddl, me)); if checked.is_err() { let _ = std::fs::remove_file(path); } @@ -295,11 +450,9 @@ fn set_access_list(path: &std::path::Path, me: &str, kind: Kind) -> std::io::Res Kind::File => FILE, Kind::Folder => FOLDER, }; - let out = system_tool(POWERSHELL) - .args(["-NoProfile", "-NonInteractive", "-Command", script]) - .env("CRAFT_ACL_PATH", path) - .env("CRAFT_ACL_USER", me) - .output()?; + let mut powershell = system_tool(POWERSHELL); + powershell.args(["-NoProfile", "-NonInteractive", "-Command", script]).env("CRAFT_ACL_PATH", path).env("CRAFT_ACL_USER", me); + let out = run(powershell)?; if out.status.success() { Ok(()) } else { @@ -309,7 +462,9 @@ fn set_access_list(path: &std::path::Path, me: &str, kind: Kind) -> std::io::Res #[cfg(windows)] fn icacls(path: &std::path::Path, args: &[String]) -> std::io::Result<()> { - let out = system_tool(ICACLS).arg(path).args(args).output()?; + let mut icacls = system_tool(ICACLS); + icacls.arg(path).args(args); + let out = run(icacls)?; if out.status.success() { Ok(()) } else { @@ -348,11 +503,9 @@ pub fn read_with_sddl(path: &std::path::Path, max: u64) -> std::io::Result<(Stri ); // Bounded so the script's `[int]` and buffer stay small; a token file is far below this. let max = max.min(1 << 20); - let out = system_tool(POWERSHELL) - .args(["-NoProfile", "-NonInteractive", "-Command", SCRIPT]) - .env("CRAFT_ACL_PATH", path) - .env("CRAFT_ACL_MAX", max.to_string()) - .output()?; + let mut powershell = system_tool(POWERSHELL); + powershell.args(["-NoProfile", "-NonInteractive", "-Command", SCRIPT]).env("CRAFT_ACL_PATH", path).env("CRAFT_ACL_MAX", max.to_string()); + let out = run(powershell)?; let read = if out.status.success() { sddl_and_bytes(&String::from_utf8_lossy(&out.stdout)) } else { None }; read.ok_or_else(|| std::io::Error::other("PowerShell could not read the file with its owner and access list")) } @@ -368,7 +521,9 @@ pub fn sddl_of(path: &std::path::Path) -> std::io::Result { describe_raw!(), "[Console]::Out.Write($sddl + [char]10)" ); - let out = system_tool(POWERSHELL).args(["-NoProfile", "-NonInteractive", "-Command", SCRIPT]).env("CRAFT_ACL_PATH", path).output()?; + let mut powershell = system_tool(POWERSHELL); + powershell.args(["-NoProfile", "-NonInteractive", "-Command", SCRIPT]).env("CRAFT_ACL_PATH", path); + let out = run(powershell)?; let read = if out.status.success() { sddl_and_bytes(&String::from_utf8_lossy(&out.stdout)) } else { None }; read.map(|(sddl, _)| sddl).ok_or_else(|| std::io::Error::other("PowerShell could not read the file's owner and access list")) } @@ -578,6 +733,84 @@ $n = [CraftProbe.Console]::GetConsoleProcessList($ids, 256) let _ = std::fs::remove_dir_all(&dir); } + /// A command that writes `ready` to its standard output and then reads its standard input until + /// it closes. + fn waiting_reader() -> std::process::Command { + #[cfg(windows)] + let command = { + let mut powershell = system_tool(POWERSHELL); + powershell.args([ + "-NoProfile", + "-NonInteractive", + "-Command", + "[Console]::Out.Write('ready'); [Console]::Out.Flush(); $null = [Console]::In.ReadToEnd()", + ]); + powershell + }; + #[cfg(not(windows))] + let command = { + let mut sh = std::process::Command::new("sh"); + sh.args(["-c", "printf ready; cat >/dev/null"]); + sh + }; + command + } + + /// A tool still running when the time is up is ended and exits. The time is up once the tool + /// has said it is waiting (a handshake, not a clock). + /// The same tool, given its input, exits by itself and nothing ends it. + #[test] + fn a_tool_that_does_not_finish_in_time_is_ended() { + let (keep, kept) = std::sync::mpsc::channel(); + // The standard input stays open, so the tool waits until it is ended. + let hold = move |stdin: std::process::ChildStdin| keep.send(stdin).map_err(std::io::Error::other); + match run_until(waiting_reader(), hold, |out| out == b"ready").unwrap() { + Ran::Ended { exited } => assert!(exited, "the tool was ended but is still running"), + Ran::Exited(out, _) => panic!("the tool exited by itself: {out:?}"), + } + drop(kept); + let close = |stdin: std::process::ChildStdin| { + drop(stdin); + Ok(()) + }; + match run_until(waiting_reader(), close, |_| false).unwrap() { + Ran::Exited(out, sent) => { + assert!(out.status.success(), "{out:?}"); + assert_eq!(out.stdout, b"ready"); + sent.unwrap(); + } + Ran::Ended { .. } => panic!("the tool was ended"), + } + } + + /// PowerShell that has created the file but not written it when the time is up is ended, the + /// call fails as timed out, and the file it created is removed; nothing took the name. A file + /// that was at the name before is another's, and it is left as it is whenever the time runs out. + #[cfg(windows)] + #[test] + fn a_private_file_whose_create_does_not_finish_in_time_is_removed() { + let dir = std::env::temp_dir().join(format!("craft-owner-only-limit-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("ctl.token"); + let entries = || std::fs::read_dir(&dir).unwrap().count(); + let (keep, kept) = std::sync::mpsc::channel(); + let hold = move |stdin: std::process::ChildStdin| keep.send(stdin).map_err(std::io::Error::other); + // The time is up once the script has created its file and waits for the contents. + let late = create_private_file_until(&file, &user(), hold, |_| entries() > 0).unwrap_err(); + drop(kept); + assert_eq!(late.kind(), std::io::ErrorKind::TimedOut, "{late}"); + assert_eq!(entries(), 0, "the file PowerShell created is removed"); + std::fs::write(&file, b"other\n").unwrap(); + let (keep, kept) = std::sync::mpsc::channel(); + let hold = move |stdin: std::process::ChildStdin| keep.send(stdin).map_err(std::io::Error::other); + let refused = create_private_file_until(&file, &user(), hold, |_| true).unwrap_err(); + drop(kept); + assert!(matches!(refused.kind(), std::io::ErrorKind::TimedOut | std::io::ErrorKind::AlreadyExists), "{refused}"); + assert_eq!(std::fs::read(&file).unwrap(), b"other\n"); + let _ = std::fs::remove_dir_all(&dir); + } + /// A folder may give its user Modify but not Full control, so a file created there doesn't let /// its owner change the owner (no `WRITE_OWNER`). An owner can always replace the access list, /// though, and the user's Full control on it then allows setting the owner.