Skip to main content

pitboard_core/
schedule.rs

1//! Keeping parked logins alive without anybody running a command.
2//!
3//! A refresh token has a finite life, and the only two things that renew one are somebody
4//! typing `pitboard` and the menu bar app's poll. So the tool is safe for a macOS user who
5//! installed the app and leaves it running, and quietly unsafe for everyone else: the
6//! whole of Linux, and any macOS user on the command line alone. Go away for the refresh
7//! window, come back, and every parked login is dead and each account needs a browser
8//! sign-in, which is precisely the cost Pitboard exists to spare people.
9//!
10//! This is opt-in, and stays opt-in. A background process that talks to Anthropic on a
11//! schedule is the shape most likely to be read as automation, so it is something a person
12//! turns on knowing what it is, and what it does is written where they can read it: it
13//! renews the owner's own parked logins and nothing else. It never switches, never asks for
14//! usage, never warms an account up, and makes no request other than the token exchange. A
15//! warm-up, which has Claude Code send a request, runs only where somebody leaves the app or
16//! `pitboard watch` running.
17//!
18//! What it installs is the system's own scheduler, never a homemade daemon: a LaunchAgent
19//! on macOS, which runs inside the login session so the keychain is unlocked, a systemd
20//! user timer on Linux, which is that system's answer, and a task in Task Scheduler on
21//! Windows, which runs only while the person is signed in. How each is asked is
22//! [`crate::host::Scheduler`]'s; what is decided here is which Pitboard it runs, how often,
23//! and whether it is this home's to change. Where there is no scheduler, it says so rather
24//! than inventing one.
25
26use 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
37/// Once a day. A refresh token's life is measured in weeks and Pitboard starts renewing
38/// three days out, so a daily check has three chances to catch each one, and a machine
39/// that was asleep for one of them still has two.
40pub(crate) const EVERY_SECONDS: u32 = 86_400;
41// How long launchd and systemd wait to start a watch service that failed again. systemd's
42// default of 100 ms would meet its start limit, five starts in 10 seconds, and give up.
43#[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/// A job Pitboard hands the system's own scheduler.
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
51pub enum Job {
52    /// `pitboard renew`, daily.
53    Renew,
54    /// `pitboard watch`, from sign-in on ([`crate::watch_service`]).
55    Watch,
56}
57
58impl Job {
59    /// What the job runs Pitboard with, marked as its run ([`SCHEDULED_RUN`], [`WATCH_RUN`]).
60    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/// Whether the schedule is installed, and what it is.
69#[derive(Debug, Clone, PartialEq, Eq)]
70pub enum Installed {
71    /// Installed, where `location` says.
72    Yes {
73        location: Location,
74        every_seconds: u32,
75    },
76    No,
77    /// This machine has no scheduler Pitboard knows how to ask.
78    Unsupported,
79}
80
81/// Why the user's systemd on Linux would not run a job for this home
82/// ([`Error::ScheduleManagerElsewhere`]).
83#[derive(Debug, Clone, PartialEq, Eq)]
84pub enum Elsewhere {
85    /// It reads no units from `units`, the folder the job is written in.
86    Folder { units: PathBuf },
87    /// It runs units with `theirs`, or with no `HOME`, rather than with `home`, where the job
88    /// would then act.
89    Home {
90        home: PathBuf,
91        theirs: Option<PathBuf>,
92    },
93}
94
95/// Where a person finds the schedule.
96#[derive(Debug, Clone, PartialEq, Eq)]
97pub enum Location {
98    /// The file launchd or systemd reads.
99    File(PathBuf),
100    /// Task Scheduler's path for the task, such as `\Pitboard\Renew S-1-5-21-…`.
101    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// The file a test's machine keeps the job in: Task Scheduler's own as a pretend keeps it.
118#[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
142/// The arguments the schedule's job runs Pitboard with where what the system's scheduler
143/// says of the job it started is not to be relied on: `pitboard renew --scheduled`. systemd
144/// passes a service a timer started `$TRIGGER_UNIT` only from version 252, and
145/// systemd.exec(5) calls it best effort, lossy and not to be relied on; a service started
146/// by hand gets none. So the unit's `ExecStart` carries the marker, and the command line,
147/// started with it, says so through [`Context::started_by_the_schedule`]. launchd names its
148/// job in `XPC_SERVICE_NAME`, so the LaunchAgent runs plain `renew`.
149pub const SCHEDULED_RUN: [&str; 2] = ["renew", "--scheduled"];
150
151/// What the watch service's job runs Pitboard with on every system, before its options: the
152/// marker [`Context::started_by_the_watch_service`] follows.
153pub const WATCH_RUN: [&str; 2] = ["watch", "--scheduled"];
154
155// Each job serves the default home alone, whatever `PITBOARD_HOME` it is given.
156pub(crate) fn serves(ctx: &Context) -> bool {
157    ctx.os
158        .same_path(&crate::home::dir(ctx), &ctx.default_pitboard_home())
159}
160
161/// Whether this process is a run `job` itself started: as the system's scheduler says,
162/// where it says, or as the marker its job is started with says ([`Job::marked`]).
163pub(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
168/// The context a run of `job` runs in: where the job started this run, the default home's,
169/// whatever `PITBOARD_HOME` says, and otherwise `ctx` as it is.
170///
171/// The schedule belongs to the default home alone ([`serves`]), whichever home installed
172/// it. Its job is never written with `PITBOARD_HOME`, but the system can still hand it one:
173/// `launchctl setenv` gives a variable to every job launchd starts, and a systemd user
174/// environment, from `systemctl --user set-environment` or `environment.d`, to every unit.
175/// A run that followed it renewed another home's parked logins and left the default home's
176/// to run out.
177///
178/// In a build for tests, a run the schedule started whose home is this account's own is
179/// stopped here, before it reads anything: it would renew the real `~/.pitboard`, and a
180/// test gives a run of the schedule a home of its own.
181pub(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/// What the store refused a run of a job, kept in Pitboard's directory until a run of it opens
199/// the store ([`ran`]): `renewal.json` for daily renewal, `watch.json` for the watch service. A
200/// run at boot can find the store locked that is open again by the time anybody looks, so
201/// doctor says it from here. Nothing kept is secret: a time, where the parked logins are kept,
202/// and codes.
203#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
204#[serde(default)]
205pub(crate) struct Refused {
206    /// When the run was.
207    pub(crate) at: i64,
208    /// Where the parked logins it could not open are kept.
209    pub(crate) vault: Option<Vault>,
210    /// Each code the store refused one of them with.
211    pub(crate) codes: BTreeSet<String>,
212}
213
214impl Refused {
215    /// Whether the store was locked, rather than unreadable another way.
216    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
228/// What the store last refused a run `job` started, where no run of it has opened the store
229/// since.
230pub(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
235/// What a run asked of the store its parked logins are in, and what that answered.
236pub(crate) enum StoreAnswer {
237    NotAsked,
238    /// It opened for every parked login the run asked about.
239    Opened,
240    /// It refused one or more with these codes.
241    Refused(BTreeSet<String>),
242}
243
244impl StoreAnswer {
245    /// What a run of renewal came to: the codes the store refused its parked logins with,
246    /// opened where it refused none, and not asked where the run renewed none.
247    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    /// What `error` says of the store: its refusal, or nothing of it.
266    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
280/// A run of `job` met `answer` from the store: renewal's under the lock it takes, the watch
281/// service's, which the system runs one of, after each decision and warm-up. A run the job
282/// started keeps the codes it was refused with, and forgets them once the store opened for every
283/// parked login it asked about. A run that asked about none keeps what was kept, and a run
284/// somebody started keeps nothing: it says nothing of what the job's runs meet.
285pub(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    // What the run renewed stands whether or not this is kept.
291    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
305/// The Pitboard `job` should run: the one the context names, or this one, by the path it was
306/// started by.
307pub(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
333/// `program`, where it will still be there when the scheduler runs it. A scheduler starts a
334/// program that is gone without telling anyone, every day, so a path that leads nowhere is
335/// refused rather than written down.
336///
337/// A path inside the copy macOS makes of an app opened where it was downloaded leads
338/// somewhere while that app runs and nowhere once it quits, so it is refused as well, and so
339/// is a program whose launcher is not beside it ([`Os::launcher`]).
340fn 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
362/// The first of what `job` starts that is not there: the launcher it names, where it names one,
363/// then `program`, the Pitboard it runs.
364pub(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
372/// Whether `program` is inside a temporary copy, which is there while it runs and gone once it
373/// quits ([`TemporaryCopy`]). Neither a schedule nor a link can rely on one, so an app asks this
374/// of the command line inside it, by the rule a schedule is refused by.
375pub fn in_a_temporary_copy(program: &Path) -> bool {
376    temporary_copy(program).is_some()
377}
378
379/// A copy a program runs from that is gone once it quits.
380#[derive(Debug, Clone, Copy, PartialEq, Eq)]
381pub(crate) enum TemporaryCopy {
382    /// The one macOS makes of an app opened where it was downloaded, through a directory named
383    /// `AppTranslocation`.
384    Translocated,
385    /// The one Windows' Explorer makes of a program opened inside a zip.
386    Zip,
387    /// The folder an AppImage's runtime mounts it in, or extracts it into to run it.
388    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
409// Explorer's `%TEMP%\Temp1_<zip>.zip`, named as seen and not measured.
410fn 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
421// type2-runtime's `.mount_`, up to six bytes of the AppImage's name and six `mkdtemp` fills, and
422// `appimage_extracted_` and the file's MD5 in lower-case hex (docs/facts/linux.md).
423fn 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
443/// Whether `job` is there as an earlier Pitboard wrote it, which installing it again mends.
444pub(crate) fn outdated(ctx: &Context, job: Job) -> bool {
445    scheduler(ctx).is_some_and(|s| s.outdated(ctx, job))
446}
447
448/// The Pitboard the installed schedule runs, read back from what `install` wrote. `None`
449/// where nothing is installed, and where what is there does not name one the way `install`
450/// writes it.
451pub(crate) fn installed_program(ctx: &Context) -> Option<PathBuf> {
452    scheduler(ctx)?.program(ctx, Job::Renew)
453}
454
455/// What a job is given of the installing Pitboard's environment, since the system starts it
456/// with its own and not the person's shell: `PITBOARD_NO_ARGV` where this context refuses
457/// the argument line, and `proxy`, the proxy variables, each by the name and with the value
458/// it was set with, so that its runs read the proxy the way those that set it did
459/// ([`crate::proxy`]).
460pub(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
468/// The proxy variables the installed schedule's job is given, as its file says, in the
469/// order written. Empty where nothing is installed.
470fn 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
486/// What the installed schedule's runs make of the proxy variables its file gives them, read
487/// as this run's are. `None` where nothing is installed.
488pub(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
496/// Install it, and ask the system to start it. Returns where it went.
497///
498/// Its job is given this context's proxy variables, which a reinstall takes again, and
499/// `PITBOARD_NO_ARGV` where this context has it ([`environment`]).
500///
501/// Refused with [`Error::ScheduleNotDefaultHome`] where this context is not the default
502/// home's ([`serves`]): the schedule renews `~/.pitboard` alone, so installing it while
503/// `PITBOARD_HOME` names another directory would leave that directory's parked logins to
504/// run out while seeming to keep them alive. `uninstall` and `repair` are not refused for
505/// it, so a schedule can always be taken away.
506pub(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
526/// This context's proxy variables, as [`environment`] takes them.
527pub(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
534// The app calls this as it starts. An app up to 0.3.0 scheduled itself, which launchd started
535// as a second menu bar app every day, and on Windows a task outlives the Pitboard it runs. Never
536// from the schedule's own run, which launchd stops as a repair unloads its job, and never with
537// the app's proxy, which names none a shell set.
538pub(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
566// A task whose settings were changed in Task Scheduler stays as it is: the change may be the
567// person's, and doctor names the way back.
568fn 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    // The system fails to start it every day.
576    Gone,
577    // An app's own program renews nothing.
578    TheApp,
579}
580
581// Doctor's judgement and the app's repair alike, for a program on `os`.
582pub(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
592/// Hand `job` to the system's scheduler, running `program` with `options` and given
593/// `environment`, and ask the system to start it.
594pub(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
609/// Take `job` away. `false` when there was nothing installed.
610pub(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
617/// Take it away. `false` when there was nothing installed.
618pub(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
626// The MSI's full uninstall deletes the app's command line; a task running Scoop's copy stays.
627pub(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    /// A home of the test's own, gone when the test is, on a machine whose scheduler asks
651    /// nobody: its files are written in that home, and launchd or systemd is never told.
652    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        /// A context read from an environment whose home is this one and that sets `vars`
671        /// besides, as the command line's is read, on the same machine in memory.
672        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    /// The variables the installed schedule's job is given, as its file says.
685    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    // This system's app's own program under `home`, as 0.3.0 scheduled it on a Mac, and the
699    // command line the app comes with.
700    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    /// Put a program at `path`, for a schedule to name, with the launcher this system starts
714    /// it through.
715    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    /// A program at `path` for a task to run, on any system, with the launcher a task starts.
727    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    /// A schedule the scheduler will not start leaves nothing behind saying renewal is on.
734    #[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    /// A repair the scheduler will not start leaves the schedule that was there, which is
750    /// what the app and doctor then go on reporting.
751    #[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    /// A machine with no scheduler Pitboard knows says so, and writes nothing.
786    #[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            // Cargo puts no launcher beside a test's program.
818            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    /// A Pitboard that is named is written down only where it will still be there when the
850    /// scheduler runs it. macOS runs an app opened where it was downloaded from a temporary
851    /// copy, which is there while the app runs and gone once it quits, so being there now
852    /// is not enough.
853    #[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    // pitboard.exe started from inside a zip in Explorer runs from Temp1_*.zip, which goes.
925    #[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    // A task starts pitboardw.exe, which starts the pitboard.exe beside it with no console, so a
951    // pitboard.exe without one is never written into a task: cargo installs pitboard.exe alone.
952    #[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    /// A copy macOS runs from a temporary place is told by a directory of the path, as the
985    /// Swift app told it by "/AppTranslocation/" in its command line's path, and by nothing
986    /// that only looks like one.
987    #[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    // A schedule that runs an app's own program renews nothing, on each system by its rule.
1037    #[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    /// What `pitboard doctor` reads back is what was written, including a path the
1061    /// scheduler's format has to escape.
1062    #[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    /// An app up to 0.3.0 scheduled itself, and launchd has started a second menu bar app
1082    /// every day since. An app that names the command line it comes with puts that in its
1083    /// place, and every other schedule is left as it is.
1084    #[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    /// A process some other job started is not the schedule's own run, and repairs the way
1192    /// one opened by hand does.
1193    #[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    // Settings changed in Task Scheduler may be the person's, so only a gone program is mended.
1216    #[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    // Started at each sign-in, it would fail at each once the removal deletes the program.
1337    #[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    /// Only what `install` writes is read, and only the way it writes it.
1373    #[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            // What systemd's timer runs is its service, beside it.
1382            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    /// The scheduler starts `renew` with the default home, so a Pitboard pointed anywhere
1394    /// else leaves the schedule alone.
1395    #[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    // RF-B1, run 38693947329: on Windows a scheduled run and one by hand both derive the
1418    // folder from `USERPROFILE`, wherever `HOME` points.
1419    #[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    // Stopped before it reads anything: the context is all that is made.
1446    #[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    /// The schedule renews the default home alone, so it is installed only from there. With
1457    /// `PITBOARD_HOME` naming any other directory, `install` is refused with
1458    /// `schedule_not_default_home`, which says what the schedule renews and how to install
1459    /// it, and nothing is written or started. `PITBOARD_HOME` naming the default home, however
1460    /// it spells it, installs as before. Neither `uninstall` nor `repair` is refused for it:
1461    /// a schedule can always be taken away, from whichever home.
1462    #[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    /// The system starts the schedule's runs with its own environment, so `install` gives its
1507    /// job the proxy variables it was started with, each under the name it was set by, even
1508    /// empty, in the order Pitboard reads them, after `PITBOARD_NO_ARGV` where that is set.
1509    /// The runs then read the same proxy. A reinstall takes the variables of the Pitboard
1510    /// that runs it, none included. What is written is only the person's to read.
1511    #[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            // One variable in any case, the first spelling given, as Windows hands it on (RF-B4);
1546            // no `PITBOARD_NO_ARGV`, read nowhere there; and the task's definition holds no proxy.
1547            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    /// A repair, which an app makes when it starts, writes the proxy variables the schedule's
1574    /// file gives, and never the app's own. The schedules it repairs are those an app of
1575    /// 0.3.0 or earlier wrote, which gave no proxy, so a repair gives none, even where the
1576    /// app's environment names one. Where such a file gives a proxy all the same, as one
1577    /// edited by hand can, the repair keeps it.
1578    #[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    /// A real context's scheduler is never asked from a test: the system's own service
1617    /// manager would reach the person's real schedule. On Linux the user's systemd is asked
1618    /// first, before anything is written, and refuses; where systemd did not start the system,
1619    /// as in a container, there is no scheduler to reach.
1620    #[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    // A machine whose parked login `there` is due at `RUN`, in the directory daily renewal
1645    // renews, with the schedule installed, and the context of that moment. Its parked logins
1646    // are the login keyring's.
1647    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    /// A run at boot can find the login keyring locked that is open again by the time anybody
1679    /// runs doctor, in the desktop session. So the run keeps what the store refused it and
1680    /// when, and doctor says it from there.
1681    #[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    /// What was kept stays until a run the schedule started opens the store: a run that asked
1709    /// it about nothing says nothing of it.
1710    #[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(&nothing_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    /// A run somebody started says nothing of what the schedule's runs meet, so it keeps
1742    /// nothing, and forgets nothing the schedule's kept.
1743    #[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}