mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-26 02:09:00 +00:00
pdf-shell-w3: net change of 2 commits
- pdf-shell-w3: written by an agent - pdf-shell-w3: review fixes (review-1)
This commit is contained in:
@@ -13,7 +13,7 @@ workspace = true
|
||||
|
||||
[features]
|
||||
default = []
|
||||
appearance = ["dep:zbus", "dep:futures-lite", "dep:async-channel", "dep:async-io", "dep:async-process", "dep:web-sys"]
|
||||
appearance = ["dep:zbus", "dep:futures-lite", "dep:async-channel", "dep:async-io", "dep:async-process", "dep:web-sys", "dep:windows"]
|
||||
browser = ["dep:wasm-bindgen", "dep:js-sys", "dep:web-sys"]
|
||||
# `SystemReader::report_contrast` and `report_reduced_motion`: preferences a test sets in place of an OS source.
|
||||
testing = ["appearance"]
|
||||
@@ -67,6 +67,8 @@ sysinfo = { version = "=0.39.6", default-features = false, features = ["system"]
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
clipboard-win = { version = "5.3.1", features = ["std"], optional = true }
|
||||
xcap = { version = "=0.9.8", optional = true }
|
||||
# WinRT's `UISettings::AnimationsEnabled` for the appearance watcher's reduced motion, without `unsafe` (MIT OR Apache-2.0).
|
||||
windows = { version = "0.62", default-features = false, features = ["std", "UI_ViewManagement"], optional = true }
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
wasm-bindgen = { version = "0.2", optional = true }
|
||||
|
||||
@@ -10,19 +10,20 @@ pull in heavier dependencies.
|
||||
| always (not wasm) | `dialogs`: reserve waiting workers before eager UI-thread native picker creation; serial requests, failure delivery and completion wakeups. The backend factory belongs to the app. |
|
||||
| always | `From<appearance::Reading> for craft_theme::SystemAppearance`, so a host hands the OS answer to `Base::resolve`. |
|
||||
| `pointer` | Move the system pointer (`pointer::warp`), installed by the app as craft-ui's `Scrub::install_warp` service for a scrub's screen-edge wrap; macOS only, `false` elsewhere. |
|
||||
| `appearance` | Linux/BSD XDG desktop preference observation (colour scheme, contrast, reduced motion, button layout); browser contrast and motion media queries; owned cancellable subscriptions, bounded reads/helper capture, legacy compatibility and reconnect. |
|
||||
| `appearance` | Linux/BSD XDG desktop preference observation (colour scheme, contrast, reduced motion, GNOME's text scale, button layout); Windows' Animation effects setting as reduced motion; browser contrast and motion media queries; owned cancellable subscriptions, bounded reads/helper capture, legacy compatibility and reconnect. |
|
||||
| `browser` | Wasm download link/object URL ownership, cleanup on setup failure or abandonment, and cleanup timer registration before clicking. |
|
||||
| always | `clock::Clock`: monotonic seconds (`web-time`, so also in the browser) for animation, autosave and deadlines, with a manual mode tests set and advance; `monotonic_ms`, `unix_ms`. |
|
||||
| always | `pacing`: `FrameCap` (desktop frame-rate cap without vsync), `WindowVisibility` (shown or hidden), `WorkBudget`/`WorkSlice` (background work per call, paused or sliced while hidden). No egui. |
|
||||
| always | The app log: `log` records to standard error and `<dir>/<app>.log` with `RUST_LOG`-style filters, rotation to `.1`/`.2`, per-instance logs while another instance runs, a size cap; `logs::crash`: the panic hook, crash log, last panic for the error window, and `catch`. |
|
||||
| always | `session::Session` and `SessionKeeper`: the documents open at the last quit and where the user was in each, stored in the app's settings (serde) for a "Reopen Last Session" preference; `to_reopen` skips what is already open; a stored list longer than 64 documents is cut. No egui. |
|
||||
| `usage` | `usage::sample`: the process's resident memory and the memory it may still use (`MemorySample`, `None` when unknown), for the status readout's Scratch and Efficiency items. Linux reads `/proc`; other platforms return `None`. |
|
||||
| always | `open::FileIntake` with `IntakeSender` (the app's Apple Events and second-instance hand-over feed it): one queue for files the OS asks the app to open and files dropped on the window (`DroppedFile`, `DropTarget`: canvas, tab strip or window); `natural_cmp` and `same_file` for opening order and duplicates; `reveal` and `open_external`; the shared open-error texts. No egui. |
|
||||
| always | `open::FileIntake` with `IntakeSender` (the app's Apple Events, second-instance hand-over and web host feed it): one queue, in arrival order, for files the OS asks the app to open (`open`, as `Intake::Open`), files it asks to open for one of the app's own actions such as combining (`open_for`, as `Intake::OpenFor` with the action's name; made absolute and sorted like `open`), files that arrive as bytes with no path (`open_bytes`, as `Intake::Bytes`), and files dropped on the window (`DroppedFile`, `DropTarget`: canvas, tab strip or window). Each batch stays separate, empty input is ignored, and every sender call wakes the UI. `natural_cmp` and `same_file` for opening order and duplicates; `reveal` (on the caller's thread; on Linux and BSD it can wait up to 2 s for the file manager, so hosts run it on their `Jobs`) and `open_external` (on the web, a new tab without `window.opener`); the shared open-error texts. No egui. |
|
||||
| always | `autosave::Autosave` (the timer: which documents are due, results by revision), `recovery_dir`, `adopt_legacy_recovery` and `RecoveryStore`: the recovery folder of copies with a JSON sidecar each (`RecoveryEntry`, the fields craft-ui's `RecoveryDialog` lists), `AUTOSAVE_FAILED`. The app serializes its documents. |
|
||||
| `clipboard` | `clipboard::Clipboard` over a `ClipboardBackend`: every copy and paste goes through it, with size limits (`ClipboardLimits`, `TooLarge`), a fence that keeps synthetic (automation) input from replacing what the user copied, and `holds_ours` to tell the app's own copy from another app's. `SystemClipboard` (arboard) reads and writes text, HTML, one bitmap and copied files; `EventClipboard` is the browser's, fed from paste events (`flavors_from_event`, `copy_through_egui` with `ui`). `EventClipboard` keeps an offered paste for the pass it was offered in and counts passes itself (`EventClipboard::for_egui` uses egui's pass number), so a menu Paste in a later pass finds nothing and the app has nothing to call at the end of a pass. A write reports which flavor the backend wrote, and `holds_ours` compares that one. The web writes only the best flavor (eframe makes each copy command its own `navigator.clipboard` write, so a second replaces the first). `has` never reads or decodes: it asks Windows and macOS for the formats on offer, Wayland for the offer's MIME types (`wl-clipboard-rs`) and X11 for the `TARGETS` list (`x11rb`); a bitmap counts only as `image/png`, the one arboard reads on Linux. `ClipboardProbe` asks a second handle on a worker thread whether Paste has anything, so a slow owner never stalls a frame. Bitmaps are read as straight RGBA8, not PNG: the `BITMAP` and `RGBA8` reads return an `image/x-rgba8` flavor (width and height as little-endian `u32`s, then the pixels) and `read_image` returns `ClipboardImage`; the crate has no PNG encoder, and `SystemClipboard::decoder` takes the app's PNG decoder for writes. SVG, PDF and RTF flavors are neither written nor read by `SystemClipboard` (a write of only those fails with `Other`); a bitmap offered only as `image/jpeg` or `image/bmp` on Wayland reads as `None`. |
|
||||
| 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 | `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`). |
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Desktop colour, contrast and motion preferences and GNOME's window-button layout through the
|
||||
//! XDG Settings portal, plus the browser's contrast and motion media queries on the web.
|
||||
//! Desktop colour, contrast, motion and text-scale preferences and GNOME's window-button layout
|
||||
//! through the XDG Settings portal, Windows' animation effects setting, plus the browser's contrast
|
||||
//! and motion media queries on the web.
|
||||
//!
|
||||
//! Derived from PdfCraft's activation-safe subscription and GNOME schema fallback,
|
||||
//! CADCraft's BSD support, and ArtCraft Launcher's ReadOne/Read compatibility.
|
||||
@@ -9,7 +10,7 @@ pub use reader::{Reading, SystemReader};
|
||||
use std::{
|
||||
sync::{
|
||||
Arc, Condvar, Mutex, PoisonError,
|
||||
atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering},
|
||||
atomic::{AtomicBool, AtomicU8, AtomicU32, AtomicU64, Ordering},
|
||||
},
|
||||
time::Duration,
|
||||
};
|
||||
@@ -38,7 +39,10 @@ struct Shared {
|
||||
contrast: AtomicU8,
|
||||
/// 0 unknown, 1 animations allowed, 2 reduced motion.
|
||||
motion: AtomicU8,
|
||||
/// Raised each time the theme, contrast or reduced motion changes; layout and icon changes leave it.
|
||||
/// The text scale's `f32` bits; 0 unknown (no usable scale is 0.0).
|
||||
text_scale: AtomicU32,
|
||||
/// Raised each time the theme, contrast, reduced motion or text scale changes; layout and icon
|
||||
/// changes leave it.
|
||||
generation: AtomicU64,
|
||||
active: AtomicBool,
|
||||
/// True once the source has answered, found no answer, or been cancelled.
|
||||
@@ -51,10 +55,29 @@ struct Shared {
|
||||
/// `XDG_CURRENT_DESKTOP` names GNOME; read once when the watcher starts.
|
||||
#[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))]
|
||||
gnome: bool,
|
||||
#[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))]
|
||||
#[cfg(any(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")), windows))]
|
||||
wake: Box<dyn Fn() + Send + Sync>,
|
||||
}
|
||||
impl Shared {
|
||||
/// No answers yet. `settled` is true for a source that has nothing to wait for.
|
||||
#[cfg(any(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")), windows))]
|
||||
fn new(active: bool, settled: bool, wake: Box<dyn Fn() + Send + Sync>) -> Self {
|
||||
Shared {
|
||||
value: AtomicU8::new(0),
|
||||
contrast: AtomicU8::new(0),
|
||||
motion: AtomicU8::new(0),
|
||||
text_scale: AtomicU32::new(0),
|
||||
generation: AtomicU64::new(0),
|
||||
active: AtomicBool::new(active),
|
||||
settled: Mutex::new(settled),
|
||||
settled_changed: Condvar::new(),
|
||||
layout: Mutex::new(None),
|
||||
icons: Mutex::new(None),
|
||||
#[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))]
|
||||
gnome: is_gnome_session(&|k| std::env::var(k).ok()),
|
||||
wake,
|
||||
}
|
||||
}
|
||||
fn get(&self) -> Option<Theme> {
|
||||
match self.value.load(Ordering::Acquire) {
|
||||
1 => Some(Theme::Dark),
|
||||
@@ -83,11 +106,15 @@ impl Shared {
|
||||
(self.wake)();
|
||||
}
|
||||
}
|
||||
#[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))]
|
||||
#[cfg(any(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")), windows))]
|
||||
fn publish_code(&self, slot: &AtomicU8, code: u8) {
|
||||
if slot.swap(code, Ordering::AcqRel) == code {
|
||||
return;
|
||||
if slot.swap(code, Ordering::AcqRel) != code {
|
||||
self.changed();
|
||||
}
|
||||
}
|
||||
/// Raises the generation for a value just stored, then wakes an active host.
|
||||
#[cfg(any(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")), windows))]
|
||||
fn changed(&self) {
|
||||
self.generation.fetch_add(1, Ordering::AcqRel);
|
||||
if self.active.load(Ordering::Acquire) {
|
||||
(self.wake)();
|
||||
@@ -103,9 +130,17 @@ impl Shared {
|
||||
},
|
||||
);
|
||||
}
|
||||
#[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))]
|
||||
#[cfg(any(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")), windows))]
|
||||
fn publish_motion(&self, reduced: bool) {
|
||||
self.publish_code(&self.motion, if reduced { 2 } else { 1 });
|
||||
self.publish_code(&self.motion, motion_code(reduced));
|
||||
}
|
||||
/// `None` is no scaling: the desktop's value is out of range, or there is none.
|
||||
#[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))]
|
||||
fn publish_text_scale(&self, scale: Option<f32>) {
|
||||
let bits = scale.map_or(0, f32::to_bits);
|
||||
if self.text_scale.swap(bits, Ordering::AcqRel) != bits {
|
||||
self.changed();
|
||||
}
|
||||
}
|
||||
#[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))]
|
||||
fn publish_layout(&self, layout: String) {
|
||||
@@ -132,6 +167,11 @@ impl Shared {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The `Shared::motion` code of `reduced`.
|
||||
#[cfg(any(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")), windows))]
|
||||
fn motion_code(reduced: bool) -> u8 {
|
||||
if reduced { 2 } else { 1 }
|
||||
}
|
||||
/// An owned subscription. Dropping cancels connection setup, reads, backoff and helper capture,
|
||||
/// and waits at most 100 ms for acknowledgement. Only a finished worker is joined: an OS call
|
||||
/// or caller wake callback can block synchronously, so an exceptional unfinished worker is
|
||||
@@ -154,13 +194,23 @@ impl Watcher {
|
||||
}
|
||||
/// Start observing with explicit control over wake notifications.
|
||||
/// An inactive subscription still updates its cache. Unsupported targets and worker
|
||||
/// startup failure return `None`; browser targets never start a desktop watcher.
|
||||
/// startup failure return `None`; browser targets never start a desktop watcher. On Windows no
|
||||
/// worker runs: reduced motion is read here and again by [`Watcher::set_active`].
|
||||
pub fn start_active(active: bool, wake: impl Fn() + Send + Sync + 'static) -> Option<Self> {
|
||||
#[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))]
|
||||
{
|
||||
Self::spawn(active, wake, portal::watch)
|
||||
}
|
||||
#[cfg(not(all(unix, not(target_os = "macos"), not(target_arch = "wasm32"))))]
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let shared = Shared::new(active, true, Box::new(wake));
|
||||
// Stored without a wake: the host reads the first answer when it builds its first frame.
|
||||
if let Some(reduced) = windows::reduced_motion() {
|
||||
shared.motion.store(motion_code(reduced), Ordering::Release);
|
||||
}
|
||||
Some(Self { shared: Arc::new(shared) })
|
||||
}
|
||||
#[cfg(not(any(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")), windows)))]
|
||||
{
|
||||
let _ = (active, wake);
|
||||
None
|
||||
@@ -170,9 +220,10 @@ impl Watcher {
|
||||
pub fn current(&self) -> Option<Theme> {
|
||||
self.shared.get()
|
||||
}
|
||||
/// Rises each time the theme, [`Watcher::contrast`] or [`Watcher::reduced_motion`] changes, before the wake
|
||||
/// callback runs; a layout or icon theme change leaves it. Read the preferences again when it moved,
|
||||
/// after reading this: a value is stored before the generation rises.
|
||||
/// Rises each time the theme, [`Watcher::contrast`], [`Watcher::reduced_motion`] or
|
||||
/// [`Watcher::text_scale`] changes, before the wake callback runs; a layout or icon theme
|
||||
/// change leaves it. Read the preferences again when it moved, after reading this: a value is
|
||||
/// stored before the generation rises.
|
||||
pub fn generation(&self) -> u64 {
|
||||
self.shared.generation.load(Ordering::Acquire)
|
||||
}
|
||||
@@ -204,8 +255,9 @@ impl Watcher {
|
||||
/// without a desktop watcher.
|
||||
///
|
||||
/// It comes over the same connection as the theme, a change runs the same wake callback, and
|
||||
/// [`Watcher::wait_first`] returns after the first read of it. macOS and Windows have no
|
||||
/// watcher: reading their settings needs platform bindings, and this crate forbids `unsafe`.
|
||||
/// [`Watcher::wait_first`] returns after the first read of it. macOS has no watcher and the
|
||||
/// Windows one reads only reduced motion: their other settings need platform bindings that
|
||||
/// call `unsafe` code, which this crate forbids.
|
||||
/// On the web use `browser_contrast`.
|
||||
pub fn contrast(&self) -> Option<Contrast> {
|
||||
match self.shared.contrast.load(Ordering::Acquire) {
|
||||
@@ -216,8 +268,10 @@ impl Watcher {
|
||||
}
|
||||
/// Whether the desktop asks for reduced motion, from the portal's `org.freedesktop.appearance`
|
||||
/// `reduced-motion`, or GNOME's `org.gnome.desktop.interface` `enable-animations` (inverted)
|
||||
/// when the portal has no `reduced-motion` key. `None` until one answers, when neither key
|
||||
/// exists, and on targets without a desktop watcher.
|
||||
/// when the portal has no `reduced-motion` key; on Windows, the inverse of the Animation effects
|
||||
/// setting (`UISettings::AnimationsEnabled`), read at start and by [`Watcher::set_active`].
|
||||
/// `None` until one answers, when neither key exists or WinRT can't be asked, and on targets
|
||||
/// without a desktop watcher.
|
||||
///
|
||||
/// Wake and [`Watcher::wait_first`] behave as for [`Watcher::contrast`]. On the web use
|
||||
/// `browser_reduced_motion`.
|
||||
@@ -228,10 +282,17 @@ impl Watcher {
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// GNOME's `text-scaling-factor` through the portal (the gsettings fallback), clamped to 0.5..=3.0. A change
|
||||
/// raises the generation and wakes, as the other appearance values do. `None` where the platform does not say.
|
||||
/// GNOME's `org.gnome.desktop.interface` `text-scaling-factor` (Settings ▸ Accessibility ▸
|
||||
/// Large Text sets 1.25) through the portal, or the `gsettings` fallback when the portal has no
|
||||
/// such key. A finite value within 0.5..=3.0 is the scale; one outside that range or one that
|
||||
/// doesn't parse is no scaling and gives `None`, never a clamped value. A change raises the
|
||||
/// generation and wakes, as the other appearance values do.
|
||||
///
|
||||
/// `None` where the platform does not say: other Linux desktops, macOS, Windows and the web,
|
||||
/// which scale the whole display instead.
|
||||
pub fn text_scale(&self) -> Option<f32> {
|
||||
todo!("SH-C24")
|
||||
let bits = self.shared.text_scale.load(Ordering::Acquire);
|
||||
(bits != 0).then(|| f32::from_bits(bits))
|
||||
}
|
||||
/// Block until the first answer is known, then return it; at most `timeout`.
|
||||
///
|
||||
@@ -248,9 +309,15 @@ impl Watcher {
|
||||
self.current()
|
||||
}
|
||||
/// Enable or suppress future change notifications without stopping observation.
|
||||
/// Changing this flag does not itself wake the host or clear the cached preference.
|
||||
/// Changing this flag does not clear the cached preference. On Windows, becoming active reads
|
||||
/// reduced motion again, since the user changes it in Settings while the app is in the
|
||||
/// background; a changed answer raises the generation and wakes the host.
|
||||
pub fn set_active(&self, active: bool) {
|
||||
self.shared.active.store(active, Ordering::Release);
|
||||
#[cfg(windows)]
|
||||
if active && let Some(reduced) = windows::reduced_motion() {
|
||||
self.shared.publish_motion(reduced);
|
||||
}
|
||||
}
|
||||
#[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))]
|
||||
fn spawn<F: std::future::Future<Output = ()> + 'static>(
|
||||
@@ -258,20 +325,7 @@ impl Watcher {
|
||||
wake: impl Fn() + Send + Sync + 'static,
|
||||
source: impl FnOnce(Arc<Shared>) -> F + Send + 'static,
|
||||
) -> Option<Self> {
|
||||
let gnome = is_gnome_session(&|k| std::env::var(k).ok());
|
||||
let shared = Arc::new(Shared {
|
||||
value: AtomicU8::new(0),
|
||||
contrast: AtomicU8::new(0),
|
||||
motion: AtomicU8::new(0),
|
||||
generation: AtomicU64::new(0),
|
||||
active: AtomicBool::new(active),
|
||||
settled: Mutex::new(false),
|
||||
settled_changed: Condvar::new(),
|
||||
layout: Mutex::new(None),
|
||||
icons: Mutex::new(None),
|
||||
gnome,
|
||||
wake: Box::new(wake),
|
||||
});
|
||||
let shared = Arc::new(Shared::new(active, false, Box::new(wake)));
|
||||
let worker_shared = Arc::clone(&shared);
|
||||
let (stop, stopped) = async_channel::bounded::<()>(1);
|
||||
let (done, finished) = std::sync::mpsc::channel();
|
||||
@@ -350,3 +404,5 @@ fn is_gnome_session(var: &dyn Fn(&str) -> Option<String>) -> bool {
|
||||
|
||||
#[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))]
|
||||
mod portal;
|
||||
#[cfg(windows)]
|
||||
mod windows;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//! The XDG Settings portal: reading colour scheme, contrast, motion, button layout and icons, and watching for changes.
|
||||
//! The XDG Settings portal: reading colour scheme, contrast, motion, text scale, button layout and icons, and
|
||||
//! watching for changes.
|
||||
|
||||
use super::{Contrast, Shared, Theme};
|
||||
use futures_lite::{StreamExt, future::zip};
|
||||
@@ -16,6 +17,11 @@ const ICONS_KEY: &str = "icon-theme";
|
||||
const CONTRAST_KEY: &str = "contrast";
|
||||
const MOTION_KEY: &str = "reduced-motion";
|
||||
const ANIMATIONS_KEY: &str = "enable-animations";
|
||||
// Read on GNOME-like sessions only (`Shared::gnome`): elsewhere the schema's key holds its default
|
||||
// or a GNOME session's value, not what this desktop applies to its own text.
|
||||
const TEXT_SCALE_KEY: &str = "text-scaling-factor";
|
||||
/// The text scales applied; outside them a desktop's factor is no scaling, never clamped.
|
||||
const TEXT_SCALES: std::ops::RangeInclusive<f64> = 0.5..=3.0;
|
||||
const TIMEOUT: Duration = Duration::from_secs(2);
|
||||
|
||||
// Outer None means unknown/malformed; Some(None) is an explicit no-preference answer.
|
||||
@@ -88,6 +94,19 @@ fn decode_icons(value: &Value<'_>) -> Option<String> {
|
||||
fn icons_reply(value: &Value<'_>, legacy: bool) -> Option<String> {
|
||||
decode_icons(unwrap_legacy(value, legacy)?)
|
||||
}
|
||||
// GNOME's `text-scaling-factor`, a double. Outer `None` means malformed; `Some(None)` is a
|
||||
// factor that is not finite or outside `TEXT_SCALES`, which means no scaling.
|
||||
fn decode_text_scale(value: &Value<'_>) -> Option<Option<f32>> {
|
||||
let Value::F64(factor) = value else { return None };
|
||||
Some((factor.is_finite() && TEXT_SCALES.contains(factor)).then_some(*factor as f32))
|
||||
}
|
||||
fn text_scale_reply(value: &Value<'_>, legacy: bool) -> Option<Option<f32>> {
|
||||
decode_text_scale(unwrap_legacy(value, legacy)?)
|
||||
}
|
||||
// `gsettings get` prints the double as text (`1.25`); text that isn't a number is malformed.
|
||||
fn gsettings_text_scale(text: &str) -> Option<Option<f32>> {
|
||||
decode_text_scale(&Value::F64(text.trim().parse().ok()?))
|
||||
}
|
||||
fn combined(standard: Option<Option<Theme>>, gnome: Option<Option<Theme>>) -> Option<Option<Theme>> {
|
||||
if standard.is_none() && gnome.is_none() { None } else { Some(standard.flatten().or(gnome.flatten())) }
|
||||
}
|
||||
@@ -137,11 +156,12 @@ pub(super) struct Fallbacks {
|
||||
theme_used: bool,
|
||||
layout_used: bool,
|
||||
icons_used: bool,
|
||||
text_scale_used: bool,
|
||||
path: Option<std::ffi::OsString>,
|
||||
}
|
||||
impl Fallbacks {
|
||||
fn from_env() -> Self {
|
||||
Self { theme_used: false, layout_used: false, icons_used: false, path: std::env::var_os("PATH") }
|
||||
Self { theme_used: false, layout_used: false, icons_used: false, text_scale_used: false, path: std::env::var_os("PATH") }
|
||||
}
|
||||
async fn get(&self, schema: &str, key: &str) -> Option<String> {
|
||||
let exe = gsettings_exe(self.path.as_deref())?;
|
||||
@@ -178,6 +198,16 @@ impl Fallbacks {
|
||||
shared.publish_layout(answer);
|
||||
}
|
||||
}
|
||||
async fn text_scale(&mut self, shared: &Shared) {
|
||||
if std::mem::replace(&mut self.text_scale_used, true) || !shared.gnome {
|
||||
return;
|
||||
}
|
||||
if let Some(text) = self.get(GNOME, TEXT_SCALE_KEY).await
|
||||
&& let Some(answer) = gsettings_text_scale(&text)
|
||||
{
|
||||
shared.publish_text_scale(answer);
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(super) async fn watch(shared: Arc<Shared>) {
|
||||
let mut retry = Duration::from_secs(5);
|
||||
@@ -209,6 +239,7 @@ async fn session(shared: &Shared, fallbacks: &mut Fallbacks, connected: &mut boo
|
||||
fallbacks.theme(shared).await;
|
||||
fallbacks.layout(shared).await;
|
||||
fallbacks.icons(shared).await;
|
||||
fallbacks.text_scale(shared).await;
|
||||
return None;
|
||||
};
|
||||
watch_connection(shared, fallbacks, connected, connection).await
|
||||
@@ -248,6 +279,11 @@ impl Answers {
|
||||
shared.publish_contrast(contrast);
|
||||
}
|
||||
}
|
||||
(GNOME, TEXT_SCALE_KEY) if shared.gnome => {
|
||||
if let Some(scale) = decode_text_scale(value) {
|
||||
shared.publish_text_scale(scale);
|
||||
}
|
||||
}
|
||||
(STANDARD, MOTION_KEY) | (GNOME, ANIMATIONS_KEY) => {
|
||||
let Some(reduced) = decode_motion(namespace, value) else { return };
|
||||
if namespace == STANDARD {
|
||||
@@ -295,19 +331,25 @@ async fn watch_connection(shared: &Shared, fallbacks: &mut Fallbacks, connected:
|
||||
subscribe(&connection, rule(CONTRAST_KEY), 8).await?,
|
||||
subscribe(&connection, rule(MOTION_KEY), 8).await?,
|
||||
subscribe(&connection, rule(ANIMATIONS_KEY), 8).await?,
|
||||
subscribe(&connection, rule(TEXT_SCALE_KEY), 8).await?,
|
||||
];
|
||||
let mut owners = subscribe(&connection, owner_rule(), 8).await?;
|
||||
// Concurrent reads, so contrast and motion are known by the time the theme settles
|
||||
// `wait_first` without adding round trips before it.
|
||||
let ((standard, gnome), (contrast, (motion, gnome_motion))) = zip(
|
||||
zip(read(&connection, STANDARD, shared.gnome), read(&connection, GNOME, shared.gnome)),
|
||||
// Concurrent reads, so contrast, motion and text scale are known by the time the theme
|
||||
// settles `wait_first` without adding round trips before it.
|
||||
let (((standard, gnome), (contrast, (motion, gnome_motion))), text_scale) = zip(
|
||||
zip(
|
||||
read_with(&connection, STANDARD, CONTRAST_KEY, contrast_reply),
|
||||
zip(read(&connection, STANDARD, shared.gnome), read(&connection, GNOME, shared.gnome)),
|
||||
zip(
|
||||
read_with(&connection, STANDARD, MOTION_KEY, |value, legacy| motion_reply(STANDARD, value, legacy)),
|
||||
read_with(&connection, GNOME, ANIMATIONS_KEY, |value, legacy| motion_reply(GNOME, value, legacy)),
|
||||
read_with(&connection, STANDARD, CONTRAST_KEY, contrast_reply),
|
||||
zip(
|
||||
read_with(&connection, STANDARD, MOTION_KEY, |value, legacy| motion_reply(STANDARD, value, legacy)),
|
||||
read_with(&connection, GNOME, ANIMATIONS_KEY, |value, legacy| motion_reply(GNOME, value, legacy)),
|
||||
),
|
||||
),
|
||||
),
|
||||
async {
|
||||
if shared.gnome { read_with(&connection, GNOME, TEXT_SCALE_KEY, text_scale_reply).await } else { None }
|
||||
},
|
||||
)
|
||||
.await;
|
||||
let mut answers = Answers { standard, gnome, motion, gnome_motion };
|
||||
@@ -315,6 +357,9 @@ async fn watch_connection(shared: &Shared, fallbacks: &mut Fallbacks, connected:
|
||||
shared.publish_contrast(contrast);
|
||||
}
|
||||
answers.publish_motion(shared);
|
||||
if let Some(scale) = text_scale {
|
||||
shared.publish_text_scale(scale);
|
||||
}
|
||||
match combined(standard, gnome) {
|
||||
Some(answer) => {
|
||||
*connected = true;
|
||||
@@ -324,6 +369,7 @@ async fn watch_connection(shared: &Shared, fallbacks: &mut Fallbacks, connected:
|
||||
fallbacks.theme(shared).await;
|
||||
fallbacks.layout(shared).await;
|
||||
fallbacks.icons(shared).await;
|
||||
fallbacks.text_scale(shared).await;
|
||||
return None;
|
||||
}
|
||||
}
|
||||
@@ -336,6 +382,10 @@ async fn watch_connection(shared: &Shared, fallbacks: &mut Fallbacks, connected:
|
||||
Some(icons) => shared.publish_icons(icons),
|
||||
None => fallbacks.icons(shared).await,
|
||||
}
|
||||
// A portal without GNOME's keys answered nothing for the text scale either.
|
||||
if text_scale.is_none() {
|
||||
fallbacks.text_scale(shared).await;
|
||||
}
|
||||
loop {
|
||||
let message = match next_event(&mut settings, &mut owners).await? {
|
||||
Event::Owner(message) => {
|
||||
@@ -390,6 +440,28 @@ mod tests {
|
||||
assert!(!gnome(&[("SWAYSOCK", "/run/sway.sock"), ("XDG_CURRENT_DESKTOP", "GNOME")]));
|
||||
assert!(!gnome(&[]));
|
||||
}
|
||||
// A desktop's text scale is applied only when it is a usable factor: Large Text's 1.25 and the
|
||||
// ends of the range are, while a factor that isn't finite or lies outside 0.5..=3.0 is no
|
||||
// scaling (not a clamped one), and text `gsettings` prints that isn't a number is no answer.
|
||||
#[test]
|
||||
fn gnome_text_scaling_factor_reads_in_range_or_not_at_all() {
|
||||
use super::{decode_text_scale, gsettings_text_scale, text_scale_reply};
|
||||
for (text, scale) in [("1.25\n", 1.25), ("1.0", 1.0), ("0.5", 0.5), ("3.0", 3.0)] {
|
||||
assert_eq!(gsettings_text_scale(text), Some(Some(scale)), "{text}");
|
||||
assert_eq!(decode_text_scale(&Value::F64(f64::from(scale))), Some(Some(scale)), "{text}");
|
||||
}
|
||||
for out_of_range in ["nan", "inf", "-2", "0", "0.49", "3.01", "100"] {
|
||||
assert_eq!(gsettings_text_scale(out_of_range), Some(None), "{out_of_range}");
|
||||
}
|
||||
for not_a_number in ["", "uint32 0", "'1.25'", "1,25"] {
|
||||
assert_eq!(gsettings_text_scale(not_a_number), None, "{not_a_number}");
|
||||
}
|
||||
// The portal answers a double; any other type is malformed. The legacy `Read` wraps it once more.
|
||||
assert_eq!(decode_text_scale(&Value::U32(1)), None);
|
||||
assert_eq!(decode_text_scale(&Value::from("1.25")), None);
|
||||
assert_eq!(text_scale_reply(&Value::Value(Box::new(Value::F64(1.5))), true), Some(Some(1.5)));
|
||||
assert_eq!(text_scale_reply(&Value::F64(1.5), true), None);
|
||||
}
|
||||
#[test]
|
||||
fn the_generation_rises_once_per_appearance_change_and_never_for_the_layout() -> Result<(), Box<dyn std::error::Error>> {
|
||||
use crate::appearance::{Contrast, SystemReader};
|
||||
@@ -403,14 +475,17 @@ mod tests {
|
||||
shared.publish_contrast(Contrast::High);
|
||||
shared.publish_contrast(Contrast::High);
|
||||
shared.publish_motion(true);
|
||||
shared.publish_text_scale(Some(1.25));
|
||||
shared.publish_text_scale(Some(1.25));
|
||||
shared.publish_layout("appmenu:close".to_owned());
|
||||
let _ = done.send(());
|
||||
},
|
||||
)
|
||||
.ok_or("worker creation failed")?;
|
||||
finished.recv_timeout(Duration::from_secs(2))?;
|
||||
assert_eq!(watcher.generation(), 3, "theme, contrast and motion each changed once");
|
||||
assert_eq!(watcher.generation(), 4, "theme, contrast, motion and text scale each changed once");
|
||||
assert_eq!((watcher.current(), watcher.contrast()), (Some(Theme::Dark), Some(Contrast::High)));
|
||||
assert_eq!(watcher.text_scale(), Some(1.25));
|
||||
|
||||
let reader = SystemReader::unwatched();
|
||||
let before = reader.generation();
|
||||
|
||||
@@ -78,6 +78,16 @@ impl SystemReader {
|
||||
self.watcher.is_some()
|
||||
}
|
||||
|
||||
/// Enables or suppresses the watcher's change notifications; see [`Watcher::set_active`]. The host
|
||||
/// calls it with `true` when its root window gains focus, which on Windows re-reads the animation
|
||||
/// effects setting the user may have changed in Settings meanwhile. Nothing happens where no
|
||||
/// watcher runs.
|
||||
pub fn set_active(&self, active: bool) {
|
||||
if let Some(watcher) = &self.watcher {
|
||||
watcher.set_active(active);
|
||||
}
|
||||
}
|
||||
|
||||
/// Takes the colour scheme the windowing integration reports (egui's `Event::SystemTheme`).
|
||||
pub fn report_theme(&self, theme: Theme) {
|
||||
let reported = &self.reported;
|
||||
@@ -98,8 +108,9 @@ impl SystemReader {
|
||||
reported.set(&reported.motion, if reduced { 2 } else { 1 });
|
||||
}
|
||||
|
||||
/// Rises each time a preference [`SystemReader::read`] answers from changes, as its source
|
||||
/// reports it: the watcher's theme, contrast or reduced motion, or a reported value. Read
|
||||
/// Rises each time a preference [`SystemReader::read`] or [`SystemReader::text_scale`] answers
|
||||
/// from changes, as its source reports it: the watcher's theme, contrast, reduced motion or text
|
||||
/// scale, or a reported value. Read
|
||||
/// again when it moved. On the web the browser's queries raise it in no case. Read it before
|
||||
/// [`SystemReader::read`]: the watcher stores a value before it raises the generation.
|
||||
pub fn generation(&self) -> u64 {
|
||||
@@ -119,9 +130,9 @@ impl SystemReader {
|
||||
}
|
||||
|
||||
/// The desktop text scale as the watcher last heard it; see [`Watcher::text_scale`]. `None` where the platform
|
||||
/// does not say.
|
||||
/// does not say, on the web and where no watcher runs; the host then applies no text scaling.
|
||||
pub fn text_scale(&self) -> Option<f32> {
|
||||
todo!("SH-C24")
|
||||
self.watcher.as_ref().and_then(Watcher::text_scale)
|
||||
}
|
||||
|
||||
/// The preferences now, without blocking.
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
//! The Windows source of the appearance watcher: Settings ▸ Accessibility ▸ Visual effects ▸
|
||||
//! Animation effects ("Show animations in Windows" in the Control Panel), read through WinRT's
|
||||
//! `UISettings::AnimationsEnabled`, which needs no `unsafe`. The user changes it in Settings, outside
|
||||
//! the app, so the watcher reads it when it starts and again each time the app becomes active.
|
||||
|
||||
/// Whether the system asks for no animations; `None` when WinRT can't be asked.
|
||||
pub(super) fn reduced_motion() -> Option<bool> {
|
||||
match ::windows::UI::ViewManagement::UISettings::new().and_then(|settings| settings.AnimationsEnabled()) {
|
||||
Ok(enabled) => Some(!enabled),
|
||||
Err(e) => {
|
||||
log::debug!("system animation effects: {e}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -228,7 +228,6 @@ impl RecoveryStore {
|
||||
None if self.owns_key(&key) || self.other_instance_alive() => None,
|
||||
None => copies.first().map(|(ext, path)| {
|
||||
let saved = std::fs::metadata(path).and_then(|m| m.modified()).unwrap_or(SystemTime::UNIX_EPOCH);
|
||||
// P3(pdf-shell-w3): SH-C28
|
||||
let meta = RecoveryMeta { name: key.clone(), original: None, extension: ext.clone(), revision: 0, protected: false };
|
||||
RecoveryEntry { key: key.clone(), meta, saved, path: path.clone() }
|
||||
}),
|
||||
@@ -313,7 +312,7 @@ pub(super) struct Sidecar {
|
||||
|
||||
/// A sidecar larger than this is not read.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(super) const MAX_SIDECAR: u64 = 1 << 20;
|
||||
pub(crate) const MAX_SIDECAR: u64 = 1 << 20;
|
||||
|
||||
/// How long a temp file of an interrupted write must have been left before it is removed, far
|
||||
/// longer than any write, so another run's write in progress is never touched.
|
||||
|
||||
@@ -30,7 +30,6 @@ fn doc(id: u64, revision: u64, dirty: bool) -> AutosaveDoc {
|
||||
}
|
||||
|
||||
fn meta(name: &str, revision: u64) -> RecoveryMeta {
|
||||
// P3(pdf-shell-w3): SH-C28
|
||||
RecoveryMeta { name: name.into(), original: None, extension: "pcraft".into(), revision, protected: false }
|
||||
}
|
||||
|
||||
@@ -112,3 +111,96 @@ fn leftovers_skip_live_instances() {
|
||||
second.remove(&found[0]).unwrap();
|
||||
assert!(!found[0].path.exists());
|
||||
}
|
||||
|
||||
/// The sidecar of an earlier run, as `RecoveryStore::write` lays it out, written by hand.
|
||||
fn sidecar(name: &str, instance: Option<&str>) -> String {
|
||||
serde_json::json!({"name": name, "original": null, "extension": "pcraft", "revision": 1, "instance": instance}).to_string()
|
||||
}
|
||||
|
||||
/// The leftover listed under `key`.
|
||||
fn listed(store: &RecoveryStore, key: &str) -> Option<RecoveryEntry> {
|
||||
store.leftovers().into_iter().find(|e| e.key == key)
|
||||
}
|
||||
|
||||
// The recovery folder is untrusted: a planted sidecar over MAX_SIDECAR is never read whole (its
|
||||
// copy is still offered, under its key), while one at the cap is read.
|
||||
#[test]
|
||||
fn a_sidecar_over_the_size_cap_is_ignored_and_one_under_it_is_read() {
|
||||
let scratch = Scratch::new();
|
||||
let store = RecoveryStore::open(scratch.0.join("Recovery")).unwrap();
|
||||
let cap = usize::try_from(MAX_SIDECAR).unwrap();
|
||||
std::fs::write(store.dir().join("big.pcraft"), b"copy").unwrap();
|
||||
let oversized = sidecar(&"x".repeat(cap), None);
|
||||
assert!(oversized.len() > cap);
|
||||
std::fs::write(store.dir().join("big.json"), &oversized).unwrap();
|
||||
let entry = listed(&store, "big").unwrap();
|
||||
assert_eq!((entry.meta.name.as_str(), entry.meta.revision), ("big", 0), "the oversized sidecar was read");
|
||||
assert_eq!(std::fs::read(&entry.path).unwrap(), b"copy");
|
||||
|
||||
let mut at_cap = sidecar("work.pdf", None);
|
||||
at_cap.push_str(&" ".repeat(cap - at_cap.len()));
|
||||
std::fs::write(store.dir().join("big.json"), &at_cap).unwrap();
|
||||
assert_eq!(listed(&store, "big").unwrap().meta.name, "work.pdf");
|
||||
}
|
||||
|
||||
// A copy whose sidecar never got written (a crash between the two writes) or can't be parsed is
|
||||
// still the user's work: it is offered under its key, and listing deletes nothing.
|
||||
#[test]
|
||||
fn an_orphan_copy_and_a_broken_sidecar_are_offered_and_listing_removes_nothing() {
|
||||
let scratch = Scratch::new();
|
||||
let store = RecoveryStore::open(scratch.0.join("Recovery")).unwrap();
|
||||
let files = ["orphan.pdf", "broken.pcraft", "broken.json"];
|
||||
for file in files {
|
||||
let bytes: &[u8] = if file.ends_with(".json") { b"{\"name\": " } else { b"work" };
|
||||
std::fs::write(store.dir().join(file), bytes).unwrap();
|
||||
}
|
||||
for _ in 0..2 {
|
||||
let orphan = listed(&store, "orphan").unwrap();
|
||||
assert_eq!((orphan.meta.name.as_str(), orphan.path.file_name().and_then(|n| n.to_str())), ("orphan", Some("orphan.pdf")));
|
||||
let broken = listed(&store, "broken").unwrap();
|
||||
assert_eq!((broken.meta.name.as_str(), broken.path.file_name().and_then(|n| n.to_str())), ("broken", Some("broken.pcraft")));
|
||||
}
|
||||
for file in files {
|
||||
assert!(store.dir().join(file).exists(), "{file} was removed by listing");
|
||||
}
|
||||
}
|
||||
|
||||
// The copy is written before its sidecar. When the sidecar can't be written (here a folder stands
|
||||
// at its name) the write reports the failure, and the copy stays and is offered after a crash.
|
||||
#[test]
|
||||
fn a_failed_sidecar_write_keeps_the_copy_offered() {
|
||||
let scratch = Scratch::new();
|
||||
let dir = scratch.0.join("Recovery");
|
||||
let crashed = RecoveryStore::open(&dir).unwrap();
|
||||
let key = crashed.key(1);
|
||||
std::fs::create_dir(dir.join(format!("{key}.json"))).unwrap();
|
||||
assert!(crashed.write(1, &meta("a.pdf", 2), b"work").is_err());
|
||||
let copy = dir.join(format!("{key}.pcraft"));
|
||||
assert_eq!(std::fs::read(©).unwrap(), b"work");
|
||||
drop(crashed);
|
||||
|
||||
let next = RecoveryStore::open(&dir).unwrap();
|
||||
let entry = listed(&next, &key).unwrap();
|
||||
assert_eq!(entry.path, copy);
|
||||
}
|
||||
|
||||
// The lock name in a sidecar is untrusted. One that leaves the folder is never opened: here it
|
||||
// would name a lock another run holds outside the folder, which would hide the copy, so the copy
|
||||
// is offered as a plain leftover and the outside file is left alone.
|
||||
#[test]
|
||||
fn a_sidecar_naming_a_lock_outside_the_folder_is_a_plain_leftover() {
|
||||
let scratch = Scratch::new();
|
||||
let store = RecoveryStore::open(scratch.0.join("Recovery")).unwrap();
|
||||
let outside = scratch.0.join("instance-held.lock");
|
||||
let held = std::fs::OpenOptions::new().read(true).write(true).create(true).truncate(false).open(&outside).unwrap();
|
||||
held.try_lock().unwrap();
|
||||
// Makes the escaping name resolve on every platform, were it ever opened.
|
||||
std::fs::create_dir(store.dir().join("instance-x")).unwrap();
|
||||
for (key, instance) in [("up", "instance-x/../../instance-held.lock"), ("back", r"instance-x\..\..\instance-held.lock")] {
|
||||
std::fs::write(store.dir().join(format!("{key}.pcraft")), b"work").unwrap();
|
||||
std::fs::write(store.dir().join(format!("{key}.json")), sidecar("a.pdf", Some(instance))).unwrap();
|
||||
let entry = listed(&store, key);
|
||||
assert_eq!(entry.map(|e| e.meta.name), Some("a.pdf".to_owned()), "{instance}");
|
||||
}
|
||||
assert!(outside.exists());
|
||||
}
|
||||
|
||||
@@ -346,7 +346,13 @@ pub(crate) fn plan_write(flavors: &[Flavor], decode: Option<&Decode>) -> Result<
|
||||
}
|
||||
HTML => return Ok((index, Put::Html { html: text_of(flavor), alt: flavors.iter().find(|f| f.mime == TEXT).map(text_of) })),
|
||||
TEXT => return Ok((index, Put::Text(text_of(flavor)))),
|
||||
URI_LIST => return Ok((index, Put::Files(parse_uri_list(&text_of(flavor))))),
|
||||
// Only `file:` URIs become files; a list with none falls through to the next flavour.
|
||||
URI_LIST => {
|
||||
let files = parse_uri_list(&text_of(flavor));
|
||||
if !files.is_empty() {
|
||||
return Ok((index, Put::Files(files)));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -373,10 +379,7 @@ impl ClipboardBackend for SystemClipboard {
|
||||
}
|
||||
Put::Html { html, alt } => handle.set_html(html, alt),
|
||||
Put::Text(text) => handle.set_text(text),
|
||||
Put::Files(files) => {
|
||||
let _ = files;
|
||||
todo!("SH-C27")
|
||||
}
|
||||
Put::Files(files) => handle.set().file_list(&files),
|
||||
}
|
||||
.map_err(system_error)?;
|
||||
Ok(index)
|
||||
|
||||
@@ -36,10 +36,11 @@ pub struct Flavor {
|
||||
}
|
||||
|
||||
impl Flavor {
|
||||
/// A [`URI_LIST`] flavor (RFC 2483) of the files `paths`.
|
||||
/// A [`URI_LIST`] flavor (RFC 2483) of the files `paths`, which a write puts on the system
|
||||
/// clipboard as copied files, the way a file manager's Copy does.
|
||||
#[cfg(all(feature = "clipboard", not(target_arch = "wasm32")))]
|
||||
pub fn files(paths: &[std::path::PathBuf]) -> Flavor {
|
||||
let _ = paths;
|
||||
todo!("SH-C27")
|
||||
Self::new(URI_LIST, super::convert::uri_list(paths, cfg!(windows)).into_bytes())
|
||||
}
|
||||
|
||||
/// A flavor of `data` with the given MIME type.
|
||||
|
||||
@@ -56,3 +56,24 @@ fn synthetic_input_never_replaces_what_the_user_copied() {
|
||||
assert_eq!(clipboard.write_text("mine").unwrap(), Written::Written);
|
||||
assert_eq!(clipboard.read_text().unwrap().as_deref(), Some("mine"));
|
||||
}
|
||||
|
||||
// Copied files reach the system clipboard as a file list holding the same paths, spaces and
|
||||
// non-ASCII names included; a URI that names no local file is never written as one, and a list
|
||||
// with no file in it leaves the write to the next flavour.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_file_list_is_written_as_files() {
|
||||
let paths = vec![std::env::temp_dir().join("a b#1.pdf"), std::env::temp_dir().join("café 100%.png")];
|
||||
let files = |plan: Result<(usize, Put), ClipboardError>| match plan {
|
||||
Ok((index, Put::Files(files))) => Some((index, files)),
|
||||
_ => None,
|
||||
};
|
||||
assert_eq!(files(plan_write(&[Flavor::files(&paths), Flavor::text("names")], None)), Some((0, paths.clone())));
|
||||
|
||||
let mut mixed = b"# copied\r\nhttps://example.com/a.pdf\r\n".to_vec();
|
||||
mixed.extend(Flavor::files(&paths[..1]).data);
|
||||
assert_eq!(files(plan_write(&[Flavor::new(URI_LIST, mixed)], None)), Some((0, paths[..1].to_vec())));
|
||||
|
||||
let web = Flavor::new(URI_LIST, b"https://example.com/a.pdf\r\n".to_vec());
|
||||
assert!(matches!(plan_write(&[web, Flavor::text("names")], None), Ok((1, Put::Text(text))) if text == "names"));
|
||||
}
|
||||
|
||||
@@ -1,18 +1,36 @@
|
||||
//! `craft_platform::default_app`.
|
||||
|
||||
use crate::default_app::path_from_arg;
|
||||
use crate::default_app::{path_from_arg, rejoin_split_paths};
|
||||
|
||||
// file:///a%20b.pdf and file://localhost/x decode to paths; http://, file://host/x, plain paths
|
||||
// and non-UTF-8 escapes pass through; file:///C:/x.pdf is C:/x.pdf on Windows.
|
||||
// file:///a%20b.pdf and file://localhost/x decode to paths; truncated and invalid escapes are
|
||||
// kept as written; http://, file://host/x, a bare file://, plain paths and non-UTF-8 escapes pass
|
||||
// through; file:///C:/x.pdf is C:/x.pdf on Windows.
|
||||
#[test]
|
||||
fn file_uris_become_paths() {
|
||||
assert_eq!(path_from_arg("file:///a%20b.pdf".into()), "/a b.pdf");
|
||||
assert_eq!(path_from_arg("file://localhost/x".into()), "/x");
|
||||
assert_eq!(path_from_arg("file:///caf%C3%A9.pdf".into()), "/café.pdf");
|
||||
assert_eq!(path_from_arg("file:///100%.pdf".into()), "/100%.pdf");
|
||||
for same in ["http://example.com/a.pdf", "file://host/x", "/plain/path.pdf", "file:///bad%FF.pdf", "mailto:a@b.c"] {
|
||||
assert_eq!(path_from_arg("file:///tmp/a%2".into()), "/tmp/a%2");
|
||||
assert_eq!(path_from_arg("file:///tmp/%zz%".into()), "/tmp/%zz%");
|
||||
for same in ["http://example.com/a.pdf", "file://host/x", "file://", "report.pdf", "/plain/path.pdf", "file:///bad%FF.pdf", "mailto:a@b.c"] {
|
||||
assert_eq!(path_from_arg(same.into()), same);
|
||||
}
|
||||
let drive = path_from_arg("file:///C:/x.pdf".into());
|
||||
assert_eq!(drive, if cfg!(windows) { "C:/x.pdf" } else { "/C:/x.pdf" });
|
||||
}
|
||||
|
||||
// A launcher that passes a path with spaces unquoted splits it; the pieces are joined back into
|
||||
// the longest run that names a file, files that exist on their own stay apart, and arguments
|
||||
// that join into nothing are kept as given so a missing file is still reported by its name.
|
||||
#[test]
|
||||
fn split_paths_with_spaces_are_rejoined() {
|
||||
let have = [r"P:\Archive\00042A26 Contract.PDF", r"C:\a b c.pdf", r"C:\a.pdf", r"C:\x y.pdf"];
|
||||
let exists = |p: &str| have.contains(&p);
|
||||
let args = |a: &[&str]| a.iter().map(|s| s.to_string()).collect::<Vec<_>>();
|
||||
assert_eq!(rejoin_split_paths(args(&[r"P:\Archive\00042A26", "Contract.PDF"]), exists), args(&[r"P:\Archive\00042A26 Contract.PDF"]));
|
||||
assert_eq!(rejoin_split_paths(args(&[r"C:\a", "b", "c.pdf", r"C:\a.pdf"]), exists), args(&[r"C:\a b c.pdf", r"C:\a.pdf"]));
|
||||
assert_eq!(rejoin_split_paths(args(&[r"C:\a.pdf", r"C:\x", "y.pdf"]), exists), args(&[r"C:\a.pdf", r"C:\x y.pdf"]));
|
||||
assert_eq!(rejoin_split_paths(args(&["missing.pdf", "other"]), exists), args(&["missing.pdf", "other"]));
|
||||
assert!(rejoin_split_paths(Vec::new(), exists).is_empty());
|
||||
}
|
||||
|
||||
@@ -27,6 +27,7 @@ mod message_tests;
|
||||
pub mod open;
|
||||
#[cfg(test)]
|
||||
mod open_tests;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub mod owner_only;
|
||||
pub mod pacing;
|
||||
#[cfg(feature = "pointer")]
|
||||
|
||||
@@ -64,3 +64,94 @@ fn rotation_keeps_previous_logs_and_a_running_instance_log() {
|
||||
assert!(rotate(&blocked, NAMES).is_err());
|
||||
let _ = std::fs::remove_file(&blocked);
|
||||
}
|
||||
|
||||
// RUST_LOG is user input: the longest matching directive decides, `a` covers `a::b` but not
|
||||
// `ab`, `a*` covers every target starting with `a`, unknown levels and empty parts are skipped,
|
||||
// and a hostile spec never panics and leaves the default.
|
||||
#[test]
|
||||
fn filter_directives_pick_the_most_specific_match_and_hostile_specs_fall_back() {
|
||||
for spec in ["warn,a=info,a::b=trace,c*=debug,d=bogus,,=error,e=,zz", "zz , a::b=trace ,a=info,warn, c*=debug"] {
|
||||
let filter = Filter::parse(spec);
|
||||
assert_eq!(filter.level_for("a::b::c"), LevelFilter::Trace, "{spec}: the longer directive wins");
|
||||
assert_eq!(filter.level_for("a::x"), LevelFilter::Info, "{spec}");
|
||||
assert_eq!(filter.level_for("a"), LevelFilter::Info, "{spec}");
|
||||
assert_eq!(filter.level_for("ab"), LevelFilter::Warn, "{spec}: `a` does not match `ab`");
|
||||
assert_eq!(filter.level_for("a::bc"), LevelFilter::Info, "{spec}: `a::b` does not match `a::bc`");
|
||||
assert_eq!((filter.level_for("c"), filter.level_for("cat::x")), (LevelFilter::Debug, LevelFilter::Debug), "{spec}");
|
||||
assert_eq!(filter.level_for("zz::q"), LevelFilter::Trace, "{spec}: a bare target turns everything on");
|
||||
assert!(filter.level_for("a::b") > filter.level_for("a") && filter.level_for("a") > filter.level_for("other"), "{spec}");
|
||||
assert_eq!(filter.max(), LevelFilter::Trace, "{spec}");
|
||||
}
|
||||
let skipped = Filter::parse("warn,d=bogus,e=,=error");
|
||||
assert_eq!((skipped.level_for("d"), skipped.level_for("e"), skipped.level_for("")), (LevelFilter::Warn, LevelFilter::Warn, LevelFilter::Warn));
|
||||
let default = Filter::parse("");
|
||||
for hostile in ["", "=", ",,", "x=bogus", " = , = ", "=trace"] {
|
||||
let filter = Filter::parse(hostile);
|
||||
assert_eq!(filter, default, "{hostile:?}");
|
||||
assert_eq!((filter.level_for("x"), filter.max()), (LevelFilter::Error, LevelFilter::Error), "{hostile:?}");
|
||||
}
|
||||
}
|
||||
|
||||
// The date comes from hand-written civil-from-days arithmetic, which nothing else checks and
|
||||
// whose mistakes look plausible: leap days, a century year without one, the epoch (and a clock
|
||||
// before it), and the milliseconds of the instant.
|
||||
#[test]
|
||||
fn timestamps_are_utc_with_milliseconds_across_leap_days() {
|
||||
use std::time::Duration;
|
||||
let at = |millis: u64| timestamp(web_time::UNIX_EPOCH + Duration::from_millis(millis));
|
||||
// 2024-02-29T00:00:00Z is 1_709_164_800 s after the epoch.
|
||||
assert_eq!(at(1_709_164_800_250), "2024-02-29T00:00:00.250Z");
|
||||
assert_eq!(at(1_709_251_199_999), "2024-02-29T23:59:59.999Z");
|
||||
assert_eq!(at(1_709_251_200_000), "2024-03-01T00:00:00.000Z", "the day after a leap day is 1 March");
|
||||
// 2000 is divisible by 400 and has a 29 February; 2100 is a century year that has none.
|
||||
assert_eq!(at(951_782_400_000), "2000-02-29T00:00:00.000Z");
|
||||
assert_eq!(at(4_107_542_399_000), "2100-02-28T23:59:59.000Z");
|
||||
assert_eq!(at(4_107_542_400_000), "2100-03-01T00:00:00.000Z", "2100 has no 29 February");
|
||||
assert_eq!(at(0), "1970-01-01T00:00:00.000Z");
|
||||
assert_eq!(at(1), "1970-01-01T00:00:00.001Z");
|
||||
let before = web_time::UNIX_EPOCH.checked_sub(Duration::from_secs(5)).unwrap();
|
||||
assert_eq!(timestamp(before), "1970-01-01T00:00:00.000Z", "a clock before the epoch reads as the epoch");
|
||||
}
|
||||
|
||||
// Lines logged before the file opens reach it in order, a flood before then keeps its first
|
||||
// MAX_PENDING lines plus one note that the rest were dropped, and a runaway log stops at its size
|
||||
// cap with one note and adds nothing after it.
|
||||
#[test]
|
||||
fn a_sink_keeps_early_lines_bounded_and_stops_at_its_size_cap() {
|
||||
let dir = temp_dir("sink");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let early = dir.join("early.log");
|
||||
let mut sink = Sink::new(MAX_FILE_BYTES);
|
||||
let extra = 3;
|
||||
for i in 0..MAX_PENDING + extra {
|
||||
sink.write(&format!("line {i}\n"));
|
||||
}
|
||||
sink.attach(std::fs::File::create(&early).unwrap());
|
||||
sink.write("after\n");
|
||||
let text = read(&early);
|
||||
let lines: Vec<&str> = text.lines().collect();
|
||||
assert_eq!(lines.len(), MAX_PENDING + 2, "the kept lines, one note, the line after attaching");
|
||||
let kept: Vec<String> = (0..MAX_PENDING).map(|i| format!("line {i}")).collect();
|
||||
assert_eq!(lines[..MAX_PENDING], kept[..]);
|
||||
assert_eq!(lines.iter().filter(|line| line.contains("dropped")).count(), 1);
|
||||
assert!(lines[MAX_PENDING].starts_with(&format!("{extra} ")), "{}", lines[MAX_PENDING]);
|
||||
assert_eq!(lines[MAX_PENDING + 1], "after");
|
||||
|
||||
let capped = dir.join("capped.log");
|
||||
let line = "0123456789\n";
|
||||
let max_bytes = u64::try_from(line.len() * 3 / 2).unwrap();
|
||||
let mut sink = Sink::new(max_bytes);
|
||||
sink.attach(std::fs::File::create(&capped).unwrap());
|
||||
sink.write(line);
|
||||
sink.write(line);
|
||||
let at_cap = read(&capped);
|
||||
let lines: Vec<&str> = at_cap.lines().collect();
|
||||
assert_eq!(lines.len(), 2, "{at_cap}");
|
||||
assert_eq!(lines[0], line.trim_end());
|
||||
assert!(lines[1].contains(&max_bytes.to_string()), "one note naming the cap: {at_cap}");
|
||||
for _ in 0..3 {
|
||||
sink.write(line);
|
||||
}
|
||||
assert_eq!(read(&capped), at_cap, "nothing follows the note");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
+40
-30
@@ -118,31 +118,45 @@ impl IntakeSender {
|
||||
if paths.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut paths: Vec<PathBuf> = paths.iter().map(|p| absolute(p)).collect();
|
||||
paths.sort_by(|a, b| natural_cmp(&a.to_string_lossy(), &b.to_string_lossy()));
|
||||
push(&self.queue, Intake::Open(paths));
|
||||
self.wake.wake();
|
||||
self.send(Intake::Open(ordered(paths)));
|
||||
}
|
||||
|
||||
/// Queues an open request for the app's own `action`, made absolute and sorted as [`open`](Self::open) does, and
|
||||
/// wakes the UI. Empty input is ignored.
|
||||
pub fn open_for(&self, paths: Vec<PathBuf>, action: impl Into<String>) {
|
||||
let _ = (paths, action);
|
||||
todo!("SH-C22")
|
||||
if paths.is_empty() {
|
||||
return;
|
||||
}
|
||||
self.send(Intake::OpenFor { paths: ordered(paths), action: action.into() });
|
||||
}
|
||||
|
||||
/// Queues a file that arrived as bytes, and wakes the UI.
|
||||
/// Queues a file that arrived as bytes, and wakes the UI. A file with neither a name nor bytes is ignored.
|
||||
pub fn open_bytes(&self, name: String, bytes: Arc<[u8]>) {
|
||||
let _ = (name, bytes);
|
||||
todo!("SH-C22")
|
||||
if name.is_empty() && bytes.is_empty() {
|
||||
return;
|
||||
}
|
||||
self.send(Intake::Bytes { name, bytes });
|
||||
}
|
||||
|
||||
/// Queues `batch` after every batch sent before it, then wakes the UI.
|
||||
fn send(&self, batch: Intake) {
|
||||
push(&self.queue, batch);
|
||||
self.wake.wake();
|
||||
}
|
||||
}
|
||||
|
||||
/// `paths` made absolute and sorted by [`natural_cmp`] of the path text, the order an OS open request opens in.
|
||||
fn ordered(paths: Vec<PathBuf>) -> Vec<PathBuf> {
|
||||
let mut paths: Vec<PathBuf> = paths.iter().map(|p| absolute(p)).collect();
|
||||
paths.sort_by(|a, b| natural_cmp(&a.to_string_lossy(), &b.to_string_lossy()));
|
||||
paths
|
||||
}
|
||||
|
||||
/// Files waiting to be opened, read once per frame on the UI thread (spec Q-S4F-7).
|
||||
///
|
||||
/// The app makes one at startup, gives [`sender`](Self::sender) to whatever hears the OS, pushes
|
||||
/// drops from its frame with [`dropped`](Self::dropped), and takes the batches with
|
||||
/// [`take`](Self::take). An [`Intake::Open`] batch comes made absolute and sorted by
|
||||
/// [`take`](Self::take). An [`Intake::Open`] or [`Intake::OpenFor`] batch comes made absolute and sorted by
|
||||
/// [`natural_cmp`] of the path text; the app focuses documents already open ([`same_file`]) and
|
||||
/// opens the rest, then brings its window to the front (on Wayland, a user-attention request).
|
||||
///
|
||||
@@ -234,9 +248,13 @@ pub const CAN_REVEAL: bool = cfg!(not(target_arch = "wasm32"));
|
||||
|
||||
/// Shows `path` selected in the system file manager: `open -R` on macOS, Explorer's
|
||||
/// `/select,"<path>"` on Windows (raw arguments; a path containing `"` is refused), and on Linux
|
||||
/// and FreeBSD the FileManager1 D-Bus call through `dbus-send` on a thread of its own, falling back
|
||||
/// to `xdg-open` on the folder. The path is made absolute first (so a name starting with `-` is
|
||||
/// never an option); a path that no longer exists is [`FILE_GONE`]. Not on wasm.
|
||||
/// and FreeBSD the FileManager1 D-Bus call through `dbus-send`, falling back to `xdg-open` on the
|
||||
/// folder. The path is made absolute first (so a name starting with `-` is never an option); a
|
||||
/// path that no longer exists is [`FILE_GONE`]. Not on wasm.
|
||||
///
|
||||
/// It runs on the caller's thread and returns the real result. On Linux and FreeBSD it can block
|
||||
/// up to the D-Bus reply timeout (2 s) before the fallback runs, so call it from the host's
|
||||
/// `Jobs`, never from the UI thread.
|
||||
// pdfcraft: crates/ui-egui/src/menus/tab_context.rs:51 reveal, :77 reveal_process, :92 reveal_via
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn reveal(path: &Path) -> Result<(), String> {
|
||||
@@ -245,20 +263,8 @@ pub fn reveal(path: &Path) -> Result<(), String> {
|
||||
if !path.try_exists().map_err(|e| e.to_string())? {
|
||||
return Err(FILE_GONE.english.into());
|
||||
}
|
||||
let platform = std::env::consts::OS;
|
||||
let run = |program: &str, args: &[OsString]| reveal_process(program, args).output().map(|o| o.status.success()).map_err(|e| e.to_string());
|
||||
if matches!(platform, "linux" | "freebsd") {
|
||||
// `dbus-send --print-reply` waits up to 2 s for the file manager (then xdg-open may run),
|
||||
// so it runs off the UI thread; a failure there has nobody to tell.
|
||||
return std::thread::Builder::new()
|
||||
.name("craft-reveal".into())
|
||||
.spawn(move || {
|
||||
let _ = reveal_via(platform, &path, run);
|
||||
})
|
||||
.map(|_| ())
|
||||
.map_err(|e| e.to_string());
|
||||
}
|
||||
reveal_via(platform, &path, run)
|
||||
reveal_via(std::env::consts::OS, &path, run)
|
||||
}
|
||||
|
||||
/// The process that runs `program` with `args`. Windows: the arguments go on the command line as
|
||||
@@ -340,13 +346,17 @@ fn reveal_command(platform: &str, path: &Path) -> Result<(&'static str, Vec<OsSt
|
||||
/// is success. The one web opener. Not on native targets (see the native `open_external`).
|
||||
#[cfg(all(target_arch = "wasm32", feature = "browser"))]
|
||||
pub fn open_external(target: &str) -> Result<(), String> {
|
||||
let _ = target;
|
||||
todo!("SH-C23")
|
||||
let window = web_sys::window().ok_or("There is no browser window to open the link in")?;
|
||||
// With `noopener` the browser hands back no window, so `None` is the usual success.
|
||||
window
|
||||
.open_with_url_and_target_and_features(target, "_blank", "noopener,noreferrer")
|
||||
.map(|_| ())
|
||||
.map_err(|e| e.as_string().unwrap_or_else(|| format!("{e:?}")))
|
||||
}
|
||||
|
||||
/// Opens a file or an `http(s)` URL with the system's handler (`open`, `rundll32
|
||||
/// url.dll,FileProtocolHandler`, `xdg-open`), without waiting for it. Not on wasm (the browser
|
||||
/// module opens URLs there).
|
||||
/// url.dll,FileProtocolHandler`, `xdg-open`), without waiting for it. On wasm the browser
|
||||
/// build's `open_external` opens the URL in a new tab instead.
|
||||
///
|
||||
/// No shell sees the target: on Windows `cmd` would run the part of a link after a `&`, and on
|
||||
/// macOS and Linux a target that starts with `-` would be read as an option, so `--` precedes it.
|
||||
|
||||
@@ -1,5 +1,55 @@
|
||||
//! `craft_platform::open`.
|
||||
|
||||
// Requests heard on another thread (a second launch, an Apple Event) reach the UI once each, in
|
||||
// the order they arrived, an open for an action never merged with a plain open, and each wakes
|
||||
// the UI: a lost wake leaves a file unopened until the user moves the mouse.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn an_intake_delivers_each_batch_once_in_order_and_wakes() {
|
||||
use crate::open::{FileIntake, Intake};
|
||||
use craft_host::Wake;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
let wakes = Arc::new(AtomicUsize::new(0));
|
||||
let counter = Arc::clone(&wakes);
|
||||
let (intake, sender) = FileIntake::new(Wake::new(move || {
|
||||
counter.fetch_add(1, Ordering::SeqCst);
|
||||
}));
|
||||
let root = std::env::temp_dir();
|
||||
let (b, a10, a2, c, d) = (root.join("b.pdf"), root.join("a10.pdf"), root.join("a2.pdf"), root.join("c.pdf"), root.join("d.pdf"));
|
||||
let bytes: Arc<[u8]> = Arc::from(&b"%PDF-1.7"[..]);
|
||||
let sent = bytes.clone();
|
||||
let (open, open_for) = ((b.clone(), a10.clone(), a2.clone()), (c.clone(), d.clone()));
|
||||
std::thread::spawn(move || {
|
||||
sender.open(vec![open.0, open.1, open.2]);
|
||||
sender.open_for(vec![open_for.0], "combine");
|
||||
sender.open_for(vec![open_for.1], "combine");
|
||||
sender.open_bytes("scan.pdf".into(), sent);
|
||||
// Empty requests queue nothing and wake nobody.
|
||||
sender.open(Vec::new());
|
||||
sender.open_for(Vec::new(), "combine");
|
||||
sender.open_bytes(String::new(), Arc::from(Vec::<u8>::new()));
|
||||
})
|
||||
.join()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
intake.take(),
|
||||
vec![
|
||||
Intake::Open(vec![a2, a10, b]),
|
||||
Intake::OpenFor { paths: vec![c], action: "combine".into() },
|
||||
Intake::OpenFor { paths: vec![d], action: "combine".into() },
|
||||
Intake::Bytes { name: "scan.pdf".into(), bytes },
|
||||
]
|
||||
);
|
||||
assert_eq!(wakes.load(Ordering::SeqCst), 4, "one wake per queued batch");
|
||||
assert!(intake.take().is_empty(), "each batch is delivered once");
|
||||
// A relative path is made absolute against the working directory, as for a plain open.
|
||||
intake.sender().open_for(vec![PathBuf::from("rel.pdf")], "print");
|
||||
assert!(matches!(intake.take().as_slice(), [Intake::OpenFor { paths, .. }] if paths.len() == 1 && paths[0].is_absolute()));
|
||||
}
|
||||
|
||||
// The target is one argument after `--` (or the Windows handler), so no shell reads a `&` and no
|
||||
// tool reads a leading `-` as an option.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
|
||||
@@ -1,45 +1,763 @@
|
||||
//! Owner-only files: a token file that only its user can read, as mode 0600 makes it on Unix. On Windows a file
|
||||
//! inherits its folder's access list, so these functions replace it with the current user and SYSTEM only and read a
|
||||
//! file with its security descriptor through one handle.
|
||||
//! Owner-only files: a token file that only its user can read, as mode 0600 makes it on Unix.
|
||||
//!
|
||||
//! On Windows a file created in a folder inherits the folder's access list, and folders such as
|
||||
//! 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
|
||||
//! 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`.
|
||||
|
||||
/// Why the file whose security descriptor is `sddl` (`O:` owner and `D:` access list, in SDDL) can't be trusted as
|
||||
/// user `me`'s own: it is owned by someone else, it has no access list, or it lets an account other than `me` or SYSTEM
|
||||
/// use it. `None` means it is `me`'s alone.
|
||||
/// 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
|
||||
/// access list (everyone may use it), or it lets an account other than `me` or SYSTEM use it.
|
||||
/// Accounts are compared by SID; `None` means it is `me`'s alone.
|
||||
///
|
||||
/// Stricter than OpenSSH's rule for private keys, which also lets Administrators in: an entry for
|
||||
/// the Administrators group would let another administrator read the token without taking the
|
||||
/// 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<String> {
|
||||
let _ = (sddl, me);
|
||||
todo!("SH-C26")
|
||||
let me = me.trim();
|
||||
let owner = section(sddl, "O:");
|
||||
match owner {
|
||||
Some(o) if same_account(o, me) => {}
|
||||
Some(o) => return Some(format!("it is owned by {}", another_account(o, ""))),
|
||||
None => return Some("its owner can't be read".into()),
|
||||
}
|
||||
let Some(dacl) = section(sddl, "D:") else {
|
||||
return Some("it has no access list, so every user may read it".into());
|
||||
};
|
||||
if dacl.starts_with("NO_ACCESS_CONTROL") {
|
||||
return Some("it has no access control, so every user may read it".into());
|
||||
}
|
||||
for ace in dacl.split('(').skip(1) {
|
||||
let ace = ace.split(')').next().unwrap_or_default();
|
||||
let parts: Vec<&str> = ace.split(';').collect();
|
||||
// `type;flags;rights;object guid;inherited object guid;account SID[;(condition)]`.
|
||||
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") {
|
||||
continue;
|
||||
}
|
||||
// An entry that grants access but names no account can't be shown to be the user's.
|
||||
let Some(sid) = parts.get(5).filter(|s| !s.is_empty()) else {
|
||||
return Some(format!("its access list has an entry that can't be read ({ace})"));
|
||||
};
|
||||
if !(same_account(sid, me) || matches!(*sid, "SY" | "S-1-5-18" | "OW" | "S-1-3-4")) {
|
||||
return Some(another_account(sid, "has access to it"));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The SID of the current user, as text.
|
||||
/// `another account (<sid>) <rest>`, with the account's name before its SID when it is one of the
|
||||
/// well-known accounts a token file can carry, such as `another account, Administrators
|
||||
/// (S-1-5-32-544), has access to it`. The SID stays, so the message reads the same in every
|
||||
/// Windows language and can still be looked up.
|
||||
fn another_account(sid: &str, rest: &str) -> String {
|
||||
match (well_known_name(sid), rest.is_empty()) {
|
||||
(Some(name), true) => format!("another account, {name} ({sid})"),
|
||||
(Some(name), false) => format!("another account, {name} ({sid}), {rest}"),
|
||||
(None, true) => format!("another account ({sid})"),
|
||||
(None, false) => format!("another account ({sid}) {rest}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The English name Windows gives a well-known SID that can be on a file's access list or own it:
|
||||
/// those a folder hands down at a drive root, in `C:\Users\Public` and in a user's profile, and
|
||||
/// Everyone. The SIDs and names are Microsoft's public list of well-known SIDs
|
||||
/// (<https://learn.microsoft.com/en-us/windows/win32/secauthz/well-known-sids>); the names are
|
||||
/// the ones `icacls` shows, without the `BUILTIN\` or `NT AUTHORITY\` prefix. Any other SID,
|
||||
/// a user's or a domain group's, has no fixed name and gets `None`.
|
||||
fn well_known_name(sid: &str) -> Option<&'static str> {
|
||||
const NAMES: [(&str, &str); 8] = [
|
||||
("S-1-1-0", "Everyone"),
|
||||
("S-1-5-3", "BATCH"),
|
||||
("S-1-5-4", "INTERACTIVE"),
|
||||
("S-1-5-6", "SERVICE"),
|
||||
("S-1-5-11", "Authenticated Users"),
|
||||
("S-1-5-18", "SYSTEM"),
|
||||
("S-1-5-32-544", "Administrators"),
|
||||
("S-1-5-32-545", "Users"),
|
||||
];
|
||||
NAMES.iter().find(|(known, _)| known.eq_ignore_ascii_case(sid)).map(|&(_, name)| name)
|
||||
}
|
||||
|
||||
/// `section(sddl, "O:")` is the owner, `"D:"` the access list: the text after the tag up to the
|
||||
/// next top-level tag.
|
||||
fn section<'a>(sddl: &'a str, tag: &str) -> Option<&'a str> {
|
||||
let start = sddl.find(tag)?.checked_add(tag.len())?;
|
||||
let rest = sddl.get(start..)?;
|
||||
// The owner and group are bare SIDs; the access lists run until the next `X:` tag outside
|
||||
// parentheses.
|
||||
let mut depth = 0usize;
|
||||
let mut end = rest.len();
|
||||
for (i, c) in rest.char_indices() {
|
||||
match c {
|
||||
'(' => depth = depth.saturating_add(1),
|
||||
')' => depth = depth.saturating_sub(1),
|
||||
':' if depth == 0 && i > 0 => {
|
||||
// The tag is the one letter before this colon.
|
||||
end = rest.get(..i).and_then(|s| s.char_indices().last()).map_or(i, |(j, _)| j);
|
||||
break;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
rest.get(..end).map(str::trim)
|
||||
}
|
||||
|
||||
/// Whether account `a` names user SID `me`. `OW` (owner rights) and `CO` are not users. An alias
|
||||
/// is never taken for the user: [`read_with_sddl`] gives every account as a full SID, because
|
||||
/// Windows' own SDDL writes some users by alias (the built-in Administrator as `LA`, whose SID
|
||||
/// depends on the machine).
|
||||
fn same_account(a: &str, me: &str) -> bool {
|
||||
a.eq_ignore_ascii_case(me)
|
||||
}
|
||||
|
||||
/// The tools Windows ships that these checks run, by their path under `%SystemRoot%\System32`.
|
||||
#[cfg(windows)]
|
||||
const WHOAMI: &str = "whoami.exe";
|
||||
#[cfg(windows)]
|
||||
const POWERSHELL: &str = r"WindowsPowerShell\v1.0\powershell.exe";
|
||||
#[cfg(windows)]
|
||||
const ICACLS: &str = "icacls.exe";
|
||||
|
||||
/// A tool Windows ships, started by its full path. Started by bare name, a `whoami.exe`,
|
||||
/// `powershell.exe` or `icacls.exe` found first (next to the app, or earlier on the search path)
|
||||
/// would answer instead, and `whoami`'s answer is what every check here trusts.
|
||||
///
|
||||
/// Each tool is a console program and the app is not, so without `CREATE_NO_WINDOW` Windows gives
|
||||
/// every one of them a console window of its own, which flashes up while the app writes its
|
||||
/// token file. The flag doesn't touch the pipes `output()` reads the answer through.
|
||||
#[cfg(windows)]
|
||||
fn system_tool(relative: &str) -> std::process::Command {
|
||||
use std::os::windows::process::CommandExt as _;
|
||||
/// `CREATE_NO_WINDOW`, from the Windows process creation flags.
|
||||
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
|
||||
let root = std::env::var_os("SystemRoot").map_or_else(|| std::path::PathBuf::from(r"C:\Windows"), std::path::PathBuf::from);
|
||||
let mut command = std::process::Command::new(root.join("System32").join(relative));
|
||||
command.creation_flags(CREATE_NO_WINDOW);
|
||||
command
|
||||
}
|
||||
|
||||
/// 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<String> {
|
||||
todo!("SH-C26")
|
||||
let out = system_tool(WHOAMI).args(["/user", "/fo", "csv", "/nh"]).output()?;
|
||||
if !out.status.success() {
|
||||
return Err(std::io::Error::other("whoami /user failed"));
|
||||
}
|
||||
sid_from_whoami(&String::from_utf8_lossy(&out.stdout)).ok_or_else(|| std::io::Error::other("whoami /user printed no SID"))
|
||||
}
|
||||
|
||||
/// Replaces the access list of `path` with user `me` and SYSTEM only, makes `me` the owner, and checks the result.
|
||||
#[cfg(any(test, windows))]
|
||||
/// The SID in `whoami /user /fo csv /nh` output, `"DOMAIN\user","S-1-5-21-…"`: the last quoted
|
||||
/// field, when it is one. Anything else (an error message, nothing) gives `None`.
|
||||
fn sid_from_whoami(text: &str) -> Option<String> {
|
||||
let last = text.trim().rsplit(',').next()?.trim().trim_matches('"');
|
||||
let digits = last.strip_prefix("S-1-")?;
|
||||
// Every part after `S-1-` is a number; an empty remainder is one empty part, so it fails too.
|
||||
digits.split('-').all(|part| !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit())).then(|| last.to_string())
|
||||
}
|
||||
|
||||
/// Replace `path`'s access list with one that only user `me` (the current user's SID, from
|
||||
/// [`current_user_sid`], which the caller reads once for every step) and SYSTEM are on, then make
|
||||
/// that user its owner (`icacls /setowner`), then read the file's descriptor back and check it with
|
||||
/// [`foreign_access`]. The whole list is replaced, not just what was inherited: on the
|
||||
/// windows-latest runner a new file in the temp folder carries an Administrators entry that `icacls
|
||||
/// /inheritance:r` leaves in place. The owner is set because a file an elevated administrator creates
|
||||
/// is owned by the Administrators group, not by the user. The list comes first: its owner may always
|
||||
/// 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<()> {
|
||||
let _ = (path, me);
|
||||
todo!("SH-C26")
|
||||
set_access_list(path, me, Kind::File)?;
|
||||
icacls(path, &["/setowner".into(), format!("*{me}")])?;
|
||||
still_foreign(&sddl_of(path)?, me)
|
||||
}
|
||||
|
||||
/// Creates the folder `dir` private to user `me`, so a file created in it is private from the moment it exists.
|
||||
/// 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.
|
||||
#[cfg(windows)]
|
||||
pub fn create_private_dir(dir: &std::path::Path, me: &str) -> std::io::Result<()> {
|
||||
let _ = (dir, me);
|
||||
todo!("SH-C26")
|
||||
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)
|
||||
}
|
||||
let restricted = restrict(dir, me);
|
||||
if restricted.is_err() {
|
||||
let _ = std::fs::remove_dir(dir);
|
||||
}
|
||||
restricted
|
||||
}
|
||||
|
||||
/// The security descriptor of `path` in SDDL form.
|
||||
/// `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))]
|
||||
fn still_foreign(sddl: &str, me: &str) -> std::io::Result<()> {
|
||||
match foreign_access(sddl, me) {
|
||||
None => Ok(()),
|
||||
Some(problem) => Err(std::io::Error::other(format!("the file could not be restricted to its owner: {problem}"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// What [`set_access_list`] restricts: a file, or a folder whose entries the files and folders
|
||||
/// created in it inherit.
|
||||
#[cfg(windows)]
|
||||
pub fn sddl_of(path: &std::path::Path) -> std::io::Result<String> {
|
||||
let _ = path;
|
||||
todo!("SH-C26")
|
||||
#[derive(Clone, Copy)]
|
||||
enum Kind {
|
||||
File,
|
||||
Folder,
|
||||
}
|
||||
|
||||
/// Reads at most `max` bytes of `path` and its security descriptor in SDDL form through one handle.
|
||||
/// 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<()> {
|
||||
// No double quotes: the command line would strip them.
|
||||
const FILE: &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 out = system_tool(POWERSHELL)
|
||||
.args(["-NoProfile", "-NonInteractive", "-Command", script])
|
||||
.env("CRAFT_ACL_PATH", path)
|
||||
.env("CRAFT_ACL_USER", me)
|
||||
.output()?;
|
||||
if out.status.success() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(std::io::Error::other(format!("PowerShell could not restrict the file to its owner: {}", String::from_utf8_lossy(&out.stderr).trim())))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn icacls(path: &std::path::Path, args: &[String]) -> std::io::Result<()> {
|
||||
let out = system_tool(ICACLS).arg(path).args(args).output()?;
|
||||
if out.status.success() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(std::io::Error::other(format!("icacls could not restrict the file to its owner: {}", String::from_utf8_lossy(&out.stderr).trim())))
|
||||
}
|
||||
}
|
||||
|
||||
/// PowerShell that turns `$raw`, a `RawSecurityDescriptor`, into `$sddl` as [`read_with_sddl`]
|
||||
/// describes it. No double quotes: the command line would strip them. An entry with no account (a
|
||||
/// custom entry) is written with none, and `foreign_access` refuses it.
|
||||
#[cfg(windows)]
|
||||
macro_rules! describe_raw {
|
||||
() => {
|
||||
"$sddl = 'O:' + $raw.Owner.Value; if ($raw.DiscretionaryAcl -ne $null) { $sddl += 'D:'; foreach ($a in $raw.DiscretionaryAcl) { $t = 'A'; if ([string]$a.AceType -like 'AccessDenied*') { $t = 'D' }; $f = ''; if ($a.AceFlags.HasFlag([Security.AccessControl.AceFlags]::InheritOnly)) { $f = 'IO' }; $sid = ''; if ($a.SecurityIdentifier) { $sid = $a.SecurityIdentifier.Value }; $sddl += '(' + $t + ';' + $f + ';' + $a.AccessMask + ';;;' + $sid + ')' } }; "
|
||||
};
|
||||
}
|
||||
|
||||
/// Open `path` shared for reading only, so that while it is open it can't be replaced, renamed or
|
||||
/// written, and read through that one handle both its security descriptor (owner and access list)
|
||||
/// and its first `max + 1` bytes. The descriptor checked is the one of the handle the bytes come
|
||||
/// from, so there is no moment at which the path could name a different file (a time-of-check to
|
||||
/// time-of-use race). The path reaches PowerShell through an environment variable, never as script
|
||||
/// text.
|
||||
///
|
||||
/// The descriptor is written in SDDL's shape but with every account as a full SID, read from the
|
||||
/// binary descriptor (`RawSecurityDescriptor`): `O:<owner>D:(<type>;<flags>;<rights>;;;<sid>)…`,
|
||||
/// where the type is `D` for a deny entry and `A` for any other, and the flags are `IO` for an
|
||||
/// inherit-only entry. Windows' own SDDL writes some accounts by alias, and the built-in
|
||||
/// Administrator's alias `LA` stands for a SID that depends on the machine.
|
||||
#[cfg(windows)]
|
||||
pub fn read_with_sddl(path: &std::path::Path, max: u64) -> std::io::Result<(String, Vec<u8>)> {
|
||||
let _ = (path, max);
|
||||
todo!("SH-C26")
|
||||
const SCRIPT: &str = concat!(
|
||||
"$fs = [IO.File]::Open($env:CRAFT_ACL_PATH, 'Open', 'Read', 'Read'); try { $raw = New-Object Security.AccessControl.RawSecurityDescriptor -ArgumentList @($fs.GetAccessControl().GetSecurityDescriptorBinaryForm(), 0); ",
|
||||
describe_raw!(),
|
||||
"$max = [int]$env:CRAFT_ACL_MAX + 1; $buf = New-Object byte[] $max; $total = 0; while ($total -lt $max) { $n = $fs.Read($buf, $total, $max - $total); if ($n -le 0) { break }; $total += $n }; [Console]::Out.Write($sddl + [char]10 + [BitConverter]::ToString($buf, 0, $total)) } finally { $fs.Dispose() }"
|
||||
);
|
||||
// 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 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"))
|
||||
}
|
||||
|
||||
/// 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).
|
||||
#[cfg(windows)]
|
||||
pub fn sddl_of(path: &std::path::Path) -> std::io::Result<String> {
|
||||
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); ",
|
||||
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 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"))
|
||||
}
|
||||
|
||||
/// [`read_with_sddl`]'s output: the SDDL, a newline, then the bytes as `[BitConverter]::ToString`
|
||||
/// prints them (`7B-22-…`, empty for none). Anything else gives `None`.
|
||||
#[cfg(any(test, windows))]
|
||||
fn sddl_and_bytes(text: &str) -> Option<(String, Vec<u8>)> {
|
||||
let (sddl, hex) = text.split_once('\n')?;
|
||||
let sddl = sddl.trim();
|
||||
if !sddl.contains("O:") {
|
||||
return None;
|
||||
}
|
||||
let hex = hex.trim();
|
||||
if hex.is_empty() {
|
||||
return Some((sddl.to_string(), Vec::new()));
|
||||
}
|
||||
// Two hex digits each; `from_str_radix` alone would also take a sign, as in `+7`.
|
||||
let byte = |pair: &str| (pair.len() == 2 && pair.bytes().all(|b| b.is_ascii_hexdigit())).then(|| u8::from_str_radix(pair, 16).ok()).flatten();
|
||||
let bytes = hex.split('-').map(byte).collect::<Option<Vec<u8>>>()?;
|
||||
Some((sddl.to_string(), bytes))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const ME: &str = "S-1-5-21-1-2-3-1001";
|
||||
|
||||
/// The SID of the user running the tests, as a caller reads it once and passes on.
|
||||
#[cfg(windows)]
|
||||
fn user() -> String {
|
||||
current_user_sid().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_users_own_file_with_system_is_trusted_and_administrators_are_not() {
|
||||
assert_eq!(foreign_access(&format!("O:{ME}G:{ME}D:P(A;;FA;;;{ME})(A;;FA;;;SY)"), ME), None);
|
||||
assert_eq!(foreign_access(&format!("O:{ME}D:(A;;2032127;;;S-1-5-18)(A;;2032127;;;{ME})"), ME), None);
|
||||
// Another administrator could read it through the Administrators group, by alias or by SID.
|
||||
for admins in ["BA", "S-1-5-32-544"] {
|
||||
let sddl = format!("O:{ME}D:PAI(A;;FA;;;SY)(A;;FR;;;{admins})(A;;FA;;;{ME})");
|
||||
assert!(foreign_access(&sddl, ME).is_some_and(|p| p.contains(admins)), "{sddl}");
|
||||
}
|
||||
// Inherit-only entries and deny entries don't grant access to the file itself.
|
||||
assert_eq!(foreign_access(&format!("O:{ME}D:(A;OICIIO;GA;;;CO)(D;;FA;;;BU)(A;;FA;;;{ME})"), ME), None);
|
||||
}
|
||||
|
||||
/// Each tool is started by its full path in System32, never looked up by name.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn the_tools_are_started_from_system32() {
|
||||
for tool in [WHOAMI, POWERSHELL, ICACLS] {
|
||||
let command = system_tool(tool);
|
||||
let path = std::path::Path::new(command.get_program());
|
||||
assert!(path.is_absolute() && path.is_file(), "{path:?}");
|
||||
assert!(path.to_string_lossy().to_ascii_lowercase().contains(r"\system32\"), "{path:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The tools start without a console window: the app has no console, so a tool that isn't
|
||||
/// told otherwise gets a window of its own, which flashes up. The started PowerShell reports
|
||||
/// its console's window and the processes attached to that console. Both are checked, because
|
||||
/// a tool started without the flag by a process that has a console shares it instead, and that
|
||||
/// console may itself have no window (a test run started by a service or an IDE).
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn the_tools_start_without_a_console_window() {
|
||||
const PROBE: &str = r#"Add-Type -Namespace CraftProbe -Name Console -MemberDefinition '[DllImport("kernel32.dll")] public static extern System.IntPtr GetConsoleWindow(); [DllImport("kernel32.dll")] public static extern uint GetConsoleProcessList(uint[] ids, uint count);'
|
||||
$ids = New-Object uint32[] 256
|
||||
$n = [CraftProbe.Console]::GetConsoleProcessList($ids, 256)
|
||||
"$([CraftProbe.Console]::GetConsoleWindow()) $($ids[0..($n-1)] -join ',')""#;
|
||||
let out = system_tool(POWERSHELL).args(["-NoProfile", "-NonInteractive", "-Command", PROBE]).output().unwrap();
|
||||
// The answer still comes back through the pipe.
|
||||
let text = String::from_utf8_lossy(&out.stdout);
|
||||
assert!(out.status.success(), "{text} {}", String::from_utf8_lossy(&out.stderr));
|
||||
let (window, attached) = text.trim().split_once(' ').unwrap();
|
||||
assert_eq!(window, "0", "the tool has a console window: {text}");
|
||||
let attached: Vec<u32> = attached.split(',').map(|id| id.parse().unwrap()).collect();
|
||||
assert!(!attached.is_empty() && !attached.contains(&std::process::id()), "the tool shares this process's console: {text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_owners_readers_and_missing_lists_are_refused() {
|
||||
let other = "S-1-5-21-1-2-3-1002";
|
||||
assert!(foreign_access(&format!("O:{other}D:(A;;FA;;;{ME})"), ME).unwrap().contains("owned by another account"));
|
||||
// Users (BU) and Authenticated Users (AU), as a folder at a drive root passes on.
|
||||
assert!(foreign_access(&format!("O:{ME}D:AI(A;ID;FA;;;{ME})(A;ID;0x1301bf;;;AU)"), ME).unwrap().contains("AU"));
|
||||
assert!(foreign_access(&format!("O:{ME}D:(A;;FR;;;BU)(A;;FA;;;{ME})"), ME).unwrap().contains("BU"));
|
||||
assert!(foreign_access(&format!("O:{ME}D:(A;;FA;;;{other})"), ME).is_some());
|
||||
assert!(foreign_access(&format!("O:{ME}G:SY"), ME).unwrap().contains("no access list"));
|
||||
assert!(foreign_access(&format!("O:{ME}D:NO_ACCESS_CONTROL"), ME).is_some());
|
||||
assert!(foreign_access("D:(A;;FA;;;SY)", ME).unwrap().contains("owner"));
|
||||
}
|
||||
|
||||
/// 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]
|
||||
fn a_colon_inside_an_entry_does_not_end_the_access_list() {
|
||||
let sddl = format!(r#"O:{ME}D:(XA;;FA;;;{ME};(@User.dept == "a:b"))(A;;FR;;;BU)"#);
|
||||
assert!(foreign_access(&sddl, ME).is_some_and(|p| p.contains("BU")), "{sddl}");
|
||||
}
|
||||
|
||||
/// A conditional entry for the user is the user's; one that grants access but whose account
|
||||
/// can't be read is refused rather than skipped.
|
||||
#[test]
|
||||
fn conditional_and_malformed_entries() {
|
||||
assert_eq!(foreign_access(&format!(r#"O:{ME}D:(XA;;FA;;;{ME};(@User.dept == "x"))"#), ME), None);
|
||||
assert!(foreign_access(&format!("O:{ME}D:(A;;FA;;;{ME})(A;;FR)"), ME).is_some_and(|p| p.contains("can't be read")));
|
||||
assert!(foreign_access(&format!("O:{ME}D:(A;;FA;;;)"), ME).is_some_and(|p| p.contains("can't be read")));
|
||||
// A conditional entry grants access like a plain one: another account on it is refused.
|
||||
let other = format!(r#"O:{ME}D:(A;;FA;;;{ME})(XA;;FR;;;BU;(@User.dept == "x"))"#);
|
||||
assert!(foreign_access(&other, ME).is_some_and(|p| p.contains("BU")), "{other}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_sid_is_read_from_whoamis_output_and_nothing_else() {
|
||||
assert_eq!(sid_from_whoami("\"desk\\ada\",\"S-1-5-21-1-2-3-1001\"\r\n").as_deref(), Some("S-1-5-21-1-2-3-1001"));
|
||||
for bad in [
|
||||
"",
|
||||
"ERROR: Access is denied.",
|
||||
"\"desk\\ada\",\"\"",
|
||||
"\"desk\\ada\",\"S-1-\"",
|
||||
"\"S-1-5-x\"",
|
||||
"\"desk\\ada\"",
|
||||
"\"desk\\ada\",\"1-5-21-7\"",
|
||||
] {
|
||||
assert_eq!(sid_from_whoami(bad), None, "{bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The real tools: a file created in a folder that lets Users read what's in it inherits that
|
||||
/// access; after `restrict_to_owner` only the current user and SYSTEM are left.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn a_file_in_a_shared_folder_is_restricted_to_its_owner() {
|
||||
let dir = std::env::temp_dir().join(format!("craft-owner-only-{}", std::process::id()));
|
||||
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 file = dir.join("ctl.json");
|
||||
std::fs::write(&file, b"{}").unwrap();
|
||||
let me = current_user_sid().unwrap();
|
||||
// Users inherit read access, so the file is refused. (Run elevated, the file is also owned
|
||||
// by Administrators, which is the reason given first.)
|
||||
let before = sddl_of(&file).unwrap();
|
||||
assert!(before.contains(";BU)") || before.contains(";S-1-5-32-545)"), "Users inherit read access: {before}");
|
||||
assert!(foreign_access(&before, &me).is_some(), "{before}");
|
||||
restrict_to_owner(&file, &user()).unwrap();
|
||||
let sddl = sddl_of(&file).unwrap();
|
||||
assert_eq!(section(&sddl, "O:"), Some(me.as_str()), "{sddl}");
|
||||
assert_eq!(foreign_access(&sddl, &me), None, "{sddl}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A file created in a private folder inside a folder that lets Users read what's in it is the
|
||||
/// user's alone from the moment it exists, before anything restricts it.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn a_file_created_in_a_private_folder_is_private_from_the_start() {
|
||||
let dir = std::env::temp_dir().join(format!("craft-owner-only-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 private = dir.join("staging");
|
||||
create_private_dir(&private, &user()).unwrap();
|
||||
let me = current_user_sid().unwrap();
|
||||
let folder = sddl_of(&private).unwrap();
|
||||
assert_eq!((section(&folder, "O:"), foreign_access(&folder, &me)), (Some(me.as_str()), None), "{folder}");
|
||||
let file = private.join("ctl.json");
|
||||
std::fs::OpenOptions::new().write(true).create_new(true).open(&file).unwrap();
|
||||
let sddl = sddl_of(&file).unwrap();
|
||||
assert!(!sddl.contains(";BU)") && !sddl.contains(";S-1-5-32-545)"), "Users must not inherit read access: {sddl}");
|
||||
assert_eq!(foreign_access(&sddl, &me), None, "{sddl}");
|
||||
// The name is taken: the folder isn't reused.
|
||||
assert!(create_private_dir(&private, &user()).is_err());
|
||||
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.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn a_file_in_a_folder_granting_only_modify_is_still_restricted() {
|
||||
let dir = std::env::temp_dir().join(format!("craft-owner-only-modify-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let me = current_user_sid().unwrap();
|
||||
let modify = std::process::Command::new("icacls")
|
||||
.arg(&dir)
|
||||
.args(["/inheritance:r", "/grant:r"])
|
||||
.arg(format!("*{me}:(OI)(CI)M"))
|
||||
.arg("*S-1-5-18:(OI)(CI)F")
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(modify.status.success(), "{}", String::from_utf8_lossy(&modify.stderr));
|
||||
let file = dir.join("ctl.json");
|
||||
std::fs::write(&file, b"{}").unwrap();
|
||||
restrict_to_owner(&file, &user()).unwrap();
|
||||
let sddl = sddl_of(&file).unwrap();
|
||||
assert_eq!((section(&sddl, "O:"), foreign_access(&sddl, &me)), (Some(me.as_str()), None), "{sddl}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A null access list (`NO_ACCESS_CONTROL`) lets every account use the file, so it is refused.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn a_file_with_no_access_list_is_refused() {
|
||||
let dir = std::env::temp_dir().join(format!("craft-owner-only-null-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let file = dir.join("ctl.json");
|
||||
std::fs::write(&file, b"{}").unwrap();
|
||||
restrict_to_owner(&file, &user()).unwrap();
|
||||
// A null access list lets everyone in; the user, as owner, may set one.
|
||||
let null = std::process::Command::new("powershell")
|
||||
.args([
|
||||
"-NoProfile",
|
||||
"-NonInteractive",
|
||||
"-Command",
|
||||
"$s = New-Object Security.AccessControl.FileSecurity; $s.SetSecurityDescriptorSddlForm('D:NO_ACCESS_CONTROL', 'Access'); [IO.File]::SetAccessControl($env:CRAFT_NULL_PATH, $s)",
|
||||
])
|
||||
.env("CRAFT_NULL_PATH", &file)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(null.status.success(), "{}", String::from_utf8_lossy(&null.stderr));
|
||||
let (sddl, _) = read_with_sddl(&file, 64).unwrap();
|
||||
let me = current_user_sid().unwrap();
|
||||
assert!(foreign_access(&sddl, &me).is_some_and(|p| p.contains("no access list")), "{sddl}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// An `OWNER RIGHTS` entry replaces what an owner may do implicitly. Granting only *write
|
||||
/// owner* that way, the access list can't be replaced although the owner can still be set: the
|
||||
/// file isn't taken as restricted. Run elevated, it can be replaced, and then must be restricted.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn a_file_whose_access_list_cant_be_replaced_is_not_restricted() {
|
||||
let dir = std::env::temp_dir().join(format!("craft-owner-only-ow-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let me = current_user_sid().unwrap();
|
||||
let file = dir.join("ctl.json");
|
||||
std::fs::write(&file, b"{}").unwrap();
|
||||
// The whole list is written, as `restrict_to_owner` does: `icacls /inheritance:r` leaves
|
||||
// the Administrators entry the windows-latest runner gives a new file, and with it an
|
||||
// elevated administrator could replace the list after all.
|
||||
let rights = std::process::Command::new("powershell")
|
||||
.args([
|
||||
"-NoProfile",
|
||||
"-NonInteractive",
|
||||
"-Command",
|
||||
"$s = New-Object Security.AccessControl.FileSecurity; $s.SetSecurityDescriptorSddlForm('D:P(A;;FR;;;' + $env:CRAFT_OW_USER + ')(A;;WO;;;OW)', 'Access'); [IO.File]::SetAccessControl($env:CRAFT_OW_PATH, $s)",
|
||||
])
|
||||
.env("CRAFT_OW_PATH", &file)
|
||||
.env("CRAFT_OW_USER", &me)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(rights.status.success(), "{}", String::from_utf8_lossy(&rights.stderr));
|
||||
// Nothing but the two entries: no Administrators entry for the elevated runner to use.
|
||||
let sddl = sddl_of(&file).unwrap();
|
||||
assert_eq!(section(&sddl, "D:"), Some(format!("(A;;524288;;;S-1-3-4)(A;;1179785;;;{me})").as_str()), "{sddl}");
|
||||
// An elevated administrator (the windows-latest runner) may replace the list anyway; then the
|
||||
// file must really be the user's alone, since the result is checked before it is trusted.
|
||||
if restrict_to_owner(&file, &user()).is_ok() {
|
||||
let after = sddl_of(&file).unwrap();
|
||||
assert!(elevated(), "the access list could not be replaced: {after}");
|
||||
assert_eq!(foreign_access(&after, &me), None, "{after}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Whether the tests run elevated: `whoami /groups` lists the high (or system) mandatory label.
|
||||
#[cfg(windows)]
|
||||
fn elevated() -> bool {
|
||||
let out = system_tool(WHOAMI).args(["/groups", "/fo", "csv", "/nh"]).output().unwrap();
|
||||
let text = String::from_utf8_lossy(&out.stdout);
|
||||
text.contains("\"S-1-16-12288\"") || text.contains("\"S-1-16-16384\"")
|
||||
}
|
||||
|
||||
/// When the tools fail, the functions say so: nothing is taken as restricted or as checked.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn tool_failures_are_errors() {
|
||||
let missing = std::env::temp_dir().join(format!("craft-owner-only-missing-{}", std::process::id())).join("none.json");
|
||||
assert!(restrict_to_owner(&missing, &user()).is_err(), "icacls on a missing file");
|
||||
assert!(sddl_of(&missing).is_err(), "Get-Acl on a missing file");
|
||||
let me = current_user_sid().unwrap();
|
||||
assert!(me.starts_with("S-1-5-") && me.split('-').count() >= 4, "{me}");
|
||||
assert!(!me.contains('"') && !me.contains('\\'), "the SID alone, not the account name: {me}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_descriptor_and_bytes_are_read_from_the_scripts_output_and_nothing_else() {
|
||||
let sddl = format!("O:{ME}D:P(A;;FA;;;{ME})");
|
||||
assert_eq!(sddl_and_bytes(&format!("{sddl}\n7B-0A-ff\r\n")), Some((sddl.clone(), vec![0x7B, 0x0A, 0xFF])));
|
||||
assert_eq!(sddl_and_bytes(&format!("{sddl}\n")), Some((sddl.clone(), Vec::new())));
|
||||
for bad in [
|
||||
String::new(),
|
||||
sddl.clone(),
|
||||
"D:P(A;;FA;;;SY)\n7B".into(),
|
||||
format!("{sddl}\n7B-2"),
|
||||
format!("{sddl}\n7B--22"),
|
||||
format!("{sddl}\n7G"),
|
||||
format!("{sddl}\n+7-22"),
|
||||
] {
|
||||
assert_eq!(sddl_and_bytes(&bad), None, "{bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The bytes come with the descriptor of the same handle, capped at `max + 1` so an oversized
|
||||
/// file shows, and the restricted file is owned by the user.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn the_file_is_read_with_its_descriptor_through_one_handle() {
|
||||
let dir = std::env::temp_dir().join(format!("craft-owner-only-read-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let file = dir.join("ctl.json");
|
||||
std::fs::write(&file, br#"{"port":1}"#).unwrap();
|
||||
restrict_to_owner(&file, &user()).unwrap();
|
||||
let me = current_user_sid().unwrap();
|
||||
let (sddl, bytes) = read_with_sddl(&file, 64).unwrap();
|
||||
assert_eq!(section(&sddl, "O:"), Some(me.as_str()), "{sddl}");
|
||||
assert_eq!((foreign_access(&sddl, &me), bytes.as_slice()), (None, &br#"{"port":1}"#[..]));
|
||||
assert_eq!(read_with_sddl(&file, 3).unwrap().1, br#"{"po"#);
|
||||
// A limit past what the script's `[int]` holds is capped, not handed to it.
|
||||
assert_eq!(read_with_sddl(&file, u64::MAX).unwrap().1, br#"{"port":1}"#);
|
||||
assert!(read_with_sddl(&dir.join("none.json"), 64).is_err());
|
||||
// A deny entry is read as one: denying Guests takes nothing from the user.
|
||||
let guests = std::process::Command::new("icacls").arg(&file).arg("/deny").arg("*S-1-5-32-546:(R)").output().unwrap();
|
||||
assert!(guests.status.success(), "{}", String::from_utf8_lossy(&guests.stderr));
|
||||
let (sddl, _) = read_with_sddl(&file, 64).unwrap();
|
||||
assert!(sddl.contains(";;;S-1-5-32-546)") && sddl.contains("(D;"), "{sddl}");
|
||||
assert_eq!(foreign_access(&sddl, &me), None, "{sddl}");
|
||||
// The handle shares the file for reading only: a file someone has open for writing (or
|
||||
// could rename or delete) isn't read, and so can't change between the check and the read.
|
||||
let writer = std::fs::OpenOptions::new().write(true).open(&file).unwrap();
|
||||
assert!(read_with_sddl(&file, 64).is_err(), "a file open for writing is not read");
|
||||
// Restricting reads the descriptor alone, so it works on the file an app holds open to
|
||||
// write the token through.
|
||||
restrict_to_owner(&file, &user()).unwrap();
|
||||
assert_eq!(foreign_access(&sddl_of(&file).unwrap(), &me), None);
|
||||
drop(writer);
|
||||
assert!(read_with_sddl(&file, 64).is_ok());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Entries of the file's own, not inherited, are replaced too: an Administrators or Users
|
||||
/// entry (as the windows-latest runner's temp folder leaves on a new file) and a deny that
|
||||
/// would keep the user from setting the owner.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn entries_of_the_files_own_are_replaced() {
|
||||
let dir = std::env::temp_dir().join(format!("craft-owner-only-own-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let me = current_user_sid().unwrap();
|
||||
let mine = format!("*{me}:(R)");
|
||||
for (name, entries) in [
|
||||
("others.json", ["/grant", "*S-1-5-32-544:(F)", "/grant", "*S-1-5-32-545:(R)"]),
|
||||
("deny.json", ["/deny", "*S-1-1-0:(WO)", "/grant", "*S-1-5-32-544:(F)"]),
|
||||
] {
|
||||
let file = dir.join(name);
|
||||
std::fs::write(&file, b"{}").unwrap();
|
||||
// The user keeps read access, so the descriptor can be read before restricting.
|
||||
let own = std::process::Command::new("icacls").arg(&file).arg("/inheritance:r").args(entries).args(["/grant", &mine]).output().unwrap();
|
||||
assert!(own.status.success(), "{}", String::from_utf8_lossy(&own.stderr));
|
||||
assert!(foreign_access(&sddl_of(&file).unwrap(), &me).is_some(), "{name}");
|
||||
restrict_to_owner(&file, &user()).unwrap();
|
||||
let sddl = sddl_of(&file).unwrap();
|
||||
assert_eq!((section(&sddl, "O:"), foreign_access(&sddl, &me)), (Some(me.as_str()), None), "{name}: {sddl}");
|
||||
assert!(!sddl.contains("(D;"), "{name}: the deny is gone: {sddl}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_descriptor_still_open_to_others_after_restricting_is_an_error() {
|
||||
assert!(still_foreign(&format!("O:{ME}D:P(A;;FA;;;SY)(A;;FA;;;{ME})"), ME).is_ok());
|
||||
for bad in [format!("O:{ME}D:P(A;;FA;;;S-1-5-32-544)(A;;FA;;;{ME})"), format!("O:S-1-5-32-544D:P(A;;FA;;;{ME})"), format!("O:{ME}")] {
|
||||
assert!(still_foreign(&bad, ME).is_err_and(|e| e.to_string().contains("could not be restricted")), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
/// [`read_with_sddl`] gives accounts as full SIDs (rights as a number, no list flags), the way a
|
||||
/// CI runner's built-in Administrator reads its own restricted file. An alias such as `LA`
|
||||
/// is never taken for the user, whatever the user's RID: on a domain-joined machine a domain
|
||||
/// account can share the local Administrator's RID 500.
|
||||
#[test]
|
||||
fn descriptors_with_full_sids_and_aliases_that_are_never_the_user() {
|
||||
let admin = "S-1-5-21-1-2-3-500";
|
||||
let full = format!("O:{admin}D:(A;;2032127;;;S-1-5-18)(A;;2032127;;;{admin})");
|
||||
assert_eq!(foreign_access(&full, admin), None);
|
||||
// Owner rights by SID, a deny by SID, an inherit-only entry for Creator Owner.
|
||||
let more = format!("O:{ME}D:(D;;1179785;;;S-1-5-32-546)(A;IO;268435456;;;S-1-3-0)(A;;2032127;;;S-1-3-4)(A;;2032127;;;{ME})");
|
||||
assert_eq!(foreign_access(&more, ME), None);
|
||||
assert!(foreign_access(&format!("O:{ME}D:(A;;1179785;;;S-1-5-32-545)(A;;2032127;;;{ME})"), ME).is_some_and(|p| p.contains("S-1-5-32-545")));
|
||||
for me in [admin, "S-1-5-21-1-2-3-501"] {
|
||||
assert!(foreign_access("O:LAD:PAI(A;;FA;;;SY)(A;;FA;;;LA)", me).is_some_and(|p| p.contains("owned by another account (LA)")), "{me}");
|
||||
assert!(foreign_access("O:LGD:P(A;;FA;;;LG)", me).is_some(), "{me}");
|
||||
}
|
||||
assert!(foreign_access(&format!("O:{admin}D:P(A;;FA;;;{admin})(A;;FR;;;LA)"), admin).is_some_and(|p| p.contains("LA")));
|
||||
}
|
||||
|
||||
/// A refusal names a well-known account as well as giving its SID, so `S-1-5-32-544` reads as
|
||||
/// Administrators without a lookup; any other SID is given alone.
|
||||
#[test]
|
||||
fn refusals_name_well_known_accounts_and_keep_their_sid() {
|
||||
for (sid, name) in [
|
||||
("S-1-5-32-544", "Administrators"),
|
||||
("S-1-5-32-545", "Users"),
|
||||
("S-1-5-11", "Authenticated Users"),
|
||||
("S-1-5-4", "INTERACTIVE"),
|
||||
("S-1-1-0", "Everyone"),
|
||||
("S-1-5-6", "SERVICE"),
|
||||
("S-1-5-3", "BATCH"),
|
||||
] {
|
||||
let sddl = format!("O:{ME}D:PAI(A;;FA;;;{ME})(A;ID;1179817;;;{sid})");
|
||||
assert_eq!(foreign_access(&sddl, ME), Some(format!("another account, {name} ({sid}), has access to it")), "{sddl}");
|
||||
}
|
||||
// SYSTEM may have access, but a file it owns isn't the user's.
|
||||
assert_eq!(foreign_access(&format!("O:S-1-5-18D:P(A;;FA;;;{ME})"), ME).as_deref(), Some("it is owned by another account, SYSTEM (S-1-5-18)"));
|
||||
assert_eq!(
|
||||
foreign_access(&format!("O:S-1-5-32-544D:P(A;;FA;;;{ME})"), ME).as_deref(),
|
||||
Some("it is owned by another account, Administrators (S-1-5-32-544)")
|
||||
);
|
||||
// Another user, a lookalike and an alias have no fixed name: the account is given as it was.
|
||||
for sid in ["S-1-5-21-1-2-3-1002", "S-1-5-32-5440", "S-1-5-1", "BA"] {
|
||||
let sddl = format!("O:{ME}D:(A;;FA;;;{ME})(A;;FR;;;{sid})");
|
||||
assert_eq!(foreign_access(&sddl, ME), Some(format!("another account ({sid}) has access to it")), "{sddl}");
|
||||
}
|
||||
assert_eq!(
|
||||
foreign_access("O:S-1-5-21-1-2-3-1002D:(A;;FA;;;SY)", ME).as_deref(),
|
||||
Some("it is owned by another account (S-1-5-21-1-2-3-1002)")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sections_stop_at_the_next_tag() {
|
||||
assert_eq!(section("O:S-1-5-18G:S-1-5-32-544D:(A;;FA;;;SY)", "O:"), Some("S-1-5-18"));
|
||||
assert_eq!(section("O:BAG:SYD:P(A;;FA;;;SY)S:(AU;SA;FA;;;WD)", "D:"), Some("P(A;;FA;;;SY)"));
|
||||
assert_eq!(section("O:BA", "D:"), None);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,6 +18,9 @@ pub struct SessionDocument {
|
||||
pub window: Option<String>,
|
||||
/// The app's view state for the document (PdfCraft's page, PhotoCraft's zoom and scroll), as
|
||||
/// the app wrote it; `Null` when it keeps none.
|
||||
// TOML has no null: written as a null, the whole typed settings save would fail. Left out, it
|
||||
// reads back as `Null` through `#[serde(default)]` and `from_json`.
|
||||
#[serde(skip_serializing_if = "serde_json::Value::is_null")]
|
||||
pub view: serde_json::Value,
|
||||
}
|
||||
|
||||
|
||||
@@ -19,3 +19,34 @@ fn quit_keeps_the_session_from_its_start() {
|
||||
keeper.quit_cancelled();
|
||||
assert_eq!(keeper.to_save(true, one.clone()), one);
|
||||
}
|
||||
|
||||
// The stored session is untrusted settings: entries without a usable path and non-text fields
|
||||
// are skipped rather than failing the whole session, a missing view is `Null`, a huge list is
|
||||
// cut at MAX_DOCUMENTS, and anything that isn't a session reads as none.
|
||||
#[test]
|
||||
fn malformed_entries_are_skipped_and_the_list_capped() {
|
||||
let value = serde_json::json!({
|
||||
"documents": [{"path": 5}, {"path": ""}, "x", {"path": "/a.pdf", "window": 3}, {"path": "/b.pdf", "view": {"page": 7}}],
|
||||
"active": 3,
|
||||
});
|
||||
let session = Session::from_json(&value);
|
||||
let read: Vec<(&str, Option<&str>, &serde_json::Value)> =
|
||||
session.documents.iter().map(|d| (d.path.as_str(), d.window.as_deref(), &d.view)).collect();
|
||||
assert_eq!(read, [("/a.pdf", None, &serde_json::Value::Null), ("/b.pdf", None, &serde_json::json!({"page": 7}))]);
|
||||
assert_eq!(session.active, None);
|
||||
let many: Vec<serde_json::Value> = (0..1000).map(|i| serde_json::json!({"path": format!("/{i}.pdf")})).collect();
|
||||
assert_eq!(Session::from_json(&serde_json::json!({"documents": many})).documents.len(), MAX_DOCUMENTS);
|
||||
assert_eq!(Session::from_json(&serde_json::json!("garbage")), Session::default());
|
||||
}
|
||||
|
||||
// TOML has no null, so a document without view state must not write one: the typed settings save
|
||||
// would fail and lose the whole session. Left out, it reads back as `Null` both ways.
|
||||
#[test]
|
||||
fn a_null_view_is_left_out_and_reads_back_as_null() {
|
||||
let session = Session { documents: vec![doc("/a.pdf"), SessionDocument { view: serde_json::json!({"page": 2}), ..doc("/b.pdf") }], active: None };
|
||||
let written = serde_json::to_value(&session).unwrap();
|
||||
assert_eq!(written["documents"][0].get("view"), None, "{written}");
|
||||
assert_eq!(written["documents"][1]["view"], serde_json::json!({"page": 2}));
|
||||
assert_eq!(serde_json::from_value::<Session>(written.clone()).unwrap(), session);
|
||||
assert_eq!(Session::from_json(&written), session);
|
||||
}
|
||||
|
||||
@@ -52,3 +52,30 @@ fn another_writer_is_a_change_and_an_own_save_is_not() {
|
||||
settle(&mut watch);
|
||||
assert!(watch.take_changes().is_empty());
|
||||
}
|
||||
|
||||
// A permission change (or a Finder tag, LaunchServices) moves only the Unix change time. With
|
||||
// the bytes the app saved still on disk that is no edit, so Save doesn't ask about a change
|
||||
// nobody made; different bytes, or none to compare, are still a difference.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_stamp_that_differs_only_in_metadata_is_not_a_content_change() {
|
||||
use std::os::unix::fs::PermissionsExt as _;
|
||||
let dir = TempDir::new("craft-watch-test").unwrap();
|
||||
let path = file(&dir, "doc.txt", "saved");
|
||||
let mut watch = watcher();
|
||||
watch.known_now(1, &path);
|
||||
let before = FileStamp::at(&path).unwrap();
|
||||
// Past the change time's resolution on every common file system.
|
||||
std::thread::sleep(std::time::Duration::from_millis(20));
|
||||
let mode = std::fs::metadata(&path).unwrap().permissions().mode();
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode ^ 0o004)).unwrap();
|
||||
let after = FileStamp::at(&path).unwrap();
|
||||
assert!(after != before && after.metadata_only_change(before), "only the change time moved");
|
||||
|
||||
assert!(!watch.disk_differs(&1, &path, Some(b"saved")));
|
||||
assert!(watch.disk_differs(&1, &path, Some(b"other")));
|
||||
assert!(watch.disk_differs(&1, &path, None), "nothing to compare with");
|
||||
|
||||
std::fs::write(&path, "edits").unwrap();
|
||||
assert!(watch.disk_differs(&1, &path, Some(b"saved")), "a content edit");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user