1use crate::context::Context;
27use crate::duty::ledger;
28use crate::error::{Error, Result};
29use crate::host::{Os, Scheduler, Vault};
30use crate::permit::Permit;
31use crate::state::Key;
32use crate::switch::Renewal;
33use serde::{Deserialize, Serialize};
34use std::collections::BTreeSet;
35use std::path::{Path, PathBuf};
36
37pub(crate) const EVERY_SECONDS: u32 = 86_400;
41#[cfg_attr(
44 windows,
45 allow(dead_code, reason = "the watch service's task asks for no restart")
46)]
47pub(crate) const RESTART_AFTER_SECONDS: u32 = 60;
48
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
51pub enum Job {
52 Renew,
54 Watch,
56}
57
58impl Job {
59 pub(crate) fn marked(self) -> [&'static str; 2] {
61 match self {
62 Job::Renew => SCHEDULED_RUN,
63 Job::Watch => WATCH_RUN,
64 }
65 }
66}
67
68#[derive(Debug, Clone, PartialEq, Eq)]
70pub enum Installed {
71 Yes {
73 location: Location,
74 every_seconds: u32,
75 },
76 No,
77 Unsupported,
79}
80
81#[derive(Debug, Clone, PartialEq, Eq)]
84pub enum Elsewhere {
85 Folder { units: PathBuf },
87 Home {
90 home: PathBuf,
91 theirs: Option<PathBuf>,
92 },
93}
94
95#[derive(Debug, Clone, PartialEq, Eq)]
97pub enum Location {
98 File(PathBuf),
100 Task(String),
102}
103
104impl std::fmt::Display for Location {
105 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
106 match self {
107 Location::File(path) => write!(f, "{}", path.display()),
108 Location::Task(task) => f.write_str(task),
109 }
110 }
111}
112
113pub(crate) fn scheduler(ctx: &Context) -> Option<&dyn Scheduler> {
114 ctx.host().scheduler()
115}
116
117#[cfg(test)]
119pub(crate) fn path(ctx: &Context) -> Option<PathBuf> {
120 job_path(ctx, Job::Renew)
121}
122
123#[cfg(test)]
124pub(crate) fn job_path(ctx: &Context, job: Job) -> Option<PathBuf> {
125 Some(match scheduler(ctx)?.location(ctx, job) {
126 Location::File(path) => path,
127 Location::Task(task) => crate::host::task::pretend_file(ctx, &task),
128 })
129}
130
131pub(crate) fn status(ctx: &Context) -> Installed {
132 match scheduler(ctx) {
133 None => Installed::Unsupported,
134 Some(s) if s.installed(ctx, Job::Renew) => Installed::Yes {
135 location: s.location(ctx, Job::Renew),
136 every_seconds: EVERY_SECONDS,
137 },
138 Some(_) => Installed::No,
139 }
140}
141
142pub const SCHEDULED_RUN: [&str; 2] = ["renew", "--scheduled"];
150
151pub const WATCH_RUN: [&str; 2] = ["watch", "--scheduled"];
154
155pub(crate) fn serves(ctx: &Context) -> bool {
157 ctx.os
158 .same_path(&crate::home::dir(ctx), &ctx.default_pitboard_home())
159}
160
161pub(crate) fn started_this_run(ctx: &Context, job: Job) -> bool {
164 ctx.started_by() == Some(job)
165 || scheduler(ctx).is_some_and(|s| s.started_this_process(job, ctx.scheduled_job()))
166}
167
168pub(crate) fn for_its_run(ctx: &Context, job: Job) -> Context {
182 if !started_this_run(ctx, job) {
183 return ctx.clone();
184 }
185 #[cfg(any(test, feature = "test-support"))]
186 assert!(
187 !crate::host::user::is_the_accounts_own_home(ctx.home()),
188 "a build for tests ran as the system's job {job:?} with this account's own home, \
189 where it would change the real Pitboard directory: give it a home of its own"
190 );
191 let run = ctx.clone().with_pitboard_home(ctx.default_pitboard_home());
192 match scheduler(&run).map(|s| s.read_by_its_runs(&run, job)) {
193 Some(given) if !given.is_empty() => run.with_proxy_variables_over(&given),
194 _ => run,
195 }
196}
197
198#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
204#[serde(default)]
205pub(crate) struct Refused {
206 pub(crate) at: i64,
208 pub(crate) vault: Option<Vault>,
210 pub(crate) codes: BTreeSet<String>,
212}
213
214impl Refused {
215 pub(crate) fn locked(&self) -> bool {
217 self.codes.contains(crate::store::Error::Locked.code())
218 }
219}
220
221fn refused_path(ctx: &Context, job: Job) -> PathBuf {
222 crate::home::dir(ctx).join(match job {
223 Job::Renew => "renewal.json",
224 Job::Watch => "watch.json",
225 })
226}
227
228pub(crate) fn refused(ctx: &Context, job: Job) -> Option<Refused> {
231 let kept: Refused = ledger::load(&refused_path(ctx, job));
232 (!kept.codes.is_empty()).then_some(kept)
233}
234
235pub(crate) enum StoreAnswer {
237 NotAsked,
238 Opened,
240 Refused(BTreeSet<String>),
242}
243
244impl StoreAnswer {
245 pub(crate) fn renewing(outcomes: &[(Key, Renewal)]) -> StoreAnswer {
248 if outcomes.is_empty() {
249 return StoreAnswer::NotAsked;
250 }
251 let codes: BTreeSet<String> = outcomes
252 .iter()
253 .filter_map(|(_, outcome)| match outcome {
254 Renewal::Failed(error) => StoreAnswer::refusing(error),
255 _ => None,
256 })
257 .collect();
258 if codes.is_empty() {
259 StoreAnswer::Opened
260 } else {
261 StoreAnswer::Refused(codes)
262 }
263 }
264
265 pub(crate) fn of(error: &Error) -> StoreAnswer {
267 StoreAnswer::refusing(error).map_or(StoreAnswer::NotAsked, |code| {
268 StoreAnswer::Refused(BTreeSet::from([code]))
269 })
270 }
271
272 fn refusing(error: &Error) -> Option<String> {
273 match error {
274 Error::Store(refused) => Some(refused.code().to_owned()),
275 _ => None,
276 }
277 }
278}
279
280pub(crate) fn ran(ctx: &Context, permit: Permit, job: Job, answer: StoreAnswer) {
286 if !started_this_run(ctx, job) {
287 return;
288 }
289 let path = refused_path(ctx, job);
290 let _ = match answer {
292 StoreAnswer::NotAsked => return,
293 StoreAnswer::Opened => ledger::forget(permit, &path),
294 StoreAnswer::Refused(codes) => {
295 let refused = Refused {
296 at: ctx.now(),
297 vault: crate::store::vault_place(ctx),
298 codes,
299 };
300 ledger::save(permit, &path, &refused)
301 }
302 };
303}
304
305pub(crate) fn program(ctx: &Context, job: Job) -> Result<PathBuf> {
308 program_of(
309 ctx.os,
310 ctx.schedule_program(),
311 crate::host::current_program,
312 job,
313 )
314}
315
316fn program_of(
317 os: Os,
318 named: Option<&Path>,
319 running: impl FnOnce() -> std::io::Result<PathBuf>,
320 job: Job,
321) -> Result<PathBuf> {
322 let program = match named {
323 Some(named) => named.to_path_buf(),
324 None => running().map_err(|source| Error::HomeUnwritable {
325 path: PathBuf::from("the running Pitboard"),
326 source,
327 })?,
328 };
329 lasting(os, &program, job)?;
330 Ok(program)
331}
332
333fn lasting(os: Os, program: &Path, job: Job) -> Result<&Path> {
341 if in_a_temporary_copy(program) {
342 return Err(Error::ScheduleProgramTemporary {
343 path: program.to_path_buf(),
344 job,
345 });
346 }
347 if !program.is_file() {
348 return Err(Error::ScheduleProgramMissing {
349 path: program.to_path_buf(),
350 job,
351 });
352 }
353 if let Some(launcher) = os.launcher(program).filter(|launcher| !launcher.is_file()) {
354 return Err(Error::ScheduleLauncherMissing {
355 path: launcher,
356 job,
357 });
358 }
359 Ok(program)
360}
361
362pub(crate) fn missing(ctx: &Context, job: Job, program: &Path) -> Option<PathBuf> {
365 scheduler(ctx)
366 .and_then(|scheduler| scheduler.launcher(ctx, job))
367 .into_iter()
368 .chain([program.to_path_buf()])
369 .find(|file| !file.is_file())
370}
371
372pub fn in_a_temporary_copy(program: &Path) -> bool {
376 temporary_copy(program).is_some()
377}
378
379#[derive(Debug, Clone, Copy, PartialEq, Eq)]
381pub(crate) enum TemporaryCopy {
382 Translocated,
385 Zip,
387 AppImage,
389}
390
391pub(crate) fn temporary_copy(program: &Path) -> Option<TemporaryCopy> {
392 if program
393 .components()
394 .any(|part| part.as_os_str() == "AppTranslocation")
395 {
396 Some(TemporaryCopy::Translocated)
397 } else if opened_from_a_zip(program) {
398 Some(TemporaryCopy::Zip)
399 } else if program
400 .components()
401 .any(|part| an_appimages_folder(part.as_os_str().as_encoded_bytes()))
402 {
403 Some(TemporaryCopy::AppImage)
404 } else {
405 None
406 }
407}
408
409fn opened_from_a_zip(program: &Path) -> bool {
411 program.to_string_lossy().split(['/', '\\']).any(|part| {
412 let name = part.to_ascii_lowercase();
413 let Some(numbered) = name.strip_prefix("temp") else {
414 return false;
415 };
416 let digits = numbered.bytes().take_while(u8::is_ascii_digit).count();
417 digits > 0 && numbered[digits..].starts_with('_') && name.ends_with(".zip")
418 })
419}
420
421fn an_appimages_folder(name: &[u8]) -> bool {
424 let mounted = name.strip_prefix(b".mount_").is_some_and(|rest| {
425 (6..=12).contains(&rest.len())
426 && rest[rest.len() - 6..].iter().all(u8::is_ascii_alphanumeric)
427 });
428 let extracted = name
429 .strip_prefix(b"appimage_extracted_")
430 .is_some_and(|digest| {
431 digest.len() == 32
432 && digest
433 .iter()
434 .all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
435 });
436 mounted || extracted
437}
438
439pub(crate) fn task(ctx: &Context, job: Job) -> Option<crate::host::task::Task> {
440 scheduler(ctx)?.task(ctx, job)
441}
442
443pub(crate) fn outdated(ctx: &Context, job: Job) -> bool {
445 scheduler(ctx).is_some_and(|s| s.outdated(ctx, job))
446}
447
448pub(crate) fn installed_program(ctx: &Context) -> Option<PathBuf> {
452 scheduler(ctx)?.program(ctx, Job::Renew)
453}
454
455pub(crate) fn environment(
461 ctx: &Context,
462 proxy: impl IntoIterator<Item = (String, String)>,
463) -> Vec<(String, String)> {
464 let refusing = (!ctx.argv_fallback()).then(|| ("PITBOARD_NO_ARGV".into(), "1".into()));
465 refusing.into_iter().chain(proxy).collect()
466}
467
468fn installed_proxy_variables(ctx: &Context) -> Vec<(String, String)> {
471 let Some(scheduler) = scheduler(ctx) else {
472 return Vec::new();
473 };
474 scheduler
475 .environment(ctx, Job::Renew)
476 .into_iter()
477 .filter(|(name, _)| {
478 crate::proxy::NAMING
479 .iter()
480 .chain(&crate::proxy::EXEMPTING)
481 .any(|proxy| proxy == name)
482 })
483 .collect()
484}
485
486pub(crate) fn installed_proxies(ctx: &Context) -> Option<crate::proxy::Proxies> {
489 if !scheduler(ctx)?.installed(ctx, Job::Renew) {
490 return None;
491 }
492 let given: crate::context::Environment = installed_proxy_variables(ctx).into_iter().collect();
493 Some(crate::proxy::Proxies::read(&given))
494}
495
496pub(crate) fn install(ctx: &Context, permit: Permit) -> Result<Location> {
507 if !serves(ctx) {
508 return Err(Error::ScheduleNotDefaultHome {
509 home: crate::home::dir(ctx),
510 default: ctx.default_pitboard_home(),
511 job: Job::Renew,
512 });
513 }
514 let location = put(
515 ctx,
516 permit,
517 Job::Renew,
518 &program(ctx, Job::Renew)?,
519 &[],
520 &environment(ctx, proxy_variables(ctx)),
521 )?;
522 crate::audit::record(ctx, permit, "schedule", "install", "ok");
523 Ok(location)
524}
525
526pub(crate) fn proxy_variables(ctx: &Context) -> impl Iterator<Item = (String, String)> + '_ {
528 ctx.proxy
529 .variables()
530 .iter()
531 .map(|(name, value)| ((*name).to_string(), value.clone()))
532}
533
534pub(crate) fn repair(ctx: &Context, permit: Permit) -> Result<bool> {
539 if scheduler(ctx).is_none() || started_this_run(ctx, Job::Renew) {
540 return Ok(false);
541 }
542 let Some(named) = ctx.schedule_program() else {
543 return Ok(false);
544 };
545 if !serves(ctx)
546 || lasting(ctx.os, named, Job::Renew).is_err()
547 || !installed_program(ctx).is_some_and(|program| broken(ctx, &program))
548 {
549 return Ok(false);
550 }
551 let kept = installed_proxy_variables(ctx);
552 let repaired = put(ctx, permit, Job::Renew, named, &[], &environment(ctx, kept));
553 crate::audit::record(
554 ctx,
555 permit,
556 "schedule",
557 "repair",
558 match &repaired {
559 Ok(_) => "ok",
560 Err(e) => e.code(),
561 },
562 );
563 repaired.map(|_| true)
564}
565
566fn broken(ctx: &Context, program: &Path) -> bool {
569 let drifted = task(ctx, Job::Renew).is_some_and(|task| !task.drifted.is_empty());
570 !drifted && fault(ctx.os, program, missing(ctx, Job::Renew, program).is_none()).is_some()
571}
572
573#[derive(Debug, Clone, Copy, PartialEq, Eq)]
574pub(crate) enum Fault {
575 Gone,
577 TheApp,
579}
580
581pub(crate) fn fault(os: Os, program: &Path, found: bool) -> Option<Fault> {
583 if !found {
584 Some(Fault::Gone)
585 } else if os.an_apps_own_program(program) {
586 Some(Fault::TheApp)
587 } else {
588 None
589 }
590}
591
592pub(crate) fn put(
595 ctx: &Context,
596 permit: Permit,
597 job: Job,
598 program: &Path,
599 options: &[String],
600 environment: &[(String, String)],
601) -> Result<Location> {
602 let Some(scheduler) = scheduler(ctx) else {
603 return Err(Error::ScheduleUnsupported { job });
604 };
605 scheduler.put(ctx, permit, job, program, options, environment)?;
606 Ok(scheduler.location(ctx, job))
607}
608
609pub(crate) fn remove(ctx: &Context, permit: Permit, job: Job) -> Result<bool> {
611 let Some(scheduler) = scheduler(ctx) else {
612 return Err(Error::ScheduleUnsupported { job });
613 };
614 scheduler.remove(ctx, permit, job)
615}
616
617pub(crate) fn uninstall(ctx: &Context, permit: Permit) -> Result<bool> {
619 if !remove(ctx, permit, Job::Renew)? {
620 return Ok(false);
621 }
622 crate::audit::record(ctx, permit, "schedule", "uninstall", "ok");
623 Ok(true)
624}
625
626pub(crate) fn uninstall_for_app(ctx: &Context, permit: Permit) -> Result<bool> {
628 let runs_the_apps = |job| {
629 ctx.schedule_program().is_some_and(|named| {
630 scheduler(ctx)
631 .and_then(|s| s.program(ctx, job))
632 .is_some_and(|program| ctx.os.same_path(&program, named))
633 })
634 };
635 let watch_removed = runs_the_apps(Job::Watch) && crate::watch_service::uninstall(ctx, permit)?;
636 let renew_removed = runs_the_apps(Job::Renew) && uninstall(ctx, permit)?;
637 Ok(watch_removed || renew_removed)
638}
639
640#[cfg(test)]
641#[allow(
642 clippy::disallowed_methods,
643 reason = "a test sets up its scratch files as a person or a tool would"
644)]
645mod tests {
646 use super::*;
647 use crate::host::memory::MemoryHost;
648 use std::sync::Arc;
649
650 struct Scratch(tempfile::TempDir, Arc<MemoryHost>);
653
654 impl Scratch {
655 fn new() -> Scratch {
656 Scratch(
657 tempfile::tempdir().expect("a scratch home"),
658 MemoryHost::new(),
659 )
660 }
661
662 fn path(&self) -> &Path {
663 self.0.path()
664 }
665
666 fn ctx(&self) -> Context {
667 Context::new(self.path().to_path_buf()).with_memory_stores(Arc::clone(&self.1))
668 }
669
670 fn read(&self, vars: &[(&str, &str)]) -> Context {
673 let home = self.path().to_string_lossy().into_owned();
674 let env: crate::context::Environment =
675 [("HOME", home.as_str()), ("USERPROFILE", home.as_str())]
676 .iter()
677 .chain(vars)
678 .copied()
679 .collect();
680 Context::for_command_line(&env).with_memory_stores(Arc::clone(&self.1))
681 }
682 }
683
684 fn given(ctx: &Context) -> Vec<(String, String)> {
686 scheduler(ctx)
687 .expect("a scheduler")
688 .environment(ctx, Job::Renew)
689 }
690
691 fn pairs(given: &[(&str, &str)]) -> Vec<(String, String)> {
692 given
693 .iter()
694 .map(|(name, value)| ((*name).to_string(), (*value).to_string()))
695 .collect()
696 }
697
698 fn the_app(home: &Path) -> (PathBuf, PathBuf) {
701 match crate::host::OS {
702 Os::MacOs | Os::Windows => (
703 home.join("Applications/Pitboard.app/Contents/MacOS/Pitboard"),
704 home.join("Applications/Pitboard.app/Contents/Helpers/pitboard"),
705 ),
706 Os::Linux => (
707 home.join("usr/bin/pitboard-app"),
708 home.join("usr/bin/pitboard"),
709 ),
710 }
711 }
712
713 fn a_program_at(path: &Path) {
716 std::fs::create_dir_all(path.parent().expect("a directory")).expect("its directory");
717 for file in crate::host::OS
718 .launcher(path)
719 .into_iter()
720 .chain([path.to_path_buf()])
721 {
722 std::fs::write(file, "").expect("a program");
723 }
724 }
725
726 fn a_task_program_at(path: &Path) {
728 a_program_at(path);
729 let launcher = Os::Windows.launcher(path).expect("a launcher's name");
730 std::fs::write(launcher, "").expect("a launcher");
731 }
732
733 #[test]
735 fn a_schedule_the_scheduler_will_not_start_is_not_left_on_disk() {
736 let home = Scratch::new();
737 let program = home.path().join("bin/pitboard");
738 a_program_at(&program);
739 let ctx = home.ctx().with_schedule_program(program);
740
741 home.1.refuse_next_start();
742 let refused = install(&ctx, Permit::for_a_test()).expect_err("refused");
743
744 assert_eq!(refused.code(), "schedule_refused");
745 assert_eq!(status(&ctx), Installed::No);
746 assert_eq!(installed_program(&ctx), None);
747 }
748
749 #[test]
752 fn a_repair_the_scheduler_will_not_start_leaves_the_schedule_as_it_was() {
753 let home = Scratch::new();
754 std::fs::create_dir_all(home.ctx().default_pitboard_home()).expect("a Pitboard home");
755 let (app, bundled) = the_app(home.path());
756 a_program_at(&app);
757 a_program_at(&bundled);
758 let ctx = home.ctx();
759 install(
760 &ctx.clone().with_schedule_program(app.clone()),
761 Permit::for_a_test(),
762 )
763 .expect("0.3.0's schedule");
764
765 home.1.refuse_next_start();
766 let refused = repair(
767 &ctx.clone().with_schedule_program(bundled),
768 Permit::for_a_test(),
769 )
770 .expect_err("refused");
771
772 assert_eq!(refused.code(), "schedule_refused");
773 assert!(matches!(status(&ctx), Installed::Yes { .. }));
774 assert_eq!(installed_program(&ctx), Some(app));
775 }
776
777 #[test]
778 fn nothing_is_installed_on_a_machine_where_nothing_was_installed() {
779 let home = Scratch::new();
780 let ctx = home.ctx();
781 assert_eq!(status(&ctx), Installed::No);
782 assert_eq!(installed_program(&ctx), None);
783 }
784
785 #[test]
787 fn a_machine_with_no_scheduler_says_so() {
788 let home = Scratch::new();
789 home.1.without_a_scheduler();
790 let program = home.path().join("bin/pitboard");
791 a_program_at(&program);
792 let ctx = home.ctx().with_schedule_program(program);
793 assert_eq!(status(&ctx), Installed::Unsupported);
794 assert_eq!(path(&ctx), None);
795 assert_eq!(
796 install(&ctx, Permit::for_a_test())
797 .expect_err("nowhere")
798 .code(),
799 "schedule_unsupported"
800 );
801 assert_eq!(
802 uninstall(&ctx, Permit::for_a_test())
803 .expect_err("nowhere")
804 .code(),
805 "schedule_unsupported"
806 );
807 assert!(!repair(&ctx, Permit::for_a_test()).expect("nothing to do"));
808 assert!(!uninstall_for_app(&ctx, Permit::for_a_test()).expect("nothing to do"));
809 }
810
811 #[test]
812 fn the_schedule_runs_the_pitboard_the_context_names_and_otherwise_this_one() {
813 let home = Scratch::new();
814 let ctx = home.ctx();
815 let running = std::env::current_exe().expect("this test's own program");
816 match crate::host::OS.launcher(&running) {
817 Some(launcher) => {
819 let refused = program(&ctx, Job::Renew).expect_err("no launcher");
820 assert_eq!(refused.code(), "schedule_launcher_missing");
821 assert!(
822 refused
823 .to_string()
824 .contains(&launcher.display().to_string()),
825 "{refused}"
826 );
827 }
828 None => {
829 let scheduled = program(&ctx, Job::Renew).expect("this program");
830 assert_eq!(
831 std::fs::canonicalize(&scheduled).expect("there"),
832 std::fs::canonicalize(&running).expect("there"),
833 "the command line schedules itself"
834 );
835 }
836 }
837 let bundled = home
838 .path()
839 .join("Applications/Pitboard.app/Contents/Helpers/pitboard");
840 a_program_at(&bundled);
841 assert_eq!(
842 program(&ctx.with_schedule_program(bundled.clone()), Job::Renew)
843 .expect("the named one"),
844 bundled,
845 "an app schedules the command line it comes with"
846 );
847 }
848
849 #[test]
854 fn a_named_pitboard_that_will_not_be_there_is_refused() {
855 let home = Scratch::new();
856 let ctx = home.ctx();
857
858 let missing = home.path().join("Pitboard.app/Contents/Helpers/pitboard");
859 let refused = install(
860 &ctx.clone().with_schedule_program(missing.clone()),
861 Permit::for_a_test(),
862 )
863 .expect_err("nothing there to run");
864 assert_eq!(refused.code(), "schedule_program_missing");
865 assert!(
866 refused.to_string().contains(&missing.display().to_string()),
867 "{refused}"
868 );
869
870 let temporary = home
871 .path()
872 .join("AppTranslocation/6A1C/d/Pitboard.app/Contents/Helpers/pitboard");
873 a_program_at(&temporary);
874 let refused = install(
875 &ctx.clone().with_schedule_program(temporary.clone()),
876 Permit::for_a_test(),
877 )
878 .expect_err("a copy that goes away");
879 assert_eq!(refused.code(), "schedule_program_temporary");
880 assert!(
881 refused
882 .to_string()
883 .contains(&temporary.display().to_string())
884 && refused.to_string().contains("Applications folder"),
885 "{refused}"
886 );
887
888 let unzipped = home
889 .path()
890 .join("Temp1_pitboard-v0.15.0-x86_64-pc-windows-msvc.zip")
891 .join("pitboard.exe");
892 a_program_at(&unzipped);
893 let refused = install(
894 &ctx.clone().with_schedule_program(unzipped),
895 Permit::for_a_test(),
896 )
897 .expect_err("a copy Explorer made of a zip");
898 assert_eq!(refused.code(), "schedule_program_temporary");
899 assert!(
900 refused
901 .to_string()
902 .contains("Install Pitboard, or extract the zip"),
903 "{refused}"
904 );
905
906 let mounted = home.path().join(".mount_PitboaJgKlbE/usr/bin/pitboard");
907 a_program_at(&mounted);
908 let refused = install(
909 &ctx.clone().with_schedule_program(mounted),
910 Permit::for_a_test(),
911 )
912 .expect_err("a copy an AppImage mounted");
913 assert_eq!(refused.code(), "schedule_program_temporary");
914 assert!(
915 refused
916 .to_string()
917 .contains("Install Pitboard rather than run it from an AppImage"),
918 "{refused}"
919 );
920
921 assert_eq!(status(&ctx), Installed::No, "nothing was written");
922 }
923
924 #[test]
926 fn the_running_pitboard_is_refused_where_a_named_one_would_be() {
927 let home = Scratch::new();
928 let unzipped = home
929 .path()
930 .join("Temp1_pitboard-v0.15.0-x86_64-pc-windows-msvc.zip")
931 .join("pitboard.exe");
932 a_program_at(&unzipped);
933 let refused = program_of(Os::Windows, None, || Ok(unzipped.clone()), Job::Renew)
934 .expect_err("a copy that goes");
935 assert_eq!(refused.code(), "schedule_program_temporary");
936 let gone = home.path().join("gone").join("pitboard");
937 let refused = program_of(Os::Linux, None, || Ok(gone.clone()), Job::Renew)
938 .expect_err("nothing there");
939 assert_eq!(refused.code(), "schedule_program_missing");
940
941 let installed = home.path().join("bin").join("pitboard");
942 a_program_at(&installed);
943 assert_eq!(
944 program_of(Os::Linux, None, || Ok(installed.clone()), Job::Renew)
945 .expect("one that lasts"),
946 installed
947 );
948 }
949
950 #[test]
953 fn a_windows_job_needs_the_launcher_beside_its_pitboard() {
954 let home = Scratch::new();
955 let installed = home.path().join("bin").join("pitboard.exe");
956 let launcher = home.path().join("bin").join("pitboardw.exe");
957 std::fs::create_dir_all(home.path().join("bin")).expect("a bin");
958 std::fs::write(&installed, "").expect("a program");
959 for job in [Job::Renew, Job::Watch] {
960 let refused = program_of(Os::Windows, Some(&installed), || unreachable!(), job)
961 .expect_err("no launcher");
962 assert_eq!(refused.code(), "schedule_launcher_missing", "{job:?}");
963 assert!(
964 refused
965 .to_string()
966 .contains(&launcher.display().to_string()),
967 "{refused}"
968 );
969 }
970 assert_eq!(
971 program_of(Os::Linux, Some(&installed), || unreachable!(), Job::Renew)
972 .expect("no launcher elsewhere"),
973 installed
974 );
975
976 std::fs::write(&launcher, "").expect("a launcher");
977 assert_eq!(
978 program_of(Os::Windows, Some(&installed), || unreachable!(), Job::Renew)
979 .expect("both there"),
980 installed
981 );
982 }
983
984 #[test]
988 fn a_temporary_copy_is_told_by_its_path() {
989 for (path, temporary) in [
990 (
991 "/private/var/folders/xy/abc/T/AppTranslocation/0A1B2C/d/Pitboard.app/Contents/\
992 Helpers/pitboard",
993 true,
994 ),
995 (
996 "/Applications/Pitboard.app/Contents/Helpers/pitboard",
997 false,
998 ),
999 (
1000 "/Users/x/MyAppTranslocation/Pitboard.app/Contents/Helpers/pitboard",
1001 false,
1002 ),
1003 (
1004 "/Users/x/AppTranslocations/Pitboard.app/Contents/Helpers/pitboard",
1005 false,
1006 ),
1007 (
1008 r"C:\Users\x\AppData\Local\Temp\Temp1_pitboard.zip\pitboard\pitboard.exe",
1009 true,
1010 ),
1011 (r"C:\Users\x\Temp12_Pitboard.ZIP\bin\pitboard.exe", true),
1012 (r"C:\Users\x\Temp_pitboard.zip\pitboard.exe", false),
1013 (r"C:\Users\x\Temp1_pitboard\pitboard.exe", false),
1014 ("/tmp/.mount_PitboaJgKlbE/usr/bin/pitboard", true),
1015 ("/run/user/1000/.mount_x1aB2c3/usr/bin/pitboard", true),
1016 (
1017 "/tmp/appimage_extracted_0123456789abcdef0123456789abcdef/usr/bin/pitboard",
1018 true,
1019 ),
1020 ("/home/x/.mount_/usr/bin/pitboard", false),
1021 ("/home/x/.mount_ab/usr/bin/pitboard", false),
1022 ("/home/x/mount_PitboaJgKlbE/usr/bin/pitboard", false),
1023 ("/home/x/.mount_PitboardThings/usr/bin/pitboard", false),
1024 ("/home/x/.mount_Pitboa-+_*.,/usr/bin/pitboard", false),
1025 ("/tmp/appimage_extracted_cache/usr/bin/pitboard", false),
1026 (
1027 "/tmp/appimage_extracted_0123456789ABCDEF0123456789ABCDEF/usr/bin/pitboard",
1028 false,
1029 ),
1030 ("/home/x/Applications/Pitboard.AppImage", false),
1031 ] {
1032 assert_eq!(in_a_temporary_copy(Path::new(path)), temporary, "{path}");
1033 }
1034 }
1035
1036 #[test]
1038 fn a_schedule_running_the_linux_app_is_at_fault() {
1039 let fault_of = |os: Os, program: &str| fault(os, Path::new(program), true);
1040 assert_eq!(
1041 fault_of(Os::Linux, "/usr/bin/pitboard-app"),
1042 Some(Fault::TheApp)
1043 );
1044 assert_eq!(fault_of(Os::Linux, "/usr/bin/pitboard"), None);
1045 assert_eq!(
1046 fault_of(Os::Linux, "/opt/Pitboard.app/Contents/MacOS/Pitboard"),
1047 None,
1048 "no bundle on Linux"
1049 );
1050 let bundle = "/Applications/Pitboard.app/Contents/MacOS/Pitboard";
1051 assert_eq!(fault_of(Os::MacOs, bundle), Some(Fault::TheApp));
1052 assert_eq!(fault_of(Os::MacOs, "/usr/bin/pitboard-app"), None);
1053 assert_eq!(fault_of(Os::Windows, bundle), Some(Fault::TheApp));
1054 assert_eq!(
1055 fault(Os::Linux, Path::new("/usr/bin/pitboard-app"), false),
1056 Some(Fault::Gone)
1057 );
1058 }
1059
1060 #[test]
1063 fn an_installed_schedule_says_which_pitboard_it_runs() {
1064 let home = Scratch::new();
1065 let bundled = home
1066 .path()
1067 .join("Tools&Apps/Pitboard.app/Contents/Helpers/pitboard");
1068 a_program_at(&bundled);
1069 let ctx = home.ctx().with_schedule_program(bundled.clone());
1070
1071 install(&ctx, Permit::for_a_test()).expect("installed");
1072 assert!(matches!(status(&ctx), Installed::Yes { .. }));
1073 assert_eq!(installed_program(&ctx), Some(bundled));
1074
1075 assert!(uninstall(&ctx, Permit::for_a_test()).expect("taken away"));
1076 assert_eq!(status(&ctx), Installed::No);
1077 assert_eq!(installed_program(&ctx), None);
1078 assert!(!uninstall(&ctx, Permit::for_a_test()).expect("nothing there"));
1079 }
1080
1081 #[test]
1085 fn a_schedule_that_runs_an_app_is_pointed_at_its_command_line() {
1086 let home = Scratch::new();
1087 std::fs::create_dir_all(home.ctx().default_pitboard_home()).expect("a Pitboard home");
1088 let (app, bundled) = the_app(home.path());
1089 a_program_at(&app);
1090 a_program_at(&bundled);
1091 let ctx = home.ctx();
1092 let the_app = ctx.clone().with_schedule_program(bundled.clone());
1093
1094 assert!(
1095 !repair(&the_app, Permit::for_a_test()).expect("nothing to do"),
1096 "nothing installed"
1097 );
1098
1099 install(
1100 &ctx.clone().with_schedule_program(app.clone()),
1101 Permit::for_a_test(),
1102 )
1103 .expect("0.3.0's schedule");
1104 assert!(
1105 !repair(&ctx, Permit::for_a_test()).expect("nothing to do"),
1106 "no command line named"
1107 );
1108 let gone = home.path().join("Old.app/Contents/Helpers/pitboard");
1109 assert!(
1110 !repair(
1111 &ctx.clone().with_schedule_program(gone),
1112 Permit::for_a_test()
1113 )
1114 .expect("nothing to do"),
1115 "a command line that is not there"
1116 );
1117 assert!(
1118 !repair(
1119 &the_app
1120 .clone()
1121 .with_pitboard_home(home.path().join("elsewhere")),
1122 Permit::for_a_test()
1123 )
1124 .expect("nothing to do"),
1125 "a schedule another home's Pitboard looks after"
1126 );
1127 assert_eq!(installed_program(&ctx), Some(app.clone()));
1128
1129 assert!(repair(&the_app, Permit::for_a_test()).expect("repaired"));
1130 assert_eq!(installed_program(&ctx), Some(bundled));
1131 let logged = crate::audit::read(&ctx, 1);
1132 assert_eq!(
1133 logged
1134 .iter()
1135 .map(|e| (e.verb.as_str(), e.subject.as_str(), e.outcome.as_str()))
1136 .collect::<Vec<_>>(),
1137 [("schedule", "repair", "ok")]
1138 );
1139
1140 assert!(
1141 !repair(&the_app, Permit::for_a_test()).expect("nothing to do"),
1142 "a schedule that runs a command line already"
1143 );
1144 install(
1145 &ctx.clone().with_schedule_program(app.clone()),
1146 Permit::for_a_test(),
1147 )
1148 .expect("the app again");
1149 let temporary = home
1150 .path()
1151 .join("AppTranslocation/6A1C/d/Pitboard.app/Contents/Helpers/pitboard");
1152 a_program_at(&temporary);
1153 assert!(
1154 !repair(
1155 &ctx.clone().with_schedule_program(temporary),
1156 Permit::for_a_test()
1157 )
1158 .expect("nothing to do"),
1159 "a command line that is gone once the app quits"
1160 );
1161 assert_eq!(installed_program(&ctx), Some(app));
1162 }
1163
1164 #[test]
1165 fn a_schedule_whose_pitboard_is_gone_is_pointed_at_the_apps_command_line() {
1166 let home = Scratch::new();
1167 std::fs::create_dir_all(home.ctx().default_pitboard_home()).expect("a Pitboard home");
1168 let brew = home.path().join("homebrew/bin/pitboard");
1169 let bundled = home
1170 .path()
1171 .join("Applications/Pitboard.app/Contents/Helpers/pitboard");
1172 a_program_at(&brew);
1173 a_program_at(&bundled);
1174 let ctx = home.ctx();
1175 install(
1176 &ctx.clone().with_schedule_program(brew.clone()),
1177 Permit::for_a_test(),
1178 )
1179 .expect("installed from Homebrew's pitboard");
1180 let the_app = ctx.clone().with_schedule_program(bundled.clone());
1181 assert!(
1182 !repair(&the_app, Permit::for_a_test()).expect("nothing to do"),
1183 "a Pitboard that is there"
1184 );
1185
1186 std::fs::remove_file(&brew).expect("Homebrew's pitboard uninstalled");
1187 assert!(repair(&the_app, Permit::for_a_test()).expect("repaired"));
1188 assert_eq!(installed_program(&ctx), Some(bundled));
1189 }
1190
1191 #[test]
1194 fn a_process_another_job_started_still_repairs() {
1195 let home = Scratch::new();
1196 std::fs::create_dir_all(home.ctx().default_pitboard_home()).expect("a Pitboard home");
1197 let (app, bundled) = the_app(home.path());
1198 a_program_at(&app);
1199 a_program_at(&bundled);
1200 let ctx = home.ctx();
1201 install(
1202 &ctx.clone().with_schedule_program(app),
1203 Permit::for_a_test(),
1204 )
1205 .expect("0.3.0's schedule");
1206
1207 let opened = ctx
1208 .clone()
1209 .with_schedule_program(bundled.clone())
1210 .with_scheduled_job("application.com.datlechin.pitboard.1.2".into());
1211 assert!(repair(&opened, Permit::for_a_test()).expect("repaired"));
1212 assert_eq!(installed_program(&ctx), Some(bundled));
1213 }
1214
1215 #[test]
1217 fn the_app_points_a_task_whose_pitboard_is_gone_at_its_own_and_nothing_else() {
1218 let home = Scratch(
1219 tempfile::tempdir().expect("a scratch home"),
1220 MemoryHost::scheduling_tasks("S-1-5-21-1"),
1221 );
1222 let ctx = home.read(&[("HTTPS_PROXY", "http://proxy.example.com:3128")]);
1223 let scoop = home
1224 .path()
1225 .join(r"scoop\apps\pitboard\current\pitboard.exe");
1226 let bundled = home.path().join(r"Programs\Pitboard\bin\pitboard.exe");
1227 a_task_program_at(&scoop);
1228 a_task_program_at(&bundled);
1229 install(
1230 &ctx.clone().with_schedule_program(scoop.clone()),
1231 Permit::for_a_test(),
1232 )
1233 .expect("installed from Scoop's pitboard");
1234 let the_app = home.read(&[]).with_schedule_program(bundled.clone());
1235 assert!(
1236 !repair(&the_app, Permit::for_a_test()).expect("nothing to do"),
1237 "a Pitboard that is there"
1238 );
1239
1240 std::fs::remove_file(&scoop).expect("Scoop's pitboard uninstalled");
1241 let kept = path(&ctx).expect("the task's file");
1242 let written = std::fs::read_to_string(&kept).expect("the task");
1243 for (setting, changed) in [
1244 ("<StartWhenAvailable>true<", "<StartWhenAvailable>false<"),
1245 (
1246 "<StopIfGoingOnBatteries>false<",
1247 "<StopIfGoingOnBatteries>true<",
1248 ),
1249 ("<Hidden>", "<Enabled>false</Enabled><Hidden>"),
1250 ] {
1251 std::fs::write(&kept, written.replace(setting, changed)).expect("changed by hand");
1252 assert!(
1253 !repair(&the_app, Permit::for_a_test()).expect("nothing to do"),
1254 "{changed}"
1255 );
1256 assert_eq!(installed_program(&ctx), Some(scoop.clone()), "{changed}");
1257 }
1258
1259 std::fs::write(&kept, &written).expect("as Pitboard wrote it");
1260 assert!(repair(&the_app, Permit::for_a_test()).expect("repaired"));
1261 assert_eq!(installed_program(&ctx), Some(bundled));
1262 assert_eq!(
1263 given(&ctx),
1264 pairs(&[("HTTPS_PROXY", "http://proxy.example.com:3128")]),
1265 "the proxy it was given, not the app's none"
1266 );
1267 assert!(
1268 !repair(&the_app, Permit::for_a_test()).expect("nothing to do"),
1269 "the app's own, which is there"
1270 );
1271 }
1272
1273 #[test]
1274 fn removing_the_app_takes_away_only_a_task_that_runs_its_command_line() {
1275 let home = Scratch(
1276 tempfile::tempdir().expect("a scratch home"),
1277 MemoryHost::scheduling_tasks("S-1-5-21-1"),
1278 );
1279 let proxied = home.read(&[("HTTPS_PROXY", "http://proxy.example.com:3128")]);
1280 let scoop = home
1281 .path()
1282 .join(r"scoop\apps\pitboard\current\pitboard.exe");
1283 let bundled = home.path().join(r"Programs\Pitboard\bin\pitboard.exe");
1284 a_task_program_at(&scoop);
1285 a_task_program_at(&bundled);
1286 let the_app = home.read(&[]).with_schedule_program(bundled.clone());
1287
1288 assert!(
1289 !uninstall_for_app(&the_app, Permit::for_a_test()).expect("nothing to do"),
1290 "nothing installed"
1291 );
1292 install(
1293 &proxied.clone().with_schedule_program(scoop.clone()),
1294 Permit::for_a_test(),
1295 )
1296 .expect("installed from Scoop's pitboard");
1297 assert!(
1298 !uninstall_for_app(&the_app, Permit::for_a_test()).expect("nothing to do"),
1299 "Scoop's"
1300 );
1301 assert_eq!(installed_program(&proxied), Some(scoop));
1302
1303 install(
1304 &proxied.clone().with_schedule_program(bundled.clone()),
1305 Permit::for_a_test(),
1306 )
1307 .expect("installed from the app");
1308 assert!(
1309 !uninstall_for_app(&home.read(&[]), Permit::for_a_test()).expect("nothing to do"),
1310 "no command line named"
1311 );
1312 let kept = path(&proxied).expect("the task's file");
1313 let written = std::fs::read_to_string(&kept).expect("the task");
1314 std::fs::write(
1315 &kept,
1316 written.replace("<Hidden>", "<Enabled>false</Enabled><Hidden>"),
1317 )
1318 .expect("turned off in Task Scheduler");
1319 assert!(uninstall_for_app(&the_app, Permit::for_a_test()).expect("taken away"));
1320 assert_eq!(status(&proxied), Installed::No);
1321 assert!(
1322 !crate::host::task::environment_file(&proxied, Job::Renew).exists(),
1323 "nor its proxy"
1324 );
1325 let logged = crate::audit::read(&proxied, 1);
1326 assert_eq!(
1327 logged
1328 .iter()
1329 .map(|e| (e.verb.as_str(), e.subject.as_str(), e.outcome.as_str()))
1330 .collect::<Vec<_>>(),
1331 [("schedule", "uninstall", "ok")]
1332 );
1333 assert!(!uninstall_for_app(&the_app, Permit::for_a_test()).expect("nothing there"));
1334 }
1335
1336 #[test]
1338 fn removing_the_app_takes_away_a_watch_service_that_runs_its_command_line() {
1339 let home = Scratch(
1340 tempfile::tempdir().expect("a scratch home"),
1341 MemoryHost::scheduling_tasks("S-1-5-21-1"),
1342 );
1343 let scoop = home
1344 .path()
1345 .join(r"scoop\apps\pitboard\current\pitboard.exe");
1346 let bundled = home.path().join(r"Programs\Pitboard\bin\pitboard.exe");
1347 a_task_program_at(&scoop);
1348 a_task_program_at(&bundled);
1349 let the_app = home.read(&[]).with_schedule_program(bundled.clone());
1350 let at = crate::watch_service::Switching::At(crate::duty::autoswitch::Policy::default());
1351 let watching = |ctx: &Context| {
1352 crate::watch_service::status(ctx) != crate::watch_service::Installed::No
1353 };
1354
1355 crate::watch_service::install(
1356 &home.read(&[]).with_schedule_program(scoop),
1357 Permit::for_a_test(),
1358 at,
1359 )
1360 .expect("installed from Scoop's pitboard");
1361 assert!(!uninstall_for_app(&the_app, Permit::for_a_test()).expect("nothing to do"));
1362 assert!(watching(&the_app), "Scoop's stays");
1363
1364 crate::watch_service::install(&the_app, Permit::for_a_test(), at)
1365 .expect("installed from the app's");
1366 install(&the_app, Permit::for_a_test()).expect("renewal too");
1367 assert!(uninstall_for_app(&the_app, Permit::for_a_test()).expect("taken away"));
1368 assert!(!watching(&the_app));
1369 assert_eq!(status(&the_app), Installed::No);
1370 }
1371
1372 #[test]
1374 fn a_schedule_pitboard_did_not_write_names_no_program() {
1375 let home = Scratch::new();
1376 let ctx = home.ctx();
1377 let installed = path(&ctx).expect("a scheduler here");
1378 std::fs::create_dir_all(installed.parent().expect("its directory")).expect("made");
1379 std::fs::write(&installed, "not what install writes\n").expect("written");
1380 if let Some(beside) = installed.parent() {
1381 std::fs::write(
1383 beside.join("pitboard-renew.service"),
1384 "[Service]\nExecStart=/bin/true\n",
1385 )
1386 .expect("written");
1387 }
1388
1389 assert!(matches!(status(&ctx), Installed::Yes { .. }));
1390 assert_eq!(installed_program(&ctx), None);
1391 }
1392
1393 #[test]
1396 fn the_schedule_belongs_to_the_default_home_alone() {
1397 let scratch = tempfile::tempdir().expect("a scratch folder");
1398 let home = scratch.path().join("home");
1399 let ctx = Context::new(home.clone());
1400 let default = crate::host::OS.default_pitboard_home(&home);
1401 assert!(serves(&ctx));
1402 let trailing = PathBuf::from(format!(
1403 "{}{}",
1404 default.display(),
1405 std::path::MAIN_SEPARATOR
1406 ));
1407 assert!(serves(&ctx.clone().with_pitboard_home(trailing)));
1408 let upper = PathBuf::from(default.to_string_lossy().to_uppercase());
1409 assert_eq!(
1410 serves(&ctx.clone().with_pitboard_home(upper)),
1411 crate::host::OS == Os::Windows,
1412 "in another case"
1413 );
1414 assert!(!serves(&ctx.with_pitboard_home(home.join("elsewhere"))));
1415 }
1416
1417 #[test]
1420 fn a_windows_schedule_renews_the_folder_in_userprofile_whatever_home_says() {
1421 let scratch = tempfile::tempdir().expect("a scratch folder");
1422 let profile = scratch.path().join("profile");
1423 let named = profile.to_string_lossy().into_owned();
1424 let env = crate::context::Environment::on(
1425 Os::Windows,
1426 [
1427 ("USERPROFILE", named.as_str()),
1428 ("HOME", "/c/Users/elsewhere"),
1429 ],
1430 );
1431 let ctx = Context::read(&env, "cli");
1432 let folder = profile.join("AppData").join("Local").join("Pitboard");
1433 assert_eq!(ctx.pitboard_home, folder);
1434 assert_eq!(env.pitboard_home(), folder, "what an app asks for");
1435 assert!(serves(&ctx));
1436 let run = for_its_run(
1437 &ctx.clone()
1438 .with_pitboard_home(profile.join("elsewhere"))
1439 .started_by_the_schedule(),
1440 Job::Renew,
1441 );
1442 assert_eq!(run.pitboard_home, folder);
1443 }
1444
1445 #[test]
1447 #[should_panic(expected = "with this account's own home")]
1448 fn a_build_for_tests_never_runs_as_the_schedule_with_the_accounts_own_home() {
1449 let own = {
1450 let _real = crate::host::user::testing::reaching_the_real_home();
1451 crate::host::user::home().expect("this account has a home")
1452 };
1453 let _ = for_its_run(&Context::new(own).started_by_the_schedule(), Job::Renew);
1454 }
1455
1456 #[test]
1463 fn a_schedule_is_installed_only_where_pitboard_home_is_the_default_home() {
1464 let home = Scratch::new();
1465 std::fs::create_dir_all(home.ctx().default_pitboard_home()).expect("a Pitboard home");
1466 let program = home.path().join("bin/pitboard");
1467 a_program_at(&program);
1468 let ctx = home.ctx().with_schedule_program(program);
1469 let default = ctx.default_pitboard_home();
1470 let elsewhere = home.path().join("elsewhere");
1471 let another = ctx.clone().with_pitboard_home(elsewhere.clone());
1472
1473 home.1.refuse_next_start();
1474 let refused = install(&another, Permit::for_a_test()).expect_err("another home");
1475 assert_eq!(refused.code(), "schedule_not_default_home");
1476 assert_eq!(refused.exit_code(), 1);
1477 assert_eq!(
1478 refused.to_string(),
1479 format!(
1480 "the renewal schedule renews only the parked logins in {}, not those in {}, \
1481 which PITBOARD_HOME names. Nothing was scheduled. To schedule it for {}, \
1482 unset PITBOARD_HOME and install it again.",
1483 default.display(),
1484 elsewhere.display(),
1485 default.display()
1486 )
1487 );
1488 assert_eq!(status(&ctx), Installed::No, "nothing was written");
1489 assert!(crate::audit::read(&another, 10).is_empty(), "nor logged");
1490
1491 let spelled = PathBuf::from(format!("{}/", default.display()));
1492 let refused = install(
1493 &ctx.clone().with_pitboard_home(spelled),
1494 Permit::for_a_test(),
1495 )
1496 .expect_err("the default home reaches the scheduler, which refuses this once");
1497 assert_eq!(refused.code(), "schedule_refused");
1498 install(&ctx, Permit::for_a_test()).expect("installed from the default home");
1499 assert!(matches!(status(&ctx), Installed::Yes { .. }));
1500
1501 assert!(!repair(&another, Permit::for_a_test()).expect("not refused"));
1502 assert!(uninstall(&another, Permit::for_a_test()).expect("taken away from another home"));
1503 assert_eq!(status(&ctx), Installed::No);
1504 }
1505
1506 #[test]
1512 fn a_schedule_is_given_the_proxy_variables_of_whoever_installs_it() {
1513 let home = Scratch::new();
1514 std::fs::create_dir_all(home.ctx().default_pitboard_home()).expect("a Pitboard home");
1515 let program = home.path().join("bin/pitboard");
1516 a_program_at(&program);
1517 let proxied = home
1518 .read(&[
1519 ("PITBOARD_NO_ARGV", "1"),
1520 ("no_proxy", "localhost"),
1521 ("HTTPS_PROXY", "http://proxy.example.com:3128"),
1522 ("ALL_PROXY", "socks5h://alice:s3cret@127.0.0.1:1080"),
1523 ("NO_PROXY", ""),
1524 ("PATH", "/usr/bin"),
1525 ])
1526 .with_schedule_program(program.clone());
1527
1528 install(&proxied, Permit::for_a_test()).expect("installed");
1529 let (all, https) = (
1530 ("ALL_PROXY", "socks5h://alice:s3cret@127.0.0.1:1080"),
1531 ("HTTPS_PROXY", "http://proxy.example.com:3128"),
1532 );
1533 let (handed, written, private) = match crate::host::OS {
1534 Os::MacOs | Os::Linux => (
1535 vec![
1536 ("PITBOARD_NO_ARGV", "1"),
1537 all,
1538 https,
1539 ("NO_PROXY", ""),
1540 ("no_proxy", "localhost"),
1541 ],
1542 path(&proxied).expect("a scheduler here"),
1543 "mode 600",
1544 ),
1545 Os::Windows => (
1548 vec![all, https, ("no_proxy", "localhost")],
1549 crate::host::task::environment_file(&proxied, Job::Renew),
1550 "open to you, SYSTEM and Administrators",
1551 ),
1552 };
1553 assert_eq!(given(&proxied), pairs(&handed));
1554 let its = installed_proxies(&proxied).expect("installed");
1555 assert!(its.same_way(&proxied.proxy), "{its:?}");
1556 assert_eq!(its.variables(), proxied.proxy.variables());
1557 assert_eq!(
1558 crate::host::fs::access(&written).map(|access| access.described),
1559 Some(private.to_string()),
1560 "a proxy's password is the person's alone to read"
1561 );
1562
1563 let direct = home.read(&[]).with_schedule_program(program);
1564 install(&direct, Permit::for_a_test()).expect("installed again");
1565 assert_eq!(given(&direct), Vec::new(), "a reinstall takes this run's");
1566 assert!(
1567 installed_proxies(&direct)
1568 .expect("installed")
1569 .same_way(&direct.proxy)
1570 );
1571 }
1572
1573 #[test]
1579 fn a_repair_writes_the_proxy_the_schedules_file_gives_and_never_the_apps() {
1580 let home = Scratch::new();
1581 std::fs::create_dir_all(home.ctx().default_pitboard_home()).expect("a Pitboard home");
1582 let (app, bundled) = the_app(home.path());
1583 a_program_at(&app);
1584 a_program_at(&bundled);
1585 let apps_own = [("HTTPS_PROXY", "http://app.example.com:3128")];
1586
1587 install(
1588 &home.read(&[]).with_schedule_program(app.clone()),
1589 Permit::for_a_test(),
1590 )
1591 .expect("0.3.0's schedule, which gives no proxy");
1592 let the_app = home.read(&apps_own).with_schedule_program(bundled.clone());
1593 assert!(repair(&the_app, Permit::for_a_test()).expect("repaired"));
1594 assert_eq!(installed_program(&the_app), Some(bundled.clone()));
1595 assert_eq!(given(&the_app), Vec::new(), "no proxy, not the app's");
1596
1597 let edited = pairs(&[
1598 ("https_proxy", "http://alice:s3cret@proxy.example.com:3128"),
1599 ("NO_PROXY", ".anthropic.com"),
1600 ]);
1601 install(
1602 &home
1603 .read(&[
1604 ("https_proxy", "http://alice:s3cret@proxy.example.com:3128"),
1605 ("NO_PROXY", ".anthropic.com"),
1606 ])
1607 .with_schedule_program(app),
1608 Permit::for_a_test(),
1609 )
1610 .expect("an app's schedule that gives a proxy, as one edited by hand");
1611 assert!(repair(&the_app, Permit::for_a_test()).expect("repaired"));
1612 assert_eq!(installed_program(&the_app), Some(bundled));
1613 assert_eq!(given(&the_app), edited, "the proxy its file gave");
1614 }
1615
1616 #[test]
1621 fn a_test_never_reaches_the_systems_own_scheduler() {
1622 let scratch = tempfile::tempdir().expect("a scratch folder");
1623 let root = scratch.path().join("root");
1624 let program = root.join("bin/pitboard");
1625 a_program_at(&program);
1626 let ctx = Context::new(root.clone()).with_schedule_program(program);
1627 let refused =
1628 install(&ctx, Permit::for_a_test()).expect_err("refused before it reaches the system");
1629 match scheduler(&ctx) {
1630 None => assert_eq!(refused.code(), "schedule_unsupported"),
1631 Some(_) => assert_eq!(refused.code(), "schedule_refused"),
1632 }
1633 if crate::host::OS == Os::Linux && scheduler(&ctx).is_some() {
1634 assert!(refused.to_string().contains("user manager"), "{refused}");
1635 }
1636 assert!(
1637 !matches!(status(&ctx), Installed::Yes { .. }),
1638 "and nothing is left written"
1639 );
1640 }
1641
1642 const RUN: i64 = crate::switch::harness::NOW + 11 * 86_400;
1643
1644 fn due(name: &str) -> (crate::switch::harness::Rig, Context) {
1648 use crate::switch::harness;
1649 let m = harness::machine_on(MemoryHost::by_form(), name).in_the_default_home();
1650 harness::renews(&m, "there-refresh", "there-refresh-2");
1651 install(&m.ctx, Permit::for_a_test()).expect("scheduled");
1652 let at = m
1653 .ctx
1654 .clone()
1655 .with_clock(Arc::new(crate::time::FixedClock::at(RUN)));
1656 (m, at)
1657 }
1658
1659 fn codes(run: &[(Key, Renewal)]) -> Vec<&'static str> {
1660 run.iter().map(|(_, outcome)| outcome.code()).collect()
1661 }
1662
1663 fn renewed(ctx: &Context) -> Vec<(Key, Renewal)> {
1664 crate::service::Pitboard::new(ctx.clone())
1665 .renew()
1666 .expect("a run")
1667 }
1668
1669 fn doctor_says(ctx: &Context) -> crate::doctor::Check {
1670 crate::service::Pitboard::new(ctx.clone())
1671 .doctor()
1672 .checks
1673 .into_iter()
1674 .find(|check| check.code == "schedule")
1675 .expect("the schedule's line")
1676 }
1677
1678 #[test]
1682 fn a_scheduled_renewal_that_cannot_open_the_store_is_recorded_and_doctor_says_so() {
1683 let (m, at) = due("refused-kept");
1684 m.mem.vault().fault_all(crate::store::memory::Fault::Locked);
1685
1686 let run = renewed(&at.clone().started_by_the_schedule());
1687
1688 assert_eq!(codes(&run), ["credential_store_locked"]);
1689 assert_eq!(
1690 refused(&m.ctx, Job::Renew),
1691 Some(Refused {
1692 at: RUN,
1693 vault: Some(Vault::SecretService),
1694 codes: ["credential_store_locked".to_string()].into(),
1695 })
1696 );
1697 m.mem.vault().heal_all();
1698 let said = doctor_says(&at.with_clock(Arc::new(crate::time::FixedClock::at(RUN + 33_120))));
1699 assert_eq!(said.level, crate::doctor::Level::Warn);
1700 assert!(
1701 said.detail
1702 .contains("9h 12m ago, could not open the login keyring: it was locked"),
1703 "{}",
1704 said.detail
1705 );
1706 }
1707
1708 #[test]
1711 fn the_next_scheduled_renewal_that_opens_the_store_clears_the_record() {
1712 let (m, at) = due("refused-forgotten");
1713 let path = crate::home::dir(&m.ctx).join("renewal.json");
1714 std::fs::write(
1715 &path,
1716 r#"{"at":1760000000,"vault":"secret_service","codes":["credential_store_locked"]}"#,
1717 )
1718 .expect("kept by an earlier run");
1719 let kept = refused(&m.ctx, Job::Renew).expect("read back");
1720 assert_eq!(
1721 (kept.at, kept.vault, kept.locked()),
1722 (1_760_000_000, Some(Vault::SecretService), true)
1723 );
1724
1725 let nothing_due = renewed(&m.ctx.clone().started_by_the_schedule());
1726 assert!(codes(¬hing_due).is_empty());
1727 assert_eq!(
1728 refused(&m.ctx, Job::Renew),
1729 Some(kept),
1730 "the store was asked nothing"
1731 );
1732
1733 let run = renewed(&at.clone().started_by_the_schedule());
1734
1735 assert_eq!(codes(&run), ["renewed"]);
1736 assert_eq!(refused(&m.ctx, Job::Renew), None);
1737 assert!(!path.exists(), "no file, rather than an empty record");
1738 assert_eq!(doctor_says(&at).level, crate::doctor::Level::Ok);
1739 }
1740
1741 #[test]
1744 fn a_renewal_by_hand_records_nothing() {
1745 let (m, at) = due("refused-by-hand");
1746 m.mem.vault().fault_all(crate::store::memory::Fault::Locked);
1747
1748 let by_hand = renewed(&at);
1749
1750 assert_eq!(codes(&by_hand), ["credential_store_locked"]);
1751 assert_eq!(refused(&m.ctx, Job::Renew), None);
1752 assert!(!crate::home::dir(&m.ctx).join("renewal.json").exists());
1753
1754 renewed(&at.clone().started_by_the_schedule());
1755 let kept = refused(&m.ctx, Job::Renew).expect("kept by the schedule's run");
1756 m.mem.vault().heal_all();
1757 assert_eq!(codes(&renewed(&at)), ["renewed"]);
1758 assert_eq!(refused(&m.ctx, Job::Renew), Some(kept));
1759 }
1760}