From ed647a5d49c88c3ade7486267a329ab5d5ffb485 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 15:18:35 -0800 Subject: [PATCH 01/87] Canvas: the body's tool pass carries the text the editor part pastes The framework takes a paste event out of egui's input and keeps its text for the focused component, so a canvas body that applies its editor's Edit(Paste) could only read the installed clipboard, which fails where the system clipboard can't be opened (a Wayland session where arboard finds no data-control protocol). ToolPass::pasted now holds the text the platform's paste event carried in the pass of that paste: Ctrl+V's, or the one a Paste command asks the platform for. --- crates/ui-canvas/src/canvas/mod.rs | 13 ++++++++ crates/ui-canvas/tests/it/canvas/editor.rs | 36 +++++++++++++++++++++- 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/crates/ui-canvas/src/canvas/mod.rs b/crates/ui-canvas/src/canvas/mod.rs index f8c7da9cab..ad3724c1bd 100644 --- a/crates/ui-canvas/src/canvas/mod.rs +++ b/crates/ui-canvas/src/canvas/mod.rs @@ -240,6 +240,8 @@ pub struct Canvas<'a> { settled: Option, /// The Menu key or Shift+F10 reached the focused canvas this pass. context_key: bool, + /// The text of the paste the editor part takes this pass, taken in `update` with its inputs. + pasted: Option>, /// The ease the app asked for from the view it drew ([`ease_from`](Self::ease_from)). ease: Option, /// The app's tool moves the view with the pointer this pass (an image-moving crop slides the view by fractional @@ -316,6 +318,7 @@ impl<'a> Canvas<'a> { snap: None, settled: None, context_key: false, + pasted: None, ease: None, follows_pointer: false, tool_regions: Vec::new(), @@ -689,6 +692,7 @@ impl<'a> Canvas<'a> { navigation: self.navigation, editor_input: self.editor_input.clone(), editor: cx.editor_handle(), + pasted: self.pasted.clone(), } } @@ -758,6 +762,11 @@ pub struct ToolPass { pub editor_input: Arc<[EditorInput]>, /// The editor part of this pass, through which the body reports its editor state; `None` without an editor. pub editor: Option, + /// The text of the paste the editor part takes this pass (its [`EditorInput::Edit`] of + /// [`EditCommand::Paste`](craft_behavior::EditCommand::Paste)), as the platform's paste event carried it: Ctrl+V's, + /// or the one a Paste command asks the platform for. The framework takes that event out of egui's input, and the + /// platform's read can succeed where the installed clipboard can't be opened. `None` in a pass without one. + pub pasted: Option>, } impl ToolPass { @@ -863,6 +872,10 @@ impl Component for Canvas<'_> { fn update(&mut self, cx: &mut Cx<'_, Self>) { // Taken once: `Cx::editor_input` empties the pass's inputs, and the body reads them from the `ToolPass`. self.editor_input = cx.editor_input().collect::>().into(); + self.pasted = match cx.clipboard().paste() { + crate::runtime::pending::Pending::Ready(content) => content.text.clone(), + _ => None, + }; // Left untaken: the canvas's generic context request is recorded as for a secondary click. self.context_key = cx.intents().untaken(&Intent::ContextMenu); // The canvas is no value component: it reads and writes its view's binding itself, as a container does. diff --git a/crates/ui-canvas/tests/it/canvas/editor.rs b/crates/ui-canvas/tests/it/canvas/editor.rs index 48153ff5f3..4cf2f9cd83 100644 --- a/crates/ui-canvas/tests/it/canvas/editor.rs +++ b/crates/ui-canvas/tests/it/canvas/editor.rs @@ -2,7 +2,7 @@ //! body through its `ToolPass`. use craft_behavior::kurbo::{Point, Size}; -use craft_behavior::{CanvasView, EditorInput, Proposal, TextPos}; +use craft_behavior::{CanvasView, EditCommand, EditorInput, Proposal, TextPos}; use craft_ui::canvas::{Canvas, tool_pass}; use craft_ui::contract::{Bind, Show as _, ShowContainer as _}; use craft_ui::primitives::{EditorPurpose, EditorState}; @@ -88,6 +88,40 @@ fn a_canvas_editor_takes_focus_on_a_background_press_and_hands_its_inputs_to_the ); } +/// One pass's editor inputs and pasted text, as the body read them from its `ToolPass`. +type PassPaste = (Vec, Option); + +/// A paste event's text reaches the body with the editor part's paste in that pass's `ToolPass`, and in no later pass: +/// the framework takes the event out of egui's input, and the body can't read the installed clipboard where it can't +/// be opened. +#[trial] +fn a_paste_events_text_reaches_the_body_with_the_editors_paste() { + let seen: Rc>> = Rc::default(); + let shown = Rc::clone(&seen); + let mut fixture = Fixture::new(move |ui| { + let room = ui.available_rect_before_wrap(); + let view = CanvasView::new(room, Point::new(PAGE.width / 2.0, PAGE.height / 2.0), 1.0); + let _ = canvas(view).show_at(ui, room, |_, body| { + let Some(pass) = tool_pass(&body.env) else { return }; + shown.borrow_mut().push((pass.editor_input.to_vec(), pass.pasted.as_deref().map(str::to_owned))); + }); + }); + fixture.room(ROOM); + fixture.settle(); + fixture.click_at((ROOM / 2.0).to_pos2()); + seen.borrow_mut().clear(); + fixture.frame(vec![Event::Paste("from the platform".into())]); + fixture.frame(vec![]); + let passes = seen.take(); + let pasted: Vec<&PassPaste> = passes.iter().filter(|(_, text)| text.is_some()).collect(); + assert!(!pasted.is_empty(), "a pass carries the paste's text: {passes:?}"); + for (inputs, text) in &pasted { + assert_eq!(text.as_deref(), Some("from the platform")); + assert!(inputs.iter().any(|input| matches!(input, EditorInput::Edit(EditCommand::Paste))), "with the editor's paste: {inputs:?}"); + } + assert!(passes.last().is_some_and(|(_, text)| text.is_none()), "a later pass carries none: {passes:?}"); +} + /// Guards `EditorHandle::report` for an editor whose view describes its text (a page editor): its report has no lines, /// so its caret reaches the input method and no empty text is announced on the canvas's node. #[trial] From c9c6010394e83d208b57d25c7e60893834bdfb97 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 10:04:42 -0800 Subject: [PATCH 02/87] automation: the control token file is private from the moment it is created On Windows, create_token_file created the token file with its folder's access list and only then restricted it to the user and SYSTEM. Another local account that the folder lets read new files could open a handle in between, and that handle keeps its read access after the list changes, so it could read the token once it was written. craft_platform::owner_only::create_private_file creates the file with an owner-only security descriptor in the call that creates it, writes the contents through that handle, and checks the result. The control token file now uses it on Windows. Unix keeps mode 0600 at create, and losing the create race to another process still reads the winner's file. --- crates/automation/src/security.rs | 36 ++++++----- crates/automation/src/security_tests.rs | 6 ++ crates/platform/README.md | 2 +- crates/platform/src/owner_only.rs | 83 +++++++++++++++++++++++++ 4 files changed, 110 insertions(+), 17 deletions(-) diff --git a/crates/automation/src/security.rs b/crates/automation/src/security.rs index 259d2f3cb2..0932374526 100644 --- a/crates/automation/src/security.rs +++ b/crates/automation/src/security.rs @@ -8,8 +8,11 @@ //! idle for [`IO_TIMEOUT`] is closed. Tokens are 64 hex characters in either case, kept //! lower-cased by the server and compared in constant time with hex letters folded. None of this depends on the transport: the TCP server and a test channel share it. +#[cfg(not(windows))] use std::fs::OpenOptions; -use std::io::{BufRead, Write}; +use std::io::BufRead; +#[cfg(not(windows))] +use std::io::Write; use std::path::Path; use std::sync::atomic::{AtomicUsize, Ordering}; use std::time::{Duration, Instant}; @@ -323,26 +326,27 @@ fn create_token_file(path: &Path, token: &str) -> Result<(), AutomationError> { 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())))?; } - let mut options = OpenOptions::new(); - options.write(true).create_new(true); - #[cfg(unix)] - { - use std::os::unix::fs::OpenOptionsExt; - options.mode(0o600); - } - let mut file = options.open(path).map_err(|e| AutomationError::Io(format!("{}: {e}", path.display())))?; - // On Windows the new file has its folder's access list: it is restricted to its user and SYSTEM before the token - // is written, and a file that cannot be restricted is removed rather than left for the token to go into later. + // 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. #[cfg(windows)] { use craft_platform::owner_only; - if let Err(e) = owner_only::current_user_sid().and_then(|me| owner_only::restrict_to_owner(path, &me)) { - drop(file); - let _ = std::fs::remove_file(path); - return Err(AutomationError::Io(format!("{}: cannot restrict the control token file to its owner: {e}", path.display()))); + 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()))) + } + #[cfg(not(windows))] + { + let mut options = OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + { + 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()))) } - writeln!(file, "{token}").map_err(|e| AutomationError::Io(format!("{}: {e}", path.display()))) } /// The server's token, lower-cased. Both given is diff --git a/crates/automation/src/security_tests.rs b/crates/automation/src/security_tests.rs index b5ba980c95..bba93f3c94 100644 --- a/crates/automation/src/security_tests.rs +++ b/crates/automation/src/security_tests.rs @@ -141,6 +141,12 @@ fn server_token_sources_and_validation() { use std::os::unix::fs::PermissionsExt; assert_eq!(std::fs::metadata(&file).unwrap().permissions().mode() & 0o777, 0o600); } + #[cfg(windows)] + { + use craft_platform::owner_only; + let sddl = owner_only::sddl_of(&file).unwrap(); + assert_eq!(owner_only::foreign_access(&sddl, &owner_only::current_user_sid().unwrap()), None, "{sddl}"); + } assert_eq!(server_token(None, Some(&file)).unwrap(), created); // An existing file's content is trimmed and lower-cased. diff --git a/crates/platform/README.md b/crates/platform/README.md index d557f93108..b6d8e949a8 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, `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`. | | 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 e664dcffe4..b60709b4af 100644 --- a/crates/platform/src/owner_only.rs +++ b/crates/platform/src/owner_only.rs @@ -205,6 +205,60 @@ pub fn create_private_dir(dir: &std::path::Path, me: &str) -> std::io::Result<() restricted } +/// 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. +#[cfg(windows)] +pub fn create_private_file(path: &std::path::Path, me: &str, contents: &[u8]) -> std::io::Result<()> { + use std::io::Write as _; + /// The exit code the script ends with when the file already exists. + const EXISTS: i32 = 3; + // No double quotes: the command line would strip them. -2147024816 and -2147024713 are the + // HRESULTs of ERROR_FILE_EXISTS and ERROR_ALREADY_EXISTS. + const SCRIPT: &str = "$ErrorActionPreference = 'Stop'; \ + $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 }; \ + 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) + .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()?; + // 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()?; + if out.status.code() == Some(EXISTS) { + return Err(std::io::Error::new(std::io::ErrorKind::AlreadyExists, "the file already exists")); + } + if !out.status.success() { + 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")), + }; + if checked.is_err() { + let _ = std::fs::remove_file(path); + } + checked +} + /// `Err` naming the problem when the descriptor read back after restricting still isn't `me`'s /// alone, so a file that only looks restricted is never used as one. #[cfg(any(test, windows))] @@ -495,6 +549,35 @@ $n = [CraftProbe.Console]::GetConsoleProcessList($ids, 256) let _ = std::fs::remove_dir_all(&dir); } + /// A file created by `create_private_file` in a folder that lets Users read what's in it is the + /// user's alone as soon as it exists, with nothing written to it yet; one created with contents + /// holds them, and an existing file is refused and left as it is. + #[cfg(windows)] + #[test] + fn a_private_file_is_private_from_the_start() { + let dir = std::env::temp_dir().join(format!("craft-owner-only-private-file-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let ok = std::process::Command::new("icacls").arg(&dir).arg("/grant").arg("*S-1-5-32-545:(OI)(CI)R").output().unwrap(); + assert!(ok.status.success(), "{}", String::from_utf8_lossy(&ok.stderr)); + let me = current_user_sid().unwrap(); + let empty = dir.join("empty.token"); + create_private_file(&empty, &user(), b"").unwrap(); + let sddl = sddl_of(&empty).unwrap(); + assert!(!sddl.contains(";BU)") && !sddl.contains(";S-1-5-32-545)"), "Users must not inherit read access: {sddl}"); + assert_eq!((section(&sddl, "O:"), foreign_access(&sddl, &me)), (Some(me.as_str()), None), "{sddl}"); + assert_eq!(std::fs::read(&empty).unwrap(), b""); + let file = dir.join("ctl.token"); + create_private_file(&file, &user(), b"secret\n").unwrap(); + let sddl = sddl_of(&file).unwrap(); + assert_eq!((section(&sddl, "O:"), foreign_access(&sddl, &me)), (Some(me.as_str()), None), "{sddl}"); + assert_eq!(std::fs::read(&file).unwrap(), b"secret\n"); + let again = create_private_file(&file, &user(), b"other\n").unwrap_err(); + assert_eq!(again.kind(), std::io::ErrorKind::AlreadyExists, "{again}"); + assert_eq!(std::fs::read(&file).unwrap(), b"secret\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. From 1798f485a28b1c5b17d3ca0551903366e9d7040a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 10:45:42 -0800 Subject: [PATCH 03/87] control: the token file is private from the moment it is created On Windows, write_token_file_with created the control token file with create_new, so the file started with its folder's access list, and only then ran icacls to restrict it to the user. Another local account that the folder lets read new files could open a handle in between, and that handle keeps its read access after the list changes, so it could read the token once it was written. On Windows the file is now created with craft_platform::owner_only::create_private_file under a name of its own beside the token file: the user and SYSTEM are the only entries from the call that creates it, and the token is written through that handle. The finished file then takes the token file's name through a hard link, so a token file another launch wrote meanwhile is kept and this write fails, as create_new did. The discovery file (current.port) is renamed into place instead, so the latest launch replaces it. The create runs on its own thread and is waited for at most 10 seconds, as icacls was waited for 5. When it does not finish in time, a folder named by the app's CONTROL_DIR gets no token, the default folder gets the file with its own access list, as before, and the late file is removed when the create finishes. While such a create is still running, later writes start no create of their own and take the timed-out path at once. Unix keeps mode 0600 at create. --- Cargo.lock | 1 + crates/control/Cargo.toml | 4 + crates/control/src/auth.rs | 367 +++++++++++++++++++++++++------------ 3 files changed, 253 insertions(+), 119 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 27b9e695a6..be23438e23 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2263,6 +2263,7 @@ dependencies = [ "craft-ai-agents", "craft-atomic", "craft-flags", + "craft-platform", "dirs", "getrandom 0.3.4", "log", diff --git a/crates/control/Cargo.toml b/crates/control/Cargo.toml index 3e756aff75..1f3851ffd0 100644 --- a/crates/control/Cargo.toml +++ b/crates/control/Cargo.toml @@ -32,6 +32,10 @@ craft-flags = { workspace = true, optional = true } dirs = { version = "7", optional = true } log = { workspace = true, optional = true } +[target.'cfg(windows)'.dependencies] +# The token file, created with an access list of its user and SYSTEM only (MIT OR Apache-2.0, ours). +craft-platform = { workspace = true } + [dev-dependencies] proptest = { workspace = true } tempfile = "3" diff --git a/crates/control/src/auth.rs b/crates/control/src/auth.rs index bb2cef86b3..d3cc93a358 100644 --- a/crates/control/src/auth.rs +++ b/crates/control/src/auth.rs @@ -101,7 +101,7 @@ impl App { /// Record `port` as the running app's, readable only by the user like the token files. pub fn write_current_port(&self, port: u16) -> Result { let path = self.current_port_path().ok_or_else(|| Error::new(ErrorKind::NotFound, "no data folder"))?; - self.write_token_file(&path, &port.to_string())?; + self.write_private(&path, &port.to_string(), true)?; Ok(path) } @@ -141,16 +141,27 @@ impl App { } /// Write `token` to `path`, readable and writable only by the user: the folder is made `0700` - /// and the file `0600` on Unix; on Windows the file's inherited permissions are replaced by one - /// entry for the user (`icacls`) before the token goes in; when that fails, the still empty file - /// is removed and no token is written. A file left by an earlier launch is replaced. The process - /// file beside it ([`pid_path`]) records this process, best effort. + /// and the file `0600` on Unix; on Windows the file is created with an access list of the user + /// and SYSTEM only and the token is written through the handle that created it + /// ([`create_for_user`]), so the file never has its folder's access list. A file left by an + /// earlier launch is replaced. The process file beside it ([`pid_path`]) records this process, + /// best effort. pub fn write_token_file(&self, path: &Path, token: &str) -> Result<()> { + self.write_private(path, token, false) + } + + /// [`App::write_token_file`]. `replace`: on Windows, a file another launch put at `path` while + /// this one was being created is replaced (the discovery file, which names the latest launch); + /// otherwise this write fails and that launch's token stays. + fn write_private(&self, path: &Path, token: &str, replace: bool) -> Result<()> { #[cfg(windows)] - let restrict = |p: &Path| restrict_to_user(p, self.custom_control_dir().is_some()); + let create = |p: &Path, contents: &[u8]| create_for_user(p, contents, self.custom_control_dir().is_some(), replace); #[cfg(not(windows))] - let restrict = |_: &Path| Ok(()); - write_token_file_with(path, token, restrict) + let create = { + let _ = replace; + create_new_file + }; + write_token_file_with(path, token, create) } } @@ -314,31 +325,18 @@ pub fn tokens_match(a: &str, b: &str) -> bool { a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0 } -/// [`App::write_token_file`], with `restrict` limiting the new file to the user (Windows). -fn write_token_file_with(path: &Path, token: &str, restrict: impl FnOnce(&Path) -> Result<()>) -> Result<()> { +/// [`App::write_token_file`], with `create` making the new file with its contents, readable only +/// by the user. +fn write_token_file_with(path: &Path, token: &str, create: impl FnOnce(&Path, &[u8]) -> Result<()>) -> Result<()> { let dir = path.parent().ok_or_else(|| Error::new(ErrorKind::InvalidInput, "no folder"))?; std::fs::create_dir_all(dir)?; let _ = std::fs::remove_file(path); - let mut opts = std::fs::OpenOptions::new(); - opts.write(true).create_new(true); #[cfg(unix)] { - use std::os::unix::fs::{OpenOptionsExt, PermissionsExt}; + use std::os::unix::fs::PermissionsExt; std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))?; - opts.mode(0o600); } - let opened = opts.open(path)?; - // On a refusal the file goes with the closure, so it is closed before it is removed. - let mut f = match restrict(path).map(|()| opened) { - Ok(f) => f, - Err(e) => { - let _ = std::fs::remove_file(path); - return Err(e); - } - }; - f.write_all(token.as_bytes())?; - f.write_all(b"\n")?; - f.sync_all()?; + create(path, format!("{token}\n").as_bytes())?; let pid = std::process::id(); let line = process_start(pid).map_or_else(|| format!("{pid}\n"), |start| format!("{pid} {start}\n")); let _ = std::fs::write(pid_path(path), line); @@ -369,74 +367,143 @@ fn held_by_another(path: &Path, token: &str) -> bool { read_token(path).is_some_and(|held| !tokens_match(&held, token.trim())) } -/// How long `icacls` may take (#6145). It finishes at once; on some computers the new process -/// is left suspended (security software holding it), and waiting on it without a limit froze -/// the app. -#[cfg(windows)] -const ICACLS_LIMIT: std::time::Duration = std::time::Duration::from_secs(5); - -/// How a run of `icacls` ended. -#[cfg(any(windows, test))] -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum IcaclsEnd { - Succeeded, - Failed, - /// It didn't finish within [`ICACLS_LIMIT`] and was ended. - TimedOut, +/// Create `path`, which must not exist yet, holding `contents`: mode `0600` on Unix. On Windows a +/// file created this way has its folder's access list; the token file there is made by +/// [`create_for_user`]. +fn create_new_file(path: &Path, contents: &[u8]) -> Result<()> { + let mut opts = std::fs::OpenOptions::new(); + opts.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + opts.mode(0o600); + } + let mut f = opts.open(path)?; + f.write_all(contents)?; + f.sync_all() } -/// Whether a token may go into a file after `icacls` ended this way. `custom_folder`: the file is -/// in the folder the app's `CONTROL_DIR` names. A timeout is accepted only in the default folder, -/// the user's own local app data, which other users can't read by default; nothing is known about -/// the permissions of any other folder. +/// How long creating the token file may take on Windows (#6145). It runs `whoami` and PowerShell; +/// on some computers a new process is left suspended (security software holding it), and waiting +/// on it without a limit froze the app. +#[cfg(windows)] +const CREATE_LIMIT: std::time::Duration = std::time::Duration::from_secs(10); + +/// Windows: create `path` with the current user as owner and an access list of that user and +/// SYSTEM only, given to Windows in the call that creates the file, with `contents` written +/// through that handle (`craft_platform::owner_only::create_private_file`), then named `path`. +/// Another account never gets a moment in which the file has its folder's access list and could be +/// opened. `custom_folder`: the file is in the folder the app's `CONTROL_DIR` names; +/// [`create_within`] says what it changes when the create takes longer than [`CREATE_LIMIT`], and +/// what `replace` changes. +#[cfg(windows)] +fn create_for_user(path: &Path, contents: &[u8], custom_folder: bool, replace: bool) -> Result<()> { + use craft_platform::owner_only; + /// How many creates that were not waited for are still running. + static STUCK: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + let private = |p: &Path, c: &[u8]| owner_only::current_user_sid().and_then(|me| owner_only::create_private_file(p, &me, c)); + create_within(path, contents, custom_folder, replace, CREATE_LIMIT, &STUCK, private).0 +} + +/// What a create that wasn't waited for gives: in a folder the app's `CONTROL_DIR` names +/// (`custom_folder`) an error of kind [`ErrorKind::TimedOut`], since nothing is known about that +/// folder's permissions; in the default folder, the user's own local app data, which other users +/// can't read by default, `path` created with that folder's access list ([`create_new_file`]). #[cfg(any(windows, test))] -fn restriction_result(end: IcaclsEnd, custom_folder: bool, path: &Path) -> Result<()> { - match end { - IcaclsEnd::Succeeded => Ok(()), - IcaclsEnd::TimedOut if !custom_folder => Ok(()), - IcaclsEnd::TimedOut => Err(Error::new(ErrorKind::TimedOut, format!("icacls did not finish in time to restrict {}", path.display()))), - IcaclsEnd::Failed => Err(Error::other(format!("icacls failed to restrict {}", path.display()))), +fn not_waited_for(path: &Path, contents: &[u8], custom_folder: bool) -> Result<()> { + if custom_folder { + Err(Error::new(ErrorKind::TimedOut, format!("creating {} for its user only did not finish in time", path.display()))) + } else { + create_new_file(path, contents) } } -/// Windows: drop inherited entries and grant only the current user full access. An `icacls` -/// that doesn't finish in time is ended, and [`restriction_result`] decides what that means. -#[cfg(windows)] -fn restrict_to_user(path: &Path, custom_folder: bool) -> Result<()> { - use std::os::windows::process::CommandExt; - let user = std::env::var("USERNAME").map_err(|_| Error::other("USERNAME is not set"))?; - let domain = std::env::var("USERDOMAIN").ok().filter(|d| !d.is_empty()); - let who = domain.map_or(user.clone(), |d| format!("{d}\\{user}")); - let child = std::process::Command::new("icacls") - .arg(path) - .args(["/inheritance:r", "/grant:r", &format!("{who}:F")]) - .stdout(std::process::Stdio::null()) - .stderr(std::process::Stdio::null()) - .creation_flags(0x0800_0000) - .spawn()?; - let end = match wait_within(child, ICACLS_LIMIT)? { - Some(status) if status.success() => IcaclsEnd::Succeeded, - Some(_) => IcaclsEnd::Failed, - None => IcaclsEnd::TimedOut, +/// Run `private`, which creates a file holding `contents` for the user alone, on a thread of its +/// own, and wait for it at most `limit`. The thread creates a file of its own beside `path` +/// (`....tmp`), and the file takes the name `path` only once `private` +/// has finished, so `path` never holds a file that is still being written: with `replace` by a +/// rename that replaces a file another launch put there meanwhile, otherwise by [`place_new`], +/// which leaves that file and fails. When +/// the thread hasn't finished in time, [`not_waited_for`] gives the result, the thread removes its +/// file whenever it does finish, and `stuck` counts it until then. While `stuck` counts any +/// thread, no other thread is started and [`not_waited_for`] answers at once, so a computer that +/// leaves new processes suspended holds at most the threads that were started together. The +/// thread's handle is returned for tests. +#[cfg(any(windows, test))] +fn create_within( + path: &Path, + contents: &[u8], + custom_folder: bool, + replace: bool, + limit: std::time::Duration, + stuck: &'static std::sync::atomic::AtomicUsize, + private: impl FnOnce(&Path, &[u8]) -> Result<()> + Send + 'static, +) -> (Result<()>, Option>) { + use std::sync::atomic::{AtomicU64, Ordering}; + use std::sync::mpsc::{RecvTimeoutError, channel}; + use std::sync::{Arc, Mutex, PoisonError}; + /// Numbers the thread's files within this process. + static COUNT: AtomicU64 = AtomicU64::new(0); + if stuck.load(Ordering::Acquire) > 0 { + return (not_waited_for(path, contents, custom_folder), None); + } + 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 (sender, receiver) = channel(); + // Set under the lock when the caller stops waiting; the thread reads it under the same lock + // before it reports, so its result is either received or its file is removed. + let abandoned = Arc::new(Mutex::new(false)); + let (own_file, owned_contents, flag) = (staged.clone(), contents.to_vec(), Arc::clone(&abandoned)); + let spawned = std::thread::Builder::new().name("craft-control-token-file".into()).spawn(move || { + let made = private(&own_file, &owned_contents); + let abandoned = flag.lock().unwrap_or_else(PoisonError::into_inner); + if *abandoned { + let _ = std::fs::remove_file(&own_file); + stuck.fetch_sub(1, Ordering::AcqRel); + } else { + let _ = sender.send(made); + } + }); + let handle = match spawned { + Ok(handle) => handle, + Err(e) => return (Err(e), None), }; - restriction_result(end, custom_folder, path) + let made = match receiver.recv_timeout(limit) { + Ok(made) => made, + Err(RecvTimeoutError::Disconnected) => Err(Error::other(format!("the thread creating {} stopped", path.display()))), + Err(RecvTimeoutError::Timeout) => { + let mut abandoned = abandoned.lock().unwrap_or_else(PoisonError::into_inner); + match receiver.try_recv() { + Ok(made) => made, + Err(_) => { + *abandoned = true; + stuck.fetch_add(1, Ordering::AcqRel); + drop(abandoned); + return (not_waited_for(path, contents, custom_folder), Some(handle)); + } + } + } + }; + let placed = made.and_then(|()| if replace { std::fs::rename(&staged, path) } else { place_new(&staged, path) }); + let _ = std::fs::remove_file(&staged); + (placed, Some(handle)) } -/// Wait for `child` at most `limit`: its exit status, or `None` (and the child ended) when it -/// hasn't finished by then. +/// Give the finished file `staged` the name `path`, which must not exist yet: a second launch +/// writing the same token file at the same time gets [`ErrorKind::AlreadyExists`], as a +/// `create_new` there would, instead of replacing the first one's token. The new name is a hard +/// link. On a volume without hard links the file is renamed once `path` is found free; there a +/// launch that puts its file at `path` between that check and the rename has it replaced, as std +/// offers no rename that refuses an existing file without `unsafe`. `staged` is left for the +/// caller to remove. #[cfg(any(windows, test))] -fn wait_within(mut child: std::process::Child, limit: std::time::Duration) -> Result> { - let start = std::time::Instant::now(); - loop { - if let Some(status) = child.try_wait()? { - return Ok(Some(status)); +fn place_new(staged: &Path, path: &Path) -> Result<()> { + match std::fs::hard_link(staged, path) { + Ok(()) => Ok(()), + Err(e) if e.kind() == ErrorKind::AlreadyExists || std::fs::symlink_metadata(path).is_ok() => { + Err(Error::new(ErrorKind::AlreadyExists, format!("{}: {e}", path.display()))) } - if start.elapsed() >= limit { - // Not waited for afterwards: a suspended process may not end at once. - let _ = child.kill(); - return Ok(None); - } - std::thread::sleep(std::time::Duration::from_millis(20)); + Err(_) => std::fs::rename(staged, path), } } @@ -456,50 +523,112 @@ mod tests { /// An app with no data folder and no environment, whose times read `t`. const TEST: App = App { name: "TestCraft", data_dir: || None, env: |_| None, utc: |secs| format!("t{secs}"), default_port: 27878 }; - /// #6145: a child that doesn't finish in time is given up on, not waited for forever. - #[cfg(unix)] + /// #6145: a private create that doesn't finish in time doesn't hold the caller up. In a folder + /// the app's `CONTROL_DIR` names, the call fails; in the default folder, the file is created + /// anyway and holds the token. Either way the file the late create makes is removed when it + /// finishes and never takes the token file's name, even when a later write has put a file + /// there. While it runs, the next create starts no thread of its own. A create that finishes in + /// time puts its file in place unless a file already has the name, and one that fails leaves + /// nothing. #[test] - fn a_slow_child_is_waited_for_only_so_long() { - use std::time::{Duration, Instant}; - let start = Instant::now(); - let slow = std::process::Command::new("sleep").arg("30").spawn().unwrap(); - assert!(wait_within(slow, Duration::from_millis(200)).unwrap().is_none()); - assert!(start.elapsed() < Duration::from_secs(5), "{:?}", start.elapsed()); - let quick = std::process::Command::new("true").spawn().unwrap(); - assert!(wait_within(quick, Duration::from_secs(5)).unwrap().is_some_and(|s| s.success())); - let failing = std::process::Command::new("false").spawn().unwrap(); - assert!(wait_within(failing, Duration::from_secs(5)).unwrap().is_some_and(|s| !s.success())); - } - - /// #6145's freeze fix stays in the default folder, the user's own; a folder picked with - /// the app's `CONTROL_DIR` gets no token unless the file was really restricted. - #[test] - fn only_the_default_folder_accepts_an_icacls_that_timed_out() { - let path = Path::new("control/7878.token"); - for custom in [false, true] { - assert!(restriction_result(IcaclsEnd::Succeeded, custom, path).is_ok()); - assert!(restriction_result(IcaclsEnd::Failed, custom, path).is_err()); + fn a_private_create_that_does_not_finish_in_time_is_not_waited_for() { + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::mpsc::channel; + use std::time::Duration; + static STUCK: AtomicUsize = AtomicUsize::new(0); + let dir = std::env::temp_dir().join(format!("craft-control-create-limit-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let names = || { + let mut names: Vec = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + names.sort(); + names + }; + for custom in [true, false] { + let path = dir.join("7878.port"); + let (go, wait) = channel::<()>(); + let (made, handle) = create_within(&path, b"7878\n", custom, false, Duration::ZERO, &STUCK, move |p, c| { + wait.recv().map_err(Error::other)?; + create_new_file(p, c) + }); + assert_eq!(STUCK.load(Ordering::Acquire), 1); + if custom { + assert_eq!(made.unwrap_err().kind(), ErrorKind::TimedOut); + assert!(!path.exists()); + let unused = |_: &Path, _: &[u8]| -> Result<()> { panic!("a second thread was started") }; + let (again, none) = create_within(&path, b"7878\n", custom, false, Duration::from_secs(600), &STUCK, unused); + assert_eq!(again.unwrap_err().kind(), ErrorKind::TimedOut); + assert!(none.is_none()); + // A later write of the same contents, as a retry of the same port would make. + create_new_file(&path, b"7878\n").unwrap(); + } else { + made.unwrap(); + } + go.send(()).unwrap(); + handle.unwrap().join().unwrap(); + assert_eq!(STUCK.load(Ordering::Acquire), 0); + assert_eq!(names(), ["7878.port"]); + assert_eq!(read_token(&path).as_deref(), Some("7878")); + std::fs::remove_file(&path).unwrap(); } - assert!(restriction_result(IcaclsEnd::TimedOut, false, path).is_ok()); - let e = restriction_result(IcaclsEnd::TimedOut, true, path).unwrap_err(); - assert_eq!(e.kind(), ErrorKind::TimedOut); - assert!(e.to_string().contains("7878.token"), "{e}"); + let path = dir.join("quick.token"); + let (made, handle) = create_within(&path, b"quick\n", true, false, Duration::from_secs(600), &STUCK, create_new_file); + made.unwrap(); + handle.unwrap().join().unwrap(); + assert_eq!(names(), ["quick.token"]); + assert_eq!(read_token(&path).as_deref(), Some("quick")); + // Another launch's file at the name is kept, as `create_new` keeps it. + let (made, handle) = create_within(&path, b"later\n", true, false, Duration::from_secs(600), &STUCK, create_new_file); + assert_eq!(made.unwrap_err().kind(), ErrorKind::AlreadyExists); + handle.unwrap().join().unwrap(); + assert_eq!(names(), ["quick.token"]); + assert_eq!(read_token(&path).as_deref(), Some("quick")); + // With `replace` (the discovery file) the later launch's file takes the name. + let (made, handle) = create_within(&path, b"later\n", true, true, Duration::from_secs(600), &STUCK, create_new_file); + made.unwrap(); + handle.unwrap().join().unwrap(); + assert_eq!(names(), ["quick.token"]); + assert_eq!(read_token(&path).as_deref(), Some("later")); + let refused = |_: &Path, _: &[u8]| -> Result<()> { Err(Error::other("refused")) }; + let (made, handle) = create_within(&dir.join("refused.token"), b"other\n", true, false, Duration::from_secs(600), &STUCK, refused); + assert!(made.is_err()); + handle.unwrap().join().unwrap(); + assert_eq!(names(), ["quick.token"]); + let _ = std::fs::remove_dir_all(&dir); } - /// A file that couldn't be restricted is removed, empty and with no process file beside it, and - /// the error goes to the caller. A restricted one gets its token. + /// A file that couldn't be created leaves no process file beside it, and the error goes to the + /// caller. A created one gets the token and a newline. #[test] - fn a_token_file_that_could_not_be_restricted_is_removed() { - let dir = std::env::temp_dir().join(format!("craft-control-restrict-{}", std::process::id())); + fn a_token_file_that_could_not_be_created_leaves_nothing() { + let dir = std::env::temp_dir().join(format!("craft-control-create-{}", std::process::id())); let path = dir.join("7879.token"); - let e = write_token_file_with(&path, "secret-token", |p| { - assert_eq!(std::fs::read(p).unwrap(), b"", "restricted before the token goes in"); - restriction_result(IcaclsEnd::TimedOut, true, p) - }) - .unwrap_err(); + let e = write_token_file_with(&path, "secret-token", |_, _| Err(Error::new(ErrorKind::TimedOut, "refused"))).unwrap_err(); assert_eq!(e.kind(), ErrorKind::TimedOut); assert!(!path.exists() && !pid_path(&path).exists()); - write_token_file_with(&path, "secret-token", |p| restriction_result(IcaclsEnd::TimedOut, false, p)).unwrap(); + write_token_file_with(&path, "secret-token", create_new_file).unwrap(); + assert_eq!(std::fs::read(&path).unwrap(), b"secret-token\n"); + assert!(pid_path(&path).exists()); + let _ = std::fs::remove_dir_all(&dir); + } + + /// On Windows the token file is its user's alone from the moment it exists: in a folder that + /// lets Users read what is created in it, the file has no entry for Users and no other + /// account's access. + #[cfg(windows)] + #[test] + fn the_token_file_is_private_from_the_start_on_windows() { + use craft_platform::owner_only; + let dir = std::env::temp_dir().join(format!("craft-control-private-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let ok = std::process::Command::new("icacls").arg(&dir).arg("/grant").arg("*S-1-5-32-545:(OI)(CI)R").output().unwrap(); + assert!(ok.status.success(), "{}", String::from_utf8_lossy(&ok.stderr)); + let path = dir.join("7880.token"); + TEST.write_token_file(&path, "secret-token").unwrap(); + let sddl = owner_only::sddl_of(&path).unwrap(); + assert!(!sddl.contains(";BU)") && !sddl.contains(";S-1-5-32-545)"), "Users must not inherit read access: {sddl}"); + assert_eq!(owner_only::foreign_access(&sddl, &owner_only::current_user_sid().unwrap()), None, "{sddl}"); assert_eq!(read_token(&path).as_deref(), Some("secret-token")); let _ = std::fs::remove_dir_all(&dir); } From cce0c76a979ec2e5dc4ac44995fe65a463e73a8b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 11:55:59 -0800 Subject: [PATCH 04/87] platform: owner_only ends a Windows tool that runs longer than 10 seconds Every whoami, PowerShell and icacls run in owner_only now goes through run_until, which waits for the tool with try_wait and a deadline (TOOL_LIMIT, 10 s) and ends it with Child::kill when the deadline passes. The call then fails with ErrorKind::TimedOut. Before, each run used output() or wait_with_output() with no limit, so a process left suspended held create_token_file and every other caller indefinitely. create_private_file writes the file under its own name beside the path (....tmp) and moves it to the path only once the contents are written, so the path never holds a partly written file. When PowerShell is ended, that file is removed once PowerShell has exited. server_token no longer reads a file left at the path by a create that ran out of time as another process's token; it returns the timeout error. --- crates/automation/src/security.rs | 34 ++- crates/automation/src/security_tests.rs | 22 ++ crates/platform/README.md | 2 +- crates/platform/src/owner_only.rs | 307 +++++++++++++++++++++--- 4 files changed, 317 insertions(+), 48 deletions(-) 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. From 1f3b0578cc2ee4354187baa18062b0983522fd53 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 11:57:46 -0800 Subject: [PATCH 05/87] suite-account: the account list is private from the moment it is created on Windows On Windows, accounts::write created each new copy of the list with plain create_new and then called restrict, which did nothing, so the copy kept its folder's access list. A portable install or ARTCRAFT_SUITE_DIR in a folder such as a new folder at the root of C:\ left the list (subjects, display names, emails, deployment URLs) readable by every local account. Every copy is now created with owner_only::create_private_file, which gives it a protected access list of the user and SYSTEM only in the call that creates it. The rename keeps that list, and a later change to the folder's list does not reach the file. The PowerShell run this needs happens before the accounts lock is taken: with_lock prepares an empty copy for its thread, opens it without delete sharing, checks its access list and holds it open until the write, so no other account can remove, rename or replace it in between. A copy that no write takes is closed and removed when the locked change ends, and empty copies that ended processes left beside the list are removed by the next preparation. --- Cargo.lock | 1 + crates/suite-account/Cargo.toml | 5 + crates/suite-account/src/accounts.rs | 176 ++++++++++++++++++++++++--- crates/suite-account/src/lock.rs | 2 + crates/suite-account/src/tests.rs | 153 +++++++++++++++++++++++ 5 files changed, 317 insertions(+), 20 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 27b9e695a6..c6fa436bf8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4103,6 +4103,7 @@ dependencies = [ name = "craft-suite-account" version = "0.1.0" dependencies = [ + "craft-platform", "dirs", "keyring", "keyring-core", diff --git a/crates/suite-account/Cargo.toml b/crates/suite-account/Cargo.toml index e1527bfd8c..75edc2a751 100644 --- a/crates/suite-account/Cargo.toml +++ b/crates/suite-account/Cargo.toml @@ -31,5 +31,10 @@ keyring = "4.2" # machine-local persistence. `keyring` installs the platform store; this reads it. keyring-core = "1" +# The account list is created with an access list of its user and SYSTEM only +# (`owner_only::create_private_file`). +[target.'cfg(windows)'.dependencies] +craft-platform = { workspace = true } + [dev-dependencies] tempfile = "3" diff --git a/crates/suite-account/src/accounts.rs b/crates/suite-account/src/accounts.rs index fb8ce5d7de..b11cb27156 100644 --- a/crates/suite-account/src/accounts.rs +++ b/crates/suite-account/src/accounts.rs @@ -263,7 +263,10 @@ pub fn read(path: &Path) -> Result { /// [`Error::Malformed`] forever. Every mutation here reads the file first. There would be /// nothing left to repair it with. /// -/// Readable by this user alone where the platform has file modes. The file holds no token. It does +/// Readable by this user alone: mode `0600` on Unix, and on Windows an access list of this user and +/// SYSTEM only from the moment the file exists, whatever folder a portable install or +/// [`crate::paths::ENV_VAR`] chose. On Windows the access list is protected, so a change to the +/// folder's list does not reach the file. The file holds no token. It does /// say who is signed in. That is nobody else's business. /// /// Refuses a list that would serialize past `MAX_BYTES`, before any file is touched. [`read`] @@ -282,14 +285,17 @@ pub fn write(path: &Path, accounts: &Accounts) -> Result<(), Error> { ))); } std::fs::create_dir_all(dir).map_err(|e| Error::Io(format!("couldn't create {} ({e})", dir.display())))?; - use std::io::Write; let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0); let pid = std::process::id(); - let tmp = dir.join(format!(".{}.{}.{}.tmp", path.file_name().and_then(|n| n.to_str()).unwrap_or("accounts"), stamp, pid)); + let file_name = path.file_name().and_then(|n| n.to_str()).unwrap_or("accounts"); + let tmp_name = format!(".{file_name}.{stamp}.{pid}.tmp"); + #[cfg(not(windows))] + let tmp = dir.join(&tmp_name); #[cfg(unix)] { use std::fs::OpenOptions; + use std::io::Write; use std::os::unix::fs::OpenOptionsExt; let mut file = OpenOptions::new() .write(true) @@ -300,14 +306,16 @@ pub fn write(path: &Path, accounts: &Accounts) -> Result<(), Error> { file.write_all(&json).map_err(|e| Error::Io(format!("couldn't write {} ({e})", tmp.display())))?; file.sync_all().map_err(|e| Error::Io(format!("couldn't flush {} ({e})", tmp.display())))?; } - #[cfg(not(unix))] + #[cfg(windows)] + let tmp = private_copy(path, dir, &tmp_name, &json)?; + #[cfg(not(any(unix, windows)))] { use std::fs::OpenOptions; + use std::io::Write; let mut file = OpenOptions::new().write(true).create_new(true).open(&tmp).map_err(|e| Error::Io(format!("couldn't create {} ({e})", tmp.display())))?; file.write_all(&json).map_err(|e| Error::Io(format!("couldn't write {} ({e})", tmp.display())))?; file.sync_all().map_err(|e| Error::Io(format!("couldn't flush {} ({e})", tmp.display())))?; - restrict(&tmp)?; } std::fs::rename(&tmp, path).map_err(|e| Error::Io(format!("couldn't replace {} ({e})", path.display())))?; // The flush above persisted the file's bytes. The rename changed a directory entry, and that @@ -324,19 +332,147 @@ pub fn write(path: &Path, accounts: &Accounts) -> Result<(), Error> { Ok(()) } -#[cfg(not(unix))] -fn restrict(_path: &Path) -> Result<(), Error> { - // A no-op today. That is a real gap this comment used to paper over. A new file in the - // platform configuration folder (the default `paths::Rule::Platform` home) inherits that - // folder's own, profile-scoped access rules. The account list is this user's alone there. - // `paths::Rule::Portable` and `paths::Rule::EnvVar` point `write` at whatever folder the - // caller named. A new file there inherits that folder's own Windows access control list, - // whatever it is. A shared or loosely permissioned folder in either of those two cases - // leaves the account list (subjects, display names, emails, never a token) readable by - // anyone else with access to it. Narrowing that needs a per-user Windows DACL on the file, - // set through the Win32 authorization API. Every binding for that API is an `unsafe fn`. - // This workspace forbids `unsafe_code` outright. Closing this for real needs either a - // maintainer-approved exception for one call site or a vetted dependency that wraps that API - // safely. Both are decisions for a dedicated PR. See `paths::Rule`. - Ok(()) +/// Write `json` to a new file beside the list at `path`, in its folder `dir`, that only this user +/// and SYSTEM can open, and return its path for [`write`] to rename into place. +/// +/// A new file on Windows takes its folder's access list, and a portable install or +/// [`crate::paths::ENV_VAR`] can name a folder that lets every local user read what is created in +/// it. Every copy is created by `owner_only::create_private_file`, which gives the file a protected +/// access list of this user and SYSTEM only in the call that creates it. The rename keeps that +/// list, and a later change to the folder's list does not reach it. That call runs PowerShell, so +/// [`prepare`] creates an empty copy before the accounts lock is taken, and this function writes +/// the list into it. Without a copy this thread prepared (a direct call, or a failed preparation), +/// the copy is created here, named `tmp_name`. +#[cfg(windows)] +fn private_copy(path: &Path, dir: &Path, tmp_name: &str, json: &[u8]) -> Result { + use std::io::Write; + if let Some((copy, mut file)) = take_prepared(path) { + match file.write_all(json).and_then(|()| file.sync_all()) { + Ok(()) => return Ok(copy), + Err(e) => { + drop(file); + let _ = std::fs::remove_file(©); + log::warn!("couldn't write a prepared copy of the account list ({e}); a new one is created"); + } + } + } + let tmp = dir.join(tmp_name); + user_sid() + .and_then(|me| craft_platform::owner_only::create_private_file(&tmp, &me, json)) + .map_err(|e| Error::Io(format!("couldn't create {} for its owner only ({e})", tmp.display())))?; + Ok(tmp) +} + +/// Copies made by [`prepare`] that wait for [`private_copy`]: the thread that made the copy, the +/// list it is for, the copy, and the copy held open without delete sharing. +#[cfg(windows)] +type Prepared = Vec<(std::thread::ThreadId, std::path::PathBuf, std::path::PathBuf, std::fs::File)>; + +/// The copy one [`prepare`] call made. Dropping it closes and removes the copy if no write took it. +#[cfg(windows)] +pub(crate) struct PreparedCopy(Option); + +#[cfg(windows)] +impl Drop for PreparedCopy { + fn drop(&mut self) { + let Some(copy) = self.0.take() else { return }; + let mut waiting = prepared(); + let Some(at) = waiting.iter().position(|(_, _, waiting, _)| *waiting == copy) else { return }; + let (_, _, copy, file) = waiting.swap_remove(at); + drop(waiting); + drop(file); + let _ = std::fs::remove_file(©); + } +} + +/// The copies waiting for [`private_copy`]. +#[cfg(windows)] +fn prepared() -> std::sync::MutexGuard<'static, Prepared> { + static PREPARED: std::sync::Mutex = std::sync::Mutex::new(Vec::new()); + PREPARED.lock().unwrap_or_else(std::sync::PoisonError::into_inner) +} + +/// The copy of the list at `path` that this thread prepared, with its open handle, removed from the +/// waiting list. A copy another thread prepared is left for that thread's write. +#[cfg(windows)] +fn take_prepared(path: &Path) -> Option<(std::path::PathBuf, std::fs::File)> { + let me = std::thread::current().id(); + let mut prepared = prepared(); + let at = prepared.iter().position(|(thread, list, ..)| *thread == me && list == path)?; + let (_, _, copy, file) = prepared.swap_remove(at); + Some((copy, file)) +} + +/// This user's SID, read once per process (`whoami` is a process start). +#[cfg(windows)] +fn user_sid() -> std::io::Result { + static SID: std::sync::OnceLock = std::sync::OnceLock::new(); + if let Some(sid) = SID.get() { + return Ok(sid.clone()); + } + let sid = craft_platform::owner_only::current_user_sid()?; + Ok(SID.get_or_init(|| sid).clone()) +} + +/// Before the accounts lock is taken, create an empty copy of the list at `path` for its owner only +/// and keep it open for [`private_copy`], so that the PowerShell run it needs doesn't hold the lock +/// other processes wait on. The caller keeps the returned [`PreparedCopy`] until its change under +/// the lock is done; a change that writes nothing then has its copy removed. A failure here is left +/// for [`write`] to handle. +/// +/// The copy is opened without delete sharing and then checked, so no other account can remove, +/// rename or replace it between the check and the write. A copy that fails the check is removed. +/// Empty copies beside the list that are at least a minute old, which ended processes left, are +/// removed first; a copy that a running process holds open can't be, since removing it needs +/// delete sharing. +#[cfg(windows)] +pub(crate) fn prepare(path: &Path) -> PreparedCopy { + use std::os::windows::fs::OpenOptionsExt as _; + use std::sync::atomic::{AtomicU64, Ordering}; + + use craft_platform::owner_only; + /// `FILE_SHARE_READ | FILE_SHARE_WRITE`: no `FILE_SHARE_DELETE`. + const SHARE_NO_DELETE: u32 = 0x1 | 0x2; + /// How old an empty copy that no process holds must be before it is removed. Another process + /// that is preparing its copy has it closed for a moment, between its creation and the open. + const LEFT_AFTER: std::time::Duration = std::time::Duration::from_secs(60); + static COUNT: AtomicU64 = AtomicU64::new(0); + + let (Some(dir), Some(name)) = (path.parent(), path.file_name().and_then(|n| n.to_str())) else { return PreparedCopy(None) }; + let Ok(me) = user_sid() else { return PreparedCopy(None) }; + let _ = std::fs::create_dir_all(dir); + for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() { + let left = entry.file_name(); + let left = left.to_string_lossy(); + if left.starts_with(&format!(".{name}.")) + && left.ends_with(".prepared.tmp") + && entry.metadata().is_ok_and(|meta| { + meta.is_file() && meta.len() == 0 && meta.modified().ok().and_then(|at| at.elapsed().ok()).is_some_and(|age| age >= LEFT_AFTER) + }) + { + let _ = std::fs::remove_file(entry.path()); + } + } + let copy = dir.join(format!(".{name}.{}.{}.prepared.tmp", std::process::id(), COUNT.fetch_add(1, Ordering::Relaxed))); + if let Err(e) = owner_only::create_private_file(©, &me, b"") { + log::warn!("couldn't prepare a copy of the account list for its owner only ({e})"); + return PreparedCopy(None); + } + let checked = std::fs::OpenOptions::new().write(true).share_mode(SHARE_NO_DELETE).open(©).and_then(|file| { + match owner_only::foreign_access(&owner_only::sddl_of(©)?, &me) { + None => Ok(file), + Some(problem) => Err(std::io::Error::other(problem)), + } + }); + match checked { + Ok(file) => { + prepared().push((std::thread::current().id(), path.to_path_buf(), copy.clone(), file)); + PreparedCopy(Some(copy)) + } + Err(e) => { + let _ = std::fs::remove_file(©); + log::warn!("a prepared copy of the account list is not this user's alone ({e}); it was removed"); + PreparedCopy(None) + } + } } diff --git a/crates/suite-account/src/lock.rs b/crates/suite-account/src/lock.rs index 160ff3e3c8..6a95e6bd2a 100644 --- a/crates/suite-account/src/lock.rs +++ b/crates/suite-account/src/lock.rs @@ -49,6 +49,8 @@ fn open_lock_file(path: &Path) -> io::Result { /// [`Error::Io`]; `f` may return any [`Error`]. pub(crate) fn with_lock(path: &Path, f: impl FnOnce() -> Result) -> Result { let lock = open_lock_file(path).map_err(|e| Error::Io(format!("couldn't open the lock beside {} ({e})", path.display())))?; + #[cfg(windows)] + let _prepared = crate::accounts::prepare(path); let start = Instant::now(); loop { match lock.try_lock() { diff --git a/crates/suite-account/src/tests.rs b/crates/suite-account/src/tests.rs index c1a614aab4..045a2065ee 100644 --- a/crates/suite-account/src/tests.rs +++ b/crates/suite-account/src/tests.rs @@ -521,6 +521,159 @@ fn write_leaves_a_previously_good_file_untouched_when_the_new_one_is_too_large() assert_eq!(accounts::read(&path).unwrap(), good, "the earlier, readable file must still be exactly what was there before"); } +/// A portable install or `ARTCRAFT_SUITE_DIR` can put the list in a folder that lets every local +/// user read the files created in it, as a new folder at a drive root does. The list written there +/// has an access list of its user and SYSTEM only. +#[cfg(windows)] +#[test] +fn the_list_in_a_folder_users_can_read_is_still_this_users_alone() { + use craft_platform::owner_only; + let dir = tempfile::tempdir().unwrap(); + let granted = std::process::Command::new("icacls").arg(dir.path()).arg("/grant").arg("*S-1-5-32-545:(OI)(CI)R").output().unwrap(); + assert!(granted.status.success(), "{}", String::from_utf8_lossy(&granted.stderr)); + let path = dir.path().join(paths::FILE); + let list = + accounts::Accounts { format: accounts::FORMAT, accounts: vec![account_at("a", 0)], active: Some("a".to_owned()), tombstones: Vec::new() }; + + accounts::write(&path, &list).unwrap(); + + let me = owner_only::current_user_sid().unwrap(); + let sddl = owner_only::sddl_of(&path).unwrap(); + assert!(!sddl.contains(";BU)") && !sddl.contains(";S-1-5-32-545)"), "Users must not inherit read access: {sddl}"); + assert_eq!(owner_only::foreign_access(&sddl, &me), None, "{sddl}"); + assert_eq!(accounts::read(&path).unwrap(), list); + // A second write, through a copy prepared before the lock as a `Store` does, leaves no copy behind. + let _copy = accounts::prepare(&path); + accounts::write(&path, &list).unwrap(); + assert_eq!(owner_only::foreign_access(&owner_only::sddl_of(&path).unwrap(), &me), None); + let names: Vec<_> = std::fs::read_dir(dir.path()).unwrap().map(|e| e.unwrap().file_name()).collect(); + assert_eq!(names, [std::ffi::OsString::from(paths::FILE)], "no temporary file is left behind"); +} + +/// The list's access list is protected: a change to its folder's access list, which Windows hands +/// down to the files in the folder that inherit from it, does not reach the list, whether the list +/// was written directly or through a `Store`. +#[cfg(windows)] +#[test] +fn a_change_to_the_folders_access_list_does_not_reach_the_list() { + use craft_platform::owner_only; + let me = owner_only::current_user_sid().unwrap(); + for through_store in [false, true] { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join(paths::FILE); + if through_store { + let store = Store::at(Some(dir.path().to_path_buf()), Memory::new()); + store.sign_in(&new_account(), &Secret::new(TOKEN), NOW).unwrap(); + } else { + let list = accounts::Accounts { + format: accounts::FORMAT, + accounts: vec![account_at("a", 0)], + active: Some("a".to_owned()), + tombstones: Vec::new(), + }; + accounts::write(&path, &list).unwrap(); + } + + let granted = std::process::Command::new("icacls").arg(dir.path()).arg("/grant").arg("*S-1-5-32-545:(OI)(CI)R").output().unwrap(); + assert!(granted.status.success(), "{}", String::from_utf8_lossy(&granted.stdout)); + + let sddl = owner_only::sddl_of(&path).unwrap(); + assert_eq!(owner_only::foreign_access(&sddl, &me), None, "through a Store: {through_store}; {sddl}"); + } +} + +/// A prepared copy that no write took is closed and removed when its change under the lock is +/// done, as for a discard of an account that is not in the list. +#[cfg(windows)] +#[test] +fn a_prepared_copy_no_write_took_is_removed() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join(paths::FILE); + let copy = accounts::prepare(&path); + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1, "the copy is made"); + drop(copy); + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0, "the copy is removed"); + + let store = Store::at(Some(dir.path().to_path_buf()), Memory::new()); + store.sign_in(&new_account(), &Secret::new(TOKEN), NOW).unwrap(); + let names = || std::fs::read_dir(dir.path()).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect::>(); + let before = names(); + let _ = store.discard("no such account"); + assert_eq!(names(), before, "a change that writes nothing leaves no copy behind"); +} + +/// A write uses the copy its own thread prepared and leaves another thread's copy for that +/// thread, which would otherwise have to create one while it holds the accounts lock. +#[cfg(windows)] +#[test] +fn a_write_takes_only_the_copy_its_thread_prepared() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join(paths::FILE); + let list = + accounts::Accounts { format: accounts::FORMAT, accounts: vec![account_at("a", 0)], active: Some("a".to_owned()), tombstones: Vec::new() }; + let copies = || std::fs::read_dir(dir.path()).unwrap().map(|e| e.unwrap().path()).filter(|p| p != &path).collect::>(); + let prepared = std::sync::Barrier::new(2); + // The other thread keeps its copy until `done` is dropped, which a failed assertion does too. + let (done, wait) = std::sync::mpsc::channel::<()>(); + std::thread::scope(|scope| { + let (list_path, prepared) = (&path, &prepared); + scope.spawn(move || { + let _other = accounts::prepare(list_path); + prepared.wait(); + let _ = wait.recv(); + }); + prepared.wait(); + let other = copies(); + assert_eq!(other.len(), 1, "{other:?}"); + let _mine = accounts::prepare(&path); + accounts::write(&path, &list).unwrap(); + assert_eq!(copies(), other, "the other thread's copy is still waiting"); + drop(done); + }); + assert_eq!(copies(), Vec::::new()); +} + +/// A prepared copy is created with an access list of its user and SYSTEM only, and can't be +/// removed, renamed or replaced, nor its folder renamed, between its check and the write. An empty +/// copy that an ended process left a minute or more ago is removed by the next preparation; a +/// newer one, which another process may be about to open, is kept. +#[cfg(windows)] +#[test] +fn a_prepared_copy_is_private_and_cannot_be_swapped_before_the_write() { + use craft_platform::owner_only; + let me = owner_only::current_user_sid().unwrap(); + let root = tempfile::tempdir().unwrap(); + let dir = root.path().join("suite"); + std::fs::create_dir(&dir).unwrap(); + let granted = std::process::Command::new("icacls").arg(&dir).arg("/grant").arg("*S-1-5-32-545:(OI)(CI)R").output().unwrap(); + assert!(granted.status.success(), "{}", String::from_utf8_lossy(&granted.stdout)); + let path = dir.join(paths::FILE); + let left = dir.join(format!(".{}.1.0.prepared.tmp", paths::FILE)); + std::fs::File::create(&left).unwrap().set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(120)).unwrap(); + let fresh = dir.join(format!(".{}.2.0.prepared.tmp", paths::FILE)); + std::fs::write(&fresh, b"").unwrap(); + + let _copy = accounts::prepare(&path); + + assert!(!left.exists(), "an old empty copy that no process holds is removed"); + assert!(fresh.exists(), "a new empty copy, which another process may be about to open, is kept"); + let copies: Vec<_> = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().path()).filter(|p| *p != fresh).collect(); + assert_eq!(copies.len(), 1, "{copies:?}"); + let copy = &copies[0]; + let sddl = owner_only::sddl_of(copy).unwrap(); + assert_eq!(owner_only::foreign_access(&sddl, &me), None, "{sddl}"); + assert!(std::fs::remove_file(copy).is_err(), "the checked copy must stay in place"); + assert!(std::fs::rename(copy, dir.join("moved")).is_err(), "the checked copy must not be renamed away"); + assert!(std::fs::rename(&dir, root.path().join("moved")).is_err(), "its folder must not be renamed away"); + + let list = + accounts::Accounts { format: accounts::FORMAT, accounts: vec![account_at("a", 0)], active: Some("a".to_owned()), tombstones: Vec::new() }; + accounts::write(&path, &list).unwrap(); + assert!(!copy.exists(), "the write used the prepared copy"); + assert_eq!(accounts::read(&path).unwrap(), list); + assert_eq!(owner_only::foreign_access(&owner_only::sddl_of(&path).unwrap(), &me), None); +} + #[test] fn a_sign_in_with_an_oversized_display_name_fails_without_bricking_the_list() { let dir = tempfile::tempdir().unwrap(); From c89a2a844f98823582e771c553b77d56143abb5f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 14:07:30 -0800 Subject: [PATCH 06/87] platform: owner_only creates a private folder with its access list and checks inherit-only entries create_private_dir created the folder with create_dir and set its access list afterwards, so for a moment the folder carried its parent's list. It now creates the folder under a name of its own with the user as owner and the user and SYSTEM as its only entries (Directory.CreateDirectory with a DirectorySecurity), then moves it to the path with Directory.Move, which fails when the path exists. A missing parent is NotFound; a relative path is made absolute first. When PowerShell is ended, the folder under its own name is removed once PowerShell has exited. sddl_of read a folder through File.GetAccessControl, which leaves out inherit-only entries, so a folder check could miss an entry that every new file inherits. It now reads a folder through Directory.GetAccessControl, and the check after create_private_dir counts inherit-only entries. foreign_access still skips them for files. --- crates/platform/README.md | 2 +- crates/platform/src/owner_only.rs | 203 +++++++++++++++++++++++------- 2 files changed, 157 insertions(+), 48 deletions(-) diff --git a/crates/platform/README.md b/crates/platform/README.md index a8377d927d..e7d1e8afae 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`. A run of a tool that takes longer than `TOOL_LIMIT` (10 s) is ended, and the call fails with `ErrorKind::TimedOut`. | +| always (native) | `owner_only`: files only their user can read on Windows, as mode `0600` makes them on Unix. `restrict_to_owner` gives a file an access list of the user and SYSTEM only, `create_private_dir` and `create_private_file` create a folder or 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 6f18c9a798..fcfdad684e 100644 --- a/crates/platform/src/owner_only.rs +++ b/crates/platform/src/owner_only.rs @@ -4,8 +4,8 @@ //! a new folder at a drive root, `C:\Users\Public` or `C:\ProgramData` let every signed-in user //! read what is created in them. `restrict_to_owner` replaces the whole list with the current //! user and SYSTEM only, makes that user the owner, and checks the result. `create_private_dir` -//! does the same for a new folder whose list the files created in it inherit, so a file can be -//! private from the moment it exists. `read_with_sddl` reads a file and its security descriptor +//! creates a folder with that owner and list from the start, which the files created in it +//! inherit, so a file can be private from the moment it exists. `read_with_sddl` reads a file and its security descriptor //! 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 @@ -23,6 +23,18 @@ /// file over. `restrict_to_owner` never grants it, so the app's own file always passes; a file /// that inherited it from a user's folder is refused. pub fn foreign_access(sddl: &str, me: &str) -> Option { + foreign(sddl, me, false) +} + +/// [`foreign_access`] for a folder's descriptor: an inherit-only entry (`IO`) counts too, since +/// every file and folder created in the folder gets it. +#[cfg(any(test, windows))] +fn foreign_folder_access(sddl: &str, me: &str) -> Option { + foreign(sddl, me, true) +} + +/// [`foreign_access`], counting inherit-only entries when `inherit_only` is set. +fn foreign(sddl: &str, me: &str, inherit_only: bool) -> Option { let me = me.trim(); let owner = section(sddl, "O:"); match owner { @@ -43,7 +55,7 @@ pub fn foreign_access(sddl: &str, me: &str) -> Option { let (Some(kind), Some(flags)) = (parts.first(), parts.get(1)) else { continue }; // Deny entries take access away, and inherit-only entries apply to children, not the file. let allows = matches!(*kind, "A" | "OA" | "XA" | "ZA"); - if !allows || flags.contains("IO") { + if !allows || (flags.contains("IO") && !inherit_only) { continue; } // An entry that grants access but names no account can't be shown to be the user's. @@ -297,32 +309,87 @@ fn sid_from_whoami(text: &str) -> Option { /// replace it, while setting the owner needs the Full control it grants (a folder may give Modify). #[cfg(windows)] pub fn restrict_to_owner(path: &std::path::Path, me: &str) -> std::io::Result<()> { - set_access_list(path, me, Kind::File)?; + set_access_list(path, me)?; icacls(path, &["/setowner".into(), format!("*{me}")])?; still_foreign(&sddl_of(path)?, me) } -/// Create the folder `dir`, which must not exist yet, and give it an access list of user `me` (as -/// for [`restrict_to_owner`]) and SYSTEM only, which every file created in it inherits; then make -/// that user its owner and check the result as [`restrict_to_owner`] does. A file created in it is -/// private from the moment it exists. Restricting a file after creating it leaves a window in which another user -/// whom the parent folder lets read it can open a handle, and Windows checks access only when a -/// handle is opened, so a later change of the list doesn't revoke it. A handle on the folder -/// itself, opened during the folder's own window, gives no access to the files created in it -/// later. The folder is removed again when it can't be restricted. +/// Create the folder `dir`, which must not exist yet and whose parent must, with user `me` (as for +/// [`restrict_to_owner`]) as its owner and an access list of that user and SYSTEM only, which every +/// file created in it inherits, given to Windows in the call that creates the folder. The folder +/// never has its parent's access list, and a file created in it is private from the moment it +/// exists. The folder is created beside `dir` under a name of its own +/// (`....tmp`) and then moved to `dir`, which fails when `dir` exists. +/// Then check its descriptor, inherit-only entries included. An existing `dir` is an error of kind +/// [`std::io::ErrorKind::AlreadyExists`] and a missing parent one of kind +/// [`std::io::ErrorKind::NotFound`]; the folder is removed again when the check fails. +/// +/// PowerShell is ended when it takes longer than [`TOOL_LIMIT`], and the call fails with an error +/// of kind [`std::io::ErrorKind::TimedOut`]; the folder under its own name is then removed once +/// PowerShell has exited. A folder PowerShell had already moved to `dir` stays there, with the +/// access list it was created with: this call can't tell it from a folder another process put at +/// `dir` since, so it doesn't remove what is there. #[cfg(windows)] pub fn create_private_dir(dir: &std::path::Path, me: &str) -> std::io::Result<()> { - std::fs::create_dir(dir)?; - fn restrict(dir: &std::path::Path, me: &str) -> std::io::Result<()> { - set_access_list(dir, me, Kind::Folder)?; - icacls(dir, &["/setowner".into(), format!("*{me}")])?; - still_foreign(&sddl_of(dir)?, me) + use std::sync::atomic::{AtomicU64, Ordering}; + /// Numbers the staged folders of this process. + static COUNT: AtomicU64 = AtomicU64::new(0); + // No double quotes: the command line would strip them. `Directory.CreateDirectory` also creates + // a missing parent and returns an existing folder as it is, hence the checks before it. + // `Directory.Move` doesn't replace an existing folder (`std::fs::rename` does, when it is + // empty). + const SCRIPT: &str = "$ErrorActionPreference = 'Stop'; \ + if (Test-Path -LiteralPath $env:CRAFT_ACL_PATH) { exit 3 }; \ + if (-not [IO.Directory]::Exists([IO.Path]::GetDirectoryName($env:CRAFT_ACL_PATH))) { exit 4 }; \ + if (Test-Path -LiteralPath $env:CRAFT_ACL_STAGED) { exit 5 }; \ + $s = New-Object Security.AccessControl.DirectorySecurity; \ + $s.SetSecurityDescriptorSddlForm('O:' + $env:CRAFT_ACL_USER + 'D:P(A;OICI;FA;;;' + $env:CRAFT_ACL_USER + ')(A;OICI;FA;;;SY)'); \ + [void][IO.Directory]::CreateDirectory($env:CRAFT_ACL_STAGED, $s); \ + try { [IO.Directory]::Move($env:CRAFT_ACL_STAGED, $env:CRAFT_ACL_PATH) } \ + catch { [IO.Directory]::Delete($env:CRAFT_ACL_STAGED); if (Test-Path -LiteralPath $env:CRAFT_ACL_PATH) { exit 3 }; throw }"; + // A relative `dir` such as `private` has no parent in its text; the script needs one. + let dir = &std::path::absolute(dir)?; + let name = dir.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + let staged = dir.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", dir) + .env("CRAFT_ACL_STAGED", &staged) + .env("CRAFT_ACL_USER", me); + let deadline = std::time::Instant::now() + TOOL_LIMIT; + let close = |stdin: std::process::ChildStdin| { + drop(stdin); + Ok(()) + }; + let out = match run_until(powershell, close, |_| std::time::Instant::now() >= deadline)? { + Ran::Exited(out, _) => out, + Ran::Ended { exited } => { + if exited { + let _ = std::fs::remove_dir(&staged); + } + return Err(timed_out("powershell.exe")); + } + }; + match out.status.code() { + Some(3) => return Err(std::io::Error::new(std::io::ErrorKind::AlreadyExists, "the folder already exists")), + Some(4) => return Err(std::io::Error::new(std::io::ErrorKind::NotFound, "the folder's parent does not exist")), + _ if !out.status.success() => { + return Err(std::io::Error::other(format!( + "PowerShell could not create the folder for its owner only: {}", + String::from_utf8_lossy(&out.stderr).trim() + ))); + } + _ => {} } - let restricted = restrict(dir, me); - if restricted.is_err() { + let checked = sddl_of(dir).and_then(|sddl| match foreign_folder_access(&sddl, me) { + None => Ok(()), + Some(problem) => Err(std::io::Error::other(format!("the folder could not be restricted to its owner: {problem}"))), + }); + if checked.is_err() { let _ = std::fs::remove_dir(dir); } - restricted + checked } /// Create the file `path`, which must not exist yet, with user `me` (as for [`restrict_to_owner`]) @@ -338,8 +405,9 @@ pub fn create_private_dir(dir: &std::path::Path, me: &str) -> std::io::Result<() /// /// 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. +/// PowerShell is not seen to exit after being ended, that file may stay, and a file PowerShell had +/// already moved to `path` stays there: this call can't tell it from a file another process put at +/// `path` since. Either 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 _; @@ -424,34 +492,17 @@ fn still_foreign(sddl: &str, me: &str) -> std::io::Result<()> { } } -/// What [`set_access_list`] restricts: a file, or a folder whose entries the files and folders -/// created in it inherit. +/// Set file `path`'s access list to Full control for `me` and SYSTEM and nothing else, protected +/// from inheritance. Only the list is written, not the owner. `me` and the path reach PowerShell +/// through environment variables, never as script text. #[cfg(windows)] -#[derive(Clone, Copy)] -enum Kind { - File, - Folder, -} - -/// Set `path`'s access list to Full control for `me` and SYSTEM and nothing else, protected from -/// inheritance; on a folder, what is created in it inherits the two entries. Only the list is -/// written, not the owner. `me` and the path reach PowerShell through environment variables, never -/// as script text. -#[cfg(windows)] -fn set_access_list(path: &std::path::Path, me: &str, kind: Kind) -> std::io::Result<()> { +fn set_access_list(path: &std::path::Path, me: &str) -> std::io::Result<()> { // No double quotes: the command line would strip them. - const FILE: &str = "$s = New-Object Security.AccessControl.FileSecurity; \ + const SCRIPT: &str = "$s = New-Object Security.AccessControl.FileSecurity; \ $s.SetSecurityDescriptorSddlForm('D:P(A;;FA;;;' + $env:CRAFT_ACL_USER + ')(A;;FA;;;SY)', 'Access'); \ [IO.File]::SetAccessControl($env:CRAFT_ACL_PATH, $s)"; - const FOLDER: &str = "$s = New-Object Security.AccessControl.DirectorySecurity; \ - $s.SetSecurityDescriptorSddlForm('D:P(A;OICI;FA;;;' + $env:CRAFT_ACL_USER + ')(A;OICI;FA;;;SY)', 'Access'); \ - [IO.Directory]::SetAccessControl($env:CRAFT_ACL_PATH, $s)"; - let script = match kind { - Kind::File => FILE, - Kind::Folder => FOLDER, - }; let mut powershell = system_tool(POWERSHELL); - powershell.args(["-NoProfile", "-NonInteractive", "-Command", script]).env("CRAFT_ACL_PATH", path).env("CRAFT_ACL_USER", me); + 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(()) @@ -512,12 +563,15 @@ pub fn read_with_sddl(path: &std::path::Path, max: u64) -> std::io::Result<(Stri /// The security descriptor of `path` as [`read_with_sddl`] writes it, read by name without opening /// the file's contents, so it works on a file that is open for writing (an app restricts its -/// token file before writing the token through the handle it created). +/// token file before writing the token through the handle it created). A folder is read as a +/// folder, so its inherit-only entries are included (`IO`); a file's reading leaves them out. #[cfg(windows)] pub fn sddl_of(path: &std::path::Path) -> std::io::Result { const SCRIPT: &str = concat!( // Stop: a failed read (a missing file) must end the script with an error, not print `O:`. - "$ErrorActionPreference = 'Stop'; $raw = New-Object Security.AccessControl.RawSecurityDescriptor -ArgumentList @([IO.File]::GetAccessControl($env:CRAFT_ACL_PATH).GetSecurityDescriptorBinaryForm(), 0); ", + "$ErrorActionPreference = 'Stop'; $p = $env:CRAFT_ACL_PATH; \ + if ([IO.Directory]::Exists($p)) { $sec = [IO.Directory]::GetAccessControl($p) } else { $sec = [IO.File]::GetAccessControl($p) }; \ + $raw = New-Object Security.AccessControl.RawSecurityDescriptor -ArgumentList @($sec.GetSecurityDescriptorBinaryForm(), 0); ", describe_raw!(), "[Console]::Out.Write($sddl + [char]10)" ); @@ -619,6 +673,15 @@ $n = [CraftProbe.Console]::GetConsoleProcessList($ids, 256) assert!(foreign_access("D:(A;;FA;;;SY)", ME).unwrap().contains("owner")); } + /// An inherit-only entry doesn't apply to a file, but does to what's created in a folder. + #[test] + fn an_inherit_only_entry_counts_for_a_folder_only() { + let sddl = format!("O:{ME}D:(A;;FA;;;{ME})(A;IO;FR;;;BU)"); + assert_eq!(foreign_access(&sddl, ME), None, "{sddl}"); + assert!(foreign_folder_access(&sddl, ME).is_some_and(|p| p.contains("BU")), "{sddl}"); + assert_eq!(foreign_folder_access(&format!("O:{ME}D:(A;;FA;;;{ME})(A;IO;FA;;;SY)"), ME), None); + } + /// A conditional entry can hold a `:` in a string; the access list doesn't end there, so the /// entry after it is still checked. #[test] @@ -704,6 +767,52 @@ $n = [CraftProbe.Console]::GetConsoleProcessList($ids, 256) let _ = std::fs::remove_dir_all(&dir); } + /// A folder's inherit-only entries are read, and the folder check counts them: every file + /// created in the folder would get them. + #[cfg(windows)] + #[test] + fn a_folders_inherit_only_entries_are_read_and_refused() { + let dir = std::env::temp_dir().join(format!("craft-owner-only-inherit-only-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let ok = std::process::Command::new("icacls").arg(&dir).arg("/grant").arg("*S-1-5-32-545:(OI)(CI)(IO)R").output().unwrap(); + assert!(ok.status.success(), "{}", String::from_utf8_lossy(&ok.stderr)); + let sddl = sddl_of(&dir).unwrap(); + assert!(sddl.contains(";IO;") && sddl.contains(";S-1-5-32-545)"), "the inherit-only entry for Users is read: {sddl}"); + let me = current_user_sid().unwrap(); + assert!(foreign_folder_access(&sddl, &me).is_some_and(|p| p.contains("S-1-5-32-545")), "{sddl}"); + let _ = std::fs::remove_dir_all(&dir); + } + + /// `create_private_dir` gives the folder its owner and list in the call that creates it, so in + /// a folder that lets Users read what's created in it, no step leaves the new folder with that + /// entry: the folder is moved to its name only after it was created with its own list. An + /// existing name and a missing parent are refused. + #[cfg(windows)] + #[test] + fn a_private_folder_has_its_list_from_the_start() { + let dir = std::env::temp_dir().join(format!("craft-owner-only-private-dir-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let ok = std::process::Command::new("icacls").arg(&dir).arg("/grant").arg("*S-1-5-32-545:(OI)(CI)R").output().unwrap(); + assert!(ok.status.success(), "{}", String::from_utf8_lossy(&ok.stderr)); + let me = current_user_sid().unwrap(); + let private = dir.join("staging"); + let made = create_private_dir(&private, &user()); + assert!(made.is_ok(), "{made:?}"); + let folder = sddl_of(&private).unwrap(); + assert_eq!((section(&folder, "O:"), foreign_folder_access(&folder, &me)), (Some(me.as_str()), None), "{folder}"); + assert!(!folder.contains(";S-1-5-32-545)") && !folder.contains(";BU)"), "Users must not inherit read access: {folder}"); + let names: Vec<_> = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name()).collect(); + assert_eq!(names, ["staging"], "no folder is left under its own name"); + let again = create_private_dir(&private, &user()).unwrap_err(); + assert_eq!(again.kind(), std::io::ErrorKind::AlreadyExists, "{again}"); + let orphan = create_private_dir(&dir.join("missing").join("staging"), &user()).unwrap_err(); + assert_eq!(orphan.kind(), std::io::ErrorKind::NotFound, "{orphan}"); + assert!(!dir.join("missing").exists()); + let _ = std::fs::remove_dir_all(&dir); + } + /// A file created by `create_private_file` in a folder that lets Users read what's in it is the /// user's alone as soon as it exists, with nothing written to it yet; one created with contents /// holds them, and an existing file is refused and left as it is. From 1418db7abe97298700d3baed74d4e2466b093c0a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 12:03:01 -0800 Subject: [PATCH 07/87] control: a token file create that owner_only timed out takes the timed-out path owner_only now ends a whoami or PowerShell run after 10 seconds and returns ErrorKind::TimedOut. create_within treats that error, when it arrives before its own 10-second wait ends, the same as a create it stopped waiting for: a CONTROL_DIR folder gets no token and the default folder gets the file with that folder's access list. Before, the default folder returned the error and got no token file. --- crates/control/src/auth.rs | 32 ++++++++++++++++++++++++++------ 1 file changed, 26 insertions(+), 6 deletions(-) diff --git a/crates/control/src/auth.rs b/crates/control/src/auth.rs index d3cc93a358..1f3438a0fa 100644 --- a/crates/control/src/auth.rs +++ b/crates/control/src/auth.rs @@ -143,7 +143,7 @@ impl App { /// Write `token` to `path`, readable and writable only by the user: the folder is made `0700` /// and the file `0600` on Unix; on Windows the file is created with an access list of the user /// and SYSTEM only and the token is written through the handle that created it - /// ([`create_for_user`]), so the file never has its folder's access list. A file left by an + /// (`create_for_user`), so the file never has its folder's access list. A file left by an /// earlier launch is replaced. The process file beside it ([`pid_path`]) records this process, /// best effort. pub fn write_token_file(&self, path: &Path, token: &str) -> Result<()> { @@ -369,7 +369,7 @@ fn held_by_another(path: &Path, token: &str) -> bool { /// Create `path`, which must not exist yet, holding `contents`: mode `0600` on Unix. On Windows a /// file created this way has its folder's access list; the token file there is made by -/// [`create_for_user`]. +/// `create_for_user`. fn create_new_file(path: &Path, contents: &[u8]) -> Result<()> { let mut opts = std::fs::OpenOptions::new(); opts.write(true).create_new(true); @@ -423,8 +423,9 @@ fn not_waited_for(path: &Path, contents: &[u8], custom_folder: bool) -> Result<( /// (`....tmp`), and the file takes the name `path` only once `private` /// has finished, so `path` never holds a file that is still being written: with `replace` by a /// rename that replaces a file another launch put there meanwhile, otherwise by [`place_new`], -/// which leaves that file and fails. When -/// the thread hasn't finished in time, [`not_waited_for`] gives the result, the thread removes its +/// which leaves that file and fails. When `private` fails with [`ErrorKind::TimedOut`] (a tool +/// `craft_platform::owner_only` ended after its own limit), [`not_waited_for`] gives the result. +/// When the thread hasn't finished in time, [`not_waited_for`] gives the result, the thread removes its /// file whenever it does finish, and `stuck` counts it until then. While `stuck` counts any /// thread, no other thread is started and [`not_waited_for`] answers at once, so a computer that /// leaves new processes suspended holds at most the threads that were started together. The @@ -484,7 +485,11 @@ fn create_within( } } }; - let placed = made.and_then(|()| if replace { std::fs::rename(&staged, path) } else { place_new(&staged, path) }); + let placed = match made { + // `owner_only` ended a tool that ran out of its own time: the same as not waiting. + Err(e) if e.kind() == ErrorKind::TimedOut => not_waited_for(path, contents, custom_folder), + made => made.and_then(|()| if replace { std::fs::rename(&staged, path) } else { place_new(&staged, path) }), + }; let _ = std::fs::remove_file(&staged); (placed, Some(handle)) } @@ -529,7 +534,7 @@ mod tests { /// finishes and never takes the token file's name, even when a later write has put a file /// there. While it runs, the next create starts no thread of its own. A create that finishes in /// time puts its file in place unless a file already has the name, and one that fails leaves - /// nothing. + /// nothing. A create that fails as timed out by itself is taken as one not waited for. #[test] fn a_private_create_that_does_not_finish_in_time_is_not_waited_for() { use std::sync::atomic::{AtomicUsize, Ordering}; @@ -594,6 +599,21 @@ mod tests { assert!(made.is_err()); handle.unwrap().join().unwrap(); assert_eq!(names(), ["quick.token"]); + // A create whose tool was ended after its own limit, within this one, is taken as one + // that was not waited for. + let ended = + |_: &Path, _: &[u8]| -> Result<()> { Err(Error::new(ErrorKind::TimedOut, "powershell.exe did not finish within 10 s and was ended")) }; + let path = dir.join("ended.token"); + let (made, handle) = create_within(&path, b"ended\n", true, false, Duration::from_secs(600), &STUCK, ended); + assert_eq!(made.unwrap_err().kind(), ErrorKind::TimedOut); + handle.unwrap().join().unwrap(); + assert_eq!(names(), ["quick.token"]); + let (made, handle) = create_within(&path, b"ended\n", false, false, Duration::from_secs(600), &STUCK, ended); + made.unwrap(); + handle.unwrap().join().unwrap(); + assert_eq!(names(), ["ended.token", "quick.token"]); + assert_eq!(read_token(&path).as_deref(), Some("ended")); + assert_eq!(STUCK.load(Ordering::Acquire), 0); let _ = std::fs::remove_dir_all(&dir); } From 3a0f4565281cb3edca7949399dfaca2c4895c9e6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 17:31:10 -0800 Subject: [PATCH 08/87] color-ui: HarmonyPanel's variation end labels sit at the two edges of the grid The row under the variations grid holds the two end labels (Shades and Tints, Cool and Warm, Muted and Vivid). It is aligned SpaceBetween but was not made full width, so it was only as wide as its two labels and they sat together at the left. The row now fills the panel's width: the left label starts at the grid's left edge and the right label ends at its right edge. --- crates/color-ui/src/ui/harmony.rs | 2 +- crates/color-ui/tests/it/panels.rs | 21 +++++++++++++++++++-- 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/crates/color-ui/src/ui/harmony.rs b/crates/color-ui/src/ui/harmony.rs index a153276ada..254d30f628 100644 --- a/crates/color-ui/src/ui/harmony.rs +++ b/crates/color-ui/src/ui/harmony.rs @@ -522,7 +522,7 @@ impl<'a> HarmonyPanel<'a> { Variation::WarmCool => (&words.cool, &words.warm), Variation::VividMuted => (&words.muted, &words.vivid), }; - Row::new().align(RowAlign::SpaceBetween).show(ui, |ui, _| { + Row::new().fill_width().align(RowAlign::SpaceBetween).show(ui, |ui, _| { Text::new(left.clone()).show(ui); Text::new(right.clone()).show(ui); }); diff --git a/crates/color-ui/tests/it/panels.rs b/crates/color-ui/tests/it/panels.rs index 840a36c56a..c915848cd9 100644 --- a/crates/color-ui/tests/it/panels.rs +++ b/crates/color-ui/tests/it/panels.rs @@ -7,8 +7,9 @@ use std::rc::Rc; use craft_behavior::{EditEvent, Mixed, Selection}; use craft_color_ui::palette::{SwatchColor, SwatchGroup}; use craft_color_ui::ui::{ - ColorPanel, ColorPanelLayout, ColorPanelMode, ColorPanelShown, ColorPanelState, HarmonyWheel, PanelTarget, PickedColor, SwatchEdit, SwatchKey, - SwatchLibrary, SwatchPalette, SwatchesCommand, SwatchesMenu, SwatchesPanel, SwatchesState, SwatchesWords, swatch_rows, + ColorPanel, ColorPanelLayout, ColorPanelMode, ColorPanelShown, ColorPanelState, HarmonyPanel, HarmonyPanelState, HarmonyPicked, HarmonyWheel, + PanelTarget, PickedColor, SwatchEdit, SwatchKey, SwatchLibrary, SwatchPalette, SwatchesCommand, SwatchesMenu, SwatchesPanel, SwatchesState, + SwatchesWords, swatch_rows, }; use craft_host::target::Os; use craft_theme::{ColorModel as _, HsbModel, Srgba}; @@ -768,3 +769,19 @@ fn a_click_on_a_harmony_wheel_marker_reports_it() { fixture.click(&marker).idle(1); assert_eq!(clicked.get(), Some(Some(1)), "the click names the second marker"); } + +/// The Color Guide's variation end labels sit at the two sides of the grid: Shades at its left edge and Tints at its +/// right edge. +#[trial] +fn the_color_guide_end_labels_sit_at_the_two_sides_of_the_grid() { + let mut fixture = Fixture::new(|ui| { + let (mut state, mut picked) = (HarmonyPanelState::default(), HarmonyPicked::default()); + let _ = HarmonyPanel::new(Bind::bound(&mut state), Bind::bound(&mut picked), RED).show(ui); + }); + fixture.room(COLOR_ROOM).settle(); + let grid = fixture.by_label("Variations").expect("the variations grid").rect; + let run = |text: &str| fixture.texts().iter().find(|run| run.text == text).map(|run| run.rect).unwrap_or_else(|| panic!("{text} is painted")); + let (shades, tints) = (run("Shades"), run("Tints")); + assert!(shades.left() <= grid.left() + 1.0 && shades.right() < grid.center().x, "Shades {shades:?} starts at the left edge of {grid:?}"); + assert!(tints.right() >= grid.right() - 1.0 && tints.left() > grid.center().x, "Tints {tints:?} ends at the right edge of {grid:?}"); +} From 6642934ce68542c46ef6f42bd015c5ca184d26a0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 17:33:33 -0800 Subject: [PATCH 09/87] color-ui: the FillStroke Color panel shows its Recent Colors caption while the host's list is empty, as production drew the labeled empty row; a host that gives no recent colors (ColorPanel::recent not called) still shows no row --- crates/color-ui/src/ui/panel.rs | 11 ++++++----- crates/color-ui/src/ui/panel/fill_stroke.rs | 14 +++++++++---- crates/color-ui/tests/it/panels.rs | 22 +++++++++++++++++++++ 3 files changed, 38 insertions(+), 9 deletions(-) diff --git a/crates/color-ui/src/ui/panel.rs b/crates/color-ui/src/ui/panel.rs index 90c92271b2..d79e86cf93 100644 --- a/crates/color-ui/src/ui/panel.rs +++ b/crates/color-ui/src/ui/panel.rs @@ -448,7 +448,7 @@ pub struct ColorPanel<'a> { wells: Option<([PairWell; 2], Bind<'a, Well>)>, edited: Option>, shown: Option, - recent: &'a [Srgba], + recent: Option<&'a [Srgba]>, recent_setup: Option, gamut: Option>, } @@ -471,7 +471,7 @@ struct Inputs<'a> { wells: Option<&'a [PairWell; 2]>, edited: Option<&'a Option>, shown: &'a ColorPanelShown, - recent: &'a [Srgba], + recent: Option<&'a [Srgba]>, recent_setup: Option<&'a RecentSetup>, } @@ -488,7 +488,7 @@ impl<'a> ColorPanel<'a> { wells: None, edited: None, shown: None, - recent: &[], + recent: None, recent_setup: None, gamut: None, } @@ -541,9 +541,10 @@ impl<'a> ColorPanel<'a> { self } - /// The Recent Colors, a spaced `SwatchPalette` that wraps and drags. + /// The Recent Colors, a spaced `SwatchPalette` that wraps and drags. The FillStroke layout shows the captioned row + /// for a host that gives them, an empty list included; without them it shows no row. pub fn recent(mut self, colors: &'a [Srgba]) -> Self { - self.recent = colors; + self.recent = Some(colors); self } diff --git a/crates/color-ui/src/ui/panel/fill_stroke.rs b/crates/color-ui/src/ui/panel/fill_stroke.rs index a3ff66c160..483f690885 100644 --- a/crates/color-ui/src/ui/panel/fill_stroke.rs +++ b/crates/color-ui/src/ui/panel/fill_stroke.rs @@ -6,10 +6,11 @@ use craft_behavior::{EditEvent, Mixed}; use craft_theme::Srgba; use craft_ui::choice::{Swatch, SwatchSpacing}; use craft_ui::contract::{Bind, Gap, LabelScheme, Props as _, Scroll, Show as _, ShowContainer as _, Sizing}; -use craft_ui::display::Text; +use craft_ui::display::{Shade, Text}; use craft_ui::form::{Field, FieldGroup}; use craft_ui::layout_components::{Row, Stack}; use craft_ui::runtime::env::Label; +use craft_ui::style::TypeRole; use craft_ui::text::{HexField, TextField}; use egui::Ui; @@ -154,14 +155,19 @@ impl Body<'_> { } } - /// The Recent Colors as a spaced palette; a pick sets the colour. + /// The Recent Colors caption over a spaced palette; a pick sets the color. The caption shows while the host's list + /// is empty, where the first applied color will go. // PLAN: Alt on a recent colour or a warning chip should set the other colour; `SwatchPaletteOutput` and // `ColorWarningChipOutput` report no modifiers (color-w1 for the palette, the owner of warning.rs for the chip). fn recent(&mut self, ui: &mut Ui) { - if self.inputs.recent.is_empty() { + let Some(recent) = self.inputs.recent else { + return; + }; + Text::new(self.words.recent_colors.clone()).role(TypeRole::Caption).shade(Shade::Faint).show(ui); + if recent.is_empty() { return; } - let swatches: Vec<(Label, Srgba)> = self.inputs.recent.iter().map(|color| (Label::from(color.to_hex()), *color)).collect(); + let swatches: Vec<(Label, Srgba)> = recent.iter().map(|color| (Label::from(color.to_hex()), *color)).collect(); let mut current = self.color(); let mut palette = SwatchPalette::new(self.words.recent_colors.clone(), Bind::bound(&mut current), &swatches).spacing(SwatchSpacing::Spaced); if let Some(setup) = self.inputs.recent_setup { diff --git a/crates/color-ui/tests/it/panels.rs b/crates/color-ui/tests/it/panels.rs index 840a36c56a..1a2f359245 100644 --- a/crates/color-ui/tests/it/panels.rs +++ b/crates/color-ui/tests/it/panels.rs @@ -408,6 +408,28 @@ fn the_other_cell_files_a_request_at_the_colour_and_a_recent_pick_sets_it() { assert_eq!(taken.picked.iter().map(|c| c.to_rgba()).collect::>(), [swatch("Violet").to_rgba()], "and still reports the pick"); } +/// The FillStroke layout shows its Recent Colors caption while the host's list is empty, as it does with colors in +/// it; a host that gives no recent colors gets no row. +#[trial] +fn a_fill_stroke_panel_shows_its_recent_colors_row_while_the_list_is_empty() { + let caption = |recent: Option<&'static [Srgba]>| { + let mut fixture = Fixture::new(move |ui| { + let mut state = ColorPanelState::default(); + let panel = ColorPanel::new(Bind::bound(&mut state), [RED, BLUE]).layout(ColorPanelLayout::FillStroke); + let _ = match recent { + Some(colors) => panel.recent(colors), + None => panel, + } + .show(ui); + }); + fixture.room(COLOR_ROOM).settle(); + fixture.texts().iter().any(|run| run.text == "Recent Colors") + }; + assert!(caption(Some(&[])), "an empty list shows the row's caption"); + assert!(caption(Some(&RECENT)), "a list with a color shows it"); + assert!(!caption(None), "a host with no recent colors shows no row"); +} + /// A palette over a colour that may be none, bound to no colour: no swatch is selected and Tab enters on the first; /// a click writes `Same(Some(colour))` and reports one `Set` from `Mixed`. #[trial] From ccf616d1f988a00801b1fc58a7ab18121f689699 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 17:29:48 -0800 Subject: [PATCH 10/87] color-ui: the FillStroke Color panel's Spectrum ramp is at least as tall as its two square end boxes (ColorRamp::square_boxes, 40 pt in Compact), near production's 46 pt floor, instead of a 10 pt band in a panel sized by its content --- crates/color-ui/src/ui/panel/fill_stroke.rs | 5 ++-- crates/color-ui/src/ui/ramp.rs | 16 ++++++++-- crates/color-ui/tests/it/panels.rs | 33 ++++++++++++++++++++- 3 files changed, 49 insertions(+), 5 deletions(-) diff --git a/crates/color-ui/src/ui/panel/fill_stroke.rs b/crates/color-ui/src/ui/panel/fill_stroke.rs index a3ff66c160..3b915e793f 100644 --- a/crates/color-ui/src/ui/panel/fill_stroke.rs +++ b/crates/color-ui/src/ui/panel/fill_stroke.rs @@ -131,8 +131,8 @@ impl Body<'_> { } } - /// The Spectrum ramp (grey in Grayscale) with a tooltip naming the shown mode. A Cmd or Ctrl click recolours and - /// picks nothing; a Shift click moves to the next mode. + /// The Spectrum ramp (gray in Grayscale) with a tooltip naming the shown mode, at least as tall as its square end + /// boxes. A Cmd or Ctrl click recolors and picks nothing; a Shift click moves to the next mode. fn spectrum(&mut self, ui: &mut Ui) { let mode = self.shown_mode(); let kind = if mode == ColorPanelMode::GrayscaleSlider { RampKind::Grayscale } else { RampKind::Spectrum }; @@ -145,6 +145,7 @@ impl Body<'_> { .gamut(gamut) .gamut_revision(revision) .web_safe(self.now.web_safe_ramp) + .square_boxes(true) .sizing(Sizing::Fill) .show(ui); self.ramp_events(ramp.edit.events); diff --git a/crates/color-ui/src/ui/ramp.rs b/crates/color-ui/src/ui/ramp.rs index 2a01579348..e541695543 100644 --- a/crates/color-ui/src/ui/ramp.rs +++ b/crates/color-ui/src/ui/ramp.rs @@ -6,8 +6,8 @@ use craft_cms::convert::CmykConverter; use craft_theme::{Hsb, Srgba}; use craft_ui::canvas::context_click; use craft_ui::contract::{ - Access, Bind, BindMut, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, Focus as _, Input, Name, Outcome, PaintUi, PartsCx, - Pointer as _, Props as _, Remember as _, Role, WordSetCx as _, + Access, Bind, BindMut, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, Focus as _, Input, MeasureCx, Name, Outcome, PaintUi, + PartsCx, Pointer as _, Props as _, Remember as _, Role, WordSetCx as _, }; use craft_ui::primitives::{Marker, PaintShape, StrokeWidth}; use craft_ui::runtime::commands::FireSource; @@ -240,6 +240,11 @@ pub struct ColorRamp<'a> { /// Whether the white and black boxes follow the bar; on by default. #[prop] boxes: bool, + /// Whether the ramp is at least as tall as its two end boxes stacked, each as tall as it is wide, in place of a + /// color band; off by default. A ramp that takes the room under other rows keeps this height in a host sized by + /// its content and in a short one. + #[prop] + square_boxes: bool, /// The ramp's kind as the host names it ("RGB Spectrum"), the bar's accessible value. #[prop(into)] kind_name: Option