1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92pub enum Os {
93 MacOs,
94 Linux,
95 Windows,
96}
97
98pub const OS: Os = os::OS;
100
101#[derive(Debug, Clone, Copy, PartialEq, Eq)]
106pub enum SecretStore {
107 Keychain,
108 CredentialManager,
109}
110
111#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
115#[serde(rename_all = "snake_case")]
116pub enum Vault {
117 Keychain,
119 SecretService,
121 Files,
123 SealedFiles,
125}
126
127impl Vault {
128 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
142pub enum Keyring {
143 Login,
145 KWallet,
147}
148
149pub(crate) const SECURITY: &str = "/usr/bin/security";
152
153const LINUX_APP: &str = "pitboard-app";
155
156impl Os {
157 pub(crate) fn secrets_tool(self) -> Option<&'static str> {
160 match self {
161 Os::MacOs => Some(SECURITY),
162 Os::Linux | Os::Windows => None,
164 }
165 }
166
167 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 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 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 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 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 pub fn home_variable(self) -> &'static str {
284 match self {
285 Os::MacOs | Os::Linux => "HOME",
286 Os::Windows => "USERPROFILE",
287 }
288 }
289
290 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 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 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 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
347pub 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
362pub 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
411pub(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
430pub(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 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#[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#[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#[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#[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 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 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#[cfg(all(not(windows), any(test, feature = "test-support")))]
536pub(crate) fn lasting_environment(_name: &str) -> Vec<String> {
537 Vec::new()
538}
539
540#[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#[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#[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#[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#[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
632pub(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#[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 Said(String),
657 Unknown,
659 Late,
663}
664
665pub(crate) fn login_path(env: &Environment) -> LoginPath {
667 os::login_path(env)
668}
669
670#[derive(Debug, Clone, PartialEq, Eq)]
672pub(crate) struct Access {
673 pub(crate) shared: bool,
675 pub(crate) described: String,
677}
678
679#[derive(Debug, Clone, Copy, PartialEq, Eq)]
681pub enum Private {
682 Yes,
683 Shared,
684 NotOwn,
685 Link,
686 NotADirectory,
687 Missing,
688}
689
690#[derive(Debug, Clone, Copy, PartialEq, Eq)]
692pub(crate) enum Kind {
693 Directory,
694 File,
695 Any,
697}
698
699#[derive(Debug, Clone, Copy, PartialEq, Eq)]
704pub enum Elevation {
705 Normal,
707 Elevated { why: &'static str },
710 Unknown,
712}
713
714#[derive(Debug, Clone, Copy, PartialEq, Eq)]
715pub enum Floor {
716 Met,
717 Below { build: u32 },
718 Unknown,
719}
720
721#[derive(Debug, Clone, Default, PartialEq, Eq)]
723pub(crate) struct WindowsSettings {
724 pub(crate) wsl: Vec<String>,
726 pub(crate) proxy: Option<String>,
728 pub(crate) admin_approval: Option<bool>,
730}
731
732pub(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 pub(crate) path: PathBuf,
751 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 pub placed: bool,
763}
764
765pub(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 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
819impl 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 Unsettled(String),
837 Unknown(String),
839 Unreadable(String),
840 Unsupported,
841}
842
843#[cfg(any(test, feature = "test-support"))]
844pub(crate) use os::write_jar;
845
846#[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
856const TOOL_PRINTS: u64 = 1 << 20;
858
859const DRAINED: std::time::Duration = std::time::Duration::from_secs(5);
862
863fn 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
881fn 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
896fn 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
917fn 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
925pub(crate) trait Host: Send + Sync + std::fmt::Debug {
937 fn foreign_secrets(&self, ctx: &Context, account: &str) -> Option<Box<dyn RawStore>>;
945
946 fn file(&self, path: PathBuf) -> Box<dyn RawStore>;
948
949 fn vault_forms(&self) -> &'static [VaultForm] {
953 &[]
954 }
955
956 fn answers(&self, _ctx: &Context, _form: VaultForm) -> bool {
960 false
961 }
962
963 fn keyring(&self, _ctx: &Context) -> Keyring {
966 Keyring::Login
967 }
968
969 fn vault(&self, ctx: &Context, form: Option<VaultForm>) -> Box<dyn RawStore>;
973
974 fn vault_is_shared(&self, form: Option<VaultForm>) -> bool;
979
980 fn listing(&self) -> std::result::Result<Vec<Listed>, String>;
982
983 fn processes(&self, program: &str) -> Option<Vec<Process>> {
986 named(OS, self.listing().ok()?, program)
987 }
988
989 fn cookies(
991 &self,
992 jar: &Path,
993 hosts: &[&str],
994 names: &[&str],
995 ) -> std::result::Result<Jar, JarError>;
996
997 fn app_version(&self, bundle: &Path) -> Option<String>;
999 fn app_id(&self, bundle: &Path) -> Option<String>;
1000
1001 fn scheduler(&self) -> Option<&dyn Scheduler>;
1004
1005 fn elevation(&self, ctx: &Context) -> Elevation;
1010
1011 fn floor(&self) -> Floor;
1012
1013 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 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 fn managed_preference(&self, domain: &str, key: &str) -> Administered;
1040
1041 fn managed_plist(&self, _path: &Path) -> Administered {
1043 Administered::Unset
1044 }
1045
1046 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 fn policy(&self, _hive: Hive, _key: &str, _value: &str) -> Administered {
1057 Administered::Unset
1058 }
1059
1060 fn program_data(&self) -> Option<PathBuf> {
1062 None
1063 }
1064
1065 fn fixed_drives(&self) -> Vec<char> {
1068 Vec::new()
1069 }
1070
1071 fn credential_names(&self, _prefix: &str) -> std::result::Result<Vec<String>, String> {
1074 Ok(Vec::new())
1075 }
1076
1077 fn user_environment(&self, _name: &str) -> Administered {
1080 Administered::Unset
1081 }
1082
1083 fn machine_environment(&self, _name: &str) -> Administered {
1087 Administered::Unset
1088 }
1089
1090 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 fn windows_settings(&self) -> WindowsSettings {
1102 WindowsSettings::default()
1103 }
1104
1105 fn kernel_is_wsl(&self) -> bool {
1108 false
1109 }
1110
1111 fn on_a_windows_drive(&self, _path: &Path) -> bool {
1114 false
1115 }
1116
1117 fn watches(&self, _dir: &Path) -> bool {
1120 true
1121 }
1122}
1123
1124pub(crate) trait Scheduler: Send + Sync + std::fmt::Debug {
1132 fn location(&self, ctx: &Context, job: Job) -> crate::schedule::Location;
1134
1135 fn installed(&self, ctx: &Context, job: Job) -> bool;
1137
1138 fn program(&self, ctx: &Context, job: Job) -> Option<PathBuf>;
1142
1143 fn options(&self, ctx: &Context, job: Job) -> Vec<String>;
1147
1148 fn environment(&self, ctx: &Context, job: Job) -> Vec<(String, String)>;
1152
1153 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 fn remove(&self, ctx: &Context, permit: Permit, job: Job) -> Result<bool>;
1174
1175 fn started_this_process(&self, job: Job, said: Option<&str>) -> bool;
1178
1179 fn read_by_its_runs(&self, _ctx: &Context, _job: Job) -> Vec<(String, String)> {
1182 Vec::new()
1183 }
1184
1185 fn task(&self, _ctx: &Context, _job: Job) -> Option<task::Task> {
1187 None
1188 }
1189
1190 fn launcher(&self, _ctx: &Context, _job: Job) -> Option<PathBuf> {
1193 None
1194 }
1195
1196 fn outdated(&self, _ctx: &Context, _job: Job) -> bool {
1199 false
1200 }
1201}
1202
1203pub 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
1214pub(crate) fn current() -> Arc<dyn Host> {
1216 os::host()
1217}
1218
1219pub(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 #[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 #[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 #[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 #[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 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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 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 #[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}