Skip to main content

pitboard_core/host/
mod.rs

1//! The machine Pitboard runs on, behind one seam.
2//!
3//! Everything that differs between operating systems is answered here, so the rest of the
4//! crate asks a question and never which system it is on. The seam has two faces.
5//!
6//! [`Host`] is the part a test replaces: the stores secrets and logins live in, the process
7//! list, the scheduler and whether this process runs as the person, reached through the
8//! [`Context`] every call carries. A test puts [`memory::MemoryHost`] there and can make any
9//! of them fail, or say this process runs as root.
10//!
11//! [`fs`], [`proc`] and [`user`] are plain functions for what the machine does the same way
12//! whoever asks, which the tests run for real: creating a file only its owner can reach, and
13//! every other change to the disk, each taking the [`Permit`] the one gate every change
14//! passes makes; asking whether a process is still alive; naming the person signed in.
15//! [`login_path`] is one too: the `PATH` the person's login shell builds, which an app the
16//! system started does not have. So is [`watch`]: a watch on one folder, through the system's
17//! own notice of a change, where the host says one hears every write ([`Host::watches`]).
18//!
19//! The system is chosen once, in this file, and nowhere else. A fact that differs by system
20//! is a `match` on [`OS`], and [`Os`] lists every system Pitboard runs on, so a system added
21//! there does not compile until each such fact has been said for it. This replaced branches
22//! that read "macOS, or else Linux", which compiled anywhere and did the Linux thing.
23
24use crate::context::{Context, Environment};
25use crate::error::Result;
26use crate::permit::Permit;
27use crate::schedule::Job;
28use crate::state::VaultForm;
29use crate::store::RawStore;
30use std::path::{Path, PathBuf};
31use std::sync::Arc;
32
33#[cfg_attr(
34    not(windows),
35    allow(
36        dead_code,
37        reason = "only Windows reads an access list; every system's tests read these rules"
38    )
39)]
40pub(crate) mod acl;
41pub(crate) mod administered;
42#[cfg(target_os = "linux")]
43mod linux;
44#[cfg(target_os = "macos")]
45mod macos;
46#[cfg(any(test, feature = "test-support"))]
47pub(crate) mod memory;
48#[cfg(any(windows, test))]
49pub(crate) mod owner;
50pub(crate) mod program;
51#[cfg_attr(
52    not(windows),
53    allow(
54        dead_code,
55        reason = "only Windows replaces a file this way; every system's tests read these rules"
56    )
57)]
58pub(crate) mod replace;
59#[cfg_attr(
60    not(windows),
61    allow(
62        dead_code,
63        reason = "only Windows schedules a task; every system's tests read these rules"
64    )
65)]
66pub(crate) mod task;
67pub(crate) mod token;
68#[cfg(unix)]
69mod unix;
70pub(crate) mod watch;
71#[cfg(windows)]
72mod windows;
73
74#[cfg(target_os = "linux")]
75use linux as os;
76#[cfg(target_os = "macos")]
77use macos as os;
78#[cfg(windows)]
79use windows as os;
80
81pub(crate) use administered::{Administered, Hive};
82pub(crate) use os::{fs, proc, user};
83#[cfg(all(windows, any(test, feature = "test-support")))]
84pub(crate) use windows::credman as windows_credman;
85#[cfg(all(windows, test))]
86pub(crate) use windows::seal::Dpapi;
87
88/// The operating systems Pitboard runs on. Windows only once it is released
89/// ([`crate::release`]): until then a Windows build of a release refuses everything, and its
90/// face, `host/windows`, refuses whatever is not built yet.
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92pub enum Os {
93    MacOs,
94    Linux,
95    Windows,
96}
97
98/// The system this build runs on.
99pub const OS: Os = os::OS;
100
101/// A system's store of secrets that holds a login ahead of a tool's file, with a ceiling on
102/// what one item takes: the login keychain on macOS, Credential Manager on Windows. On Linux
103/// Claude Code keeps its login in `.credentials.json` alone (`live_chain_order`), so no file
104/// there is behind a store, and no store's ceiling refuses a write.
105#[derive(Debug, Clone, Copy, PartialEq, Eq)]
106pub enum SecretStore {
107    Keychain,
108    CredentialManager,
109}
110
111/// Where a home keeps its parked logins of Claude Code and Codex, as a person would look for
112/// them: on macOS the keychain, on Windows sealed files, on Linux the form the home recorded.
113/// Kept in a record by its [`Vault::code`].
114#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
115#[serde(rename_all = "snake_case")]
116pub enum Vault {
117    /// Items of the login keychain, which every home on the Mac shares.
118    Keychain,
119    /// Items of the Secret Service's default collection, which every home of the session shares.
120    SecretService,
121    /// Files in the home's `vault`, which only this account reads.
122    Files,
123    /// Files in the home's `vault`, sealed to this Windows account.
124    SealedFiles,
125}
126
127impl Vault {
128    /// What a program branches on: `keychain`, `secret_service`, `files` or `sealed_files`.
129    pub fn code(self) -> &'static str {
130        match self {
131            Vault::Keychain => "keychain",
132            Vault::SecretService => "secret_service",
133            Vault::Files => "files",
134            Vault::SealedFiles => "sealed_files",
135        }
136    }
137}
138
139/// What answers for the Secret Service on Linux, which the store parked logins are kept in is
140/// named for.
141#[derive(Debug, Clone, Copy, PartialEq, Eq)]
142pub enum Keyring {
143    /// gnome-keyring's login keyring, and whatever else answers, or nothing.
144    Login,
145    /// KDE's KWallet, through ksecretd or the kwalletd before it.
146    KWallet,
147}
148
149/// The only program trusted to read Claude Code's keychain item. Named here so the backend
150/// that runs it and the doctor check that looks for it cannot drift apart.
151pub(crate) const SECURITY: &str = "/usr/bin/security";
152
153// The Linux app's program, which its packages put beside `pitboard`.
154const LINUX_APP: &str = "pitboard-app";
155
156impl Os {
157    /// The program Pitboard reaches the system's own store of secrets through, where it goes
158    /// through one rather than calling the system directly.
159    pub(crate) fn secrets_tool(self) -> Option<&'static str> {
160        match self {
161            Os::MacOs => Some(SECURITY),
162            // Credential Manager is called directly, through Windows' own API.
163            Os::Linux | Os::Windows => None,
164        }
165    }
166
167    // What a person types to make `paths` private to themselves: on Windows two `icacls` a
168    // path, naming them by `sid`, and none without it or for files and folders alike.
169    pub(crate) fn make_private_commands(
170        self,
171        kind: Kind,
172        paths: &[&str],
173        sid: Option<&str>,
174    ) -> Vec<String> {
175        match self {
176            Os::MacOs | Os::Linux => {
177                let mode = match kind {
178                    Kind::Directory => "700",
179                    Kind::File => "600",
180                    Kind::Any => "go-rwx",
181                };
182                vec![format!("chmod {mode} {}", paths.join(" "))]
183            }
184            Os::Windows => match (kind, sid) {
185                (Kind::Directory | Kind::File, Some(sid)) => paths
186                    .iter()
187                    .flat_map(|path| acl::icacls(kind == Kind::Directory, path, sid))
188                    .collect(),
189                _ => Vec::new(),
190            },
191        }
192    }
193
194    pub(crate) fn remove_file_command(self, path: &Path) -> String {
195        match self {
196            Os::MacOs | Os::Linux => {
197                format!("rm '{}'", path.display().to_string().replace('\'', r"'\''"))
198            }
199            Os::Windows => {
200                let mut quoted = String::new();
201                for c in path.display().to_string().chars() {
202                    // PowerShell takes each of these as a single quote, so each is doubled.
203                    if matches!(c, '\'' | '\u{2018}' | '\u{2019}' | '\u{201a}' | '\u{201b}') {
204                        quoted.push(c);
205                    }
206                    quoted.push(c);
207                }
208                format!("Remove-Item -LiteralPath '{quoted}'")
209            }
210        }
211    }
212
213    // Looking in one asks the person whether Pitboard may. Linux and Windows guard none.
214    pub(crate) fn guarded_folders(self) -> &'static [&'static str] {
215        match self {
216            Os::MacOs => &[
217                "Desktop",
218                "Documents",
219                "Downloads",
220                "Library/Mobile Documents",
221                "Library/CloudStorage",
222            ],
223            Os::Linux | Os::Windows => &[],
224        }
225    }
226
227    // Homebrew's on a Mac, also npm's global `bin` there (`install_places`), and on Linux its
228    // default prefix's (docs/facts/linux.md).
229    pub(crate) fn package_bins(self, env: &Environment) -> Vec<PathBuf> {
230        match self {
231            Os::MacOs => vec!["/opt/homebrew/bin".into(), "/usr/local/bin".into()],
232            Os::Linux => vec!["/home/linuxbrew/.linuxbrew/bin".into()],
233            Os::Windows => [
234                ("APPDATA", &["npm"][..]),
235                ("LOCALAPPDATA", &["Microsoft", "WinGet", "Links"]),
236                ("USERPROFILE", &["scoop", "shims"]),
237            ]
238            .into_iter()
239            .filter_map(|(variable, below)| {
240                let mut place = env.named_folder(variable)?;
241                place.extend(below);
242                Some(place)
243            })
244            .collect(),
245        }
246    }
247
248    /// Whether `a` and `b` are one path, as Pitboard compares the places a program runs
249    /// from: component by component, exactly on macOS and Linux, and in any case on Windows,
250    /// whose file systems take `Codex.exe` and `codex.exe` for one file. Their process lists
251    /// give a program's path as it was started or as the file system has it, and the places a
252    /// tool's holders name are named by their makers in one case. Every comparison of where
253    /// a program runs from goes through this, so a system whose paths ignore case says so
254    /// once.
255    pub(crate) fn same_path(self, a: &Path, b: &Path) -> bool {
256        match self {
257            Os::MacOs | Os::Linux => a == b,
258            Os::Windows => same_path_in_any_case(a, b),
259        }
260    }
261
262    pub(crate) fn variable_key(self, name: &std::ffi::OsStr) -> std::ffi::OsString {
263        match self {
264            Os::MacOs | Os::Linux => name.to_os_string(),
265            Os::Windows => name
266                .to_string_lossy()
267                .chars()
268                .map(upper_one_for_one)
269                .collect::<String>()
270                .into(),
271        }
272    }
273
274    pub(crate) fn user_variable(self) -> &'static str {
275        match self {
276            Os::MacOs | Os::Linux => "USER",
277            Os::Windows => "USERNAME",
278        }
279    }
280
281    // Bun 1.4.3's `os.homedir` on Windows is libuv's `uv_os_homedir`: `USERPROFILE`, else
282    // `GetUserProfileDirectoryW`. Git Bash sets `HOME`, which no tool takes for the home there.
283    pub fn home_variable(self) -> &'static str {
284        match self {
285            Os::MacOs | Os::Linux => "HOME",
286            Os::Windows => "USERPROFILE",
287        }
288    }
289
290    // From the home it is handed, so a scheduled run and one by hand agree.
291    pub(crate) fn default_pitboard_home(self, home: &Path) -> PathBuf {
292        match self {
293            Os::MacOs | Os::Linux => home.join(".pitboard"),
294            Os::Windows => home.join("AppData").join("Local").join("Pitboard"),
295        }
296    }
297
298    // Never beside the Windows app's `Pitboard.exe`, since NTFS takes the two names for one.
299    pub(crate) fn app_command_line(self, app: &Path) -> Option<PathBuf> {
300        match self {
301            Os::MacOs => (app.extension() == Some("app".as_ref()))
302                .then(|| app.join("Contents/Helpers/pitboard")),
303            Os::Linux => (app.file_name() == Some(LINUX_APP.as_ref()))
304                .then(|| app.with_file_name("pitboard")),
305            Os::Windows => app
306                .file_name()
307                .filter(|name| name.eq_ignore_ascii_case("Pitboard.exe"))
308                .and_then(|_| app.parent())
309                .map(|install| install.join("bin").join("pitboard.exe")),
310        }
311    }
312
313    // What a scheduler starts to run `program`. On Windows, `pitboardw.exe` beside
314    // `pitboard.exe`, which has no console and starts it with none: below Windows 11 24H2 a task
315    // gives a console program a window (docs/facts/windows-runners.md).
316    pub(crate) fn launcher(self, program: &Path) -> Option<PathBuf> {
317        match self {
318            Os::MacOs | Os::Linux => None,
319            Os::Windows => {
320                let mut name = program.file_stem()?.to_os_string();
321                name.push("w");
322                if let Some(extension) = program.extension() {
323                    name.push(".");
324                    name.push(extension);
325                }
326                Some(program.with_file_name(name))
327            }
328        }
329    }
330
331    // The program an app itself starts, where no command line is kept, so a schedule that runs
332    // it renews nothing. Windows keeps macOS's bundle rule, which no path there meets.
333    pub(crate) fn an_apps_own_program(self, program: &Path) -> bool {
334        match self {
335            Os::MacOs | Os::Windows => {
336                let mut dirs = program
337                    .ancestors()
338                    .skip(1)
339                    .map(|dir| dir.file_name().and_then(|n| n.to_str()));
340                dirs.next() == Some(Some("MacOS")) && dirs.next() == Some(Some("Contents"))
341            }
342            Os::Linux => program.file_name() == Some(LINUX_APP.as_ref()),
343        }
344    }
345}
346
347/// Whether `a` and `b` are one path as Windows compares them: component by component, each
348/// name in any case ([`same_name_in_any_case`]). Said once, for every comparison of paths on
349/// Windows, the core's and an app's.
350pub fn same_path_in_any_case(a: &Path, b: &Path) -> bool {
351    let (mut a, mut b) = (a.components(), b.components());
352    loop {
353        match (a.next(), b.next()) {
354            (None, None) => return true,
355            (Some(one), Some(other))
356                if same_name_in_any_case(one.as_os_str(), other.as_os_str()) => {}
357            _ => return false,
358        }
359    }
360}
361
362// One text per Windows path, read lexically on every system: two spellings of one folder key
363// alike, and a short name or a link keys apart, as a symlink does on macOS.
364pub fn path_key_in_any_case(path: &str) -> String {
365    let path = path.replace('/', r"\");
366    let path = match path.get(..8) {
367        Some(verbatim) if verbatim.eq_ignore_ascii_case(r"\\?\UNC\") => {
368            format!(r"\\{}", &path[8..])
369        }
370        _ => path.strip_prefix(r"\\?\").unwrap_or(&path).to_owned(),
371    };
372    let upper = |name: &str| name.chars().map(upper_one_for_one).collect::<String>();
373    let drive = path
374        .as_bytes()
375        .get(..2)
376        .filter(|head| head[0].is_ascii_alphabetic() && head[1] == b':')
377        .map(|head| char::from(head[0].to_ascii_uppercase()));
378    let (root, rest) = if let Some(unc) = path.strip_prefix(r"\\") {
379        let mut parts = unc.splitn(3, '\\');
380        let (server, share) = (parts.next().unwrap_or(""), parts.next().unwrap_or(""));
381        (
382            format!(r"\\{}\{}\", upper(server), upper(share)),
383            parts.next().unwrap_or(""),
384        )
385    } else if let Some(drive) = drive {
386        match path[2..].strip_prefix('\\') {
387            Some(rest) => (format!(r"{drive}:\"), rest),
388            None => (format!("{drive}:"), &path[2..]),
389        }
390    } else if let Some(rest) = path.strip_prefix('\\') {
391        (r"\".to_owned(), rest)
392    } else {
393        (String::new(), path.as_str())
394    };
395    let rooted = root.ends_with('\\');
396    let mut names: Vec<&str> = Vec::new();
397    for name in rest.split('\\') {
398        match name {
399            "" | "." => {}
400            ".." if names.last().is_some_and(|last| *last != "..") => {
401                names.pop();
402            }
403            ".." if rooted => {}
404            name => names.push(name),
405        }
406    }
407    let names: Vec<String> = names.into_iter().map(upper).collect();
408    root + &names.join(r"\")
409}
410
411// As libuv's realpath and Codex's `AbsolutePathBuf` spell what `GetFinalPathNameByHandleW`
412// gives, read lexically on every system.
413pub(crate) fn without_verbatim_prefix(path: PathBuf) -> PathBuf {
414    let Some(text) = path.to_str() else {
415        return path;
416    };
417    if let Some(unc) = text.strip_prefix(r"\\?\UNC\") {
418        return PathBuf::from(format!(r"\\{unc}"));
419    }
420    match text.strip_prefix(r"\\?\") {
421        Some(rest) if drive_absolute(rest) => PathBuf::from(rest),
422        _ => path,
423    }
424}
425
426fn drive_absolute(path: &str) -> bool {
427    matches!(path.as_bytes(), [drive, b':', b'\\' | b'/', ..] if drive.is_ascii_alphabetic())
428}
429
430// A full path as Rust's `Path::is_absolute` reads one on Windows, on any system: from a drive's
431// root, `\\server\share`, or a `\\?\` or `\\.\` path, `/` taken for `\`.
432pub(crate) fn windows_absolute(path: &str) -> bool {
433    let separator = |c: char| c == '\\' || c == '/';
434    let Some(rest) = path
435        .strip_prefix(separator)
436        .and_then(|rest| rest.strip_prefix(separator))
437    else {
438        return drive_absolute(path);
439    };
440    // With a `/` in it, `\\?\` is no verbatim path but a server named `?`.
441    if path.starts_with(r"\\?\")
442        || rest
443            .strip_prefix('.')
444            .is_some_and(|device| device.starts_with(separator))
445    {
446        return true;
447    }
448    let mut names = rest.split(separator);
449    names.next().is_some_and(|server| !server.is_empty())
450        && names.next().is_some_and(|share| !share.is_empty())
451}
452
453// Claude Desktop's on Windows, which no test reads (AGENTS.md). Its `Claude-3p` there is named
454// by analogy with macOS's, unmeasured: a guard may refuse more than is there.
455#[cfg(any(test, feature = "test-support"))]
456pub(crate) fn claude_desktop_on_windows(roaming: &[PathBuf], local: &[PathBuf]) -> Vec<PathBuf> {
457    let roaming = roaming
458        .iter()
459        .flat_map(|dir| ["Claude", "Claude-3p"].map(|name| dir.join(name)));
460    roaming
461        .chain(local.iter().map(|dir| dir.join("AnthropicClaude")))
462        .collect()
463}
464
465// Where the Windows app's account windows keep their WebView2 sign-ins, each build its own.
466#[cfg(any(test, feature = "test-support"))]
467pub(crate) fn pitboard_app_on_windows(local: &[PathBuf]) -> Vec<PathBuf> {
468    local
469        .iter()
470        .flat_map(|dir| ["Pitboard App", "Pitboard App Debug"].map(|name| dir.join(name)))
471        .collect()
472}
473
474// Where the Linux app keeps its own data and cache, each build its own: the account windows'
475// sign-ins among them, as on Windows.
476#[cfg(any(test, feature = "test-support"))]
477pub(crate) fn pitboard_app_on_linux(data: &[PathBuf], cache: &[PathBuf]) -> Vec<PathBuf> {
478    data.iter()
479        .chain(cache)
480        .flat_map(|dir| {
481            ["com.usepitboard.Pitboard", "com.usepitboard.Pitboard.Devel"].map(|id| dir.join(id))
482        })
483        .collect()
484}
485
486// Where this account keeps a real login, or would, and where `started_in` says, for a build for
487// tests to refuse. This account's own are asked of the system, never of the environment: its
488// XDG folders are the defaults in the home the system names.
489#[cfg(any(test, feature = "test-support"))]
490pub(crate) fn real_login_places(
491    started_in: Option<&Context>,
492) -> std::result::Result<Vec<PathBuf>, String> {
493    let home = user::accounts_own_home().ok_or("this system names no home for this account")?;
494    let pitboard = user::accounts_own_pitboard_home()
495        .ok_or("this system names no Pitboard folder for this account")?;
496    let own = Context::new(home).with_pitboard_home(pitboard);
497    // A test's child is started with scratch app data folders inside its own config folder.
498    let (roaming, local) = user::app_data_folders(started_in.is_some());
499    Ok(std::iter::once(&own)
500        .chain(started_in)
501        .flat_map(|ctx| {
502            let mut places = vec![
503                crate::provider::claude::paths::config_dir(ctx),
504                crate::provider::claude::paths::config_file(ctx),
505                crate::provider::codex::paths::home(ctx),
506                ctx.pitboard_home.clone(),
507                ctx.default_pitboard_home(),
508            ];
509            match ctx.os {
510                Os::MacOs => places.extend([
511                    ctx.home.join("Library/Application Support/Claude"),
512                    ctx.home.join("Library/Application Support/Claude-3p"),
513                    PathBuf::from("/Applications/Claude.app"),
514                ]),
515                Os::Linux => places.extend(pitboard_app_on_linux(
516                    ctx.data_home.as_slice(),
517                    ctx.cache_home.as_slice(),
518                )),
519                // Asked of the system below, with the ones this process was started with.
520                Os::Windows => {}
521            }
522            places
523        })
524        .chain(claude_desktop_on_windows(&roaming, &local))
525        .chain(pitboard_app_on_windows(&local))
526        .filter(|place| place.is_absolute())
527        .collect())
528}
529
530#[cfg(all(windows, any(test, feature = "test-support")))]
531pub(crate) use windows::lasting_environment;
532
533// What the account's lasting environment names, which a test's own may have inherited: nothing
534// off Windows.
535#[cfg(all(not(windows), any(test, feature = "test-support")))]
536pub(crate) fn lasting_environment(_name: &str) -> Vec<String> {
537    Vec::new()
538}
539
540// Is, holds or lies in, for a build for tests to refuse, the same on every system: through
541// every link, one to nothing yet included, and in any case, as macOS's own volumes compare.
542#[cfg(any(test, feature = "test-support"))]
543pub(crate) fn lies_in(path: &Path, place: &Path) -> bool {
544    let path = std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf());
545    let (real, real_place) = (resolved(&path, LINKS), resolved(place, LINKS));
546    near(&path, place)
547        || near(&real, &real_place)
548        || meets(&real, &real_place)
549        || meets(&real_place, &real)
550}
551
552// So a loop of links ends, as the system's own lookup does.
553#[cfg(any(test, feature = "test-support"))]
554const LINKS: u8 = 32;
555
556#[cfg(any(test, feature = "test-support"))]
557fn near(a: &Path, b: &Path) -> bool {
558    begins(a, b) || begins(b, a)
559}
560
561// `canonicalize` spells `C:\x` as `\\?\C:\x`.
562#[cfg(any(test, feature = "test-support"))]
563fn begins(path: &Path, with: &Path) -> bool {
564    let with = without_verbatim_prefix(with.to_path_buf());
565    without_verbatim_prefix(path.to_path_buf())
566        .ancestors()
567        .any(|above| same_path_in_any_case(above, &with))
568}
569
570// A folder above `a` that is `b`'s deepest existing one, whatever either is named:
571// `canonicalize` keeps /System/Volumes/Data/Users, which is /Users.
572#[cfg(any(test, feature = "test-support"))]
573fn meets(a: &Path, b: &Path) -> bool {
574    let Some((deepest, below_b)) = b
575        .ancestors()
576        .find_map(|above| Some((fs::file_id(above)?, b.strip_prefix(above).ok()?)))
577    else {
578        return false;
579    };
580    a.ancestors().any(|above| {
581        fs::file_id(above) == Some(deepest)
582            && a.strip_prefix(above)
583                .is_ok_and(|below_a| near(below_a, below_b))
584    })
585}
586
587// The deepest part that exists, resolved, or a link there followed though it leads nowhere
588// yet; the rest after it as written, less each `..`, as a folder made there would take it.
589#[cfg(any(test, feature = "test-support"))]
590fn resolved(path: &Path, links: u8) -> PathBuf {
591    for found in path.ancestors() {
592        let Ok(rest) = path.strip_prefix(found) else {
593            continue;
594        };
595        if let Ok(real) = std::fs::canonicalize(found) {
596            return beyond(real, rest);
597        }
598        let link = std::fs::symlink_metadata(found).is_ok_and(|it| it.file_type().is_symlink());
599        if let (true, Some(left), Ok(to)) = (link, links.checked_sub(1), std::fs::read_link(found))
600        {
601            let to = match found.parent() {
602                Some(parent) => parent.join(to),
603                None => to,
604            };
605            return resolved(&beyond(to, rest), left);
606        }
607    }
608    path.to_path_buf()
609}
610
611#[cfg(any(test, feature = "test-support"))]
612fn beyond(mut at: PathBuf, rest: &Path) -> PathBuf {
613    for part in rest.components() {
614        match part {
615            std::path::Component::ParentDir => {
616                at.pop();
617            }
618            std::path::Component::CurDir => {}
619            part => at.push(part),
620        }
621    }
622    at
623}
624
625fn same_name_in_any_case(a: &std::ffi::OsStr, b: &std::ffi::OsStr) -> bool {
626    let (a, b) = (a.to_string_lossy(), b.to_string_lossy());
627    a.chars()
628        .map(upper_one_for_one)
629        .eq(b.chars().map(upper_one_for_one))
630}
631
632// As Windows upper-cases a name: one UTF-16 unit for one, so ß and anything past the BMP stay.
633pub(crate) fn upper_one_for_one(c: char) -> char {
634    if u32::from(c) > 0xFFFF {
635        return c;
636    }
637    let mut upper = c.to_uppercase();
638    match (upper.next(), upper.next()) {
639        (Some(one), None) => one,
640        _ => c,
641    }
642}
643
644/// What the person's login shell said its `PATH` is.
645#[derive(Debug, Clone, PartialEq, Eq)]
646#[cfg_attr(
647    windows,
648    allow(
649        dead_code,
650        reason = "only a login shell is late, and Windows has none: its `Path` is read from \
651                  the registry"
652    )
653)]
654pub(crate) enum LoginPath {
655    /// It said this.
656    Said(String),
657    /// It could not be asked, or did not say. Asking again would get the same.
658    Unknown,
659    /// It had not answered in time, and was stopped. Startup files are slowest while the
660    /// machine is busy, which is when an app that opens at login first asks, so this is not
661    /// the last word: a later ask may find what this one could not.
662    Late,
663}
664
665// A login shell can take seconds, so never on an app's main thread.
666pub(crate) fn login_path(env: &Environment) -> LoginPath {
667    os::login_path(env)
668}
669
670/// Who besides a file's owner can reach it, as the system says.
671#[derive(Debug, Clone, PartialEq, Eq)]
672pub(crate) struct Access {
673    /// Whether anybody but the owner can read or change it.
674    pub(crate) shared: bool,
675    // For a person to read: `mode 600`, or on Windows who may reach it, never by SID.
676    pub(crate) described: String,
677}
678
679// What a folder Pitboard keeps logins in is, as `fs::private_dir` finds it.
680#[derive(Debug, Clone, Copy, PartialEq, Eq)]
681pub enum Private {
682    Yes,
683    Shared,
684    NotOwn,
685    Link,
686    NotADirectory,
687    Missing,
688}
689
690// What a person makes private with the commands `Os::make_private_commands` gives.
691#[derive(Debug, Clone, Copy, PartialEq, Eq)]
692pub(crate) enum Kind {
693    Directory,
694    File,
695    /// Directories and files alike.
696    Any,
697}
698
699/// Whether this process runs as the person themselves, as the system says. Pitboard changes
700/// nothing unless it is [`Elevation::Normal`]: what a run with more rights than the person's
701/// own writes is not theirs, in their own home and their own keychain, and their next
702/// ordinary run may not be able to read it, replace it or take it away.
703#[derive(Debug, Clone, Copy, PartialEq, Eq)]
704pub enum Elevation {
705    /// As the person themselves.
706    Normal,
707    /// With rights that are not the person's own. `why` says how, in words that follow
708    /// "Pitboard runs", such as `as root`, `with sudo` or `as administrator`.
709    Elevated { why: &'static str },
710    /// The system could not say, which Pitboard takes as a reason to change nothing.
711    Unknown,
712}
713
714#[derive(Debug, Clone, Copy, PartialEq, Eq)]
715pub enum Floor {
716    Met,
717    Below { build: u32 },
718    Unknown,
719}
720
721// What Windows' settings say that changes what Pitboard or a tool does there.
722#[derive(Debug, Clone, Default, PartialEq, Eq)]
723pub(crate) struct WindowsSettings {
724    // The distributions WSL holds for this account, by `DistributionName` under HKCU's `Lxss`.
725    pub(crate) wsl: Vec<String>,
726    // `ProxyServer` where `ProxyEnable` is not 0, as hyper-util 0.1.20 reads them for Codex.
727    pub(crate) proxy: Option<String>,
728    // `EnableLUA`, which runs administrators in Admin Approval Mode where it is not 0.
729    pub(crate) admin_approval: Option<bool>,
730}
731
732// Windows 10 version 2004's build, the first a package with an external location registers on.
733pub(crate) const WINDOWS_FLOOR: u32 = 19041;
734
735#[cfg(any(windows, test))]
736pub(crate) fn windows_floor(version: Option<(u32, u32, u32)>) -> Floor {
737    match version {
738        None => Floor::Unknown,
739        Some((major, minor, build)) if (major, minor, build) >= (10, 0, WINDOWS_FLOOR) => {
740            Floor::Met
741        }
742        Some((_, _, build)) => Floor::Below { build },
743    }
744}
745
746#[derive(Debug, Clone, PartialEq, Eq)]
747pub(crate) struct Process {
748    pub(crate) pid: u32,
749    // macOS gives what it was started as, which a shell gives as the bare name.
750    pub(crate) path: PathBuf,
751    // The family of the Windows package it runs from.
752    pub(crate) package: Option<String>,
753}
754
755#[derive(Debug, Clone, PartialEq, Eq)]
756pub struct Listed {
757    pub pid: u32,
758    pub parent: u32,
759    pub path: PathBuf,
760    pub package: Option<String>,
761    // False where Windows would not say whose it is or where it runs from: `path` is its name.
762    pub placed: bool,
763}
764
765// None where one of them cannot be placed, since it may be any kind of holder.
766pub(crate) fn named(os: Os, all: Vec<Listed>, program: &str) -> Option<Vec<Process>> {
767    let files: Vec<String> = match os {
768        Os::MacOs | Os::Linux => vec![program.to_owned()],
769        Os::Windows => {
770            let mut files = vec![format!("{program}.exe")];
771            // winget's Codex is the nested portable codex-<triple>.exe behind Links\codex.exe;
772            // Toolhelp names the image the link resolves to (codex_windows_install_places).
773            if program == "codex" {
774                files.push("codex-x86_64-pc-windows-msvc.exe".to_owned());
775                files.push("codex-aarch64-pc-windows-msvc.exe".to_owned());
776            }
777            files
778        }
779    };
780    let runs = |name: &std::ffi::OsStr| match os {
781        Os::MacOs | Os::Linux => files.iter().any(|file| name == file.as_str()),
782        Os::Windows => files
783            .iter()
784            .any(|file| same_name_in_any_case(name, std::ffi::OsStr::new(file))),
785    };
786    let found: Vec<Listed> = all
787        .into_iter()
788        .filter(|p| p.path.file_name().is_some_and(runs))
789        .collect();
790    if found.iter().any(|p| !p.placed) {
791        return None;
792    }
793    Some(
794        found
795            .into_iter()
796            .map(|p| Process {
797                pid: p.pid,
798                path: p.path,
799                package: p.package,
800            })
801            .collect(),
802    )
803}
804
805pub struct Jar {
806    pub version: i64,
807    pub compatible: i64,
808    pub cookies: Vec<Cookie>,
809}
810
811pub struct Cookie {
812    pub host: String,
813    pub name: String,
814    pub path: String,
815    pub stored: Vec<u8>,
816    pub expires_utc: i64,
817}
818
819// Lengths only: a cookie's value is a login.
820impl std::fmt::Debug for Cookie {
821    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
822        f.debug_struct("Cookie")
823            .field("host", &self.host)
824            .field("name", &self.name)
825            .field("path", &self.path)
826            .field("stored", &format_args!("{} bytes", self.stored.len()))
827            .field("expires_utc", &self.expires_utc)
828            .finish()
829    }
830}
831
832#[derive(Debug)]
833pub enum JarError {
834    Absent,
835    // a write is under way, or the jar is held
836    Unsettled(String),
837    // read, and not a shape Pitboard knows
838    Unknown(String),
839    Unreadable(String),
840    Unsupported,
841}
842
843#[cfg(any(test, feature = "test-support"))]
844pub(crate) use os::write_jar;
845
846// What a run is handed to read. Windows takes `Nothing` alone.
847#[derive(Debug, Clone, Copy)]
848pub(crate) enum Input<'a> {
849    Nothing,
850    #[cfg_attr(not(target_os = "macos"), allow(dead_code))]
851    Stdin(&'a [u8]),
852    #[cfg_attr(windows, allow(dead_code))]
853    Descriptor3(&'a [u8]),
854}
855
856// What is kept of what a warm-up's tool prints.
857const TOOL_PRINTS: u64 = 1 << 20;
858
859// How long what a run printed is waited for once it ended: something that left its group may
860// still hold a pipe.
861const DRAINED: std::time::Duration = std::time::Duration::from_secs(5);
862
863// Up to `kept` bytes of what a pipe carries, read on a thread of its own so a chatty program
864// cannot stall.
865fn drained(
866    pipe: Option<impl std::io::Read + Send + 'static>,
867    kept: u64,
868) -> std::sync::mpsc::Receiver<Vec<u8>> {
869    let (said, printed) = std::sync::mpsc::channel();
870    std::thread::spawn(move || {
871        use std::io::Read;
872        let mut bytes = Vec::new();
873        if let Some(pipe) = pipe {
874            let _ = pipe.take(kept).read_to_end(&mut bytes);
875        }
876        let _ = said.send(bytes);
877    });
878    printed
879}
880
881// What a run that ended with `status` printed, both pipes by one deadline.
882fn output(
883    status: std::process::ExitStatus,
884    stdout: std::sync::mpsc::Receiver<Vec<u8>>,
885    stderr: std::sync::mpsc::Receiver<Vec<u8>>,
886) -> std::io::Result<std::process::Output> {
887    let by = std::time::Instant::now() + DRAINED;
888    let (stdout, stderr) = printed(&stdout, &stderr, by)?;
889    Ok(std::process::Output {
890        status,
891        stdout,
892        stderr,
893    })
894}
895
896// A pipe still open at `by` fails the run, rather than answer with part of what it said.
897fn printed(
898    stdout: &std::sync::mpsc::Receiver<Vec<u8>>,
899    stderr: &std::sync::mpsc::Receiver<Vec<u8>>,
900    by: std::time::Instant,
901) -> std::io::Result<(Vec<u8>, Vec<u8>)> {
902    let read = |pipe: &std::sync::mpsc::Receiver<Vec<u8>>| {
903        pipe.recv_timeout(by.saturating_duration_since(std::time::Instant::now()))
904            .map_err(|_| {
905                std::io::Error::new(
906                    std::io::ErrorKind::TimedOut,
907                    format!(
908                        "its output was still open {}s after it ended",
909                        DRAINED.as_secs()
910                    ),
911                )
912            })
913    };
914    Ok((read(stdout)?, read(stderr)?))
915}
916
917// What `ceiling` stopped, as a run says it.
918fn timed_out(ceiling: std::time::Duration) -> std::io::Error {
919    std::io::Error::new(
920        std::io::ErrorKind::TimedOut,
921        format!("no answer within {}s", ceiling.as_secs()),
922    )
923}
924
925/// The machine Pitboard is standing on, as one value rather than a set of `cfg` branches
926/// spread through the crate. A host answers where another program's secrets may be, where
927/// Pitboard's own parked logins go, what this user is running and how daily renewal is
928/// scheduled. It takes the context on every call because a context is built by a builder
929/// and can still change after it exists.
930///
931/// It was called `Platform` until a second provider was on the way. The name said "which
932/// operating system", the body reached into Claude Code's own slot hashing, and once
933/// "provider" became a word this codebase uses, a reader meeting `Platform` could not tell
934/// which of the two axes it meant. What stays behind this name is the machine, and only the
935/// machine: which item or file a tool keeps its login in is the tool's to say.
936pub(crate) trait Host: Send + Sync + std::fmt::Debug {
937    /// Secrets another program keeps in the system's own store of them, under `account`:
938    /// the login keychain on macOS, Credential Manager's generic items on Windows. `None`
939    /// where the system has no such store, and a tool keeps its login in a file instead.
940    ///
941    /// Which items and which account is the other program's business, so both are handed
942    /// in. Deriving them here is how Claude Code's slot hashing came to live inside what
943    /// claimed to be an operating-system abstraction.
944    fn foreign_secrets(&self, ctx: &Context, account: &str) -> Option<Box<dyn RawStore>>;
945
946    /// The single file at `path`, as a store.
947    fn file(&self, path: PathBuf) -> Box<dyn RawStore>;
948
949    /// The forms a home may keep its parked logins in, where this system offers a choice,
950    /// which each home records in `state.json`: Linux's Secret Service and files. None where
951    /// the system keeps them one way, as macOS does in the keychain and Windows in sealed files.
952    fn vault_forms(&self) -> &'static [VaultForm] {
953        &[]
954    }
955
956    /// Whether a vault of `form` answers here, for a form this system offers: files always do,
957    /// and the Secret Service where something on this session's bus has a default collection,
958    /// locked or not. Nothing is unlocked to tell.
959    fn answers(&self, _ctx: &Context, _form: VaultForm) -> bool {
960        false
961    }
962
963    /// What answers for the Secret Service on this session's bus, where this system parks in
964    /// one. Nothing is started or unlocked to tell.
965    fn keyring(&self, _ctx: &Context) -> Keyring {
966        Keyring::Login
967    }
968
969    /// Where Pitboard's own parked logins go: the system's store of secrets where there is
970    /// one, a private directory of files where there is not, and where the system offers
971    /// both, the one `form` names. This one really is a fact about the machine.
972    fn vault(&self, ctx: &Context, form: Option<VaultForm>) -> Box<dyn RawStore>;
973
974    /// Whether every `PITBOARD_HOME` on this machine that keeps its parks in `form` parks
975    /// them in the one vault. A keychain or a Secret Service collection belongs to the whole
976    /// login session, so a park in it that one home cannot account for may be another home's;
977    /// a vault of files lives inside its home, and nothing in it can be anybody else's.
978    fn vault_is_shared(&self, form: Option<VaultForm>) -> bool;
979
980    // Every process this user runs, in any session; Err says why the list could not be read.
981    fn listing(&self) -> std::result::Result<Vec<Listed>, String>;
982
983    // By the program's own name, so a script that merely mentions it is not counted. None is
984    // not the same as none running. Another user's processes use that user's login.
985    fn processes(&self, program: &str) -> Option<Vec<Process>> {
986        named(OS, self.listing().ok()?, program)
987    }
988
989    // a Chromium jar's rows for `hosts`, and those named one of `names` on any host, as stored
990    fn cookies(
991        &self,
992        jar: &Path,
993        hosts: &[&str],
994        names: &[&str],
995    ) -> std::result::Result<Jar, JarError>;
996
997    // None on a real host in a build for tests; a test names a version through `app_at`.
998    fn app_version(&self, bundle: &Path) -> Option<String>;
999    fn app_id(&self, bundle: &Path) -> Option<String>;
1000
1001    /// The system's own scheduler, which runs Pitboard's jobs ([`crate::schedule::Job`]).
1002    /// `None` where there is none Pitboard knows how to ask.
1003    fn scheduler(&self) -> Option<&dyn Scheduler>;
1004
1005    /// Whether this process runs as the person themselves, which is what the one gate every
1006    /// change passes asks ([`crate::permit::Permit`]). Takes the context because part of
1007    /// the answer can be in the environment this process was started with, such as the
1008    /// `SUDO_UID` sudo sets.
1009    fn elevation(&self, ctx: &Context) -> Elevation;
1010
1011    fn floor(&self) -> Floor;
1012
1013    /// The file at `path`, outside every home, that only an administrator writes, such as
1014    /// Codex's `/etc/codex/requirements.toml`. Which file is the tool's to say.
1015    ///
1016    /// Unset in a build for tests, on the real hosts ([`administered::READ_BY_REAL_HOSTS`]).
1017    fn administered_file(&self, path: &Path) -> Administered {
1018        if administered::READ_BY_REAL_HOSTS {
1019            administered::read_text(path)
1020        } else {
1021            Administered::Unset
1022        }
1023    }
1024
1025    // As `administered_file`, read as `administered::read_up_to` reads it.
1026    fn administered_file_up_to(&self, path: &Path, limit: u64) -> Administered {
1027        if administered::READ_BY_REAL_HOSTS {
1028            administered::read_up_to(path, limit)
1029        } else {
1030            Administered::Unset
1031        }
1032    }
1033
1034    /// The text an administrator's configuration profile forces `key` of the program whose
1035    /// preferences are `domain` to: a managed preference, on macOS. Unset where nothing
1036    /// forces it, whoever set it otherwise, and on a system with no managed preferences.
1037    ///
1038    /// Unset in a build for tests, on the real hosts ([`administered::READ_BY_REAL_HOSTS`]).
1039    fn managed_preference(&self, domain: &str, key: &str) -> Administered;
1040
1041    // A configuration profile's plist as JSON: on macOS alone, and never in a build for tests.
1042    fn managed_plist(&self, _path: &Path) -> Administered {
1043        Administered::Unset
1044    }
1045
1046    // None in a build for tests, on the real hosts.
1047    fn administered_folder(&self, dir: &Path) -> Vec<PathBuf> {
1048        if administered::READ_BY_REAL_HOSTS {
1049            administered::listed(dir)
1050        } else {
1051            Vec::new()
1052        }
1053    }
1054
1055    // A Windows policy value; unset elsewhere, and in a build for tests, on the real hosts.
1056    fn policy(&self, _hive: Hive, _key: &str, _value: &str) -> Administered {
1057        Administered::Unset
1058    }
1059
1060    // Windows' `FOLDERID_ProgramData`, where it can say; none elsewhere.
1061    fn program_data(&self) -> Option<PathBuf> {
1062        None
1063    }
1064
1065    // The letters of Windows' fixed drives, at whose root a path with no drive leads; none
1066    // elsewhere.
1067    fn fixed_drives(&self) -> Vec<char> {
1068        Vec::new()
1069    }
1070
1071    // The names of Credential Manager's items that begin `prefix`, never what they hold; none
1072    // elsewhere, and none in a build for tests on the real hosts.
1073    fn credential_names(&self, _prefix: &str) -> std::result::Result<Vec<String>, String> {
1074        Ok(Vec::new())
1075    }
1076
1077    // As `HKCU\Environment` holds it, which a program started from now on is given; unset
1078    // elsewhere, and in a build for tests on the real hosts.
1079    fn user_environment(&self, _name: &str) -> Administered {
1080        Administered::Unset
1081    }
1082
1083    // As `HKLM`'s `Session Manager\Environment` holds it, which a program started from now on is
1084    // given where `HKCU\Environment` does not name it; unset elsewhere, and in a build for tests
1085    // on the real hosts.
1086    fn machine_environment(&self, _name: &str) -> Administered {
1087        Administered::Unset
1088    }
1089
1090    // Whether Credential Manager holds a generic item named `target`, never what it holds; Err
1091    // says why it cannot tell. None is held where there is no Credential Manager.
1092    fn credential_held(
1093        &self,
1094        _ctx: &Context,
1095        _target: &str,
1096    ) -> std::result::Result<bool, crate::store::Error> {
1097        Ok(false)
1098    }
1099
1100    // None elsewhere, and none in a build for tests on the real hosts.
1101    fn windows_settings(&self) -> WindowsSettings {
1102        WindowsSettings::default()
1103    }
1104
1105    // Whether `/proc/version` names Microsoft, as Codex tells WSL (`codex_wsl`); false elsewhere,
1106    // and in a build for tests on the real hosts.
1107    fn kernel_is_wsl(&self) -> bool {
1108        false
1109    }
1110
1111    // Whether `path`, or the nearest folder above it that opens, is on 9p, as WSL 2 mounts
1112    // Windows' drives; false off Linux.
1113    fn on_a_windows_drive(&self, _path: &Path) -> bool {
1114        false
1115    }
1116
1117    /// Whether a watch of the folder `dir` ([`watch`]) hears every write there. Where it does
1118    /// not, a front end looks at Pitboard's files every few seconds instead.
1119    fn watches(&self, _dir: &Path) -> bool {
1120        true
1121    }
1122}
1123
1124/// The system's own scheduler, which starts Pitboard's jobs ([`crate::schedule::Job`]):
1125/// `pitboard renew` once a day, and `pitboard watch` from sign-in on. launchd on macOS, a
1126/// systemd user unit on Linux, Task Scheduler on Windows. Never a homemade daemon.
1127///
1128/// What Pitboard decides about a job, which program it runs, with what, and whether it is
1129/// this home's to change, is [`crate::schedule`]'s. This is only how the system is asked, and
1130/// what it says back.
1131pub(crate) trait Scheduler: Send + Sync + std::fmt::Debug {
1132    /// Where the job is kept, where a person would look for it.
1133    fn location(&self, ctx: &Context, job: Job) -> crate::schedule::Location;
1134
1135    /// Whether the job is there.
1136    fn installed(&self, ctx: &Context, job: Job) -> bool;
1137
1138    /// The Pitboard the job runs, read back from what [`Scheduler::put`] wrote. `None` where
1139    /// nothing is installed, and where what is there does not name one the way `put` writes
1140    /// it.
1141    fn program(&self, ctx: &Context, job: Job) -> Option<PathBuf>;
1142
1143    /// The options the job runs Pitboard with after its marker ([`Job::marked`]), such as
1144    /// `--at 90`, as [`Scheduler::put`] wrote them, read back. Empty where nothing is
1145    /// installed, and where what is there does not run Pitboard the way `put` writes it.
1146    fn options(&self, ctx: &Context, job: Job) -> Vec<String>;
1147
1148    /// The variables the job is given, by name, as [`Scheduler::put`] wrote them, read back.
1149    /// Empty where nothing is installed, and where what is there gives none the way `put`
1150    /// writes them. The system can give a job more of its own, which this does not say.
1151    fn environment(&self, ctx: &Context, job: Job) -> Vec<(String, String)>;
1152
1153    /// Hand the system `job`, which runs `program` with the job's marker and `options`, given
1154    /// `environment`, each variable by name, besides what the system gives every job, and ask
1155    /// the system to start it. What is written can hold a proxy's password, so only the person
1156    /// can read it, whatever was there before.
1157    ///
1158    /// Where the system will not start it, what was there goes back as it was, and is
1159    /// started again. The status, doctor and the app all read what is there, so a job left
1160    /// written that nothing runs would say it is on while it is not, which is the failure
1161    /// nobody would notice until the parked logins had run out or an account had.
1162    fn put(
1163        &self,
1164        ctx: &Context,
1165        permit: Permit,
1166        job: Job,
1167        program: &Path,
1168        options: &[String],
1169        environment: &[(String, String)],
1170    ) -> Result<()>;
1171
1172    /// Stop the job and take it away. `false` when nothing was there.
1173    fn remove(&self, ctx: &Context, permit: Permit, job: Job) -> Result<bool>;
1174
1175    /// Whether this process is a run `job` started. `said` is the job a test says this
1176    /// process runs as; `None` leaves it to what the system says.
1177    fn started_this_process(&self, job: Job, said: Option<&str>) -> bool;
1178
1179    // What a run it started reads for itself of what `put` was given: none where the system
1180    // hands the job its variables.
1181    fn read_by_its_runs(&self, _ctx: &Context, _job: Job) -> Vec<(String, String)> {
1182        Vec::new()
1183    }
1184
1185    // What the system says of the job beyond what Pitboard wrote: Task Scheduler's alone.
1186    fn task(&self, _ctx: &Context, _job: Job) -> Option<task::Task> {
1187        None
1188    }
1189
1190    // The launcher the job starts its Pitboard through, read back from what `put` wrote, where
1191    // it names one ([`Os::launcher`]): Task Scheduler's alone.
1192    fn launcher(&self, _ctx: &Context, _job: Job) -> Option<PathBuf> {
1193        None
1194    }
1195
1196    // Whether the job is there as an earlier Pitboard wrote it, which installing again mends:
1197    // systemd's alone.
1198    fn outdated(&self, _ctx: &Context, _job: Job) -> bool {
1199        false
1200    }
1201}
1202
1203// Time awake since a fixed moment (boot on Windows, the first call elsewhere); a sleep adds none.
1204pub fn awake() -> std::time::Duration {
1205    os::awake()
1206}
1207
1208#[cfg(any(windows, test))]
1209pub(crate) fn from_interrupt_time(units: u64) -> std::time::Duration {
1210    std::time::Duration::from_secs(units / 10_000_000)
1211        + std::time::Duration::from_nanos(units % 10_000_000 * 100)
1212}
1213
1214/// The host this build is standing on, which is what every real context uses.
1215pub(crate) fn current() -> Arc<dyn Host> {
1216    os::host()
1217}
1218
1219/// The path this program was started by, where that lasts longer than the file it runs.
1220pub(crate) fn current_program() -> std::io::Result<PathBuf> {
1221    os::current_program()
1222}
1223
1224#[cfg(test)]
1225mod tests {
1226    use super::*;
1227
1228    #[test]
1229    fn a_vault_is_kept_by_its_code() {
1230        for vault in [
1231            Vault::Keychain,
1232            Vault::SecretService,
1233            Vault::Files,
1234            Vault::SealedFiles,
1235        ] {
1236            let kept = serde_json::to_value(vault).expect("kept");
1237            assert_eq!(kept, vault.code(), "{vault:?}");
1238            assert_eq!(serde_json::from_value::<Vault>(kept).expect("read"), vault);
1239        }
1240    }
1241
1242    // As a pipe a program started meanwhile took with it, or one that left the run's group.
1243    #[test]
1244    fn a_pipe_still_open_once_a_run_ended_fails_the_run() {
1245        let closed = || {
1246            let (reader, writer) = std::io::pipe().expect("a pipe");
1247            drop(writer);
1248            drained(Some(reader), u64::MAX)
1249        };
1250        let soon = std::time::Instant::now() + DRAINED;
1251        assert!(printed(&closed(), &closed(), soon).is_ok());
1252        let (reader, _held) = std::io::pipe().expect("a pipe");
1253        let refused = printed(
1254            &drained(Some(reader), u64::MAX),
1255            &closed(),
1256            std::time::Instant::now(),
1257        )
1258        .expect_err("still open");
1259        assert_eq!(refused.kind(), std::io::ErrorKind::TimedOut);
1260    }
1261
1262    // This crate's clippy.toml replaces the root's, so it repeats each of its rules.
1263    #[test]
1264    fn the_crates_lints_keep_every_rule_of_the_workspaces_and_refuse_stds_creates() {
1265        let read = |path: &str| {
1266            std::fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join(path)).expect(path)
1267        };
1268        let rules = |text: &str| -> Vec<String> {
1269            text.lines()
1270                .filter(|line| line.trim_start().starts_with("{ path"))
1271                .map(str::to_owned)
1272                .collect()
1273        };
1274        let own = rules(&read("clippy.toml"));
1275        for rule in rules(&read("../../clippy.toml")) {
1276            assert!(own.contains(&rule), "{rule}");
1277        }
1278        for create in [
1279            "std::fs::write",
1280            "std::fs::OpenOptions::create",
1281            "std::fs::create_dir_all",
1282        ] {
1283            let named = format!("{{ path = \"{create}\",");
1284            assert!(own.iter().any(|rule| rule.contains(&named)), "{create}");
1285        }
1286    }
1287
1288    /// A machine without a store of secrets must say so rather than hand back something
1289    /// that behaves like one. A tool's own module builds its chain out of this answer, so a
1290    /// host that always offered one would build a chain that cannot work.
1291    #[test]
1292    fn a_store_of_secrets_is_offered_only_where_there_is_one() {
1293        let ctx = Context::for_unit_test();
1294        let offered = ctx.host().foreign_secrets(&ctx, "someone");
1295        assert_eq!(
1296            offered.map(|k| k.kind()),
1297            match OS {
1298                Os::MacOs => Some(crate::store::Backend::Keychain),
1299                Os::Linux => None,
1300                Os::Windows => Some(crate::store::Backend::CredentialManager),
1301            }
1302        );
1303        assert_eq!(
1304            ctx.host().file(PathBuf::from("/nowhere/at/all")).kind(),
1305            crate::store::Backend::File
1306        );
1307    }
1308
1309    fn listed(pid: u32, path: &str) -> Listed {
1310        Listed {
1311            pid,
1312            parent: 1,
1313            path: PathBuf::from(path),
1314            package: None,
1315            placed: true,
1316        }
1317    }
1318
1319    // 0.162.1's Windows package holds codex.exe beside programs whose names start like it.
1320    #[test]
1321    fn a_program_is_named_by_its_file_as_each_system_names_it() {
1322        let all = || {
1323            vec![
1324                listed(
1325                    1,
1326                    "C:/Users/a/.codex/packages/standalone/current/bin/Codex.EXE",
1327                ),
1328                listed(2, "C:/n/vendor/codex-resources/codex-command-runner.exe"),
1329                listed(3, "C:/n/vendor/bin/codex-code-mode-host.exe"),
1330                listed(4, "C:/n/vendor/codex-path/rg.exe"),
1331                listed(5, "/usr/local/bin/codex"),
1332                listed(6, "C:/n/codex"),
1333                // winget's nested portable, which Toolhelp names behind Links\codex.exe.
1334                listed(
1335                    7,
1336                    "C:/Users/a/AppData/Local/Microsoft/WinGet/Packages/OpenAI.Codex_x/codex-x86_64-pc-windows-msvc.exe",
1337                ),
1338                listed(
1339                    8,
1340                    "C:/Users/a/AppData/Local/Microsoft/WinGet/Packages/OpenAI.Codex_x/codex-aarch64-pc-windows-msvc.exe",
1341                ),
1342            ]
1343        };
1344        let pids = |os: Os| {
1345            named(os, all(), "codex").map(|found| found.iter().map(|p| p.pid).collect::<Vec<_>>())
1346        };
1347        assert_eq!(pids(Os::Windows), Some(vec![1, 7, 8]));
1348        assert_eq!(pids(Os::MacOs), Some(vec![5, 6]));
1349        assert_eq!(pids(Os::Linux), Some(vec![5, 6]));
1350    }
1351
1352    // Such as the same person's elevated codex: it may be any kind of holder.
1353    #[test]
1354    fn a_process_that_cannot_be_placed_makes_the_answer_unknown() {
1355        let unplaced = |name: &str| Listed {
1356            placed: false,
1357            ..listed(7, name)
1358        };
1359        let placed = listed(1, "C:/x/codex.exe");
1360        assert_eq!(
1361            named(
1362                Os::Windows,
1363                vec![placed.clone(), unplaced("codex.exe")],
1364                "codex"
1365            ),
1366            None
1367        );
1368        assert_eq!(
1369            named(Os::Windows, vec![placed, unplaced("svchost.exe")], "codex")
1370                .map(|found| found.len()),
1371            Some(1),
1372            "unless it is not the program"
1373        );
1374    }
1375
1376    /// A path is the same one only in the same case on macOS and Linux, as Pitboard has always
1377    /// compared where a program runs from there. A doubled or trailing separator still
1378    /// leaves it the same path.
1379    #[test]
1380    fn paths_are_compared_exactly_on_macos_and_linux() {
1381        for os in [Os::MacOs, Os::Linux] {
1382            let same = |a: &str, b: &str| os.same_path(Path::new(a), Path::new(b));
1383            assert!(same("ChatGPT.app", "ChatGPT.app"), "{os:?}");
1384            assert!(
1385                same("/Applications/ChatGPT.app/", "/Applications//ChatGPT.app"),
1386                "{os:?}"
1387            );
1388            assert!(!same("chatgpt.app", "ChatGPT.app"), "{os:?}");
1389            assert!(!same("ChatGPT.app", "ChatGPT"), "{os:?}");
1390        }
1391    }
1392
1393    /// On Windows a path is the same one in any case, and only as Windows changes a name's
1394    /// case: a name written decomposed is another name, and so is one whose upper case is
1395    /// longer than itself.
1396    #[test]
1397    fn paths_are_compared_in_any_case_on_windows() {
1398        let same = |a: &str, b: &str| Os::Windows.same_path(Path::new(a), Path::new(b));
1399        assert!(same("Codex.exe", "codex.EXE"));
1400        assert!(same("/Programs/OpenAI/Codex/", "/programs//openai/CODEX"));
1401        assert!(same(r"C:\Users\Dana\Codex.exe", r"c:\users\dana\codex.exe"));
1402        assert!(same("Éclair", "éCLAIR"));
1403        assert!(!same("e\u{301}clair", "\u{e9}clair"), "not normalised");
1404        assert!(!same("Straße", "STRASSE"), "ß is upper case as it is");
1405        assert!(!same("Codex.exe", "Codex"));
1406        assert!(!same("/a/b", "/a/b/c"));
1407    }
1408
1409    #[test]
1410    fn a_verbatim_path_is_spelled_as_libuv_and_codex_spell_it() {
1411        let plain = |path: &str| without_verbatim_prefix(PathBuf::from(path));
1412        assert_eq!(
1413            plain(r"\\?\C:\Users\X\.codex"),
1414            PathBuf::from(r"C:\Users\X\.codex")
1415        );
1416        assert_eq!(
1417            plain(r"\\?\UNC\server\share\x"),
1418            PathBuf::from(r"\\server\share\x")
1419        );
1420        for kept in [
1421            r"C:\Users\X",
1422            r"\\?\Volume{0}\x",
1423            r"\\server\share",
1424            "/Users/x",
1425        ] {
1426            assert_eq!(plain(kept), PathBuf::from(kept), "{kept}");
1427        }
1428    }
1429
1430    // Read by the text alone, on every system, as Foundation standardises a file URL on macOS.
1431    #[test]
1432    fn a_windows_path_has_one_key_however_it_is_spelled() {
1433        let key = path_key_in_any_case;
1434        for spelling in [
1435            r"C:\Users\X\AppData\Local\Pitboard",
1436            r"c:\users\x\appdata\local\pitboard\",
1437            r"\\?\C:\Users\X\AppData\Local\Pitboard",
1438            "C:/Users/X/AppData/Local/Pitboard",
1439            r"C:\Users\X\.\AppData\Local\..\Local\Pitboard",
1440            r"C:\Users\\X\AppData\Local\Pitboard",
1441        ] {
1442            assert_eq!(
1443                key(spelling),
1444                r"C:\USERS\X\APPDATA\LOCAL\PITBOARD",
1445                "{spelling}"
1446            );
1447        }
1448        assert_eq!(key(r"\\server\share\Pitboard"), r"\\SERVER\SHARE\PITBOARD");
1449        assert_eq!(
1450            key(r"\\?\UNC\server\share\Pitboard"),
1451            r"\\SERVER\SHARE\PITBOARD"
1452        );
1453        assert_eq!(key(r"C:\..\Pitboard"), r"C:\PITBOARD");
1454        assert_eq!(key(r"C:\"), r"C:\");
1455        assert_eq!(key(r"C:\Users\Straße"), r"C:\USERS\STRAßE");
1456        assert_ne!(key("C:\\Users\\e\u{301}"), key("C:\\Users\\\u{e9}"));
1457        assert_ne!(
1458            key(r"C:\Users\XAVIER~1\AppData\Local\Pitboard"),
1459            key(r"C:\Users\Xavier Dana\AppData\Local\Pitboard"),
1460            "no short name is expanded"
1461        );
1462    }
1463
1464    // One answer on every system: macOS's own volumes ignore case, and Windows drops `..` as
1465    // written, which a folder made where none is yet would do too.
1466    #[test]
1467    fn a_path_lies_in_a_place_in_any_case_and_past_a_folder_not_made_yet() {
1468        let scratch = tempfile::tempdir().expect("a scratch folder");
1469        let root = scratch.path().join("root");
1470        let place = root.join("Library/Application Support");
1471        let lies = |path: &str| lies_in(&root.join(path), &place);
1472        assert!(lies("Library/Application Support/x"));
1473        assert!(lies("library/APPLICATION SUPPORT/x"), "in any case");
1474        assert!(lies("LIBRARY"), "it holds it");
1475        assert!(lies("never-made/../Library/Application Support/x"));
1476        assert!(!lies("Library/Application Supportx"));
1477        assert!(!lies("never-made/Library/Application Support"));
1478        assert!(!lies("Library/../elsewhere/Application Support"));
1479        assert!(!root.exists());
1480    }
1481
1482    #[test]
1483    fn claude_desktops_windows_folders_are_refused_in_any_spelling() {
1484        let (roaming, local) = (
1485            PathBuf::from("/p/AppData/Roaming"),
1486            PathBuf::from("/p/AppData/Local"),
1487        );
1488        let places =
1489            claude_desktop_on_windows(std::slice::from_ref(&roaming), std::slice::from_ref(&local));
1490        let refused = |path: PathBuf| places.iter().any(|place| lies_in(&path, place));
1491        for path in [
1492            roaming.join("Claude"),
1493            roaming.join("claude").join("Cookies"),
1494            roaming.join("CLAUDE-3P"),
1495            local.join("AnthropicClaude").join("app-1.0"),
1496            roaming.clone(),
1497        ] {
1498            assert!(refused(path.clone()), "{}", path.display());
1499        }
1500        for path in [
1501            roaming.join("Claudette"),
1502            local.join("Claude"),
1503            local.join("Pitboard"),
1504        ] {
1505            assert!(!refused(path.clone()), "{}", path.display());
1506        }
1507    }
1508
1509    // Compared by component, so `Pitboard` and `Pitboard App` are never inside one another.
1510    #[test]
1511    fn the_windows_apps_folders_are_refused_in_any_spelling() {
1512        let local = PathBuf::from("/p/AppData/Local");
1513        let places = pitboard_app_on_windows(std::slice::from_ref(&local));
1514        let refused = |path: PathBuf| places.iter().any(|place| lies_in(&path, place));
1515        for path in [
1516            local.join("Pitboard App").join("WebView2"),
1517            local.join("pitboard app debug").join("x"),
1518            local.join("PITBOARD APP"),
1519            local.clone(),
1520        ] {
1521            assert!(refused(path.clone()), "{}", path.display());
1522        }
1523        for path in [
1524            local.join("Pitboard Apps"),
1525            local.join("Pitboard"),
1526            local.join("Pitboard").join("App"),
1527            local.join("Pitboard App Debugger"),
1528        ] {
1529            assert!(!refused(path.clone()), "{}", path.display());
1530        }
1531    }
1532
1533    // Compared by component, so the release's folder and the debug build's never hold each other.
1534    #[test]
1535    fn the_linux_apps_folders_are_refused_in_any_spelling() {
1536        let (data, cache) = (PathBuf::from("/h/.local/share"), PathBuf::from("/h/.cache"));
1537        let places =
1538            pitboard_app_on_linux(std::slice::from_ref(&data), std::slice::from_ref(&cache));
1539        let refused = |path: PathBuf| places.iter().any(|place| lies_in(&path, place));
1540        for path in [
1541            data.join("com.usepitboard.Pitboard").join("window.json"),
1542            data.join("com.usepitboard.pitboard.devel").join("x"),
1543            cache.join("COM.USEPITBOARD.PITBOARD"),
1544            cache.join("com.usepitboard.Pitboard.Devel"),
1545            data.clone(),
1546            cache.clone(),
1547        ] {
1548            assert!(refused(path.clone()), "{}", path.display());
1549        }
1550        for path in [
1551            data.join("com.usepitboard.Pitboards"),
1552            data.join("com.usepitboard.Pitboard.Develop"),
1553            data.join("com.usepitboard"),
1554            cache.join("pitboard"),
1555            PathBuf::from("/h/.config/com.usepitboard.Pitboard"),
1556        ] {
1557            assert!(!refused(path.clone()), "{}", path.display());
1558        }
1559    }
1560
1561    #[test]
1562    #[cfg(windows)]
1563    fn a_verbatim_path_lies_where_its_plain_spelling_does() {
1564        let lies = |path: &str, place: &str| lies_in(Path::new(path), Path::new(place));
1565        assert!(lies(
1566            r"\\?\C:\Users\Dana\Library\x",
1567            r"c:\users\dana\library"
1568        ));
1569        assert!(lies(
1570            r"C:\Users\Dana\Library\x",
1571            r"\\?\c:\users\dana\library"
1572        ));
1573        assert!(!lies(
1574            r"\\?\D:\Users\Dana\Library\x",
1575            r"C:\Users\Dana\Library"
1576        ));
1577    }
1578
1579    // Homebrew's default prefix on Linux, where its `claude-code` and `codex` casks install too.
1580    #[test]
1581    fn an_app_on_linux_looks_in_homebrews_bin() {
1582        let env = Environment::on(Os::Linux, [("HOME", "/home/x")]);
1583        let brew = PathBuf::from("/home/linuxbrew/.linuxbrew/bin");
1584        assert_eq!(Os::Linux.package_bins(&env), std::slice::from_ref(&brew));
1585        for tool in crate::provider::ProviderId::ALL {
1586            if let Some(cli) = tool.cli() {
1587                assert!((cli.install_places)(&env).contains(&brew), "{tool}");
1588            }
1589        }
1590        assert!(crate::app::command_line_places(&env, None).contains(&brew));
1591    }
1592
1593    // Linux's packages put `pitboard-app` beside `pitboard` in one `bin`.
1594    #[test]
1595    fn each_systems_app_names_the_command_line_it_comes_with() {
1596        let names = |os: Os, app: &str| os.app_command_line(Path::new(app));
1597        let helper = |app: &str| Some(Path::new(app).join("Contents/Helpers/pitboard"));
1598        for (os, app, inside) in [
1599            (
1600                Os::Linux,
1601                "/usr/bin/pitboard-app",
1602                Some(PathBuf::from("/usr/bin/pitboard")),
1603            ),
1604            (
1605                Os::Linux,
1606                "/home/x/.local/bin/pitboard-app",
1607                Some(PathBuf::from("/home/x/.local/bin/pitboard")),
1608            ),
1609            (Os::Linux, "/usr/bin/pitboard", None),
1610            (Os::Linux, "/usr/bin/Pitboard-App", None),
1611            (Os::Linux, "/usr/bin/pitboard-app.desktop", None),
1612            (Os::Linux, "/Applications/Pitboard.app", None),
1613            (
1614                Os::MacOs,
1615                "/Applications/Pitboard.app",
1616                helper("/Applications/Pitboard.app"),
1617            ),
1618            (Os::MacOs, "/usr/bin/pitboard-app", None),
1619            (
1620                Os::Windows,
1621                "C:/Program Files/Pitboard/Pitboard.exe",
1622                Some(PathBuf::from("C:/Program Files/Pitboard/bin/pitboard.exe")),
1623            ),
1624            (Os::Windows, "C:/Program Files/Pitboard/pitboard-app", None),
1625        ] {
1626            assert_eq!(names(os, app), inside, "{os:?} {app}");
1627        }
1628    }
1629
1630    // launchd, a systemd user timer where systemd started Linux, and Task Scheduler.
1631    #[test]
1632    fn a_scheduler_is_offered_where_pitboard_writes_for_one() {
1633        assert_eq!(
1634            current().scheduler().is_some(),
1635            OS != Os::Linux || Path::new("/run/systemd/system").is_dir()
1636        );
1637    }
1638
1639    /// This system's host reads sudo from the environment the context was read from, which
1640    /// is where sudo says it, and root from the process itself, with the home's owner on
1641    /// Linux. Set but empty, `SUDO_UID` says nothing, as every variable Pitboard reads that
1642    /// way.
1643    #[test]
1644    fn the_host_reads_sudo_from_the_context_and_root_from_the_process() {
1645        let ctx_under = |value: &str| {
1646            let env: Environment = [("HOME", "/Users/x"), ("SUDO_UID", value)]
1647                .into_iter()
1648                .collect();
1649            Context::for_command_line(&env)
1650        };
1651        let under = |value: &str| {
1652            let ctx = ctx_under(value);
1653            ctx.host().elevation(&ctx)
1654        };
1655        #[cfg(target_os = "linux")]
1656        let unsudoed = |ctx: &Context| user::linux_elevation(false, &crate::home::written(ctx));
1657        #[cfg(not(target_os = "linux"))]
1658        let unsudoed = |_: &Context| user::elevation(false);
1659        assert_eq!(
1660            under("501"),
1661            match OS {
1662                Os::MacOs | Os::Linux => Elevation::Elevated { why: "with sudo" },
1663                Os::Windows => user::elevation(false),
1664            }
1665        );
1666        let ctx = Context::for_unit_test();
1667        assert_eq!(
1668            ctx.host().elevation(&ctx),
1669            unsudoed(&ctx),
1670            "withheld from a unit test, so only root is read"
1671        );
1672        assert_eq!(under(""), unsudoed(&ctx_under("")));
1673    }
1674
1675    // Instant reads the same clock on macOS and Linux, and a clock that counts sleep on Windows.
1676    #[test]
1677    fn time_awake_moves_with_this_process_while_it_is_awake() {
1678        let (awake_at, instant_at) = (awake(), std::time::Instant::now());
1679        std::thread::sleep(std::time::Duration::from_millis(50));
1680        let (passed, measured) = (awake() - awake_at, instant_at.elapsed());
1681        // Wide enough for a busy runner, narrow enough to catch a unit read ten times off.
1682        assert!(
1683            passed > measured / 2 && passed < measured * 2,
1684            "{passed:?} against {measured:?}"
1685        );
1686    }
1687
1688    #[test]
1689    fn interrupt_time_is_in_hundreds_of_nanoseconds() {
1690        use std::time::Duration;
1691        assert_eq!(from_interrupt_time(10_000_000), Duration::from_secs(1));
1692        assert_eq!(from_interrupt_time(1), Duration::from_nanos(100));
1693        assert_eq!(
1694            from_interrupt_time(36_000_000_015),
1695            Duration::new(3600, 1_500)
1696        );
1697    }
1698
1699    // 19045 is Windows 10 22H2, 19044 LTSC 2021, 20348 Windows Server 2022, 22631 Windows 11
1700    // 23H2, 18363 Windows 10 1909 and 17763 LTSC 2019 and Windows Server 2019.
1701    #[test]
1702    fn the_floor_is_windows_10_2004_with_server_2022_counted() {
1703        for met in [
1704            (10, 0, 19041),
1705            (10, 0, 19044),
1706            (10, 0, 19045),
1707            (10, 0, 20348),
1708            (10, 0, 22631),
1709            (10, 0, 26100),
1710            (11, 0, 100),
1711        ] {
1712            assert_eq!(windows_floor(Some(met)), Floor::Met, "{met:?}");
1713        }
1714        for (version, build) in [
1715            ((10, 0, 19040), 19040),
1716            ((10, 0, 18363), 18363),
1717            ((10, 0, 17763), 17763),
1718            ((6, 3, 9600), 9600),
1719        ] {
1720            assert_eq!(
1721                windows_floor(Some(version)),
1722                Floor::Below { build },
1723                "{version:?}"
1724            );
1725        }
1726        assert_eq!(windows_floor(None), Floor::Unknown);
1727        assert_eq!(WINDOWS_FLOOR, 19041);
1728    }
1729
1730    #[test]
1731    fn the_floor_is_met_on_the_systems_the_tests_run_on() {
1732        assert_eq!(current().floor(), Floor::Met);
1733    }
1734}