Skip to main content

runner_manager_platform/
secrets.rs

1// owner: d2-machine-secret-store
2
3//! The one persisted GitHub credential, in a place a boot-time service can
4//! read.
5//!
6//! `07-security.md` counts the persisted credential surface and gets to one:
7//! *"The product now holds exactly one persisted GitHub credential and one
8//! short-lived sensitive value."* This module is where that one credential
9//! lives. The short-lived one — the encoded JIT configuration — belongs to
10//! [`crate::process::RestrictiveHandoff`] and is not stored here or anywhere
11//! else.
12//!
13//! # The constraint that decides the whole design
14//!
15//! D13 requires the service to start at **machine boot**.
16//! `05-infrastructure.md`: *"A boot-time service runs outside any user's login
17//! session and cannot read a per-user keychain on any supported OS: macOS
18//! LaunchAgents start only at login, and Windows Credential Manager vaults are
19//! per-user."* So the default store is machine-scoped, and every per-user
20//! secret facility on all three operating systems is unavailable to it by
21//! construction rather than by preference.
22//!
23//! | OS | [`SecretScope::Machine`] | [`SecretScope::User`] |
24//! |---|---|---|
25//! | Windows | DPAPI **machine** scope, in a file under `%ProgramData%` with its own protected DACL | DPAPI **user** scope, in a file under `%LOCALAPPDATA%` with its own protected DACL |
26//! | macOS | System Keychain (`/Library/Keychains/System.keychain`) | the account's login keychain |
27//! | Linux | `0600` file under `/var/lib/runner-manager`, plus the systemd credential the service is started with | `0600` file under `$XDG_DATA_HOME/runner-manager` |
28//!
29//! `service install --start-at login` is the escape hatch
30//! `07-security.md` promises operators who reject machine-scoped storage:
31//! *"Operators who reject this can use `service install --start-at login` and
32//! keep a user-scoped store, accepting no unattended restart."* Both columns
33//! implement [`SecretStore`], the active one is chosen by
34//! [`SecretScope::for_start_mode`], and [`ActiveStore`] is what `host show`
35//! and `service status` print so the choice is inspectable rather than
36//! implied.
37//!
38//! # The accepted trade-off, implemented honestly
39//!
40//! A local administrator or `root` on this machine can read a machine-scoped
41//! secret. `07-security.md` records that as an accepted consequence, on the
42//! grounds that such an account *"can already read the runner's own
43//! credentials and job workspaces"*. Nothing here tries to defeat it, and
44//! nothing here pretends to. What is defended is the case that is actually in
45//! the threat model: **an ordinary local user who is not an administrator must
46//! not be able to read the stored value**, and [`SecretStore::protection`]
47//! reports whether that holds, per OS, through the one cross-platform name
48//! [`crate::process::permissions_summary`] already defines.
49//!
50//! Delete is delete, not erasure. [`crate::process::RestrictiveHandoff`] sets
51//! out why no userspace program can promise that the bytes are unrecoverable —
52//! a journal, a snapshot, or an SSD's wear levelling each keep copies an
53//! overwrite never reaches — and the same disclaimer applies here. The Linux
54//! backend overwrites before unlinking because the value is at rest in
55//! plaintext there and the overwrite is free; that is a best effort and is not
56//! a claim.
57//!
58//! # What never holds this value
59//!
60//! SQLite, TOML configuration, logs, diagnostics, UI state, and command-line
61//! arguments. The type system carries as much of that as it can: the value
62//! crosses this module's surface only as a [`SecretString`], which has no
63//! `Display` and a redacting `Debug`, and no error in [`SecretStoreError`]
64//! carries the value or any part of it. `client_id` is public by design
65//! (`07-security.md`: *"Public by design; may appear in logs and
66//! documentation"*) and is not a secret this store handles.
67//!
68//! # Blocking, not async
69//!
70//! DPAPI, Security.framework and `open(2)` are blocking calls that take
71//! microseconds. This runs twice in the life of a process — once at `auth
72//! login`, once at startup — so an async surface would buy nothing and would
73//! oblige every caller to be in a runtime to read a file.
74//!
75//! # Where a test may point it, and where it may not
76//!
77//! [`PlatformSecretStore::standard`] resolves the production location in the
78//! table above. [`PlatformSecretStore::rooted_at`] puts the same backend under
79//! a directory the caller names, exactly as
80//! [`crate::paths::AppPaths::rooted_at`] does for the four application-data
81//! directories, and for the same two reasons: a test needs a disposable store,
82//! and a service installed against an explicitly configured root has to
83//! reproduce one.
84//!
85//! **No test in this crate writes to a standard location**, and that is a
86//! deliberate constraint rather than an oversight. Two of the six standard
87//! locations need `root` to create (`/var/lib`, the System Keychain), and the
88//! other four are the operator's real store — a suite that wrote there would
89//! destroy a developer's `auth login` every time it ran. So the standard
90//! locations are asserted by *resolution*, and every round trip runs against a
91//! rooted store. What that does and does not cover is written out at
92//! [`PlatformSecretStore::rooted_at`].
93
94use std::fmt;
95use std::path::{Path, PathBuf};
96
97use runner_manager_domain::model::StartMode;
98use secrecy::{ExposeSecret, SecretString};
99
100/// The product identity, resolved from the one place that defines it.
101///
102/// `crate::paths` owns these three segments and builds the four
103/// application-data directories out of them. This module builds *different*
104/// locations — `%ProgramData%\<org>\<app>`, `$XDG_DATA_HOME/<app>`, the macOS
105/// keychain service — but out of the same identity, and it must stay the same
106/// identity. Spelled a second time here, a drift would move the secret store
107/// out from under an upgraded binary and the token would read as simply
108/// absent, which is the one failure mode this store must never produce
109/// silently.
110use crate::paths::{APPLICATION, ORGANIZATION, QUALIFIER};
111
112/// Reverse-domain service name for the macOS keychain item.
113///
114/// Composed rather than written out, for the reason above. It is a `LazyLock`
115/// because the three segments are `const`s and neither `concat!` nor a `const
116/// fn` can join them — `concat!` takes literals, not constant items. The
117/// composition is asserted against the documented literal by
118/// `the_standard_locations_are_the_documented_ones`, which keeps its own
119/// hard-coded strings precisely so that it is an *independent* oracle rather
120/// than a second copy of this expression.
121#[cfg(target_os = "macos")]
122static KEYCHAIN_SERVICE: std::sync::LazyLock<String> =
123    std::sync::LazyLock::new(|| format!("{QUALIFIER}.{ORGANIZATION}.{APPLICATION}"));
124
125/// The keychain account, and the stem of the file name on the two platforms
126/// that use a file. One value, one name, everywhere.
127const ITEM: &str = "user-access-token";
128
129/// Which value a [`PlatformSecretStore`] holds.
130///
131/// Every item lives in the same protected place, with the same per-OS
132/// protection; only its name differs. The GitHub credential is the default.
133#[derive(Debug, Clone, Copy, PartialEq, Eq)]
134pub enum SecretItem {
135    /// The GitHub user access token (`auth login`).
136    GithubCredential,
137    /// The Ed25519 private key this host proves itself to a coordinator with
138    /// (`coordinator join`).
139    CoordinatorKey,
140}
141
142impl SecretItem {
143    /// The item's name: the keychain account, or the file stem.
144    #[must_use]
145    pub const fn as_str(self) -> &'static str {
146        match self {
147            Self::GithubCredential => ITEM,
148            Self::CoordinatorKey => "coordinator-host-key",
149        }
150    }
151}
152
153/// The directory a file-backed store keeps its value in, under whichever root
154/// the scope resolved to. Never `config/` — `05-infrastructure.md` reserves
155/// that for *"non-secret TOML and SQLite"*.
156const DIRECTORY: &str = "secrets";
157
158// ---------------------------------------------------------------------------
159// Scope
160// ---------------------------------------------------------------------------
161
162/// Which of the two stores a value lives in.
163///
164/// Not a preference and not a tuning knob: it is a direct function of the
165/// service's start mode, because a service that starts at boot has no login
166/// session to read a user-scoped store from. [`SecretScope::for_start_mode`]
167/// is that function, and it is total in both directions —
168/// [`SecretScope::start_mode`] is its inverse, which is what lets
169/// [`ActiveStore`] state whether the store in use agrees with the start mode
170/// actually configured.
171#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
172pub enum SecretScope {
173    /// Readable by a service running at machine boot, outside any login
174    /// session. The default, and what `--start-at boot` requires.
175    Machine,
176    /// Readable only inside the operator's login session. What
177    /// `--start-at login` gets, at the cost of no unattended restart.
178    User,
179}
180
181impl SecretScope {
182    /// The store a given start mode obliges.
183    #[must_use]
184    pub const fn for_start_mode(mode: StartMode) -> Self {
185        match mode {
186            StartMode::Boot => Self::Machine,
187            StartMode::Login => Self::User,
188        }
189    }
190
191    /// The start mode this store is the one correct choice for.
192    #[must_use]
193    pub const fn start_mode(self) -> StartMode {
194        match self {
195            Self::Machine => StartMode::Boot,
196            Self::User => StartMode::Login,
197        }
198    }
199
200    /// The name `host show`, `service status`, and the `scope` log field use.
201    #[must_use]
202    pub const fn as_str(self) -> &'static str {
203        match self {
204            Self::Machine => "machine",
205            Self::User => "user",
206        }
207    }
208}
209
210impl fmt::Display for SecretScope {
211    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
212        f.write_str(self.as_str())
213    }
214}
215
216// ---------------------------------------------------------------------------
217// Errors
218// ---------------------------------------------------------------------------
219
220/// Something went wrong reaching the secret store.
221///
222/// **No variant carries the stored value, and none ever may.** Every one of
223/// them is formatted into an operator-facing message and into a `tracing`
224/// event, and `07-security.md`'s release gate is that the user access token is
225/// *"absent from logs, databases, snapshots, crash reports, and CLI output"*.
226/// A variant that carried the value would put it in all four at once.
227///
228/// Note what is *not* here: an "absent" variant. A load that finds nothing is
229/// [`Ok(None)`], because absence is the ordinary state of this store before
230/// `auth login` and after `auth logout`, and a caller that has to distinguish
231/// "not logged in" from "the keychain is unreachable" cannot be asked to do it
232/// by matching on an error kind.
233#[derive(Debug, thiserror::Error)]
234pub enum SecretStoreError {
235    /// The store's location could not be worked out at all.
236    #[error("cannot work out where the {scope}-scoped secret store lives: {reason}")]
237    Resolve {
238        /// Which store was being resolved.
239        scope: SecretScope,
240        /// What was missing, in terms an operator can act on.
241        reason: String,
242    },
243
244    /// The value could not be written.
245    #[error(
246        "cannot write the user access token to the {scope}-scoped store at {location}: {source}"
247    )]
248    Store {
249        /// Which store.
250        scope: SecretScope,
251        /// Where it lives, as [`SecretStore::location`] reports it.
252        location: String,
253        /// The underlying platform error.
254        #[source]
255        source: std::io::Error,
256    },
257
258    /// The value could not be read back.
259    #[error(
260        "cannot read the user access token from the {scope}-scoped store at {location}: {source}"
261    )]
262    Load {
263        /// Which store.
264        scope: SecretScope,
265        /// Where it lives.
266        location: String,
267        /// The underlying platform error.
268        #[source]
269        source: std::io::Error,
270    },
271
272    /// The value could not be removed.
273    ///
274    /// Worth an error rather than a shrug, for the reason
275    /// `05-infrastructure.md` gives the credential-disclosure response: step 2
276    /// is *"Run `auth logout` on every host to purge the machine-scoped secret
277    /// store"*, and an operator following that procedure has to be told when a
278    /// host did not comply.
279    #[error(
280        "cannot delete the user access token from the {scope}-scoped store at {location}: {source}"
281    )]
282    Delete {
283        /// Which store.
284        scope: SecretScope,
285        /// Where it lives.
286        location: String,
287        /// The underlying platform error.
288        #[source]
289        source: std::io::Error,
290    },
291
292    /// Something is stored, and it is not a value this store wrote.
293    ///
294    /// Deliberately not folded into [`SecretStoreError::Load`] and deliberately
295    /// not reported as absence. A caller that saw absence would silently start
296    /// a device-flow login and overwrite whatever is there; a caller that saw a
297    /// transient read failure would retry forever. This is neither: it is an
298    /// operator-actionable condition whose remedy is `auth logout` followed by
299    /// `auth login`.
300    #[error(
301        "the {scope}-scoped store at {location} does not hold a user access token this product \
302         wrote: {detail}. Run `auth logout` to purge it and `auth login` to obtain a fresh token."
303    )]
304    Corrupt {
305        /// Which store.
306        scope: SecretScope,
307        /// Where it lives.
308        location: String,
309        /// What is wrong with what is there, in terms that name no part of it.
310        /// A byte count is not a disclosure; the bytes would be, so they are
311        /// never carried.
312        detail: String,
313    },
314
315    /// The access control protecting the value could not be read back.
316    #[error("cannot inspect what protects the {scope}-scoped store at {}: {source}", guard.display())]
317    Inspect {
318        /// Which store.
319        scope: SecretScope,
320        /// The filesystem object whose access control was being read.
321        guard: PathBuf,
322        /// The underlying error.
323        #[source]
324        source: crate::process::HandoffError,
325    },
326}
327
328// ---------------------------------------------------------------------------
329// What the operations report
330// ---------------------------------------------------------------------------
331
332/// What [`SecretStore::delete`] found.
333///
334/// Both variants are success. `auth logout` on a host that was never logged in
335/// is not a failure, and the credential-disclosure procedure in
336/// `05-infrastructure.md` is run across *every* host precisely because the
337/// operator does not know which ones hold a value.
338#[derive(Debug, Clone, Copy, PartialEq, Eq)]
339pub enum Removal {
340    /// A value was there and is not any more.
341    Removed,
342    /// There was nothing to remove.
343    AlreadyAbsent,
344}
345
346impl Removal {
347    /// Whether this call is the one that removed something.
348    #[must_use]
349    pub const fn removed_something(self) -> bool {
350        matches!(self, Self::Removed)
351    }
352}
353
354/// What actually stands between the stored value and an ordinary local user.
355///
356/// The three operating systems protect it with three different mechanisms, so
357/// the useful cross-platform question is not "what is the mode" but "**which
358/// object's access control decides who can read this, and does it exclude an
359/// unprivileged local user**". [`Protection::guard`] answers the first half and
360/// [`Protection::readable_by_other_local_users`] the second.
361///
362/// | store | guard |
363/// |---|---|
364/// | Windows, either scope | the file holding the DPAPI blob, whose DACL is protected and names no broad trustee |
365/// | Linux, either scope | the `0600` file |
366/// | macOS, login or rooted keychain | the keychain database file |
367/// | macOS, System Keychain | `/var/db/SystemKey`, the root-only master key that unlocks it |
368///
369/// That last row is the one worth reading twice.
370/// `/Library/Keychains/System.keychain` is itself world-readable, and saying so
371/// and stopping would be both true and useless: its contents are encrypted, and
372/// what decides who can decrypt them is the mode of the master key beside it.
373/// Reporting the keychain database there would answer a question nobody asked
374/// and would answer it wrongly.
375#[derive(Debug, Clone, PartialEq, Eq)]
376pub struct Protection {
377    guard: PathBuf,
378    description: String,
379    readable_by_other_local_users: bool,
380}
381
382impl Protection {
383    /// The filesystem object whose access control was inspected.
384    #[must_use]
385    pub fn guard(&self) -> &Path {
386        &self.guard
387    }
388
389    /// The platform's own description of it — a Unix mode, or a DACL in SDDL
390    /// form. For diagnostics and for test failure messages.
391    #[must_use]
392    pub fn description(&self) -> &str {
393        &self.description
394    }
395
396    /// Whether an ordinary local user other than the owner could read the
397    /// stored value.
398    ///
399    /// A local administrator or `root` is deliberately outside this question;
400    /// see this module's documentation and `07-security.md`.
401    #[must_use]
402    pub const fn readable_by_other_local_users(&self) -> bool {
403        self.readable_by_other_local_users
404    }
405}
406
407impl fmt::Display for Protection {
408    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
409        write!(
410            f,
411            "{} ({}){}",
412            self.guard.display(),
413            self.description,
414            if self.readable_by_other_local_users {
415                " -- READABLE BY OTHER LOCAL USERS"
416            } else {
417                ""
418            }
419        )
420    }
421}
422
423/// Which store is in use, and whether that is the one the configured start
424/// mode obliges.
425///
426/// `05-infrastructure.md` requires the start mode to be visible in `host show`
427/// and in TUI host settings, and requires `service status` to say when
428/// `--start-at login` means the agent does not run until the operator logs in.
429/// This is the value both of those print. It exists as a type rather than as a
430/// formatted string in two places so that the two cannot drift.
431///
432/// [`ActiveStore::agrees_with_start_mode`] is the check worth having: the store
433/// a process opened and the start mode recorded for the installed service are
434/// two independently persisted facts, and a host whose service was switched
435/// from `boot` to `login` without the token being moved is a host whose daemon
436/// will start and then fail to find a credential. Saying so in `service status`
437/// is cheaper than finding out at three in the morning.
438#[derive(Debug, Clone, PartialEq, Eq)]
439pub struct ActiveStore {
440    scope: SecretScope,
441    start_mode: StartMode,
442    location: String,
443}
444
445impl ActiveStore {
446    /// Pairs a store with the start mode currently configured for the service.
447    #[must_use]
448    pub fn of(store: &dyn SecretStore, start_mode: StartMode) -> Self {
449        Self {
450            scope: store.scope(),
451            start_mode,
452            location: store.location(),
453        }
454    }
455
456    /// The store in use.
457    #[must_use]
458    pub const fn scope(&self) -> SecretScope {
459        self.scope
460    }
461
462    /// The start mode configured for the service.
463    #[must_use]
464    pub const fn start_mode(&self) -> StartMode {
465        self.start_mode
466    }
467
468    /// Where the store keeps its value, in the platform's own terms.
469    #[must_use]
470    pub fn location(&self) -> &str {
471        &self.location
472    }
473
474    /// Whether the store in use is the one this start mode obliges.
475    #[must_use]
476    pub fn agrees_with_start_mode(&self) -> bool {
477        SecretScope::for_start_mode(self.start_mode) == self.scope
478    }
479}
480
481impl fmt::Display for ActiveStore {
482    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
483        write!(
484            f,
485            "{}-scoped secret store at {} (service starts at {})",
486            self.scope, self.location, self.start_mode
487        )?;
488        if !self.agrees_with_start_mode() {
489            write!(
490                f,
491                " -- MISMATCH: starting at {} needs the {}-scoped store",
492                self.start_mode,
493                SecretScope::for_start_mode(self.start_mode)
494            )?;
495        }
496        Ok(())
497    }
498}
499
500// ---------------------------------------------------------------------------
501// The port
502// ---------------------------------------------------------------------------
503
504/// Store, load, delete — and say where the value lives and what protects it.
505///
506/// `Send + Sync` because the agent holds one across `tokio` tasks; `Debug`
507/// because every other port in this workspace is, and because a store that
508/// could not be printed in an error context would be replaced by a path that
509/// could.
510pub trait SecretStore: fmt::Debug + Send + Sync {
511    /// Which of the two stores this is.
512    fn scope(&self) -> SecretScope;
513
514    /// Where the value lives, in the platform's own terms. What `host show`
515    /// and `service status` print, and never the value itself.
516    fn location(&self) -> String;
517
518    /// Writes the value, replacing whatever was there.
519    ///
520    /// # Errors
521    ///
522    /// [`SecretStoreError::Store`].
523    fn store(&self, secret: &SecretString) -> Result<(), SecretStoreError>;
524
525    /// Refuses when [`SecretStore::store`] would, without writing anything.
526    ///
527    /// For a caller about to do something that only a successful write makes
528    /// safe. Renewal is that caller: GitHub retires a refresh token the moment
529    /// it is exchanged, so a process that exchanges it and then cannot store
530    /// the replacement has destroyed the credential for every process sharing
531    /// this store. On a boot-mode host that is any TUI or CLI command started
532    /// without the privilege the machine-scoped store needs to be written,
533    /// even though it can read it.
534    ///
535    /// A permission check, not a promise: a write can still fail for reasons
536    /// no check can foresee. It answers the question that is stable across a
537    /// process's lifetime -- whether *this* account may write here at all.
538    ///
539    /// # Errors
540    ///
541    /// [`SecretStoreError::Store`], carrying why a write would be refused.
542    fn ensure_writable(&self) -> Result<(), SecretStoreError>;
543
544    /// Reads the value back, or reports that there is none.
545    ///
546    /// `Ok(None)` is absence and is not an error; see [`SecretStoreError`].
547    ///
548    /// # Errors
549    ///
550    /// [`SecretStoreError::Load`] when the store cannot be reached, and
551    /// [`SecretStoreError::Corrupt`] when what is there is not a value this
552    /// store wrote.
553    fn load(&self) -> Result<Option<SecretString>, SecretStoreError>;
554
555    /// Removes the value.
556    ///
557    /// # Errors
558    ///
559    /// [`SecretStoreError::Delete`].
560    fn delete(&self) -> Result<Removal, SecretStoreError>;
561
562    /// What stands between the stored value and an ordinary local user.
563    ///
564    /// # Errors
565    ///
566    /// [`SecretStoreError::Inspect`].
567    fn protection(&self) -> Result<Protection, SecretStoreError>;
568}
569
570// ---------------------------------------------------------------------------
571// The platform store
572// ---------------------------------------------------------------------------
573
574/// The real store: DPAPI on Windows, a keychain on macOS, a `0600` file plus
575/// systemd credentials on Linux.
576///
577/// One type with three bodies rather than three types, because the choice is
578/// made by `cfg` at compile time and a caller never has one without the other
579/// two being impossible. The scope, by contrast, is a runtime choice and is a
580/// field.
581#[derive(Debug, Clone, PartialEq, Eq)]
582pub struct PlatformSecretStore {
583    scope: SecretScope,
584    site: sys::Site,
585}
586
587impl PlatformSecretStore {
588    /// Resolves the platform-standard location for `scope`.
589    ///
590    /// This is what production uses and what `host show` reports. Nothing is
591    /// touched on disk here; the directory, the file, and the keychain are
592    /// created by the first [`SecretStore::store`].
593    ///
594    /// # Errors
595    ///
596    /// [`SecretStoreError::Resolve`] when the platform cannot say where the
597    /// location is — no `%ProgramData%` on Windows, no home directory for this
598    /// account on the two Unixes. A service account configured with no profile
599    /// is the way that actually happens, and the message says so.
600    pub fn standard(scope: SecretScope) -> Result<Self, SecretStoreError> {
601        let site = sys::standard_site(scope).map_err(|reason| SecretStoreError::Resolve {
602            scope,
603            reason: reason.to_string(),
604        })?;
605        Ok(Self { scope, site })
606    }
607
608    /// Resolves the store the configured start mode obliges.
609    ///
610    /// The one constructor a daemon should use: it makes the store a function
611    /// of the recorded start mode rather than of whichever constructor the
612    /// call site happened to reach for.
613    ///
614    /// # Errors
615    ///
616    /// As [`PlatformSecretStore::standard`].
617    pub fn for_start_mode(mode: StartMode) -> Result<Self, SecretStoreError> {
618        Self::standard(SecretScope::for_start_mode(mode))
619    }
620
621    /// Places the same backend under a root the caller names.
622    ///
623    /// [`crate::paths::AppPaths::rooted_at`] is the precedent and the reasoning
624    /// is the same: a test needs a disposable store, and a service installed
625    /// against an explicitly configured root has to reproduce one. A relative
626    /// root stays relative, which is the caller's decision to make.
627    ///
628    /// # What a rooted store does and does not exercise
629    ///
630    /// Everything that makes a scope a scope, on two of the three platforms.
631    /// The Windows backend picks its DPAPI flag and its DACL from the scope,
632    /// not from the site, so a rooted machine-scoped store is protected and
633    /// encrypted exactly as the standard one is. The Linux backend's `0600`
634    /// file, its atomic replace, and its systemd-credential read path are the
635    /// same code under either root.
636    ///
637    /// macOS is where a rooted store is genuinely weaker, and it is worth being
638    /// precise about how. A rooted store is a keychain this program creates in
639    /// the root directory, and both scopes get one; what the standard sites
640    /// have and it does not is the *choice of keychain* — the System Keychain
641    /// against the login keychain — and the System Keychain's root-only master
642    /// key. The keychain calls themselves, the item, the not-found handling and
643    /// the delete are identical. The password protecting a rooted keychain is
644    /// [`ROOTED_KEYCHAIN_PASSWORD`], which is a constant in a public binary and
645    /// therefore protects nothing on its own: what protects a rooted keychain
646    /// is the mode of the directory it is in, which is the same protection the
647    /// Linux backend relies on for a value it stores in plaintext.
648    ///
649    /// # Errors
650    ///
651    /// [`SecretStoreError::Resolve`]; in practice it cannot fail, because the
652    /// caller supplied the root.
653    pub fn rooted_at(scope: SecretScope, root: impl AsRef<Path>) -> Result<Self, SecretStoreError> {
654        let site =
655            sys::rooted_site(scope, root.as_ref()).map_err(|reason| SecretStoreError::Resolve {
656                scope,
657                reason: reason.to_string(),
658            })?;
659        Ok(Self { scope, site })
660    }
661
662    /// The same store, holding `item` instead of the GitHub credential.
663    #[must_use]
664    pub fn for_item(self, item: SecretItem) -> Self {
665        Self {
666            scope: self.scope,
667            site: sys::with_item(self.site, item.as_str()),
668        }
669    }
670
671    /// The filesystem object whose access control decides who can read this
672    /// store, whether or not anything is stored yet.
673    ///
674    /// Separate from [`SecretStore::protection`] because the guard can be named
675    /// before the store exists, which is what lets `host show` report the
676    /// machine store's protection on a host that has never logged in.
677    #[must_use]
678    pub fn guard(&self) -> PathBuf {
679        sys::guard(&self.site)
680    }
681
682    /// Turns platform bytes into the value, or says why they are not one.
683    fn decode(&self, bytes: Vec<u8>) -> Result<SecretString, SecretStoreError> {
684        use secrecy::zeroize::Zeroize as _;
685
686        let length = bytes.len();
687        // A zero-length value is not a credential and cannot have been written
688        // by `store`, which refuses one. Treating it as absence would hide a
689        // truncated write behind a device-flow login.
690        if length == 0 {
691            return Err(self.corrupt("it is empty"));
692        }
693
694        match String::from_utf8(bytes) {
695            Ok(text) => Ok(SecretString::from(text)),
696            Err(error) => {
697                // The bytes are not the value, but they may still be *a* value
698                // — something else's, or a partially overwritten one. Scrub the
699                // buffer rather than dropping it, and report only its length.
700                let mut bytes = error.into_bytes();
701                bytes.zeroize();
702                Err(self.corrupt(&format!("the {length} bytes there are not valid UTF-8")))
703            }
704        }
705    }
706
707    fn corrupt(&self, detail: &str) -> SecretStoreError {
708        SecretStoreError::Corrupt {
709            scope: self.scope,
710            location: self.location(),
711            detail: detail.to_string(),
712        }
713    }
714}
715
716impl SecretStore for PlatformSecretStore {
717    fn scope(&self) -> SecretScope {
718        self.scope
719    }
720
721    fn location(&self) -> String {
722        sys::describe(&self.site)
723    }
724
725    fn store(&self, secret: &SecretString) -> Result<(), SecretStoreError> {
726        let failed = |source| SecretStoreError::Store {
727            scope: self.scope,
728            location: self.location(),
729            source,
730        };
731
732        let exposed = secret.expose_secret();
733        if exposed.is_empty() {
734            // Refused here rather than accepted and stored, because an empty
735            // value is indistinguishable from a truncated one on the way back
736            // out and `decode` has to reject it either way.
737            return Err(failed(std::io::Error::new(
738                std::io::ErrorKind::InvalidInput,
739                "an empty value is not a user access token",
740            )));
741        }
742
743        sys::store(&self.site, self.scope, exposed.as_bytes()).map_err(failed)?;
744
745        tracing::info!(
746            event = "secret_store_written",
747            scope = self.scope.as_str(),
748            "the user access token was written to the secret store"
749        );
750        Ok(())
751    }
752
753    fn ensure_writable(&self) -> Result<(), SecretStoreError> {
754        sys::ensure_writable(&self.site).map_err(|source| SecretStoreError::Store {
755            scope: self.scope,
756            location: self.location(),
757            source,
758        })
759    }
760
761    fn load(&self) -> Result<Option<SecretString>, SecretStoreError> {
762        let bytes = sys::load(&self.site, self.scope).map_err(|source| {
763            // A backend reports "there is something here and it is not ours"
764            // as `InvalidData` -- a DPAPI blob this machine's key cannot
765            // unprotect, a keychain item of the wrong shape. That is the
766            // `Corrupt` condition, not a transient read failure, and the
767            // difference decides whether a caller retries or tells the
768            // operator to run `auth logout`.
769            if source.kind() == std::io::ErrorKind::InvalidData {
770                self.corrupt(&source.to_string())
771            } else {
772                SecretStoreError::Load {
773                    scope: self.scope,
774                    location: self.location(),
775                    source,
776                }
777            }
778        })?;
779
780        match bytes {
781            Some(bytes) => self.decode(bytes).map(Some),
782            None => Ok(None),
783        }
784    }
785
786    fn delete(&self) -> Result<Removal, SecretStoreError> {
787        let removed = sys::delete(&self.site).map_err(|source| SecretStoreError::Delete {
788            scope: self.scope,
789            location: self.location(),
790            source,
791        })?;
792
793        let removal = if removed {
794            Removal::Removed
795        } else {
796            Removal::AlreadyAbsent
797        };
798
799        tracing::info!(
800            event = "secret_store_purged",
801            scope = self.scope.as_str(),
802            outcome = if removal.removed_something() {
803                "removed"
804            } else {
805                "already_absent"
806            },
807            "the user access token was purged from the secret store"
808        );
809        Ok(removal)
810    }
811
812    fn protection(&self) -> Result<Protection, SecretStoreError> {
813        let guard = sys::guard(&self.site);
814        let summary = crate::process::permissions_summary(&guard).map_err(|source| {
815            SecretStoreError::Inspect {
816                scope: self.scope,
817                guard: guard.clone(),
818                source,
819            }
820        })?;
821
822        Ok(Protection {
823            guard,
824            description: summary.description,
825            readable_by_other_local_users: summary.readable_by_other_local_users,
826        })
827    }
828}
829
830/// The password protecting a keychain created by
831/// [`PlatformSecretStore::rooted_at`] on macOS.
832///
833/// A constant in a public binary, and therefore not a secret. It is here
834/// because `SecKeychainCreate` requires *a* password and the alternative —
835/// passing `NULL` — prompts the operator for one, which a daemon must never
836/// do. What protects a rooted keychain is the mode of the directory it is
837/// created in; see [`PlatformSecretStore::rooted_at`].
838///
839/// Public so that a test can assert this is what it is, rather than discovering
840/// it by reading the backend.
841pub const ROOTED_KEYCHAIN_PASSWORD: &str = "runner-manager-rooted-keychain";
842
843/// The name of the systemd credential the Linux machine-scoped store reads
844/// before it reads its own file.
845///
846/// `05-infrastructure.md` puts the Linux machine store at *"`0600` file plus
847/// systemd credentials"*, and the second half is a read path rather than a
848/// write path: `systemd` decrypts a credential into a private `ramfs` at
849/// `$CREDENTIALS_DIRECTORY` and mounts it read-only, so a service given
850/// `LoadCredentialEncrypted=` gets the value without the file ever being
851/// readable by anything but that unit. A store that ignored it would oblige an
852/// operator who had set one up to keep a second plaintext copy on disk.
853pub const SYSTEMD_CREDENTIAL: &str = "runner-manager.user-access-token";
854
855/// The environment variable `systemd` sets for a unit that was given
856/// credentials. Read once, at [`PlatformSecretStore::standard`] time.
857pub const CREDENTIALS_DIRECTORY: &str = "CREDENTIALS_DIRECTORY";
858
859// ---------------------------------------------------------------------------
860// Platform implementations
861// ---------------------------------------------------------------------------
862//
863// Each `sys` module offers the same nine items, and the shared code above is
864// the only caller:
865//
866//   Site                        -- where one store keeps its value
867//   standard_site(scope)        -> the production location for that scope
868//   rooted_site(scope, root)    -> the same backend under a caller-named root
869//   describe(&Site)             -> what `host show` prints
870//   guard(&Site)                -> the object whose access control decides
871//                                  who can read the value
872//   store(&Site, scope, bytes)  -> write, replacing whatever was there
873//   ensure_writable(&Site)      -> refuse when `store` would be refused by
874//                                  permissions, without writing anything
875//   load(&Site, scope)          -> Ok(None) when nothing is stored;
876//                                  ErrorKind::InvalidData when something is
877//                                  stored and it is not ours
878//   delete(&Site)               -> Ok(false) when there was nothing to remove
879//
880// `standard_site` and `rooted_site` fail with a `String` rather than an
881// `io::Error`, because a resolution failure is never an `errno`: it is "this
882// account has no home directory" or "this Windows reports no %ProgramData%",
883// and both want a sentence an operator can act on.
884
885/// The stem every temporary file this module writes shares, so that a crash
886/// leaves something [`sweep_temporaries`] can recognise rather than an
887/// anonymous file beside the store.
888#[cfg(not(target_os = "macos"))]
889const TEMP_PREFIX: &str = "user-access-token.";
890
891/// Removes temporary files left in `directory` by an interrupted write.
892///
893/// Called from `delete` and not from `store`, and that order is deliberate:
894/// two `store` calls can be in flight at once and a sweep there could remove a
895/// live temporary out from under the other one. `delete` is `auth logout`,
896/// which is where "leave no remnant" is the actual requirement.
897#[cfg(not(target_os = "macos"))]
898fn sweep_temporaries(directory: &Path) {
899    let Ok(entries) = std::fs::read_dir(directory) else {
900        return;
901    };
902    for entry in entries.flatten() {
903        let name = entry.file_name();
904        let Some(name) = name.to_str() else { continue };
905        if name.starts_with(TEMP_PREFIX) && name.ends_with(".tmp") {
906            let _ = std::fs::remove_file(entry.path());
907        }
908    }
909}
910
911/// Overwrites every byte of a file with zeroes, in place.
912///
913/// Returns `Ok(false)` when there is nothing there, which is the ordinary state
914/// of a store that was never written.
915///
916/// # What this is and is not
917///
918/// It is **not** secure erasure and nothing here claims it is. The reasoning is
919/// [`crate::process::RestrictiveHandoff`]'s, unchanged: a journal, a
920/// copy-on-write snapshot, or an SSD's wear levelling can each keep a copy that
921/// an overwrite never reaches. It is here because it costs one `write` and
922/// because on Linux the stored value is at rest in **plaintext** — the mode is
923/// the whole access control there — so leaving the bytes in the block after the
924/// inode is unlinked is worse than not.
925///
926/// # Why it is a separate function, and not `cfg`-gated to Linux
927///
928/// Both are the same reason, and it is a testing reason rather than a
929/// portability one. Folded into the delete path, the zero fill was asserted by
930/// nothing: a test could only observe the file's *absence* afterwards, which is
931/// what removing it proves too, so the fill could have been deleted outright
932/// and the suite would have stayed green. Split out, the fill is observable —
933/// [`tests::overwrite_zeroes_every_byte_and_leaves_the_file_there`] reads the
934/// bytes back before anything unlinks them. Compiled on Windows as well as
935/// Linux, that test runs on every leg of the matrix rather than on one, and the
936/// Windows delete path calls it too: the value there is ciphertext, so the fill
937/// buys less, but it costs the same and it keeps the mechanism on a path a
938/// developer can execute.
939#[cfg(not(target_os = "macos"))]
940fn overwrite(path: &Path) -> std::io::Result<bool> {
941    use std::io::Write as _;
942
943    let mut file = match std::fs::OpenOptions::new().write(true).open(path) {
944        Ok(file) => file,
945        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),
946        Err(error) => return Err(error),
947    };
948
949    let length = usize::try_from(file.metadata()?.len()).unwrap_or(0);
950    file.write_all(&vec![0u8; length])?;
951    file.flush()?;
952    file.sync_all()?;
953    Ok(true)
954}
955
956/// Drops trailing ASCII whitespace from a value that came from outside this
957/// module.
958///
959/// There is exactly one such value: the systemd credential. `store` writes no
960/// newline and its own file is read back verbatim, deliberately — trimming
961/// there would quietly repair a corruption this store would rather report. A
962/// credential, though, is produced by the operator through `systemd-creds
963/// encrypt`, and `echo`, `printf '%s\n'`, and every text editor put a newline
964/// on the end. Used byte for byte, that newline becomes part of the token and
965/// surfaces much later inside an `Authorization` header, where it looks like a
966/// bad credential rather than a bad read.
967///
968/// Trailing only. A token has no interior whitespace, but if one ever did,
969/// silently rewriting its middle would be a worse bug than the one this fixes.
970#[cfg(not(target_os = "macos"))]
971// `allow` rather than `expect`: on Windows this is dead in a normal build and
972// live in a test build, because the test below is the whole reason it is
973// compiled there, and an `expect` that is fulfilled in only one of the two
974// configurations warns in the other.
975#[cfg_attr(
976    windows,
977    allow(
978        dead_code,
979        reason = "the systemd credential path is Linux-only; this is compiled on Windows so \
980                  that its unit test runs on every leg of the matrix rather than on the one \
981                  platform a developer usually cannot execute"
982    )
983)]
984fn trim_trailing_ascii_whitespace(mut bytes: Vec<u8>) -> Vec<u8> {
985    while bytes.last().is_some_and(u8::is_ascii_whitespace) {
986        bytes.pop();
987    }
988    bytes
989}
990
991/// Refuses when this process may not create entries in the directory a write
992/// to `target` replaces it from.
993///
994/// Both Unix backends write by creating a new file beside the old one and
995/// renaming it over. The Linux store does that itself; a keychain does it
996/// inside Security.framework, in this process -- `create
997/// /Library/Keychains/System.keychain.sb-...: Permission denied` is what an
998/// unprivileged TUI logged there. So the right to create entries in that
999/// directory is exactly the permission a write turns on.
1000///
1001/// The nearest directory that exists is the one asked, because `store` creates
1002/// any that are missing. `AT_EACCESS` asks with the effective IDs, which are
1003/// the ones the write itself would use, so a command run under `sudo` passes.
1004#[cfg(unix)]
1005fn ensure_directory_writable(target: &Path) -> std::io::Result<()> {
1006    use std::os::unix::ffi::OsStrExt as _;
1007
1008    let Some(directory) = target.ancestors().skip(1).find(|path| path.is_dir()) else {
1009        return Ok(());
1010    };
1011    let c_path =
1012        std::ffi::CString::new(directory.as_os_str().as_bytes()).map_err(std::io::Error::other)?;
1013    // SAFETY: `c_path` is a NUL-terminated string that outlives the call, and
1014    // `faccessat` only reads it.
1015    let status = unsafe {
1016        libc::faccessat(
1017            libc::AT_FDCWD,
1018            c_path.as_ptr(),
1019            libc::W_OK | libc::X_OK,
1020            libc::AT_EACCESS,
1021        )
1022    };
1023    if status == 0 {
1024        return Ok(());
1025    }
1026    let error = std::io::Error::last_os_error();
1027    Err(std::io::Error::new(
1028        error.kind(),
1029        format!(
1030            "this account may not create files in {} ({error}), so the store would refuse the \
1031             write",
1032            directory.display()
1033        ),
1034    ))
1035}
1036
1037// ---------------------------------------------------------------------------
1038
1039#[cfg(windows)]
1040mod sys {
1041    //! DPAPI, in a file whose DACL is this store's real access control.
1042    //!
1043    //! # Two mechanisms, and which one is doing the work
1044    //!
1045    //! `CryptProtectData` with `CRYPTPROTECT_LOCAL_MACHINE` produces a blob
1046    //! that **any process on this machine** can unprotect. That is not a
1047    //! weakness in the flag, it is the definition of machine scope, and it is
1048    //! what D13 needs: a service starting at boot, under an account that has
1049    //! never logged in, has no user master key to decrypt with. The
1050    //! consequence is that the encryption is not the access control — the
1051    //! file's DACL is. `07-security.md` says the same thing from the other
1052    //! end: *"Stored only in the machine-scoped secret store, ACL'd to the
1053    //! service account."*
1054    //!
1055    //! The user-scoped store passes no scope flag, so the blob is bound to the
1056    //! calling account's master key. There the encryption *is* an access
1057    //! control, and the DACL is a second one.
1058    //!
1059    //! # The DACL, and why it is not `process.rs`'s
1060    //!
1061    //! [`crate::process::RestrictiveHandoff`] writes
1062    //! `D:P(A;;FA;;;BA)(A;;FA;;;<this account>)` and documents at length why it
1063    //! carries no `SY` ACE: that file's writer and reader are the same
1064    //! process, so if the process is `LocalSystem` its own SID *is* S-1-5-18
1065    //! and a separate ACE adds nothing.
1066    //!
1067    //! This store's writer and reader are **not** the same process. `auth
1068    //! login` runs as the interactive operator; the daemon runs as whatever
1069    //! `service install` registered, which defaults to `LocalSystem`. So `SY`
1070    //! is load-bearing here in exactly the case where it was redundant there,
1071    //! and the machine-scoped DACL carries it. The user-scoped DACL does not,
1072    //! because a user-scoped store is deliberately not for a service.
1073    //!
1074    //! The third trustee is `OW` — OWNER RIGHTS, S-1-3-4 — rather than the
1075    //! creating account's SID read back out of the process token. When a DACL
1076    //! contains an ACE for OWNER RIGHTS, that ACE is what the object's owner
1077    //! gets, and the owner of a file is the account that created it. So `OW`
1078    //! says "the account that ran `auth login` keeps access to what it stored"
1079    //! without opening a process token, without a `TOKEN_USER` buffer, and
1080    //! without a second copy of the SID lookup `process.rs` already carries.
1081    //!
1082    //! **That sentence held only while `auth login` was the sole writer.** Token
1083    //! renewal made the daemon a second writer under a different account, and
1084    //! because every write creates a new file, the owner moved with it and `OW`
1085    //! stopped meaning the operator. [`replacement_sddl`] is what keeps the
1086    //! grant `OW` describes from evaporating; it carries the previous owner's
1087    //! SID onto the replacement explicitly.
1088    //!
1089    //! # One store per host, and what a second operator actually gets
1090    //!
1091    //! An earlier version of this paragraph said that ownership moves with the
1092    //! write, so a second non-administrative operator's `auth login` "takes"
1093    //! the store. **That was wrong, and it was wrong in the optimistic
1094    //! direction.** Ownership does not move, because the write never lands:
1095    //! `store` finishes with a replacing rename, a replacing rename deletes the
1096    //! target, and delete is granted by `DELETE` on the file or
1097    //! `FILE_DELETE_CHILD` on its parent. `sddl(Machine)` names `SY`, `BA` and
1098    //! `OW`, none of which is operator B; and a stock `%ProgramData%` grants
1099    //! `BUILTIN\Users` only `(OI)(CI)(RX)` plus `(CI)(WD,AD,WEA,WA)` — `WD`
1100    //! lets B create the temporary, and the absence of `DC` and `DE` is what
1101    //! denies the rename. So B's `auth login` **fails**.
1102    //!
1103    //! That is the correct behaviour, and it is the behaviour this store now
1104    //! states rather than stumbles into. **The machine-scoped value is the
1105    //! host's one credential, not an operator's.** `07-security.md` counts the
1106    //! persisted credential surface and gets to one; `service install`
1107    //! registers one service reading one store; the domain has one `Host` and
1108    //! `d1`'s lock permits one agent. A second operator does not get a second
1109    //! store, and whether B may overwrite A's token is a policy question whose
1110    //! answer is "only if B is trusted with this host" — which on Windows is
1111    //! spelled *administrator*, and `BA` already grants it.
1112    //!
1113    //! What changed is the *failure*, not the policy. [`cannot_replace`] asks
1114    //! before anything is encrypted or written, so B gets a message naming the
1115    //! three ways forward instead of a bare "Access is denied" raised at the
1116    //! last step of the write, after a valid machine-decryptable blob of a live
1117    //! token has already been placed on disk.
1118    //!
1119    //! Widening the DACL was considered and rejected. The DACL is the **entire**
1120    //! access control here — a machine-scope DPAPI blob is unprotectable by any
1121    //! process on the host, by definition — so an ACE that let B replace the
1122    //! file would also let every interactive account on the machine read the
1123    //! one credential the product holds. The reader that actually matters is
1124    //! the service account, which `SY` covers by default and which `d3` grants
1125    //! explicitly when `service install` registers a least-privilege account
1126    //! instead (`05-infrastructure.md`, service behaviour, item 2).
1127    //!
1128    //! [`crate::process::permissions_summary`] reads the result back, and it
1129    //! treats an *unprotected* DACL as broadly readable because an inherited
1130    //! one is not this program's to vouch for. That is why every DACL below
1131    //! begins `D:P`, and why the file carries its own rather than inheriting
1132    //! `%ProgramData%`'s, which grants `BU` read.
1133    //!
1134    //! # Write, then replace
1135    //!
1136    //! The blob goes to a temporary file *carrying its final DACL from the
1137    //! moment it exists*, is `sync_all`ed, and is then renamed over the target.
1138    //! `process.rs` argues the first half — a file created and then tightened
1139    //! is readable for however long the gap lasts. The second half is this
1140    //! store's own: the value is long-lived, so a write interrupted half way
1141    //! must not leave a truncated blob where a whole one was.
1142
1143    use std::fs::File;
1144    use std::io::{self, Write as _};
1145    use std::os::windows::ffi::OsStrExt;
1146    use std::os::windows::io::FromRawHandle;
1147    use std::path::{Path, PathBuf};
1148
1149    use windows::Win32::Foundation::{ERROR_SUCCESS, HLOCAL, LocalFree};
1150    use windows::Win32::Security::Authorization::{
1151        ConvertSidToStringSidW, ConvertStringSecurityDescriptorToSecurityDescriptorW,
1152        GetNamedSecurityInfoW, SDDL_REVISION_1, SE_FILE_OBJECT,
1153    };
1154    use windows::Win32::Security::Cryptography::{
1155        CRYPT_INTEGER_BLOB, CRYPTPROTECT_LOCAL_MACHINE, CRYPTPROTECT_UI_FORBIDDEN,
1156        CryptProtectData, CryptUnprotectData,
1157    };
1158    use windows::Win32::Security::{
1159        OWNER_SECURITY_INFORMATION, PSECURITY_DESCRIPTOR, PSID, SECURITY_ATTRIBUTES,
1160    };
1161    use windows::Win32::Storage::FileSystem::{
1162        CREATE_NEW, CreateFileW, FILE_ATTRIBUTE_NORMAL, FILE_GENERIC_READ, FILE_GENERIC_WRITE,
1163        FILE_SHARE_NONE,
1164    };
1165    use windows::core::{PCWSTR, PWSTR};
1166
1167    use super::{
1168        APPLICATION, DIRECTORY, ITEM, ORGANIZATION, QUALIFIER, SecretScope, TEMP_PREFIX, overwrite,
1169        sweep_temporaries,
1170    };
1171
1172    /// Optional entropy mixed into every blob.
1173    ///
1174    /// **Not a secret**, and nothing here pretends otherwise: it is a constant
1175    /// in a published binary. It binds a blob to this product, so that a
1176    /// machine-scoped blob found on disk is not readable by a passing program
1177    /// that merely calls `CryptUnprotectData` with no arguments, and so that a
1178    /// value written by some future second store cannot be silently read back
1179    /// by this one. Against an attacker holding the binary it buys nothing.
1180    const ENTROPY: &[u8] = b"io.github.IvanMurzak.runner-manager/user-access-token/v1";
1181
1182    /// The file the blob lives in.
1183    #[derive(Debug, Clone, PartialEq, Eq)]
1184    pub(super) struct Site {
1185        file: PathBuf,
1186    }
1187
1188    pub(super) fn with_item(mut site: Site, item: &'static str) -> Site {
1189        site.file.set_file_name(format!("{item}.dpapi"));
1190        site
1191    }
1192
1193    pub(super) fn standard_site(scope: SecretScope) -> Result<Site, String> {
1194        let root = match scope {
1195            // `%ProgramData%` rather than `%LOCALAPPDATA%`, because the whole
1196            // requirement is that an account which has never logged in can
1197            // read it — and `%LOCALAPPDATA%` does not exist for such an
1198            // account until its profile is loaded.
1199            SecretScope::Machine => std::env::var_os("ProgramData")
1200                .map(PathBuf::from)
1201                .ok_or_else(|| {
1202                    "this Windows reports no %ProgramData%, so the machine-wide \
1203                     application-data directory cannot be resolved. Set ProgramData, or \
1204                     install the service with --start-at login to use the user-scoped store."
1205                        .to_string()
1206                })?
1207                .join(ORGANIZATION)
1208                .join(APPLICATION),
1209            SecretScope::User => {
1210                directories::ProjectDirs::from(QUALIFIER, ORGANIZATION, APPLICATION)
1211                    .ok_or_else(|| {
1212                        "the operating system reports no home directory for this account, so \
1213                         the user-scoped store cannot be resolved. A service account \
1214                         configured with no profile normally hits this; give the account a \
1215                         home directory, or use the machine-scoped store."
1216                            .to_string()
1217                    })?
1218                    .data_local_dir()
1219                    .to_path_buf()
1220            }
1221        };
1222        Ok(Site {
1223            file: root.join(DIRECTORY).join(format!("{ITEM}.dpapi")),
1224        })
1225    }
1226
1227    pub(super) fn rooted_site(scope: SecretScope, root: &Path) -> Result<Site, String> {
1228        // The scope is a path segment here and is not one under a standard
1229        // site, because a standard site gets its separation from the root:
1230        // `%ProgramData%` against `%LOCALAPPDATA%`. Under one caller-named root
1231        // there is no such separation, and two stores sharing a file is the
1232        // failure `the_two_variants_do_not_share_a_value` exists to catch --
1233        // `auth logout` under one scope would silently purge the other.
1234        Ok(Site {
1235            file: root
1236                .join(DIRECTORY)
1237                .join(scope.as_str())
1238                .join(format!("{ITEM}.dpapi")),
1239        })
1240    }
1241
1242    pub(super) fn describe(site: &Site) -> String {
1243        format!("DPAPI blob at {}", site.file.display())
1244    }
1245
1246    pub(super) fn guard(site: &Site) -> PathBuf {
1247        site.file.clone()
1248    }
1249
1250    /// The protected DACL a store of this scope gets, in SDDL.
1251    ///
1252    /// Split out and `pub(super)` so a test can assert the exact string rather
1253    /// than infer it from a file, and so a reviewer can read the two DACLs
1254    /// side by side.
1255    pub(super) const fn sddl(scope: SecretScope) -> &'static str {
1256        match scope {
1257            SecretScope::Machine => "D:P(A;;FA;;;SY)(A;;FA;;;BA)(A;;FA;;;OW)",
1258            SecretScope::User => "D:P(A;;FA;;;BA)(A;;FA;;;OW)",
1259        }
1260    }
1261
1262    /// The DACL a *replacement* gets: [`sddl`], plus the account that owned
1263    /// what is being replaced.
1264    ///
1265    /// # Why `OW` alone stopped being enough
1266    ///
1267    /// `OW` is OWNER RIGHTS, and the owner of a file is whoever created it.
1268    /// That made `OW` an exact statement of *"the account that ran `auth login`
1269    /// keeps access to what it stored"* for as long as `auth login` was the
1270    /// only writer.
1271    ///
1272    /// Token renewal made the daemon a second writer with a different
1273    /// identity. [`store`] finishes by renaming a temporary over the target, so
1274    /// every write creates a new file, and the new file's owner is whoever
1275    /// created it — `LocalSystem` for a daemon installed at boot. `OW` then
1276    /// resolves to `LocalSystem`, the operator matches none of the three ACEs,
1277    /// and an unelevated `auth status` cannot read the store or even its ACL.
1278    ///
1279    /// Observed on 2026-08-29: a store readable at `07:50Z` and unreadable at
1280    /// `07:58Z`, with nothing between the two but the daemon renewing its
1281    /// eight-hour token. See `docs/spikes/token-expiry-and-renewal.md`.
1282    ///
1283    /// # Why the previous owner, rather than preserving ownership
1284    ///
1285    /// Setting a new file's owner to an account that is not the caller's needs
1286    /// `SE_RESTORE_NAME`, which `LocalSystem` holds but a least-privilege
1287    /// service account — which `service install` can register — does not. An
1288    /// ACE needs nothing: the writer created the file and so may say who else
1289    /// reaches it. This works the same for both, which is why it is the
1290    /// mechanism rather than the fallback.
1291    ///
1292    /// This widens nothing. The previous owner already had full control
1293    /// through `OW`; carrying the SID forward is what keeps a grant that
1294    /// already existed from evaporating when somebody else writes.
1295    ///
1296    /// # Why the previous *grants* and not just the previous owner
1297    ///
1298    /// Carrying the owner alone survives exactly one write and then undoes
1299    /// itself. After the first renewal the owner is the daemon and the operator
1300    /// is named by an ACE; at the second renewal the owner read back is the
1301    /// *daemon's*, so a DACL rebuilt from the owner drops the operator and
1302    /// locks them out again — the same failure, deferred by eight hours. What
1303    /// is carried is therefore every SID the previous DACL granted, which
1304    /// includes the ACE the previous write added.
1305    ///
1306    /// [`carried_grants`] reads that set and drops the SIDs the constant
1307    /// already covers, so the DACL cannot grow by one ACE per write.
1308    pub(super) fn replacement_sddl(scope: SecretScope, carried: &[String]) -> String {
1309        let mut text = sddl(scope).to_owned();
1310        for sid in carried {
1311            // The SID goes in where a two-letter alias usually does; SDDL takes
1312            // either.
1313            text.push_str("(A;;FA;;;");
1314            text.push_str(sid);
1315            text.push(')');
1316        }
1317        text
1318    }
1319
1320    /// Trustees the constant DACL already grants, in both spellings.
1321    ///
1322    /// The aliases are what [`sddl`] itself writes, so re-emitting them would
1323    /// double every ACE in the base. The two SIDs are the same accounts as
1324    /// `SY` and `BA`, which is the spelling [`previous_owner`] hands back:
1325    /// `ConvertSidToStringSidW` always answers `S-1-…`, never an alias.
1326    const ALREADY_GRANTED: [&str; 5] = ["SY", "BA", "OW", "S-1-5-18", "S-1-5-32-544"];
1327
1328    /// Every account the value being replaced was readable by, so that
1329    /// replacing it does not quietly take the store away from one of them.
1330    ///
1331    /// The owner, because `OW` granted it; plus the SIDs already named
1332    /// explicitly, because those are the owners of earlier writes that this
1333    /// mechanism already rescued. Bounded by [`ALREADY_GRANTED`] and by
1334    /// deduplication: in practice the set is the one operator who signed in.
1335    ///
1336    /// Deliberately infallible, for the reason [`previous_owner`] gives.
1337    fn carried_grants(path: &Path) -> Vec<String> {
1338        // The reader `protection` already goes through, rather than a second
1339        // descriptor round trip of this module's own.
1340        let dacl = crate::process::permissions_summary(path)
1341            .map(|summary| summary.description)
1342            .unwrap_or_default();
1343        let mut grants = merge_grants(previous_owner(path).as_deref(), &dacl);
1344
1345        // ------------------------------------------------------------------
1346        // AND THIS WRITER, BY NAME, BECAUSE `OW` DOES NOT SURVIVE.
1347        // ------------------------------------------------------------------
1348        // `OW` was chosen to mean "the account that wrote this keeps access",
1349        // and it does -- until anybody changes the owner, at which point
1350        // Windows **deletes the OWNER RIGHTS ACE**. Taking ownership of the
1351        // file therefore removes the only thing granting the new owner access:
1352        // they end up owning a file they cannot read, holding `READ_CONTROL`
1353        // and `WRITE_DAC` and nothing else. Read back from a real host on
1354        // 2026-08-30, after `takeown` had been offered as the repair:
1355        //
1356        //     O:S-1-5-21-...-1001 G:SY D:P(A;;FA;;;SY)(A;;FA;;;BA)
1357        //
1358        // -- the owner is the operator, and `OW` is simply gone.
1359        //
1360        // So the writer is named by SID as well. `OW` stays because it costs
1361        // nothing and still covers the ordinary case, but nothing depends on
1362        // it any more. `ALREADY_GRANTED` drops the service accounts, so a
1363        // daemon writing under `LocalSystem` adds no ACE at all and the set
1364        // stays at the one operator who signed in.
1365        if let Ok(writer) = crate::process::current_user_sid()
1366            && !ALREADY_GRANTED.contains(&&*writer)
1367            && !grants.contains(&writer)
1368        {
1369            grants.push(writer);
1370        }
1371        grants
1372    }
1373
1374    /// [`carried_grants`] without the two reads, which is where its one rule
1375    /// lives and the only part a test can drive.
1376    ///
1377    /// A test process is one account: it cannot become `LocalSystem`, so it
1378    /// cannot make the owner move between writes, so driving [`store`] can
1379    /// never reach the case this rule exists for. Passing the owner and the
1380    /// DACL in is what makes "the writer is not the previous owner" reachable
1381    /// at all.
1382    pub(super) fn merge_grants(previous_owner: Option<&str>, previous_dacl: &str) -> Vec<String> {
1383        let mut carried: Vec<String> = Vec::new();
1384        let mut add = |sid: &str| {
1385            if !ALREADY_GRANTED.contains(&sid) && !carried.iter().any(|seen| seen == sid) {
1386                carried.push(sid.to_owned());
1387            }
1388        };
1389        if let Some(owner) = previous_owner {
1390            add(owner);
1391        }
1392        for trustee in trustees(previous_dacl) {
1393            add(&trustee);
1394        }
1395        carried
1396    }
1397
1398    /// Every trustee an SDDL DACL names, in whatever spelling it names them.
1399    ///
1400    /// An ACE is `(type;flags;rights;object;inherit;trustee)`, so the trustee is
1401    /// what follows the last `;` before the closing parenthesis.
1402    ///
1403    /// # Why not "the ones written as `S-1-…`"
1404    ///
1405    /// Because Windows does not read back what was written. A DACL built with
1406    /// `S-1-5-21-…-500` comes out of
1407    /// `ConvertSecurityDescriptorToStringSecurityDescriptorW` as `(A;;FA;;;LA)`
1408    /// — the alias for the built-in Administrator — and any other well-known
1409    /// account behaves the same way. Filtering on the `S-1-` prefix therefore
1410    /// dropped exactly the accounts whose grant had already been rescued once,
1411    /// so the carry survived one write and undid itself on the next, which is
1412    /// the bug it exists to prevent.
1413    ///
1414    /// Found by CI, whose Windows runner signs in as that account. It passes on
1415    /// an ordinary developer machine, where the operator has a plain
1416    /// `S-1-5-21-…-1001` that survives the round trip unchanged.
1417    ///
1418    /// [`ALREADY_GRANTED`] is what keeps the base DACL's own aliases out.
1419    pub(super) fn trustees(sddl: &str) -> Vec<String> {
1420        let mut found = Vec::new();
1421        for ace in sddl.split('(').skip(1) {
1422            let Some(body) = ace.split(')').next() else {
1423                continue;
1424            };
1425            let Some(trustee) = body.rsplit(';').next() else {
1426                continue;
1427            };
1428            if !trustee.is_empty() && !found.iter().any(|seen| seen == trustee) {
1429                found.push(trustee.to_owned());
1430            }
1431        }
1432        found
1433    }
1434
1435    /// The SID of the account that owns the file already there, as a string.
1436    ///
1437    /// `None` when there is no file, when its owner cannot be read, or when the
1438    /// SID will not convert — all of which mean the same thing to the caller:
1439    /// there is no previous grant to carry forward, so write [`sddl`] as it
1440    /// stands. A first write reaches this with nothing on disk and takes that
1441    /// path.
1442    ///
1443    /// Deliberately infallible. A store that refused to write because it could
1444    /// not read a security descriptor would trade a working credential for a
1445    /// tidier ACL.
1446    fn previous_owner(path: &Path) -> Option<String> {
1447        let wide = to_wide(path);
1448        let mut owner = PSID::default();
1449        let mut descriptor = PSECURITY_DESCRIPTOR(std::ptr::null_mut());
1450        // SAFETY: `wide` is NUL-terminated and outlives the call. `descriptor`
1451        // receives a LocalAlloc'd descriptor freed below on every path, and
1452        // `owner` points into it rather than owning anything itself.
1453        let status = unsafe {
1454            GetNamedSecurityInfoW(
1455                PCWSTR(wide.as_ptr()),
1456                SE_FILE_OBJECT,
1457                OWNER_SECURITY_INFORMATION,
1458                Some(&mut owner),
1459                None,
1460                None,
1461                None,
1462                &mut descriptor,
1463            )
1464        };
1465        if status != ERROR_SUCCESS {
1466            return None;
1467        }
1468
1469        let mut sid_string = PWSTR::null();
1470        // SAFETY: `owner` points into the descriptor, which is still live.
1471        let converted = unsafe { ConvertSidToStringSidW(owner, &mut sid_string) };
1472        let text = match converted {
1473            // SAFETY: the conversion succeeded, so `sid_string` is a
1474            // LocalAlloc'd NUL-terminated string, freed immediately after.
1475            Ok(()) => {
1476                let text = unsafe { sid_string.to_string() }.ok();
1477                unsafe {
1478                    let _ = LocalFree(Some(HLOCAL(sid_string.0.cast())));
1479                }
1480                text
1481            }
1482            Err(_) => None,
1483        };
1484        // SAFETY: LocalAlloc'd by `GetNamedSecurityInfoW`, freed exactly once.
1485        unsafe {
1486            let _ = LocalFree(Some(HLOCAL(descriptor.0)));
1487        }
1488        text
1489    }
1490
1491    /// The access right a replacing rename needs on the file it replaces.
1492    ///
1493    /// `MOVEFILE_REPLACE_EXISTING` deletes the target, and delete is granted by
1494    /// `DELETE` on the object or by `FILE_DELETE_CHILD` on its parent. Probing
1495    /// for it is `CreateFileW` with `dwDesiredAccess = DELETE`, which
1496    /// [`std::os::windows::fs::OpenOptionsExt::access_mode`] reaches without
1497    /// another FFI declaration.
1498    const DELETE: u32 = 0x0001_0000;
1499
1500    /// Whether this account may replace the value already in the store, and if
1501    /// not, why an operator is seeing it.
1502    ///
1503    /// Returns `None` when there is nothing there, or when the existing value
1504    /// can be replaced — the ordinary cases.
1505    ///
1506    /// # What this catches
1507    ///
1508    /// A second non-administrative operator on a shared host. Their `auth
1509    /// login` inherits `WD` (create file) from `%ProgramData%` so the temporary
1510    /// file is written happily, and then the rename over the first operator's
1511    /// file is denied, because `sddl(Machine)` names `SY`, `BA` and `OW` and
1512    /// this account is none of the three. Left to the rename, that surfaces as
1513    /// a bare "Access is denied" at the last step of the write, after a valid
1514    /// machine-decryptable blob of a real token has already been put on disk.
1515    ///
1516    /// # Why it refuses rather than widening the DACL
1517    ///
1518    /// **This product keeps one machine-scoped credential per host, and that is
1519    /// the intended model rather than an accident of the ACL.**
1520    /// `07-security.md` counts the persisted credential surface and gets to
1521    /// one; `05-infrastructure.md` has `service install` register one service
1522    /// reading one store; the domain has one `Host`, and `d1`'s single-instance
1523    /// lock allows one agent. The value is *the host's* credential, not an
1524    /// operator's — so a second operator does not get a second store, and the
1525    /// question "may B overwrite A's token" is a policy question with a policy
1526    /// answer: only if B is trusted with the host, which on Windows means
1527    /// administrator.
1528    ///
1529    /// Widening the DACL to make the rename succeed would give every
1530    /// interactive account on the machine write access to the one credential
1531    /// the product holds, and read access with it, since the DACL is the
1532    /// **entire** access control here — a machine-scope DPAPI blob is
1533    /// unprotectable by any process on the host by definition. That trade is
1534    /// not worth a smoother second login.
1535    fn cannot_replace(site: &Site) -> Option<io::Error> {
1536        use std::os::windows::fs::OpenOptionsExt as _;
1537
1538        match std::fs::OpenOptions::new()
1539            .access_mode(DELETE)
1540            .open(&site.file)
1541        {
1542            // Replaceable, or nothing there to replace.
1543            Ok(_) => None,
1544            Err(error) if error.kind() == io::ErrorKind::NotFound => None,
1545            Err(error) if error.kind() == io::ErrorKind::PermissionDenied => Some(io::Error::new(
1546                io::ErrorKind::PermissionDenied,
1547                format!(
1548                    "the machine-scoped store at {} already holds a token that belongs to \
1549                     another account on this host, and this account may not replace it. This \
1550                     product keeps one machine-scoped credential per host -- it is the host's \
1551                     credential, not an operator's -- so a second operator does not get a \
1552                     second store. Either run `auth logout` as the account that stored it, or \
1553                     run `auth login` from an elevated prompt, since the local Administrators \
1554                     group is granted access, or install the service with `--start-at login`, \
1555                     which uses the per-user store instead. Nothing was written.",
1556                    site.file.display()
1557                ),
1558            )),
1559            // Anything else is not this condition. Say nothing and let the
1560            // write report whatever it actually runs into, rather than
1561            // inventing a diagnosis from an unrelated errno.
1562            Err(_) => None,
1563        }
1564    }
1565
1566    pub(super) fn ensure_writable(site: &Site) -> io::Result<()> {
1567        if let Some(refusal) = cannot_replace(site) {
1568            return Err(refusal);
1569        }
1570        Ok(())
1571    }
1572
1573    pub(super) fn store(site: &Site, scope: SecretScope, plaintext: &[u8]) -> io::Result<()> {
1574        let directory = site
1575            .file
1576            .parent()
1577            .ok_or_else(|| io::Error::other("the store path has no parent directory"))?;
1578        std::fs::create_dir_all(directory)?;
1579
1580        // Before anything is encrypted or written. The point of asking here is
1581        // that the alternative -- finding out at the rename -- means a valid,
1582        // machine-decryptable blob of a live token has already been placed on
1583        // disk before the refusal.
1584        if let Some(refusal) = cannot_replace(site) {
1585            return Err(refusal);
1586        }
1587
1588        let blob = protect(plaintext, scope)?;
1589
1590        // Read before the temporary exists, from the file about to be replaced.
1591        // A renewal writes as the daemon's account and would otherwise take
1592        // `OW` away from the operator who signed in; see `replacement_sddl`.
1593        let descriptor = replacement_sddl(scope, &carried_grants(&site.file));
1594
1595        let temporary = directory.join(format!("{TEMP_PREFIX}{}.tmp", uuid::Uuid::new_v4()));
1596        let written = (|| -> io::Result<()> {
1597            let mut file = create_protected_file(&temporary, &descriptor)?;
1598            file.write_all(&blob)?;
1599            file.flush()?;
1600            file.sync_all()
1601        })();
1602        if let Err(error) = written {
1603            return Err(discard(&temporary, error));
1604        }
1605
1606        // `std::fs::rename` is `MoveFileExW(.., MOVEFILE_REPLACE_EXISTING)` on
1607        // Windows, so this replaces a previous token rather than failing. The
1608        // file keeps its own security descriptor across the move, so the DACL
1609        // applied at creation is the one the store ends up with.
1610        if let Err(error) = std::fs::rename(&temporary, &site.file) {
1611            // The probe above should have caught the second-operator case, but
1612            // it is a probe and this is a race: another account can take the
1613            // file between the two calls. Report the same diagnosis rather than
1614            // the bare denial, then discard the blob either way.
1615            let error = if error.kind() == io::ErrorKind::PermissionDenied {
1616                cannot_replace(site).unwrap_or(error)
1617            } else {
1618                error
1619            };
1620            return Err(discard(&temporary, error));
1621        }
1622        Ok(())
1623    }
1624
1625    /// Scrubs and removes a temporary that will not become the store, and folds
1626    /// a failure to do so into the error the caller is already returning.
1627    ///
1628    /// A temporary that survives a failed `store` is a valid machine-scope
1629    /// DPAPI blob of a real token, sitting under a name nobody looks at.
1630    /// Removing it was already the behaviour; what was missing is that the
1631    /// removal was `let _ =`, so a temporary that could *not* be removed left
1632    /// the token on disk with nothing said about it.
1633    ///
1634    /// A blanket [`sweep_temporaries`] is deliberately not used here. Its own
1635    /// documentation says why: two `store` calls can be in flight at once, and
1636    /// sweeping the directory would remove the other one's live temporary. This
1637    /// removes exactly the file this call created.
1638    fn discard(temporary: &Path, error: io::Error) -> io::Error {
1639        let _ = overwrite(temporary);
1640        match std::fs::remove_file(temporary) {
1641            Ok(()) => error,
1642            Err(removal) if removal.kind() == io::ErrorKind::NotFound => error,
1643            Err(removal) => io::Error::new(
1644                error.kind(),
1645                format!(
1646                    "{error}. A temporary file holding the encrypted token was also left at \
1647                     {} and could not be removed ({removal}); delete it by hand.",
1648                    temporary.display()
1649                ),
1650            ),
1651        }
1652    }
1653
1654    /// Why an operator cannot read a store that is theirs, and the one command
1655    /// that gives it back.
1656    ///
1657    /// # The state this diagnoses
1658    ///
1659    /// A file that exists and that this account may not read. On this store
1660    /// that has one cause: the DACL grants `SY`, `BA` and `OW`, and the owner
1661    /// is whoever wrote last. A daemon under `LocalSystem` renewing the token
1662    /// became that owner, so `OW` stopped meaning the operator.
1663    ///
1664    /// # Why it names `icacls` and not `takeown`
1665    ///
1666    /// **Because `takeown` makes it permanent.** Changing an object's owner
1667    /// makes Windows delete its OWNER RIGHTS ACE, so taking ownership removes
1668    /// the one thing that would have granted the new owner access: they end up
1669    /// owning a file they cannot read, holding `READ_CONTROL` and `WRITE_DAC`
1670    /// and nothing else.
1671    ///
1672    /// This was offered as the repair on 2026-08-30 and appeared to work,
1673    /// because the `auth status` that followed ran in the same elevated prompt
1674    /// and succeeded through `BA`. The store read back:
1675    ///
1676    /// ```text
1677    /// O:S-1-5-21-...-1001 G:SY D:P(A;;FA;;;SY)(A;;FA;;;BA)
1678    /// ```
1679    ///
1680    /// The operator owns it. `OW` is gone. An unelevated read is still denied,
1681    /// and no renewal will ever bring it back.
1682    ///
1683    /// An explicit grant has none of that: it adds an ACE, changes no owner,
1684    /// deletes nothing, and is exactly the shape [`carried_grants`] then
1685    /// preserves on every later write.
1686    ///
1687    /// # Why a message and not a repair
1688    ///
1689    /// Naming an account in the DACL of the file holding this host's
1690    /// credential is not something a status command should do under an
1691    /// operator, and the account that can is an administrator, which this
1692    /// process may not be. So it says exactly what to run.
1693    fn locked_out(site: &Site, source: &io::Error) -> io::Error {
1694        io::Error::new(
1695            io::ErrorKind::PermissionDenied,
1696            format!(
1697                "{source}. The file exists but this account may not read it, which on this \
1698                 store means its owner changed: the service renews the token under its own \
1699                 account. Grant this account access explicitly from an elevated prompt -- it \
1700                 returns immediately, and stays, because every later renewal carries the \
1701                 grant forward:\n    icacls \"{}\" /grant \"%USERNAME%:(F)\"\nDo NOT use \
1702                 `takeown`: changing the owner makes Windows delete the OWNER RIGHTS ACE, \
1703                 which leaves this account owning a file it still cannot read. An `auth \
1704                 logout` followed by `auth login`, also elevated, is the heavier alternative \
1705                 and costs a fresh sign-in.",
1706                site.file.display()
1707            ),
1708        )
1709    }
1710
1711    pub(super) fn load(site: &Site, _scope: SecretScope) -> io::Result<Option<Vec<u8>>> {
1712        let blob = match std::fs::read(&site.file) {
1713            Ok(blob) => blob,
1714            Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
1715            // Asked before the bare denial is returned, for the same reason
1716            // `cannot_replace` exists on the write path: `Access is denied` on
1717            // a file the operator owns the machine of is a true statement that
1718            // helps nobody.
1719            Err(error) if error.kind() == io::ErrorKind::PermissionDenied => {
1720                return Err(locked_out(site, &error));
1721            }
1722            Err(error) => return Err(error),
1723        };
1724        if blob.is_empty() {
1725            // An empty file is the remnant of an interrupted write, not a
1726            // value. Reported as `InvalidData` so the caller says `Corrupt`
1727            // rather than starting a fresh login over the top of it.
1728            return Err(io::Error::new(
1729                io::ErrorKind::InvalidData,
1730                "the stored file is empty",
1731            ));
1732        }
1733        unprotect(&blob).map(Some)
1734    }
1735
1736    pub(super) fn delete(site: &Site) -> io::Result<bool> {
1737        // Zeroed before it is unlinked, the same as the Linux backend. The
1738        // value here is a DPAPI blob rather than plaintext, so the fill buys
1739        // less; it costs one `write`, and it keeps one mechanism instead of two
1740        // on the path the Definition of Done calls "leaves no recoverable
1741        // remnant". `overwrite`'s documentation carries the disclaimer.
1742        let _ = overwrite(&site.file);
1743
1744        let removed = match std::fs::remove_file(&site.file) {
1745            Ok(()) => true,
1746            Err(error) if error.kind() == io::ErrorKind::NotFound => false,
1747            Err(error) => return Err(error),
1748        };
1749        if let Some(directory) = site.file.parent() {
1750            sweep_temporaries(directory);
1751        }
1752        Ok(removed)
1753    }
1754
1755    // -- DPAPI ---------------------------------------------------------------
1756
1757    /// Turns a windows-rs error into one whose [`io::Error::kind`] means
1758    /// something.
1759    ///
1760    /// `Error::code()` is an **HRESULT**, and handing that straight to
1761    /// `from_raw_os_error` is what an earlier version did. It produces an
1762    /// `io::Error` whose `raw_os_error` is `0x8007_0005` rather than `5`, so
1763    /// `kind()` is `Uncategorized` and a caller cannot tell "access denied"
1764    /// from anything else — which matters here, because the second operator
1765    /// case below is precisely an access denial a caller has to recognise.
1766    ///
1767    /// The `0x8007_xxxx` range is `HRESULT_FROM_WIN32`, so its low sixteen bits
1768    /// are the Win32 code and unwrapping them restores the classification.
1769    /// Anything outside that range is not a Win32 error and is passed through
1770    /// as it is.
1771    pub(super) fn io_error(error: &windows::core::Error) -> io::Error {
1772        let code = error.code().0;
1773        if (code as u32) & 0xffff_0000 == 0x8007_0000 {
1774            io::Error::from_raw_os_error(code & 0xffff)
1775        } else {
1776            io::Error::from_raw_os_error(code)
1777        }
1778    }
1779
1780    /// A blob descriptor over a buffer the caller keeps alive.
1781    fn blob_of(bytes: &mut [u8]) -> CRYPT_INTEGER_BLOB {
1782        CRYPT_INTEGER_BLOB {
1783            cbData: u32::try_from(bytes.len()).unwrap_or(u32::MAX),
1784            pbData: bytes.as_mut_ptr(),
1785        }
1786    }
1787
1788    /// Copies `len` bytes out of `ptr` and zeroes the source.
1789    ///
1790    /// Split out from [`take_blob`] for one reason: a scrub that happens inside
1791    /// an `unsafe` block around a DPAPI buffer can be asserted by nothing —
1792    /// once `LocalFree` has run there is nothing left to look at. Given a
1793    /// pointer, the scrub is a property a test can check against a buffer Rust
1794    /// owns, which is what
1795    /// [`tests::windows::the_dpapi_buffer_is_scrubbed_before_it_is_freed`]
1796    /// does.
1797    ///
1798    /// # Safety
1799    ///
1800    /// `ptr` must be valid for reads *and writes* of `len` bytes, and must not
1801    /// be aliased for the duration of the call.
1802    pub(super) unsafe fn copy_and_scrub(ptr: *mut u8, len: usize) -> Vec<u8> {
1803        use secrecy::zeroize::Zeroize as _;
1804
1805        // SAFETY: the caller guarantees `ptr` is valid for `len` bytes and
1806        // unaliased, so one exclusive slice over it is sound.
1807        let source = unsafe { std::slice::from_raw_parts_mut(ptr, len) };
1808        let copy = source.to_vec();
1809        source.zeroize();
1810        copy
1811    }
1812
1813    /// Copies a DPAPI-allocated output blob into a `Vec`, scrubs the original,
1814    /// and frees it.
1815    ///
1816    /// The scrub is not optional and is not only for tidiness. On the
1817    /// [`unprotect`] path this buffer holds **the user access token in
1818    /// plaintext**, and `LocalFree` returns it to the process heap exactly as
1819    /// it is — where a later allocation, a crash dump, or a core file can pick
1820    /// it up. Every other copy this module makes is scrubbed (`protect`'s
1821    /// input, `decode`'s rejected bytes); this one was the exception.
1822    ///
1823    /// It runs on the [`protect`] path too, where the buffer is ciphertext and
1824    /// the scrub buys nothing. Making it conditional would buy a branch and an
1825    /// opportunity to get the condition wrong.
1826    ///
1827    /// # Safety
1828    ///
1829    /// `out` must be an output blob DPAPI filled in and that has not yet been
1830    /// freed.
1831    unsafe fn take_blob(out: &mut CRYPT_INTEGER_BLOB) -> Vec<u8> {
1832        if out.pbData.is_null() {
1833            return Vec::new();
1834        }
1835        // SAFETY: DPAPI filled this blob in, so the pointer is valid for
1836        // `cbData` bytes and nothing else holds a reference to it.
1837        let bytes = unsafe { copy_and_scrub(out.pbData, out.cbData as usize) };
1838        // SAFETY: the buffer was `LocalAlloc`ed by DPAPI and is freed once.
1839        unsafe {
1840            let _ = LocalFree(Some(HLOCAL(out.pbData.cast())));
1841        }
1842        out.pbData = std::ptr::null_mut();
1843        out.cbData = 0;
1844        bytes
1845    }
1846
1847    fn protect(plaintext: &[u8], scope: SecretScope) -> io::Result<Vec<u8>> {
1848        use secrecy::zeroize::Zeroize as _;
1849
1850        let mut input = plaintext.to_vec();
1851        let mut entropy = ENTROPY.to_vec();
1852        let input_blob = blob_of(&mut input);
1853        let entropy_blob = blob_of(&mut entropy);
1854        let mut out = CRYPT_INTEGER_BLOB::default();
1855
1856        // `CRYPTPROTECT_UI_FORBIDDEN` on both scopes, without exception. A
1857        // daemon that starts at boot has no desktop to draw a prompt on, and a
1858        // call blocked waiting for one is indistinguishable from a hang.
1859        let flags = CRYPTPROTECT_UI_FORBIDDEN
1860            | match scope {
1861                SecretScope::Machine => CRYPTPROTECT_LOCAL_MACHINE,
1862                SecretScope::User => 0,
1863            };
1864
1865        // SAFETY: both input descriptors point into `input` and `entropy`,
1866        // which outlive the call; `out` is a zeroed descriptor DPAPI fills in
1867        // and `take_blob` frees exactly once.
1868        let result = unsafe {
1869            CryptProtectData(
1870                &raw const input_blob,
1871                PCWSTR::null(),
1872                Some(&raw const entropy_blob),
1873                None,
1874                None,
1875                flags,
1876                &raw mut out,
1877            )
1878        };
1879
1880        // The plaintext copy this function made is scrubbed on every path out,
1881        // the failure path included.
1882        input.zeroize();
1883
1884        result.map_err(|error| io_error(&error))?;
1885        // SAFETY: `CryptProtectData` returned success, so `out` is a blob it
1886        // allocated and has not freed.
1887        Ok(unsafe { take_blob(&mut out) })
1888    }
1889
1890    fn unprotect(blob: &[u8]) -> io::Result<Vec<u8>> {
1891        let mut input = blob.to_vec();
1892        let mut entropy = ENTROPY.to_vec();
1893        let input_blob = blob_of(&mut input);
1894        let entropy_blob = blob_of(&mut entropy);
1895        let mut out = CRYPT_INTEGER_BLOB::default();
1896
1897        // SAFETY: as `protect`.
1898        let result = unsafe {
1899            CryptUnprotectData(
1900                &raw const input_blob,
1901                None,
1902                Some(&raw const entropy_blob),
1903                None,
1904                None,
1905                CRYPTPROTECT_UI_FORBIDDEN,
1906                &raw mut out,
1907            )
1908        };
1909
1910        match result {
1911            // SAFETY: success, so `out` is DPAPI's and unfreed.
1912            Ok(()) => Ok(unsafe { take_blob(&mut out) }),
1913            // Every way this fails means one thing to a caller: there are bytes
1914            // here and they are not a value this store can read back. Reported
1915            // as `InvalidData` so it surfaces as `Corrupt` and sends the
1916            // operator to `auth logout`, rather than as a transient read
1917            // failure that something would retry forever.
1918            Err(error) => Err(io::Error::new(
1919                io::ErrorKind::InvalidData,
1920                format!(
1921                    "the stored bytes could not be unprotected with this machine's DPAPI key \
1922                     ({error})"
1923                ),
1924            )),
1925        }
1926    }
1927
1928    // -- The protected file --------------------------------------------------
1929
1930    fn to_wide(path: &Path) -> Vec<u16> {
1931        path.as_os_str()
1932            .encode_wide()
1933            .chain(std::iter::once(0))
1934            .collect()
1935    }
1936
1937    /// Creates a new file carrying `descriptor` from the moment it exists.
1938    ///
1939    /// Takes the SDDL rather than the scope because a replacement's DACL is
1940    /// [`sddl`] plus the previous owner — see [`replacement_sddl`] — and a file
1941    /// that is created and then widened is unreadable to the account it is
1942    /// being widened for for however long the gap lasts.
1943    fn create_protected_file(path: &Path, descriptor: &str) -> io::Result<File> {
1944        let sddl_wide: Vec<u16> = descriptor
1945            .encode_utf16()
1946            .chain(std::iter::once(0))
1947            .collect();
1948
1949        let mut descriptor = PSECURITY_DESCRIPTOR(std::ptr::null_mut());
1950        // SAFETY: `sddl_wide` is a NUL-terminated UTF-16 buffer that outlives
1951        // the call, and `descriptor` receives a LocalAlloc'd descriptor freed
1952        // below on both paths.
1953        unsafe {
1954            ConvertStringSecurityDescriptorToSecurityDescriptorW(
1955                PCWSTR(sddl_wide.as_ptr()),
1956                SDDL_REVISION_1,
1957                &mut descriptor,
1958                None,
1959            )
1960        }
1961        .map_err(|error| io_error(&error))?;
1962
1963        let attributes = SECURITY_ATTRIBUTES {
1964            nLength: u32::try_from(size_of::<SECURITY_ATTRIBUTES>()).unwrap_or(u32::MAX),
1965            lpSecurityDescriptor: descriptor.0,
1966            // False: no child process this agent spawns has any business
1967            // inheriting a handle to the token.
1968            bInheritHandle: windows::core::BOOL(0),
1969        };
1970
1971        let wide = to_wide(path);
1972        // SAFETY: `wide` is NUL-terminated and outlives the call; `attributes`
1973        // points at a descriptor that is still live here.
1974        let handle = unsafe {
1975            CreateFileW(
1976                PCWSTR(wide.as_ptr()),
1977                FILE_GENERIC_READ.0 | FILE_GENERIC_WRITE.0,
1978                FILE_SHARE_NONE,
1979                Some(&raw const attributes),
1980                CREATE_NEW,
1981                FILE_ATTRIBUTE_NORMAL,
1982                None,
1983            )
1984        };
1985
1986        // SAFETY: the descriptor was LocalAlloc'd by the conversion above and
1987        // is freed exactly once, after the last use of `attributes`.
1988        unsafe {
1989            let _ = LocalFree(Some(HLOCAL(descriptor.0)));
1990        }
1991
1992        let handle = handle.map_err(|error| io_error(&error))?;
1993        // SAFETY: `CreateFileW` returned success, so the handle is a valid
1994        // owned file handle this `File` takes over.
1995        Ok(unsafe { File::from_raw_handle(handle.0) })
1996    }
1997}
1998
1999// ---------------------------------------------------------------------------
2000
2001/// The System keychain's refusal of an ordinary account, explained.
2002///
2003/// `auth login` without `--start-at` on a Mac with no service used to reach
2004/// for this store and print only `SecKeychainItemCreateFromContent returned
2005/// -61`, after the operator had already approved the device code.
2006#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
2007fn system_keychain_write_refused(source: &str) -> String {
2008    format!(
2009        "{source}. The machine-scoped store is the System keychain, and only root may write \
2010         it. It holds the credential for a service that starts at boot; sign in for that one \
2011         with `sudo runner-manager auth login --start-at boot`. For a service that runs as you \
2012         (`runner-manager service install --start-at login`), sign in to your own login \
2013         keychain instead: `runner-manager auth login --start-at login`"
2014    )
2015}
2016
2017#[cfg(target_os = "macos")]
2018mod sys {
2019    //! A generic-password item in a keychain, and which keychain is the whole
2020    //! of the scope.
2021    //!
2022    //! | scope | keychain | why |
2023    //! |---|---|---|
2024    //! | [`SecretScope::Machine`] | `/Library/Keychains/System.keychain` | the only keychain a process with no login session can open. A LaunchAgent starts at login; a LaunchDaemon starts at boot and has no user keychain to reach for. |
2025    //! | [`SecretScope::User`] | `~/Library/Keychains/login.keychain-db` | the operator's own keychain, unlocked by their login, gone when they log out. |
2026    //!
2027    //! # Why the login keychain is opened by path
2028    //!
2029    //! `SecKeychainCopyDefault` would give the account's *current* default
2030    //! keychain, which is more nearly what an operator expects. It hands back a
2031    //! handle and no path — and this store has to be able to name the file
2032    //! whose mode protects the value, both for `host show` and for
2033    //! [`super::SecretStore::protection`]. A store that could not say what
2034    //! protects it would be asserting the security property by assumption.
2035    //! So the login keychain is resolved by path, `login.keychain-db` first and
2036    //! the pre-Sierra `login.keychain` second, and an operator who has moved
2037    //! their default elsewhere gets the store in their login keychain rather
2038    //! than wherever the default now points.
2039    //!
2040    //! # User interaction is disabled around every call
2041    //!
2042    //! `SecKeychainSetUserInteractionAllowed(false)` for the duration of each
2043    //! operation, unconditionally. A daemon started at boot has no desktop, and
2044    //! a keychain call that decides to draw an unlock panel there does not fail
2045    //! — it waits. `errSecInteractionNotAllowed` returned in a second is a
2046    //! diagnosable condition; a process wedged behind an invisible dialog is
2047    //! not.
2048    //!
2049    //! # What a rooted keychain is for
2050    //!
2051    //! [`super::PlatformSecretStore::rooted_at`] creates a keychain of its own
2052    //! under the caller's root. That is the only way the suite can exercise
2053    //! this backend at all: writing to `/Library/Keychains/System.keychain`
2054    //! needs `root`, and writing to the login keychain would destroy a
2055    //! developer's real `auth login` every time the tests ran. What it covers
2056    //! and what it does not is set out on `rooted_at` itself.
2057
2058    use std::io;
2059    use std::os::unix::fs::{DirBuilderExt as _, PermissionsExt as _};
2060    use std::path::{Path, PathBuf};
2061
2062    use security_framework::os::macos::keychain::{CreateOptions, KeychainSettings, SecKeychain};
2063
2064    use super::{
2065        DIRECTORY, ITEM, KEYCHAIN_SERVICE, ROOTED_KEYCHAIN_PASSWORD, SecretScope, StartMode,
2066    };
2067
2068    /// The composed product identity, as a plain `&str`.
2069    ///
2070    /// [`KEYCHAIN_SERVICE`] is a `LazyLock<String>` so that it is built from
2071    /// `crate::paths`'s three segments rather than written out a second time.
2072    /// This is the one place that unwraps it, so the call sites below read as
2073    /// they did when it was a constant.
2074    pub(super) fn service() -> &'static str {
2075        &KEYCHAIN_SERVICE
2076    }
2077
2078    /// `errSecItemNotFound`. Hard-coded rather than imported because
2079    /// `security-framework-sys` is not a dependency of this workspace and
2080    /// adding one would be an A-group change for a single integer.
2081    const ERR_SEC_ITEM_NOT_FOUND: i32 = -25300;
2082    /// `errSecNoSuchKeychain`. What a keychain file that is not there answers
2083    /// with, which is absence rather than failure.
2084    const ERR_SEC_NO_SUCH_KEYCHAIN: i32 = -25294;
2085
2086    /// The System Keychain's master key. Root-only, and the reason an
2087    /// unprivileged local user cannot read a machine-scoped item even though
2088    /// the keychain database beside it is world-readable.
2089    const SYSTEM_KEYCHAIN_MASTER_KEY: &str = "/var/db/SystemKey";
2090    /// The machine-scoped keychain itself.
2091    const SYSTEM_KEYCHAIN: &str = "/Library/Keychains/System.keychain";
2092
2093    /// Which keychain, and where it is.
2094    #[derive(Debug, Clone, PartialEq, Eq)]
2095    pub(super) struct Site {
2096        path: PathBuf,
2097        kind: Kind,
2098        /// The keychain account the value is stored under.
2099        item: &'static str,
2100    }
2101
2102    pub(super) fn with_item(site: Site, item: &'static str) -> Site {
2103        Site { item, ..site }
2104    }
2105
2106    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
2107    enum Kind {
2108        /// The System Keychain. Written by `root`, readable by a LaunchDaemon.
2109        System,
2110        /// The operator's login keychain.
2111        Login,
2112        /// A keychain this program created under a caller-named root.
2113        Rooted,
2114    }
2115
2116    pub(super) fn standard_site(scope: SecretScope) -> Result<Site, String> {
2117        match scope {
2118            SecretScope::Machine => Ok(Site {
2119                path: PathBuf::from(SYSTEM_KEYCHAIN),
2120                kind: Kind::System,
2121                item: ITEM,
2122            }),
2123            SecretScope::User => {
2124                let home = directories::BaseDirs::new()
2125                    .ok_or_else(|| {
2126                        "the operating system reports no home directory for this account, so \
2127                         the login keychain cannot be resolved. A service account configured \
2128                         with no profile normally hits this; use the machine-scoped store, \
2129                         which is what --start-at boot installs."
2130                            .to_string()
2131                    })?
2132                    .home_dir()
2133                    .join("Library")
2134                    .join("Keychains");
2135
2136                // Sierra renamed the login keychain and kept the old one
2137                // working, so a machine upgraded across that boundary can have
2138                // either. Prefer the modern name, fall back to the legacy one
2139                // only when it is the one that actually exists, and resolve to
2140                // the modern name when neither does so that a first `auth
2141                // login` creates the right thing.
2142                let modern = home.join("login.keychain-db");
2143                let legacy = home.join("login.keychain");
2144                let path = if modern.exists() || !legacy.exists() {
2145                    modern
2146                } else {
2147                    legacy
2148                };
2149                Ok(Site {
2150                    path,
2151                    kind: Kind::Login,
2152                    item: ITEM,
2153                })
2154            }
2155        }
2156    }
2157
2158    pub(super) fn rooted_site(scope: SecretScope, root: &Path) -> Result<Site, String> {
2159        // A keychain per scope, for the reason the Windows and Linux backends
2160        // give a directory per scope: under one caller-named root the two
2161        // stores have nothing else keeping them apart, and two stores sharing
2162        // one item means `auth logout` under either scope purges both.
2163        Ok(Site {
2164            path: root
2165                .join(DIRECTORY)
2166                .join(scope.as_str())
2167                .join("runner-manager.keychain-db"),
2168            kind: Kind::Rooted,
2169            item: ITEM,
2170        })
2171    }
2172
2173    pub(super) fn describe(site: &Site) -> String {
2174        let kind = match site.kind {
2175            Kind::System => "System",
2176            Kind::Login => "login",
2177            Kind::Rooted => "rooted",
2178        };
2179        format!(
2180            "{kind} keychain {}, item {}/{}",
2181            site.path.display(),
2182            service(),
2183            site.item
2184        )
2185    }
2186
2187    pub(super) fn guard(site: &Site) -> PathBuf {
2188        match site.kind {
2189            // Not the keychain database. `/Library/Keychains/System.keychain`
2190            // is world-readable and its contents are encrypted; the mode that
2191            // decides who can decrypt them belongs to the master key beside it.
2192            // Reporting the database here would answer a question nobody asked,
2193            // and answer it wrongly.
2194            Kind::System => PathBuf::from(SYSTEM_KEYCHAIN_MASTER_KEY),
2195            Kind::Login | Kind::Rooted => site.path.clone(),
2196        }
2197    }
2198
2199    /// `errSecWrPerm`: the keychain refused to be written.
2200    const ERR_SEC_WR_PERM: i32 = -61;
2201
2202    /// A Security.framework status, carried inside the `io::Error` so that a
2203    /// caller acts on the code rather than on the words.
2204    #[derive(Debug)]
2205    struct Status {
2206        message: String,
2207        code: i32,
2208    }
2209
2210    impl std::fmt::Display for Status {
2211        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2212            f.write_str(&self.message)
2213        }
2214    }
2215
2216    impl std::error::Error for Status {}
2217
2218    /// The status an error from this module carries, if it carries one.
2219    fn status_of(error: &io::Error) -> Option<i32> {
2220        error
2221            .get_ref()?
2222            .downcast_ref::<Status>()
2223            .map(|status| status.code)
2224    }
2225
2226    fn sec_error(error: &security_framework::base::Error) -> io::Error {
2227        io::Error::other(Status {
2228            message: format!("Security.framework returned {} ({error})", error.code()),
2229            code: error.code(),
2230        })
2231    }
2232
2233    fn is_absence(error: &security_framework::base::Error) -> bool {
2234        matches!(
2235            error.code(),
2236            ERR_SEC_ITEM_NOT_FOUND | ERR_SEC_NO_SUCH_KEYCHAIN
2237        )
2238    }
2239
2240    /// `errSecDuplicateItem`, which this store only ever meets in one
2241    /// situation. See [`replace_unreadable`].
2242    const ERR_SEC_DUPLICATE_ITEM: i32 = -25299;
2243
2244    /// `errSecAuthFailed`, which a keychain answers when the item is there and
2245    /// the caller may not have it — because the ACL does not name the program
2246    /// asking, or because the keychain's master key is out of this account's
2247    /// reach. [`locked_out`] tells those two apart.
2248    const ERR_SEC_AUTH_FAILED: i32 = -25293;
2249
2250    fn is_duplicate(error: &security_framework::base::Error) -> bool {
2251        error.code() == ERR_SEC_DUPLICATE_ITEM
2252    }
2253
2254    /// Whether this process is `root`.
2255    ///
2256    /// Only ever used to *explain* a refusal, never to decide whether to
2257    /// attempt one: the keychain is the authority on what this process may
2258    /// read, and a privilege check of our own that disagreed with it would be a
2259    /// second, wrong answer.
2260    fn is_root() -> bool {
2261        // SAFETY: `geteuid` takes no argument, reads only this process's own
2262        // credentials, and is documented never to fail.
2263        unsafe { libc::geteuid() == 0 }
2264    }
2265
2266    /// Removes the item without reading it, so that a value this program may
2267    /// not read can still be replaced.
2268    ///
2269    /// # Why this is needed at all
2270    ///
2271    /// A keychain grants access per *application*, and the daemon runs a copy
2272    /// of the binary that `service install` makes. Replacing that copy — which
2273    /// is what an upgrade is — produces a program the item's ACL does not name,
2274    /// and it reads `-25293` from the credential it is supposed to own.
2275    ///
2276    /// `auth login` is the remedy, and before this it could not be: the
2277    /// crate's `set_generic_password` is
2278    ///
2279    /// ```text
2280    /// match self.find_generic_password(service, account) {
2281    ///     Ok((_, mut item)) => item.set_password(password),
2282    ///     _ => self.add_generic_password(service, account, password),
2283    /// }
2284    /// ```
2285    ///
2286    /// so a `find` refused by the ACL falls through to `add`, and `add` meets
2287    /// the item that is already there: **`-25299`**. Update refused because the
2288    /// item cannot be read, add refused because it exists. A device flow that
2289    /// had already completed then had nowhere to put the token it obtained,
2290    /// and the refresh half went with it.
2291    ///
2292    /// Watched on 2026-08-30, upgrading a real host from 0.1.12 to 0.1.15.
2293    ///
2294    /// # Why deleting works where updating does not
2295    ///
2296    /// `SecItemDelete` matches on the query — class, keychain, service,
2297    /// account — and never asks for the data, so the ACL that guards *reading*
2298    /// does not apply. The value is being replaced either way, which is the
2299    /// only reason destroying it is the right move here.
2300    fn replace_unreadable(keychain: &SecKeychain, account: &str) -> io::Result<()> {
2301        delete_by_query(keychain, account).map_err(|error| sec_error(&error))
2302    }
2303
2304    /// The delete itself, with the platform error kept intact.
2305    ///
2306    /// Separate from [`replace_unreadable`] only so that
2307    /// [`remove_any_existing`] can read the status code rather than the
2308    /// rendered message.
2309    fn delete_by_query(
2310        keychain: &SecKeychain,
2311        account: &str,
2312    ) -> Result<(), security_framework::base::Error> {
2313        use security_framework::item::{ItemClass, ItemSearchOptions};
2314
2315        ItemSearchOptions::new()
2316            .class(ItemClass::generic_password())
2317            .keychains(std::slice::from_ref(keychain))
2318            .service(service())
2319            .account(account)
2320            .delete()
2321    }
2322
2323    /// [`replace_unreadable`], for a caller that does not know whether there is
2324    /// anything there.
2325    ///
2326    /// Nothing to delete is the ordinary state of a first `auth login`, and is
2327    /// success.
2328    fn remove_any_existing(keychain: &SecKeychain, account: &str) -> io::Result<()> {
2329        match delete_by_query(keychain, account) {
2330            Ok(()) => Ok(()),
2331            Err(error) if is_absence(&error) => Ok(()),
2332            Err(error) => Err(sec_error(&error)),
2333        }
2334    }
2335
2336    /// Suppresses keychain UI for as long as the returned guard lives.
2337    ///
2338    /// Best effort: a platform that refuses the call is not a reason to fail
2339    /// the operation, only a reason not to have the guarantee. The guard
2340    /// re-enables interaction on drop, so this never leaks process-wide state
2341    /// past the call that took it.
2342    fn without_user_interaction()
2343    -> Option<security_framework::os::macos::keychain::KeychainUserInteractionLock> {
2344        SecKeychain::disable_user_interaction().ok()
2345    }
2346
2347    /// Opens the keychain, creating a rooted one if asked and if it is missing.
2348    ///
2349    /// `Ok(None)` means "there is no such keychain", which for a read is
2350    /// absence rather than failure.
2351    fn open(site: &Site, create_if_missing: bool) -> io::Result<Option<SecKeychain>> {
2352        match site.kind {
2353            Kind::System | Kind::Login => {
2354                if !site.path.exists() {
2355                    return Ok(None);
2356                }
2357                SecKeychain::open(&site.path)
2358                    .map(Some)
2359                    .map_err(|error| sec_error(&error))
2360            }
2361            Kind::Rooted if site.path.exists() => {
2362                let mut keychain =
2363                    SecKeychain::open(&site.path).map_err(|error| sec_error(&error))?;
2364                keychain
2365                    .unlock(Some(ROOTED_KEYCHAIN_PASSWORD))
2366                    .map_err(|error| sec_error(&error))?;
2367                Ok(Some(keychain))
2368            }
2369            Kind::Rooted if create_if_missing => Ok(Some(create_rooted(site)?)),
2370            Kind::Rooted => Ok(None),
2371        }
2372    }
2373
2374    fn create_rooted(site: &Site) -> io::Result<SecKeychain> {
2375        let directory = site
2376            .path
2377            .parent()
2378            .ok_or_else(|| io::Error::other("the rooted keychain path has no parent directory"))?;
2379        // `0700` at `mkdir(2)` time, for the reason `crate::paths` gives: a
2380        // two-step create-then-chmod leaves a window, and here the window is
2381        // over the directory whose mode is the only thing protecting a rooted
2382        // keychain.
2383        std::fs::DirBuilder::new()
2384            .mode(0o700)
2385            .recursive(true)
2386            .create(directory)?;
2387        std::fs::set_permissions(directory, std::fs::Permissions::from_mode(0o700))?;
2388
2389        let mut keychain = CreateOptions::new()
2390            .password(ROOTED_KEYCHAIN_PASSWORD)
2391            // Never. A daemon has no operator to ask.
2392            .prompt_user(false)
2393            .create(&site.path)
2394            .map_err(|error| sec_error(&error))?;
2395
2396        // No auto-lock and no lock on sleep: an agent that has been running for
2397        // a week must not find its own store locked. The keychain is inside a
2398        // `0700` directory, so locking would add nothing an unprivileged local
2399        // user could defeat anyway.
2400        let mut settings = KeychainSettings::new();
2401        settings.set_lock_on_sleep(false);
2402        settings.set_lock_interval(None);
2403        keychain
2404            .set_settings(&settings)
2405            .map_err(|error| sec_error(&error))?;
2406
2407        // `SecKeychainCreate` is documented to take a POSIX path and is
2408        // expected to use it verbatim; the `-db` suffix `security
2409        // create-keychain` is known for is appended to a *bare name*, and the
2410        // name above already carries it. If that expectation is ever wrong the
2411        // next line fails with a bare `NotFound` on a path nobody would think
2412        // to look at, so say what actually appeared instead.
2413        if !site.path.exists() {
2414            return Err(io::Error::other(format!(
2415                "SecKeychainCreate reported success but there is no keychain at {}. {} holds {:?}",
2416                site.path.display(),
2417                directory.display(),
2418                std::fs::read_dir(directory)
2419                    .map(|entries| entries
2420                        .flatten()
2421                        .map(|entry| entry.file_name().to_string_lossy().into_owned())
2422                        .collect::<Vec<_>>())
2423                    .unwrap_or_default()
2424            )));
2425        }
2426
2427        restrict(site)?;
2428        Ok(keychain)
2429    }
2430
2431    /// Sets a keychain this program created to `0600`.
2432    ///
2433    /// Called after creation *and* after every write. A keychain database is
2434    /// rewritten by `securityd` rather than by this process, and a rewrite that
2435    /// went through a fresh file would take the umask's mode rather than the
2436    /// one set at creation — which is the mode this store's entire access
2437    /// control rests on for a rooted keychain, and which
2438    /// `the_guard_is_0600_and_its_directory_is_0700` asserts.
2439    ///
2440    /// Never applied to the System or login keychains: their modes are the
2441    /// operating system's business, not this program's.
2442    fn restrict(site: &Site) -> io::Result<()> {
2443        if site.kind != Kind::Rooted {
2444            return Ok(());
2445        }
2446        std::fs::set_permissions(&site.path, std::fs::Permissions::from_mode(0o600))
2447    }
2448
2449    /// The keychain database is rewritten beside itself, in this process, so
2450    /// its directory is what a write needs. Root's alone for the System
2451    /// keychain -- which every local account can nevertheless *read* an item
2452    /// from, once it is granted to every application.
2453    pub(super) fn ensure_writable(site: &Site) -> io::Result<()> {
2454        super::ensure_directory_writable(&site.path)
2455    }
2456
2457    pub(super) fn store(site: &Site, _scope: SecretScope, plaintext: &[u8]) -> io::Result<()> {
2458        write(site, plaintext).map_err(|error| {
2459            if site.kind == Kind::System && !is_root() && status_of(&error) == Some(ERR_SEC_WR_PERM)
2460            {
2461                io::Error::new(
2462                    io::ErrorKind::PermissionDenied,
2463                    super::system_keychain_write_refused(&error.to_string()),
2464                )
2465            } else {
2466                error
2467            }
2468        })
2469    }
2470
2471    fn write(site: &Site, plaintext: &[u8]) -> io::Result<()> {
2472        let _no_ui = without_user_interaction();
2473        let keychain = open(site, true)?.ok_or_else(|| {
2474            io::Error::new(
2475                io::ErrorKind::NotFound,
2476                format!(
2477                    "there is no keychain at {}. The machine-scoped store needs the System \
2478                     Keychain, which only root may write; the user-scoped store needs a login \
2479                     keychain, which exists once the account has logged in.",
2480                    site.path.display()
2481                ),
2482            )
2483        })?;
2484
2485        if grants_every_application(site) {
2486            // Removed and written afresh, never updated. An item keeps the
2487            // access it was created with, so `set_generic_password` on an
2488            // existing item would leave the per-binary grant in place — which
2489            // is the whole condition this branch exists to end. Deleting by
2490            // query needs no permission to *read* the value, so it works even
2491            // against an item this program is already locked out of.
2492            remove_any_existing(&keychain, site.item)?;
2493            add_granted_to_every_application(&keychain, site.item, plaintext)?;
2494        } else {
2495            match keychain.set_generic_password(service(), site.item, plaintext) {
2496                Ok(()) => {}
2497                // The item is there and this program may not read it, so the
2498                // crate's update-or-add could do neither. Take it away and
2499                // write a fresh one, which is what replacing a credential means
2500                // anyway.
2501                Err(error) if is_duplicate(&error) => {
2502                    replace_unreadable(&keychain, site.item)?;
2503                    keychain
2504                        .set_generic_password(service(), site.item, plaintext)
2505                        .map_err(|error| sec_error(&error))?;
2506                }
2507                Err(error) => return Err(sec_error(&error)),
2508            }
2509        }
2510
2511        restrict(site)
2512    }
2513
2514    // -----------------------------------------------------------------------
2515    // Who the stored item is granted to
2516    // -----------------------------------------------------------------------
2517
2518    /// The name the keychain shows for this grant, if it ever shows one.
2519    const ACCESS_DESCRIPTOR: &str = "runner-manager user access token";
2520
2521    /// Whether items in this keychain are granted to **every** application
2522    /// rather than to the one binary that wrote them.
2523    ///
2524    /// # The failure this ends
2525    ///
2526    /// A keychain ACL names *applications*, and identifies an unsigned one by
2527    /// its code directory hash — so replacing the binary produces a program the
2528    /// ACL does not name. Replacing the binary is what an upgrade is. The
2529    /// daemon then reads `errSecAuthFailed` from the credential it is supposed
2530    /// to own, exits `13`, and launchd restarts it every fifteen seconds
2531    /// forever; watched on a real host upgrading 0.1.12 to 0.1.15, and again on
2532    /// 0.1.16 to 0.1.17.
2533    ///
2534    /// The remedy the store used to print — sign in again, from a graphical
2535    /// terminal, with the exact copy of the binary that will do the reading —
2536    /// works exactly once, until the next upgrade. It is not a remedy, it is a
2537    /// recurring outage with instructions.
2538    ///
2539    /// # Why widening the grant costs nothing on these two keychains
2540    ///
2541    /// The per-application ACL is only a boundary where something else is
2542    /// **not** already the boundary, and on both of these it is:
2543    ///
2544    /// * The **System Keychain** is decrypted with `/var/db/SystemKey`, which
2545    ///   is `root`-only. Every process that can read an item there is already
2546    ///   `root`, and `07-security.md` records that *"a local administrator or
2547    ///   `root` can read the token"* as an accepted trade-off of machine-scoped
2548    ///   storage. Granting every application does not admit one caller that the
2549    ///   master key was keeping out.
2550    /// * A **rooted** keychain is protected by the `0700` directory it sits in
2551    ///   and is unlocked with [`ROOTED_KEYCHAIN_PASSWORD`], a constant in a
2552    ///   public binary. Its ACL was never the thing holding anybody out either.
2553    ///
2554    /// The **login** keychain is the one place where the ACL is a real boundary
2555    /// — every process running as the operator can reach that keychain, and the
2556    /// per-application grant is what stops one of them reading this token
2557    /// silently. So it keeps the default.
2558    ///
2559    /// Widening would not help there anyway. The login keychain also records
2560    /// the *partition* of the code that created an item -- `cdhash:<hash>` for
2561    /// an ad-hoc signed binary -- and refuses every other partition without a
2562    /// prompt, whatever the application list says. Measured on macOS 27 with
2563    /// two ad-hoc builds of one program: an item granted to every application
2564    /// in the login keychain was refused to the second build, and the same item
2565    /// in a keychain of its own was not. What survives an upgrade there is the
2566    /// new build writing the item itself, which the daemon arranges while it
2567    /// upgrades (`hand_over_credential_to_new_binary` in the application).
2568    fn grants_every_application(site: &Site) -> bool {
2569        match site.kind {
2570            Kind::System | Kind::Rooted => true,
2571            Kind::Login => false,
2572        }
2573    }
2574
2575    /// Adds the item with its access already decided.
2576    ///
2577    /// # Why not add it and then widen it
2578    ///
2579    /// That was the first shape of this, and it deadlocks a headless process.
2580    /// `SecKeychainItemSetAccess` *changes* an existing item's access control,
2581    /// which is itself an ACL-guarded operation, and macOS asks the person at
2582    /// the desk to confirm it — through Authorization Services, which
2583    /// `SecKeychainSetUserInteractionAllowed(false)` does not suppress. The
2584    /// call does not fail; `SecurityAgent` starts and the process waits behind
2585    /// a panel that a daemon has no desktop to draw on. Watched here: the store
2586    /// hung indefinitely with `SecurityAgent` running.
2587    ///
2588    /// Supplying the access at creation asks nobody anything, because there is
2589    /// no existing access to be authorized against. It is also what
2590    /// `security add-generic-password -A` does, and for the same reason.
2591    fn add_granted_to_every_application(
2592        keychain: &SecKeychain,
2593        account: &str,
2594        plaintext: &[u8],
2595    ) -> io::Result<()> {
2596        use core_foundation::base::TCFType as _;
2597
2598        let access = AnyApplicationAccess::create()?;
2599
2600        // The two attributes that identify a generic password. Both buffers
2601        // outlive the call below, which is the whole of the safety argument for
2602        // the raw pointers in the attribute list.
2603        let service_name = service();
2604
2605        let mut attributes = [
2606            ffi::SecKeychainAttribute {
2607                tag: ffi::SEC_SERVICE_ITEM_ATTR,
2608                length: u32::try_from(service_name.len()).map_err(|_| {
2609                    io::Error::other(
2610                        "the keychain service name is longer than an attribute can carry",
2611                    )
2612                })?,
2613                data: service_name.as_ptr().cast::<std::ffi::c_void>().cast_mut(),
2614            },
2615            ffi::SecKeychainAttribute {
2616                tag: ffi::SEC_ACCOUNT_ITEM_ATTR,
2617                length: u32::try_from(account.len()).map_err(|_| {
2618                    io::Error::other(
2619                        "the keychain account name is longer than an attribute can carry",
2620                    )
2621                })?,
2622                data: account.as_ptr().cast::<std::ffi::c_void>().cast_mut(),
2623            },
2624        ];
2625        let mut list = ffi::SecKeychainAttributeList {
2626            count: 2,
2627            attr: attributes.as_mut_ptr(),
2628        };
2629        let length = u32::try_from(plaintext.len())
2630            .map_err(|_| io::Error::other("the value is longer than a keychain item can hold"))?;
2631
2632        // SAFETY: the attribute list, its two buffers and `plaintext` all
2633        // outlive the call; `keychain` and `access` are live references; the
2634        // item is not asked for, so nothing is returned that must be released.
2635        let status = unsafe {
2636            ffi::SecKeychainItemCreateFromContent(
2637                ffi::SEC_GENERIC_PASSWORD_ITEM_CLASS,
2638                &raw mut list,
2639                length,
2640                plaintext.as_ptr().cast(),
2641                keychain.as_concrete_TypeRef().cast(),
2642                access.raw(),
2643                std::ptr::null_mut(),
2644            )
2645        };
2646        os_status("SecKeychainItemCreateFromContent", status)
2647    }
2648
2649    /// A `SecAccess` whose every access-control entry names no application,
2650    /// which is how Security.framework spells *"any application, without
2651    /// prompting"*.
2652    ///
2653    /// `SecAccessCreate` with a null trusted list produces the system default:
2654    /// entries naming just the calling application. Each is then rewritten with
2655    /// a null application list, keeping the prompt text and selector the system
2656    /// chose. This is what `security add-generic-password -A` does, in the same
2657    /// order.
2658    struct AnyApplicationAccess(ffi::SecAccessRef);
2659
2660    impl AnyApplicationAccess {
2661        fn create() -> io::Result<Self> {
2662            use core_foundation::base::TCFType as _;
2663            use core_foundation::string::CFString;
2664
2665            let descriptor = CFString::new(ACCESS_DESCRIPTOR);
2666            let mut access: ffi::SecAccessRef = std::ptr::null_mut();
2667            // SAFETY: `descriptor` outlives the call; a null trusted list is
2668            // the documented way to ask for the default entries; `access` is a
2669            // valid out-pointer and is only read when the call reports success.
2670            let status = unsafe {
2671                ffi::SecAccessCreate(
2672                    descriptor.as_concrete_TypeRef().cast(),
2673                    std::ptr::null(),
2674                    &raw mut access,
2675                )
2676            };
2677            os_status("SecAccessCreate", status)?;
2678            if access.is_null() {
2679                return Err(io::Error::other(
2680                    "SecAccessCreate reported success and produced no access",
2681                ));
2682            }
2683            let owned = Self(access);
2684            owned.widen()?;
2685            Ok(owned)
2686        }
2687
2688        fn raw(&self) -> ffi::SecAccessRef {
2689            self.0
2690        }
2691
2692        /// Rewrites every entry to name no application.
2693        fn widen(&self) -> io::Result<()> {
2694            let mut list: ffi::CFArrayRef = std::ptr::null();
2695            // SAFETY: `self.0` is a live `SecAccessRef`; `list` is a valid
2696            // out-pointer, and the array it returns is owned by this call.
2697            let status = unsafe { ffi::SecAccessCopyACLList(self.0, &raw mut list) };
2698            os_status("SecAccessCopyACLList", status)?;
2699            let entries = CfOwned(list.cast());
2700
2701            // SAFETY: `list` came back retained from the call above.
2702            let count = unsafe { ffi::CFArrayGetCount(list) };
2703            for index in 0..count {
2704                // SAFETY: `index` is within the count the array just reported.
2705                let entry = unsafe { ffi::CFArrayGetValueAtIndex(list, index) };
2706                if entry.is_null() {
2707                    continue;
2708                }
2709                widen_one(entry.cast_mut().cast())?;
2710            }
2711            drop(entries);
2712            Ok(())
2713        }
2714    }
2715
2716    impl Drop for AnyApplicationAccess {
2717        fn drop(&mut self) {
2718            // SAFETY: created retained by `SecAccessCreate` and released once.
2719            unsafe { ffi::CFRelease(self.0.cast_const().cast()) };
2720        }
2721    }
2722
2723    /// One access-control entry, rewritten to name no application.
2724    ///
2725    /// An entry whose contents cannot be read in this simple form is left
2726    /// alone rather than failing the store: `SecAccessCreate`'s default
2727    /// includes entries that are not application lists at all, and the one that
2728    /// decides whether the value can be decrypted is not among them.
2729    fn widen_one(entry: ffi::SecACLRef) -> io::Result<()> {
2730        let mut applications: ffi::CFArrayRef = std::ptr::null();
2731        let mut description: ffi::CFStringRef = std::ptr::null();
2732        let mut prompt: u16 = 0;
2733        // SAFETY: `entry` is an element of a live ACL array, and all three
2734        // out-pointers are valid. Anything returned is owned by this call.
2735        let copied = unsafe {
2736            ffi::SecACLCopyContents(
2737                entry,
2738                &raw mut applications,
2739                &raw mut description,
2740                &raw mut prompt,
2741            )
2742        };
2743        if copied != 0 {
2744            return Ok(());
2745        }
2746        let previous = CfOwned(applications.cast());
2747        let text = CfOwned(description.cast());
2748
2749        // SAFETY: `entry` is live and `description` is either null or a live
2750        // string; a null application list is the documented "any application".
2751        let status =
2752            unsafe { ffi::SecACLSetContents(entry, std::ptr::null(), description, prompt) };
2753        drop(previous);
2754        drop(text);
2755        os_status("SecACLSetContents", status)
2756    }
2757
2758    /// A Core Foundation value this code owns a reference to.
2759    struct CfOwned(*const std::ffi::c_void);
2760
2761    impl Drop for CfOwned {
2762        fn drop(&mut self) {
2763            if !self.0.is_null() {
2764                // SAFETY: every construction site holds a reference returned by
2765                // a `Copy`/`Create` call, and releases it exactly once.
2766                unsafe { ffi::CFRelease(self.0) };
2767            }
2768        }
2769    }
2770
2771    /// `noErr` is success; anything else is named with the call that returned
2772    /// it, because an operator reading `-25244` needs to know which of five
2773    /// calls produced it.
2774    fn os_status(call: &'static str, status: i32) -> io::Result<()> {
2775        if status == 0 {
2776            Ok(())
2777        } else {
2778            Err(io::Error::other(Status {
2779                message: format!("{call} returned {status}"),
2780                code: status,
2781            }))
2782        }
2783    }
2784
2785    /// The Security and Core Foundation entry points that `security-framework`
2786    /// does not wrap.
2787    ///
2788    /// Declared here rather than pulled in as another dependency:
2789    /// `security-framework-sys` binds neither `SecAccess*` nor `SecACL*`, so a
2790    /// dependency would have to be a new one, for five functions whose
2791    /// signatures are fixed platform ABI.
2792    mod ffi {
2793        use std::ffi::c_void;
2794
2795        pub type CFArrayRef = *const c_void;
2796        pub type CFStringRef = *const c_void;
2797        pub type CFIndex = isize;
2798        pub type SecAccessRef = *mut c_void;
2799        pub type SecACLRef = *mut c_void;
2800        pub type SecKeychainRef = *mut c_void;
2801        pub type SecKeychainItemRef = *mut c_void;
2802
2803        /// `kSecGenericPasswordItemClass`, the four-character code `'genp'`.
2804        pub const SEC_GENERIC_PASSWORD_ITEM_CLASS: u32 = u32::from_be_bytes(*b"genp");
2805        /// `kSecServiceItemAttr`, `'svce'`.
2806        pub const SEC_SERVICE_ITEM_ATTR: u32 = u32::from_be_bytes(*b"svce");
2807        /// `kSecAccountItemAttr`, `'acct'`.
2808        pub const SEC_ACCOUNT_ITEM_ATTR: u32 = u32::from_be_bytes(*b"acct");
2809        /// `kSecUnlockStateStatus`, the bit `SecKeychainGetStatus` sets for an
2810        /// unlocked keychain.
2811        pub const SEC_UNLOCK_STATE_STATUS: u32 = 1;
2812
2813        /// `SecKeychainAttribute` from `SecBase.h`.
2814        #[repr(C)]
2815        pub struct SecKeychainAttribute {
2816            pub tag: u32,
2817            pub length: u32,
2818            pub data: *mut c_void,
2819        }
2820
2821        /// `SecKeychainAttributeList` from `SecBase.h`.
2822        #[repr(C)]
2823        pub struct SecKeychainAttributeList {
2824            pub count: u32,
2825            pub attr: *mut SecKeychainAttribute,
2826        }
2827
2828        #[link(name = "CoreFoundation", kind = "framework")]
2829        unsafe extern "C" {
2830            pub fn CFRelease(value: *const c_void);
2831            pub fn CFArrayGetCount(array: CFArrayRef) -> CFIndex;
2832            pub fn CFArrayGetValueAtIndex(array: CFArrayRef, index: CFIndex) -> *const c_void;
2833        }
2834
2835        #[link(name = "Security", kind = "framework")]
2836        unsafe extern "C" {
2837            pub fn SecAccessCreate(
2838                descriptor: CFStringRef,
2839                trusted_list: CFArrayRef,
2840                access: *mut SecAccessRef,
2841            ) -> i32;
2842            pub fn SecAccessCopyACLList(access: SecAccessRef, list: *mut CFArrayRef) -> i32;
2843            pub fn SecACLCopyContents(
2844                entry: SecACLRef,
2845                applications: *mut CFArrayRef,
2846                description: *mut CFStringRef,
2847                prompt_selector: *mut u16,
2848            ) -> i32;
2849            pub fn SecACLSetContents(
2850                entry: SecACLRef,
2851                applications: CFArrayRef,
2852                description: CFStringRef,
2853                prompt_selector: u16,
2854            ) -> i32;
2855            pub fn SecKeychainGetStatus(keychain: SecKeychainRef, status: *mut u32) -> i32;
2856            pub fn SecKeychainItemCreateFromContent(
2857                item_class: u32,
2858                attributes: *mut SecKeychainAttributeList,
2859                length: u32,
2860                data: *const c_void,
2861                keychain: SecKeychainRef,
2862                initial_access: SecAccessRef,
2863                item: *mut SecKeychainItemRef,
2864            ) -> i32;
2865        }
2866    }
2867
2868    pub(super) fn load(site: &Site, _scope: SecretScope) -> io::Result<Option<Vec<u8>>> {
2869        let _no_ui = without_user_interaction();
2870        let Some(keychain) = open(site, false)? else {
2871            return Ok(None);
2872        };
2873
2874        match keychain.find_generic_password(service(), site.item) {
2875            Ok((password, _item)) => Ok(Some(password.as_ref().to_vec())),
2876            Err(error) if is_absence(&error) => Ok(None),
2877            // The one refusal an operator can act on, and the one they cannot
2878            // guess. See `locked_out`.
2879            Err(error) if error.code() == ERR_SEC_AUTH_FAILED => {
2880                Err(locked_out(site, &keychain, &error))
2881            }
2882            Err(error) => Err(sec_error(&error)),
2883        }
2884    }
2885
2886    /// Why a keychain refuses a program its own credential, and what ends it.
2887    ///
2888    /// # Three states wear the same number
2889    ///
2890    /// `errSecAuthFailed` is what a keychain says when the item is there and
2891    /// the caller may not have it, and there are three quite different reasons
2892    /// for that. Telling an operator the wrong one sends them to a remedy that
2893    /// cannot work, so this reads which one it is instead of guessing:
2894    ///
2895    /// 1. **The account may not open the keychain at all.** The System Keychain
2896    ///    is decrypted with `/var/db/SystemKey`, which is `root`-only, so an
2897    ///    ordinary `runner-manager status` gets `-25293` on a perfectly healthy
2898    ///    credential. Nothing is broken and nothing needs repairing — the value
2899    ///    belongs to the account the boot-mode daemon runs as.
2900    /// 2. **The keychain is locked for this session.** A login keychain is
2901    ///    unlocked for the desktop session that logged in, and an SSH session
2902    ///    is not that session: measured on macOS 27, even the binary that wrote
2903    ///    an item reads `-25293` over SSH while the LaunchAgent beside it reads
2904    ///    the same item fine. Nothing about the item is wrong, and signing in
2905    ///    from there cannot work either.
2906    /// 3. **The item was written by a different build.** The login keychain
2907    ///    partitions every item to the code that created it, and an ad-hoc
2908    ///    signed binary's partition is its code hash, so every release is a
2909    ///    stranger to the item the previous one wrote. The daemon hands its
2910    ///    credential to the new build while it upgrades (see
2911    ///    `daemon adopt-credential`); this is what is left when that did not
2912    ///    happen, and one sign-in by the build that will read it ends it.
2913    fn locked_out(
2914        site: &Site,
2915        keychain: &SecKeychain,
2916        error: &security_framework::base::Error,
2917    ) -> io::Error {
2918        let code = error.code();
2919        match site.kind {
2920            Kind::System if !is_root() => io::Error::new(
2921                io::ErrorKind::PermissionDenied,
2922                format!(
2923                    "Security.framework returned {code} ({error}). The machine-scoped store is the \
2924                     System Keychain, and what decrypts it is /var/db/SystemKey, which only \
2925                     root may read -- so this is what a healthy credential looks like to an \
2926                     account that is not the one holding it. The boot-mode daemon runs as root \
2927                     and reads it. Nothing here needs repairing: run this command with sudo if \
2928                     you need the value itself, or install with `--start-at login` to keep the \
2929                     token in your own login keychain instead."
2930                ),
2931            ),
2932            Kind::Login if is_locked(keychain) => io::Error::new(
2933                io::ErrorKind::PermissionDenied,
2934                format!(
2935                    "Security.framework returned {code} ({error}). {} is locked for this \
2936                     session, so nothing in it can be read from here -- the service, which runs \
2937                     in the desktop session, may be reading it fine. An SSH session does not \
2938                     share the desktop session's unlocked login keychain. Run this from a \
2939                     Terminal in the Mac's desktop session, or unlock the keychain for this \
2940                     session first with `security unlock-keychain`.",
2941                    site.path.display()
2942                ),
2943            ),
2944            Kind::Login => io::Error::other(format!(
2945                "Security.framework returned {code} ({error}). The item is there and this keychain \
2946                 does not grant it to the program asking. macOS ties a login-keychain item to the \
2947                 exact build that wrote it -- an ad-hoc signed binary is known by the hash of its \
2948                 code -- so every release, and every rebuild, is a different program to it. The \
2949                 service hands its credential to the new build while it upgrades; an item written \
2950                 by a version that could not, or by a binary the service does not run, needs one \
2951                 more sign-in by the build that will read it: run {}.",
2952                crate::service::sign_in_instruction(StartMode::Login)
2953            )),
2954            // The System Keychain as root, and a rooted keychain: both grant
2955            // every application, so only an item from before that can refuse.
2956            Kind::System | Kind::Rooted => io::Error::other(format!(
2957                "Security.framework returned {code} ({error}). The item is there and this keychain \
2958                 does not grant it to the program asking. An earlier version granted the stored \
2959                 token to the single binary that wrote it, and an upgrade replaces that binary -- \
2960                 so an item written by one of those versions locks out every later copy, the \
2961                 daemon's included. Signing in once more rewrites it so that every application \
2962                 may read it: run `runner-manager auth login`, with sudo if this is the \
2963                 machine-scoped store."
2964            )),
2965        }
2966    }
2967
2968    /// Whether `keychain` is locked as far as this process can tell.
2969    ///
2970    /// Unlocking is per security session, so the answer is this session's: a
2971    /// login keychain reads as unlocked to a LaunchAgent and as locked to an SSH
2972    /// login of the same account at the same moment. A status this process
2973    /// cannot read is treated as unlocked, so that the explanation falls back to
2974    /// the one it gave before this was asked.
2975    fn is_locked(keychain: &SecKeychain) -> bool {
2976        use core_foundation::base::TCFType as _;
2977
2978        let mut status = 0_u32;
2979        // SAFETY: `keychain` is a live reference and `status` a valid
2980        // out-pointer that is only read when the call reports success.
2981        let result = unsafe {
2982            ffi::SecKeychainGetStatus(keychain.as_concrete_TypeRef().cast(), &raw mut status)
2983        };
2984        result == 0 && status & ffi::SEC_UNLOCK_STATE_STATUS == 0
2985    }
2986
2987    pub(super) fn delete(site: &Site) -> io::Result<bool> {
2988        let _no_ui = without_user_interaction();
2989        let Some(keychain) = open(site, false)? else {
2990            return Ok(false);
2991        };
2992
2993        match keychain.find_generic_password(service(), site.item) {
2994            Ok((password, item)) => {
2995                // The password buffer holds the value. Drop it before anything
2996                // else happens, so it exists for as few instructions as it can.
2997                drop(password);
2998                // `SecKeychainItem::delete` consumes the item and discards the
2999                // OSStatus, so the only way to know it worked is to look. An
3000                // `auth logout` that reported success without removing anything
3001                // would be a lie told during a credential-disclosure response.
3002                item.delete();
3003                match keychain.find_generic_password(service(), site.item) {
3004                    Err(error) if is_absence(&error) => Ok(true),
3005                    Ok(_) => Err(io::Error::other(
3006                        "the keychain item is still present after being deleted",
3007                    )),
3008                    Err(error) => Err(sec_error(&error)),
3009                }
3010            }
3011            // `auth logout` is one of the remedies this store hands out, and
3012            // before this it could not run against the state that most needs
3013            // it: `find` is refused by the ACL, so the item this program may
3014            // not read was also an item it could not remove. The query-based
3015            // delete never asks for the data. See `replace_unreadable`.
3016            Err(error) if error.code() == ERR_SEC_AUTH_FAILED => {
3017                replace_unreadable(&keychain, site.item)?;
3018                Ok(true)
3019            }
3020            Err(error) if is_absence(&error) => Ok(false),
3021            Err(error) => Err(sec_error(&error)),
3022        }
3023    }
3024}
3025
3026// ---------------------------------------------------------------------------
3027
3028#[cfg(all(unix, not(target_os = "macos")))]
3029mod sys {
3030    //! A `0600` file, and the systemd credential that takes precedence over it.
3031    //!
3032    //! `05-infrastructure.md` gives the Linux machine store as *"`0600` file
3033    //! plus systemd credentials"*, and the two halves are not alternatives.
3034    //!
3035    //! **The file** is what `auth login` writes and what `auth logout` removes.
3036    //! It holds the token at rest with no encryption, because there is no key
3037    //! to encrypt it with that a boot-time service could also reach — a key in
3038    //! a second file is not a key, it is an indirection. Its mode is therefore
3039    //! the entire access control, which is why it is `0600` inside a `0700`
3040    //! directory and why [`super::SecretStore::protection`] reports the mode
3041    //! rather than something more reassuring.
3042    //!
3043    //! **The systemd credential** is a *read* path, not a write path. A unit
3044    //! given `LoadCredentialEncrypted=` has the value decrypted into a private
3045    //! `ramfs` at `$CREDENTIALS_DIRECTORY`, mounted read-only and visible to
3046    //! no other unit, and nothing is ever written to the agent's own disk. An
3047    //! operator who has gone to that trouble should not also have to keep a
3048    //! plaintext copy beside it, so a credential — when one is present — wins.
3049    //!
3050    //! That precedence is the reason `store` and `delete` refuse rather than
3051    //! pretend. A `store` whose value would be shadowed by the credential on
3052    //! the very next `load` has not stored anything useful, and an `auth
3053    //! logout` that removed the file while the credential kept the daemon
3054    //! authenticated would be a false negative in the one procedure —
3055    //! `05-infrastructure.md`'s credential-disclosure response — where a false
3056    //! negative is worst. Both say what the operator has to change instead.
3057    //!
3058    //! # Machine scope is `/var/lib`, and that is the point
3059    //!
3060    //! `$XDG_DATA_HOME` resolves under `$HOME`, and an account that has never
3061    //! logged in has no `$HOME` to speak of; `$XDG_RUNTIME_DIR` is cleared when
3062    //! the session ends, which is exactly the event a boot-time service starts
3063    //! before. `/var/lib/runner-manager` belongs to no session and survives a
3064    //! reboot, which is the whole requirement.
3065
3066    use std::io::{self, Write as _};
3067    use std::os::unix::fs::{DirBuilderExt as _, OpenOptionsExt as _, PermissionsExt as _};
3068    use std::path::{Path, PathBuf};
3069
3070    use super::{
3071        APPLICATION, CREDENTIALS_DIRECTORY, DIRECTORY, ITEM, ORGANIZATION, QUALIFIER,
3072        SYSTEMD_CREDENTIAL, SecretScope, TEMP_PREFIX, overwrite, sweep_temporaries,
3073        trim_trailing_ascii_whitespace,
3074    };
3075
3076    /// Where a machine-scoped store lives. Not under any home directory and
3077    /// not under any runtime directory; see the module documentation.
3078    /// The FHS directory for state a program owns; the product's own segment
3079    /// is [`APPLICATION`], not a second spelling of it.
3080    const MACHINE_PREFIX: &str = "/var/lib";
3081
3082    /// The file, and the systemd credential that outranks it.
3083    #[derive(Debug, Clone, PartialEq, Eq)]
3084    pub(super) struct Site {
3085        file: PathBuf,
3086        credential: Option<PathBuf>,
3087    }
3088
3089    /// A sibling file in the same protected directory. The systemd
3090    /// credential carries the GitHub credential only, so any other item is
3091    /// read from its file alone.
3092    pub(super) fn with_item(mut site: Site, item: &'static str) -> Site {
3093        site.file.set_file_name(item);
3094        if item != ITEM {
3095            site.credential = None;
3096        }
3097        site
3098    }
3099
3100    impl Site {
3101        /// Points this site at a credentials directory the caller names.
3102        pub(super) fn with_credentials_directory(mut self, directory: &Path) -> Self {
3103            self.credential = Some(directory.join(SYSTEMD_CREDENTIAL));
3104            self
3105        }
3106
3107        /// The systemd credential this site would read, if it has one.
3108        pub(super) fn credential(&self) -> Option<&Path> {
3109            self.credential.as_deref()
3110        }
3111    }
3112
3113    /// `$CREDENTIALS_DIRECTORY/<name>`, when systemd set one.
3114    fn credential_from_environment() -> Option<PathBuf> {
3115        std::env::var_os(CREDENTIALS_DIRECTORY)
3116            .filter(|value| !value.is_empty())
3117            .map(|value| PathBuf::from(value).join(SYSTEMD_CREDENTIAL))
3118    }
3119
3120    pub(super) fn standard_site(scope: SecretScope) -> Result<Site, String> {
3121        match scope {
3122            SecretScope::Machine => Ok(Site {
3123                file: Path::new(MACHINE_PREFIX)
3124                    .join(APPLICATION)
3125                    .join(DIRECTORY)
3126                    .join(ITEM),
3127                credential: credential_from_environment(),
3128            }),
3129            SecretScope::User => {
3130                let root = directories::ProjectDirs::from(QUALIFIER, ORGANIZATION, APPLICATION)
3131                    .ok_or_else(|| {
3132                        "the operating system reports no home directory for this account, \
3133                             so the user-scoped store cannot be resolved. A service account \
3134                             configured with no profile normally hits this; use the \
3135                             machine-scoped store, which is what --start-at boot installs."
3136                            .to_string()
3137                    })?
3138                    .data_local_dir()
3139                    .to_path_buf();
3140                Ok(Site {
3141                    file: root.join(DIRECTORY).join(ITEM),
3142                    // A user-scoped store is deliberately not for a service, so
3143                    // it never consults a service's credentials.
3144                    credential: None,
3145                })
3146            }
3147        }
3148    }
3149
3150    pub(super) fn rooted_site(scope: SecretScope, root: &Path) -> Result<Site, String> {
3151        // A directory per scope. A standard site gets its separation from the
3152        // root -- `/var/lib` against `$XDG_DATA_HOME` -- and under one
3153        // caller-named root there is none, so two stores would share a file
3154        // and `auth logout` under either scope would purge both.
3155        Ok(Site {
3156            file: root.join(DIRECTORY).join(scope.as_str()).join(ITEM),
3157            credential: None,
3158        })
3159    }
3160
3161    pub(super) fn describe(site: &Site) -> String {
3162        match &site.credential {
3163            Some(credential) => format!(
3164                "0600 file at {} (superseded by the systemd credential at {})",
3165                site.file.display(),
3166                credential.display()
3167            ),
3168            None => format!("0600 file at {}", site.file.display()),
3169        }
3170    }
3171
3172    pub(super) fn guard(site: &Site) -> PathBuf {
3173        // The object that actually holds the value being read. When systemd
3174        // supplied one, that is its credential file in the unit's private
3175        // ramfs, and reporting the agent's own file instead would describe the
3176        // protection of something nothing reads.
3177        match &site.credential {
3178            Some(credential) if credential.exists() => credential.clone(),
3179            _ => site.file.clone(),
3180        }
3181    }
3182
3183    /// The refusal both `store` and `delete` owe an operator whose unit
3184    /// supplies a credential.
3185    fn shadowed_by_credential(site: &Site, verb: &str) -> Option<io::Error> {
3186        let credential = site.credential.as_ref()?;
3187        if !credential.exists() {
3188            return None;
3189        }
3190        Some(io::Error::other(format!(
3191            "this process was started with the systemd credential `{SYSTEMD_CREDENTIAL}`, which \
3192             takes precedence over {}. {verb} Change the credential in the unit that supplies \
3193             it -- `systemd-creds` and `LoadCredentialEncrypted=` -- and restart the service.",
3194            site.file.display()
3195        )))
3196    }
3197
3198    pub(super) fn ensure_writable(site: &Site) -> io::Result<()> {
3199        if let Some(error) = shadowed_by_credential(
3200            site,
3201            "A token written here would be shadowed by it on the very next load.",
3202        ) {
3203            return Err(error);
3204        }
3205        super::ensure_directory_writable(&site.file)
3206    }
3207
3208    pub(super) fn store(site: &Site, _scope: SecretScope, plaintext: &[u8]) -> io::Result<()> {
3209        if let Some(error) = shadowed_by_credential(
3210            site,
3211            "A token written here would be shadowed by it on the very next load, so nothing \
3212             was written.",
3213        ) {
3214            return Err(error);
3215        }
3216
3217        let directory = site
3218            .file
3219            .parent()
3220            .ok_or_else(|| io::Error::other("the store path has no parent directory"))?;
3221        // `0700` through `mkdir(2)` rather than a following `chmod`, exactly as
3222        // `crate::paths::AppPaths::create_all` argues; and then set explicitly,
3223        // because `mkdir` applies the umask and a directory that was already
3224        // there may predate this rule.
3225        std::fs::DirBuilder::new()
3226            .mode(0o700)
3227            .recursive(true)
3228            .create(directory)?;
3229        std::fs::set_permissions(directory, std::fs::Permissions::from_mode(0o700))?;
3230
3231        let temporary = directory.join(format!("{TEMP_PREFIX}{}.tmp", uuid::Uuid::new_v4()));
3232        let written = (|| -> io::Result<()> {
3233            // `mode` is applied by `open(2)`, so the file never exists at any
3234            // other permissions; `create_new` makes it exclusive, so a path
3235            // pre-created by another account is an error rather than a file
3236            // this process writes a token into.
3237            let mut file = std::fs::OpenOptions::new()
3238                .write(true)
3239                .create_new(true)
3240                .mode(0o600)
3241                .open(&temporary)?;
3242            file.write_all(plaintext)?;
3243            file.flush()?;
3244            file.sync_all()
3245        })();
3246        if let Err(error) = written {
3247            let _ = std::fs::remove_file(&temporary);
3248            return Err(error);
3249        }
3250
3251        if let Err(error) = std::fs::rename(&temporary, &site.file) {
3252            let _ = std::fs::remove_file(&temporary);
3253            return Err(error);
3254        }
3255
3256        // Best effort: without it the rename can still be lost to a power cut
3257        // that the file's own `sync_all` survived. Not worth failing a store
3258        // that has already succeeded.
3259        if let Ok(handle) = std::fs::File::open(directory) {
3260            let _ = handle.sync_all();
3261        }
3262        Ok(())
3263    }
3264
3265    pub(super) fn load(site: &Site, _scope: SecretScope) -> io::Result<Option<Vec<u8>>> {
3266        if let Some(credential) = &site.credential {
3267            match std::fs::read(credential) {
3268                // Trimmed, and *only* here. The operator produced this file
3269                // with `systemd-creds encrypt`, and `echo`, `printf '%s\n'` and
3270                // every text editor leave a newline on the end. Byte for byte
3271                // that newline becomes part of the token and fails much later
3272                // inside an `Authorization` header, where it reads as a bad
3273                // credential rather than as a bad read.
3274                Ok(bytes) => return Ok(Some(trim_trailing_ascii_whitespace(bytes))),
3275                // No credential of that name: fall through to the file. A unit
3276                // can be given credentials without being given this one.
3277                Err(error) if error.kind() == io::ErrorKind::NotFound => {}
3278                Err(error) => return Err(error),
3279            }
3280        }
3281
3282        // Not trimmed. `store` writes the value verbatim and with no newline,
3283        // so anything trailing here is corruption rather than formatting, and
3284        // silently repairing it would hide the one thing `Corrupt` exists to
3285        // report.
3286        match std::fs::read(&site.file) {
3287            Ok(bytes) => Ok(Some(bytes)),
3288            Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
3289            Err(error) => Err(error),
3290        }
3291    }
3292
3293    pub(super) fn delete(site: &Site) -> io::Result<bool> {
3294        let shadowed = shadowed_by_credential(
3295            site,
3296            "The file below was removed, but the credential is still supplying a token and \
3297             this host is not purged.",
3298        );
3299
3300        let removed = overwrite_then_remove(&site.file)?;
3301        if let Some(directory) = site.file.parent() {
3302            sweep_temporaries(directory);
3303        }
3304
3305        match shadowed {
3306            Some(error) => Err(error),
3307            None => Ok(removed),
3308        }
3309    }
3310
3311    /// Zeroes the file's bytes, then unlinks it.
3312    ///
3313    /// The zero fill is [`overwrite`], which lives in the parent module so that
3314    /// it is a function a test can watch rather than a side effect inside a
3315    /// delete; its documentation carries the "best effort, not a claim"
3316    /// reasoning in full.
3317    ///
3318    /// Not being able to overwrite is not a reason to skip the unlink. The
3319    /// unlink is the part that matters, it may still succeed, and a store that
3320    /// refused to purge because it could not scrub first would fail `auth
3321    /// logout` in exactly the situation where finishing it matters most.
3322    fn overwrite_then_remove(path: &Path) -> io::Result<bool> {
3323        let _ = overwrite(path);
3324
3325        match std::fs::remove_file(path) {
3326            Ok(()) => Ok(true),
3327            Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
3328            Err(error) => Err(error),
3329        }
3330    }
3331}
3332
3333// ---------------------------------------------------------------------------
3334// The Linux-only half of the surface
3335// ---------------------------------------------------------------------------
3336
3337/// Systemd credentials, which exist on no other platform.
3338///
3339/// A separate `impl` block rather than a cross-platform method that does
3340/// nothing on two of three operating systems: a caller that names
3341/// [`PlatformSecretStore::with_credentials_directory`] is writing code that
3342/// only means something on Linux, and it should not compile anywhere else.
3343#[cfg(all(unix, not(target_os = "macos")))]
3344impl PlatformSecretStore {
3345    /// Points this store at a systemd credentials directory the caller names,
3346    /// instead of the one `$CREDENTIALS_DIRECTORY` named.
3347    ///
3348    /// [`PlatformSecretStore::standard`] already reads the environment
3349    /// variable, so a daemon started by systemd needs none of this. It is here
3350    /// for the two callers that cannot use the environment: a test, which must
3351    /// not mutate a process-wide variable that every other test is reading at
3352    /// the same time, and `service install`, which resolves what the unit it is
3353    /// about to write will set.
3354    #[must_use]
3355    pub fn with_credentials_directory(mut self, directory: impl AsRef<Path>) -> Self {
3356        self.site = self.site.with_credentials_directory(directory.as_ref());
3357        self
3358    }
3359
3360    /// The systemd credential this store reads before it reads its own file,
3361    /// when it has one.
3362    #[must_use]
3363    pub fn credential_path(&self) -> Option<&Path> {
3364        self.site.credential()
3365    }
3366}
3367
3368// ---------------------------------------------------------------------------
3369// Tests
3370// ---------------------------------------------------------------------------
3371
3372#[cfg(test)]
3373mod tests {
3374    use super::*;
3375
3376    use tempfile::TempDir;
3377
3378    #[test]
3379    fn a_system_keychain_write_refusal_says_which_sign_in_to_run() {
3380        let explained =
3381            system_keychain_write_refused("SecKeychainItemCreateFromContent returned -61");
3382        assert!(explained.starts_with("SecKeychainItemCreateFromContent returned -61. "));
3383        assert!(explained.contains("only root may write it"), "{explained}");
3384        assert!(
3385            explained.contains("`runner-manager auth login --start-at login`"),
3386            "{explained}"
3387        );
3388        assert!(
3389            explained.contains("`sudo runner-manager auth login --start-at boot`"),
3390            "{explained}"
3391        );
3392    }
3393
3394    /// Shaped like a real `ghu_` user access token and unmistakably not one.
3395    ///
3396    /// **Assembled at run time from fragments on purpose.** The whole literal
3397    /// therefore appears in no source file and in no compiled artifact, which
3398    /// is what lets `tests/no_token_outside_the_store.rs` scan this repository
3399    /// — `target/` included — and treat any hit as a real leak rather than as
3400    /// its own test data. A `const` here, or a `concat!`, would be folded into
3401    /// the binary and would make that scan meaningless.
3402    fn fixture_token() -> SecretString {
3403        SecretString::from(format!("{}{}", "ghu_", "d2FixtureNotARealCredential000000"))
3404    }
3405
3406    /// A second, equally fake token, for the tests that need two.
3407    fn other_token() -> SecretString {
3408        SecretString::from(format!("{}{}", "ghu_", "d2SecondFixtureNotARealOne000000"))
3409    }
3410
3411    fn exposed(secret: &SecretString) -> String {
3412        secret.expose_secret().to_string()
3413    }
3414
3415    fn rooted(scope: SecretScope, root: &TempDir) -> PlatformSecretStore {
3416        PlatformSecretStore::rooted_at(scope, root.path()).expect("a rooted store resolves")
3417    }
3418
3419    fn stored(store: &PlatformSecretStore) -> String {
3420        exposed(
3421            &store
3422                .load()
3423                .expect("the store is readable")
3424                .expect("a value was stored"),
3425        )
3426    }
3427
3428    // -----------------------------------------------------------------------
3429    // The scope is a function of the start mode, in both directions
3430    // -----------------------------------------------------------------------
3431
3432    #[test]
3433    fn the_scope_is_decided_by_the_start_mode() {
3434        assert_eq!(
3435            SecretScope::for_start_mode(StartMode::Boot),
3436            SecretScope::Machine,
3437            "a service that starts at boot has no login session to read a user-scoped store from"
3438        );
3439        assert_eq!(
3440            SecretScope::for_start_mode(StartMode::Login),
3441            SecretScope::User
3442        );
3443    }
3444
3445    #[test]
3446    fn every_scope_names_the_start_mode_it_is_the_answer_to() {
3447        for scope in [SecretScope::Machine, SecretScope::User] {
3448            assert_eq!(SecretScope::for_start_mode(scope.start_mode()), scope);
3449        }
3450        for mode in [StartMode::Boot, StartMode::Login] {
3451            assert_eq!(SecretScope::for_start_mode(mode).start_mode(), mode);
3452        }
3453    }
3454
3455    #[test]
3456    fn for_start_mode_opens_the_store_that_start_mode_obliges() {
3457        for mode in [StartMode::Boot, StartMode::Login] {
3458            let Ok(store) = PlatformSecretStore::for_start_mode(mode) else {
3459                // Resolution needs a home directory or a %ProgramData%. A host
3460                // with neither cannot run the product at all, and saying so is
3461                // more useful than a panic that names neither.
3462                panic!("the standard store for --start-at {mode} could not be resolved");
3463            };
3464            assert_eq!(store.scope(), SecretScope::for_start_mode(mode));
3465        }
3466    }
3467
3468    // -----------------------------------------------------------------------
3469    // Store, load, delete -- both variants
3470    // -----------------------------------------------------------------------
3471
3472    #[test]
3473    fn a_machine_scoped_store_round_trips() {
3474        let root = TempDir::new().expect("a temporary directory");
3475        let store = rooted(SecretScope::Machine, &root);
3476        let token = fixture_token();
3477
3478        assert!(
3479            store
3480                .load()
3481                .expect("an empty store reads cleanly")
3482                .is_none(),
3483            "nothing is stored before the first `auth login`"
3484        );
3485
3486        store.store(&token).expect("the token is stored");
3487        assert_eq!(stored(&store), exposed(&token));
3488
3489        assert_eq!(
3490            store.delete().expect("the token is purged"),
3491            Removal::Removed
3492        );
3493        assert!(
3494            store
3495                .load()
3496                .expect("a purged store reads cleanly")
3497                .is_none()
3498        );
3499    }
3500
3501    #[test]
3502    fn a_user_scoped_store_round_trips() {
3503        let root = TempDir::new().expect("a temporary directory");
3504        let store = rooted(SecretScope::User, &root);
3505        let token = fixture_token();
3506
3507        store.store(&token).expect("the token is stored");
3508        assert_eq!(stored(&store), exposed(&token));
3509        assert_eq!(
3510            store.delete().expect("the token is purged"),
3511            Removal::Removed
3512        );
3513        assert!(
3514            store
3515                .load()
3516                .expect("a purged store reads cleanly")
3517                .is_none()
3518        );
3519    }
3520
3521    #[test]
3522    fn the_two_variants_do_not_share_a_value() {
3523        // Both under one root, because that is the arrangement most likely to
3524        // let them collide by accident.
3525        let root = TempDir::new().expect("a temporary directory");
3526        let machine = rooted(SecretScope::Machine, &root);
3527        let user = rooted(SecretScope::User, &root);
3528
3529        machine.store(&fixture_token()).expect("stored");
3530        user.store(&other_token()).expect("stored");
3531
3532        assert_eq!(stored(&machine), exposed(&fixture_token()));
3533        assert_eq!(stored(&user), exposed(&other_token()));
3534
3535        machine.delete().expect("purged");
3536        assert!(
3537            machine.load().expect("readable").is_none(),
3538            "the machine store is empty"
3539        );
3540        assert_eq!(
3541            stored(&user),
3542            exposed(&other_token()),
3543            "purging one variant must not purge the other; `auth logout` under \
3544             --start-at boot has no business touching a user-scoped store"
3545        );
3546    }
3547
3548    #[test]
3549    fn the_coordinator_key_and_the_github_credential_do_not_share_a_value() {
3550        let root = TempDir::new().expect("a temporary directory");
3551        let github = rooted(SecretScope::Machine, &root);
3552        let key = rooted(SecretScope::Machine, &root).for_item(SecretItem::CoordinatorKey);
3553
3554        github.store(&fixture_token()).expect("stored");
3555        key.store(&other_token()).expect("stored");
3556        assert_eq!(stored(&github), exposed(&fixture_token()));
3557        assert_eq!(stored(&key), exposed(&other_token()));
3558        assert_ne!(github.location(), key.location());
3559
3560        key.delete().expect("purged");
3561        assert!(key.load().expect("readable").is_none());
3562        assert_eq!(
3563            stored(&github),
3564            exposed(&fixture_token()),
3565            "`coordinator leave` must not sign the host out of GitHub"
3566        );
3567    }
3568
3569    #[test]
3570    fn storing_again_replaces_the_value() {
3571        let root = TempDir::new().expect("a temporary directory");
3572        let store = rooted(SecretScope::Machine, &root);
3573
3574        store.store(&fixture_token()).expect("stored");
3575        store.store(&other_token()).expect("stored again");
3576
3577        assert_eq!(
3578            stored(&store),
3579            exposed(&other_token()),
3580            "a re-issued token replaces the old one rather than being refused"
3581        );
3582    }
3583
3584    // -----------------------------------------------------------------------
3585    // Absence is not an error, and delete is idempotent
3586    // -----------------------------------------------------------------------
3587
3588    #[test]
3589    fn a_load_after_delete_reports_absence_rather_than_a_failure() {
3590        let root = TempDir::new().expect("a temporary directory");
3591        let store = rooted(SecretScope::Machine, &root);
3592        store.store(&fixture_token()).expect("stored");
3593        store.delete().expect("purged");
3594
3595        // Phrased as a match rather than as `is_none`, because the property
3596        // under test is which *arm* the caller lands in. An `Err` here is the
3597        // failure the Definition of Done names: "a load after delete reports
3598        // absence rather than an error that a caller might mistake for a
3599        // transient failure".
3600        match store.load() {
3601            Ok(None) => {}
3602            Ok(Some(_)) => panic!("the value survived a delete"),
3603            Err(error) => panic!("absence was reported as a failure a caller may retry: {error}"),
3604        }
3605    }
3606
3607    #[test]
3608    fn deleting_what_is_not_there_is_success_and_says_so() {
3609        let root = TempDir::new().expect("a temporary directory");
3610        let store = rooted(SecretScope::Machine, &root);
3611
3612        assert_eq!(
3613            store
3614                .delete()
3615                .expect("purging an empty store is not a failure"),
3616            Removal::AlreadyAbsent,
3617            "`auth logout` is run on every host during a credential-disclosure \
3618             response, including the ones that were never logged in"
3619        );
3620
3621        store.store(&fixture_token()).expect("stored");
3622        assert_eq!(store.delete().expect("purged"), Removal::Removed);
3623        assert_eq!(
3624            store.delete().expect("purged again"),
3625            Removal::AlreadyAbsent
3626        );
3627    }
3628
3629    /// "Delete leaves no recoverable remnant" — stated as the same property on
3630    /// all three platforms, and checked through whatever *carries* the value on
3631    /// each.
3632    ///
3633    /// The distinction is one CI caught rather than one this test was written
3634    /// with. A file-backed store keeps the value *in* the guard, so the remnant
3635    /// question is "is the file gone". A keychain-backed store keeps it in an
3636    /// item *inside* the guard, and the guard is a database that legitimately
3637    /// outlives every item it ever held — asserting the keychain disappears
3638    /// would be asserting that `auth logout` deletes the operator's login
3639    /// keychain, which would be a bug rather than a purge.
3640    ///
3641    /// So the two things asserted everywhere are the two that mean the same
3642    /// thing everywhere: nothing readable is left, and no byte of the value is
3643    /// lying in whatever does remain.
3644    #[test]
3645    fn deleting_leaves_no_recoverable_remnant() {
3646        let root = TempDir::new().expect("a temporary directory");
3647        let store = rooted(SecretScope::Machine, &root);
3648        store.store(&fixture_token()).expect("stored");
3649
3650        let guard = store.guard();
3651        assert!(guard.exists(), "something was written");
3652        store.delete().expect("purged");
3653
3654        assert!(
3655            store
3656                .load()
3657                .expect("a purged store reads cleanly")
3658                .is_none(),
3659            "the value is still readable through the store's own API"
3660        );
3661        if let Ok(bytes) = std::fs::read(&guard) {
3662            let token = exposed(&fixture_token());
3663            assert!(
3664                !bytes
3665                    .windows(token.len())
3666                    .any(|window| window == token.as_bytes()),
3667                "the value is still lying in {} after a purge",
3668                guard.display()
3669            );
3670        }
3671
3672        // A file-backed store additionally leaves nothing at all: neither the
3673        // named file, nor a `user-access-token.<uuid>.tmp` from a write that was
3674        // interrupted, which is the token on disk under a name nobody looks at.
3675        #[cfg(not(target_os = "macos"))]
3676        {
3677            assert!(
3678                !guard.exists(),
3679                "the stored value is still at {}",
3680                guard.display()
3681            );
3682            if let Some(directory) = guard.parent()
3683                && let Ok(entries) = std::fs::read_dir(directory)
3684            {
3685                let remnants: Vec<_> = entries
3686                    .flatten()
3687                    .map(|entry| entry.file_name().to_string_lossy().into_owned())
3688                    .filter(|name| name.starts_with("user-access-token"))
3689                    .collect();
3690                assert!(
3691                    remnants.is_empty(),
3692                    "a purge left {remnants:?} in {}",
3693                    directory.display()
3694                );
3695            }
3696        }
3697    }
3698
3699    /// The negative control for the sweep above: a temporary file from an
3700    /// interrupted write is a token on disk, and a purge that only removed the
3701    /// file it was told about would leave it there.
3702    #[cfg(not(target_os = "macos"))]
3703    #[test]
3704    fn a_purge_sweeps_a_temporary_left_by_an_interrupted_write() {
3705        let root = TempDir::new().expect("a temporary directory");
3706        let store = rooted(SecretScope::Machine, &root);
3707        store.store(&fixture_token()).expect("stored");
3708
3709        let directory = store
3710            .guard()
3711            .parent()
3712            .expect("the guard has a directory")
3713            .to_path_buf();
3714        let abandoned = directory.join(format!("{TEMP_PREFIX}00000000-dead-beef.tmp"));
3715        std::fs::write(&abandoned, exposed(&fixture_token())).expect("planted");
3716
3717        store.delete().expect("purged");
3718        assert!(
3719            !abandoned.exists(),
3720            "a purge left {} behind, which is the token on disk under a name nobody looks at",
3721            abandoned.display()
3722        );
3723    }
3724
3725    // -----------------------------------------------------------------------
3726    // What is not a value
3727    // -----------------------------------------------------------------------
3728
3729    #[test]
3730    fn an_empty_value_is_refused_rather_than_stored() {
3731        let root = TempDir::new().expect("a temporary directory");
3732        let store = rooted(SecretScope::Machine, &root);
3733
3734        let error = store
3735            .store(&SecretString::from(String::new()))
3736            .expect_err("an empty value is not a token");
3737        assert!(matches!(error, SecretStoreError::Store { .. }));
3738        assert!(
3739            store.load().expect("readable").is_none(),
3740            "a refused store wrote nothing"
3741        );
3742    }
3743
3744    #[test]
3745    fn bytes_that_are_not_a_token_are_reported_as_corrupt_and_not_as_absence() {
3746        let root = TempDir::new().expect("a temporary directory");
3747        let store = rooted(SecretScope::Machine, &root);
3748
3749        // `decode` is the half of the read path that is the same on all three
3750        // operating systems, and it is reachable here because these tests are a
3751        // child of the module. The platform half -- a DPAPI blob this key
3752        // cannot unprotect, a file of raw bytes -- is exercised per OS below.
3753        let error = store
3754            .decode(vec![0xff, 0xfe, 0xfd])
3755            .expect_err("invalid UTF-8 is not a token");
3756        assert!(
3757            matches!(error, SecretStoreError::Corrupt { .. }),
3758            "got {error:?}"
3759        );
3760        assert!(
3761            store.decode(Vec::new()).is_err(),
3762            "an empty value read back is a truncated write, not an absence"
3763        );
3764    }
3765
3766    #[test]
3767    fn no_error_this_module_produces_repeats_the_value() {
3768        let root = TempDir::new().expect("a temporary directory");
3769        let store = rooted(SecretScope::Machine, &root);
3770        let token = exposed(&fixture_token());
3771
3772        // Every variant that can be constructed without a real platform
3773        // failure, rendered both ways a caller can render one.
3774        let errors = vec![
3775            SecretStoreError::Resolve {
3776                scope: SecretScope::Machine,
3777                reason: "no %ProgramData%".to_string(),
3778            },
3779            store
3780                .store(&SecretString::from(String::new()))
3781                .expect_err("empty is refused"),
3782            store
3783                .decode(token.clone().into_bytes())
3784                .err()
3785                .unwrap_or_else(|| store.corrupt("a placeholder")),
3786            store.corrupt("the bytes there are not valid UTF-8"),
3787            store
3788                .protection()
3789                .err()
3790                .unwrap_or_else(|| SecretStoreError::Inspect {
3791                    scope: SecretScope::Machine,
3792                    guard: store.guard(),
3793                    source: crate::process::permissions_summary(std::path::Path::new(
3794                        "a-path-that-is-not-there",
3795                    ))
3796                    .expect_err("a missing path cannot be inspected"),
3797                }),
3798        ];
3799
3800        for error in errors {
3801            let rendered = format!("{error} / {error:?}");
3802            assert!(
3803                !rendered.contains(&token),
3804                "an error rendered the token: {rendered}"
3805            );
3806        }
3807    }
3808
3809    // -----------------------------------------------------------------------
3810    // Who can read it
3811    // -----------------------------------------------------------------------
3812
3813    #[test]
3814    fn a_stored_value_is_not_readable_by_an_unprivileged_local_user() {
3815        for scope in [SecretScope::Machine, SecretScope::User] {
3816            let root = TempDir::new().expect("a temporary directory");
3817            let store = rooted(scope, &root);
3818            store.store(&fixture_token()).expect("stored");
3819
3820            let protection = store.protection().expect("the guard is inspectable");
3821            assert!(
3822                !protection.readable_by_other_local_users(),
3823                "the {scope}-scoped store is readable by other local users: {protection}"
3824            );
3825        }
3826    }
3827
3828    /// The negative control for the assertion above.
3829    ///
3830    /// A check that only ever returns "not readable" proves nothing, and this
3831    /// one is the whole of the evidence for a `security_critical` Definition of
3832    /// Done item. So: take a store that has just passed, loosen the one thing
3833    /// that was protecting it, and require the same call to report the leak.
3834    #[test]
3835    fn the_readability_check_reports_a_guard_that_was_loosened() {
3836        let root = TempDir::new().expect("a temporary directory");
3837        let store = rooted(SecretScope::Machine, &root);
3838        store.store(&fixture_token()).expect("stored");
3839        let guard = store.guard();
3840
3841        assert!(
3842            !store
3843                .protection()
3844                .expect("inspectable")
3845                .readable_by_other_local_users(),
3846            "the control starts from a store that passes"
3847        );
3848
3849        #[cfg(unix)]
3850        {
3851            use std::os::unix::fs::PermissionsExt as _;
3852            std::fs::set_permissions(&guard, std::fs::Permissions::from_mode(0o644))
3853                .expect("the guard can be loosened");
3854        }
3855        #[cfg(windows)]
3856        {
3857            // Replaced with a file created the ordinary way, which inherits the
3858            // temporary directory's DACL instead of carrying a protected one of
3859            // its own. That is exactly the mistake the backend exists to avoid:
3860            // an inherited DACL is whatever the parent grants, and under
3861            // `%ProgramData%` the parent grants Builtin Users read.
3862            std::fs::remove_file(&guard).expect("the guard can be replaced");
3863            std::fs::write(&guard, b"not a protected file").expect("written");
3864        }
3865
3866        let protection = store
3867            .protection()
3868            .expect("the loosened guard is still inspectable");
3869        assert!(
3870            protection.readable_by_other_local_users(),
3871            "a loosened guard was reported as safe, so the assertion above proves nothing: \
3872             {protection}"
3873        );
3874    }
3875
3876    #[test]
3877    fn the_protection_names_the_object_it_inspected() {
3878        let root = TempDir::new().expect("a temporary directory");
3879        let store = rooted(SecretScope::Machine, &root);
3880        store.store(&fixture_token()).expect("stored");
3881
3882        let protection = store.protection().expect("inspectable");
3883        assert_eq!(protection.guard(), store.guard());
3884        assert!(
3885            !protection.description().is_empty(),
3886            "a protection with no description is not a diagnosis"
3887        );
3888    }
3889
3890    // -----------------------------------------------------------------------
3891    // What `host show` and `service status` print
3892    // -----------------------------------------------------------------------
3893
3894    #[test]
3895    fn the_active_store_is_reported_and_agrees_with_the_start_mode() {
3896        let root = TempDir::new().expect("a temporary directory");
3897
3898        for mode in [StartMode::Boot, StartMode::Login] {
3899            let store = rooted(SecretScope::for_start_mode(mode), &root);
3900            let active = ActiveStore::of(&store, mode);
3901
3902            assert_eq!(active.scope(), SecretScope::for_start_mode(mode));
3903            assert_eq!(active.start_mode(), mode);
3904            assert!(active.agrees_with_start_mode());
3905
3906            let rendered = active.to_string();
3907            assert!(
3908                rendered.contains(active.scope().as_str()),
3909                "`host show` must name the variant in use: {rendered}"
3910            );
3911            assert!(
3912                rendered.contains(&mode.to_string()),
3913                "`service status` must name the start mode: {rendered}"
3914            );
3915            assert!(
3916                !rendered.contains("MISMATCH"),
3917                "a matching pair must not be reported as a mismatch: {rendered}"
3918            );
3919        }
3920    }
3921
3922    #[test]
3923    fn a_store_that_disagrees_with_the_start_mode_says_so() {
3924        let root = TempDir::new().expect("a temporary directory");
3925        // The failure this exists to catch: a service switched to `--start-at
3926        // boot` while the token is still in the operator's user-scoped store.
3927        // The daemon starts, finds nothing, and the only clue is here.
3928        let store = rooted(SecretScope::User, &root);
3929        let active = ActiveStore::of(&store, StartMode::Boot);
3930
3931        assert!(!active.agrees_with_start_mode());
3932        let rendered = active.to_string();
3933        assert!(rendered.contains("MISMATCH"), "{rendered}");
3934        assert!(rendered.contains("machine"), "{rendered}");
3935    }
3936
3937    #[test]
3938    fn the_reported_location_is_not_the_value() {
3939        let root = TempDir::new().expect("a temporary directory");
3940        let store = rooted(SecretScope::Machine, &root);
3941        store.store(&fixture_token()).expect("stored");
3942
3943        let token = exposed(&fixture_token());
3944        let active = ActiveStore::of(&store, StartMode::Boot);
3945        for rendered in [
3946            store.location(),
3947            active.to_string(),
3948            format!("{store:?}"),
3949            format!("{active:?}"),
3950            store.protection().expect("inspectable").to_string(),
3951        ] {
3952            assert!(
3953                !rendered.contains(&token),
3954                "a report carried the value: {rendered}"
3955            );
3956        }
3957    }
3958
3959    // -----------------------------------------------------------------------
3960    // Where the standard stores live
3961    // -----------------------------------------------------------------------
3962
3963    /// The property that makes a machine-scoped store readable after a reboot,
3964    /// stated as a location rather than as a hope.
3965    ///
3966    /// Every per-user directory on all three operating systems hangs off the
3967    /// account's home directory, and an account that has never logged in does
3968    /// not have one mounted. A machine store under `$HOME` would work on the
3969    /// developer's laptop and fail on the first boot of the machine it was
3970    /// installed on, which is the failure this assertion exists to make
3971    /// impossible to introduce.
3972    #[test]
3973    fn the_machine_store_is_not_under_the_home_directory() {
3974        let store = PlatformSecretStore::standard(SecretScope::Machine)
3975            .expect("the machine store resolves");
3976        let guard = store.guard();
3977
3978        let Some(base) = directories::BaseDirs::new() else {
3979            panic!("this account has no home directory, so the assertion cannot be made");
3980        };
3981        assert!(
3982            !guard.starts_with(base.home_dir()),
3983            "the machine store at {} is under the home directory {}",
3984            guard.display(),
3985            base.home_dir().display()
3986        );
3987    }
3988
3989    #[test]
3990    fn the_user_store_is_under_the_home_directory() {
3991        // The mirror of the assertion above, and the reason `--start-at login`
3992        // means what it says: this store is gone when the operator logs out.
3993        let store =
3994            PlatformSecretStore::standard(SecretScope::User).expect("the user store resolves");
3995        let Some(base) = directories::BaseDirs::new() else {
3996            panic!("this account has no home directory, so the assertion cannot be made");
3997        };
3998        assert!(
3999            store.guard().starts_with(base.home_dir()),
4000            "the user store at {} is not under the home directory {}",
4001            store.guard().display(),
4002            base.home_dir().display()
4003        );
4004    }
4005
4006    #[test]
4007    fn the_standard_locations_are_the_documented_ones() {
4008        let machine = PlatformSecretStore::standard(SecretScope::Machine).expect("resolves");
4009        let user = PlatformSecretStore::standard(SecretScope::User).expect("resolves");
4010
4011        #[cfg(windows)]
4012        {
4013            let program_data = std::path::PathBuf::from(
4014                std::env::var_os("ProgramData").expect("Windows sets ProgramData"),
4015            );
4016            assert_eq!(
4017                machine.guard(),
4018                program_data
4019                    .join("IvanMurzak")
4020                    .join("runner-manager")
4021                    .join("secrets")
4022                    .join("user-access-token.dpapi")
4023            );
4024            assert!(user.location().contains("DPAPI"), "{}", user.location());
4025        }
4026        #[cfg(target_os = "macos")]
4027        {
4028            assert_eq!(
4029                machine.guard(),
4030                std::path::Path::new("/var/db/SystemKey"),
4031                "the System Keychain's protection is its root-only master key, \
4032                 not the world-readable database beside it"
4033            );
4034            assert!(
4035                machine
4036                    .location()
4037                    .contains("/Library/Keychains/System.keychain"),
4038                "{}",
4039                machine.location()
4040            );
4041            assert!(
4042                user.location().contains("login.keychain"),
4043                "{}",
4044                user.location()
4045            );
4046        }
4047        #[cfg(all(unix, not(target_os = "macos")))]
4048        {
4049            assert_eq!(
4050                machine.guard(),
4051                std::path::Path::new("/var/lib/runner-manager/secrets/user-access-token")
4052            );
4053            assert!(user.location().contains("0600"), "{}", user.location());
4054        }
4055    }
4056
4057    /// The independent oracle for the identity `secrets.rs` now *borrows* from
4058    /// [`crate::paths`] rather than spelling out.
4059    ///
4060    /// Borrowing removes the drift the reviewer named — two files can no longer
4061    /// disagree — but it moves the risk rather than removing it: a change in
4062    /// `paths.rs` now silently moves the secret store as well as the four
4063    /// application-data directories, and a token that has moved reads as simply
4064    /// absent. The literals below are the only place in this module that is
4065    /// *not* derived from those constants, which is exactly what makes them
4066    /// able to catch such a change.
4067    #[test]
4068    fn the_product_identity_is_the_one_paths_defines() {
4069        assert_eq!(QUALIFIER, "io.github");
4070        assert_eq!(ORGANIZATION, "IvanMurzak");
4071        assert_eq!(APPLICATION, "runner-manager");
4072
4073        #[cfg(target_os = "macos")]
4074        assert_eq!(
4075            sys::service(),
4076            "io.github.IvanMurzak.runner-manager",
4077            "the keychain service names the product; a change here moves every \
4078             stored item and the token reads as absent"
4079        );
4080    }
4081
4082    /// Finding 2's replacement, and the whole of what the zero fill claims.
4083    ///
4084    /// The test it replaces stored, deleted, and asserted the file was gone —
4085    /// which is what *removing* it proves too, so
4086    /// `overwrite`'s `write_all` could have been deleted outright and the suite
4087    /// would have stayed green. This one observes the fill itself: it reads the
4088    /// bytes back **before** anything unlinks them, so the subject of the test
4089    /// cannot be removed without it failing.
4090    ///
4091    /// Not `cfg`-gated to Linux, although Linux is the platform whose stored
4092    /// value is plaintext, because the mechanism is shared and a test that only
4093    /// a CI leg can run is a test its author never watched fail.
4094    #[cfg(not(target_os = "macos"))]
4095    #[test]
4096    fn overwrite_zeroes_every_byte_and_leaves_the_file_there() {
4097        let root = TempDir::new().expect("a temporary directory");
4098        let path = root.path().join("value");
4099        let token = exposed(&fixture_token());
4100        std::fs::write(&path, &token).expect("written");
4101
4102        assert!(overwrite(&path).expect("overwritten"), "the file was there");
4103
4104        let after = std::fs::read(&path).expect("still there, so the fill is observable");
4105        assert_eq!(
4106            after.len(),
4107            token.len(),
4108            "the overwrite must not truncate; a shorter file leaves the tail of the old \
4109             value in the block"
4110        );
4111        assert!(
4112            after.iter().all(|byte| *byte == 0),
4113            "the file still holds non-zero bytes after an overwrite: {after:?}"
4114        );
4115        assert!(
4116            !after
4117                .windows(token.len())
4118                .any(|window| window == token.as_bytes()),
4119            "the value survived the overwrite"
4120        );
4121    }
4122
4123    #[cfg(not(target_os = "macos"))]
4124    #[test]
4125    fn overwriting_what_is_not_there_is_not_a_failure() {
4126        let root = TempDir::new().expect("a temporary directory");
4127        assert!(
4128            !overwrite(&root.path().join("absent")).expect("absence is not an error"),
4129            "a store that was never written has nothing to scrub"
4130        );
4131    }
4132
4133    /// Finding 6's pure half, run on every leg.
4134    ///
4135    /// The systemd credential path that uses this is Linux-only, so its
4136    /// end-to-end test is too; the decision the trim makes is not
4137    /// platform-specific, and testing it here is what let this be watched
4138    /// failing on the machine it was written on.
4139    #[cfg(not(target_os = "macos"))]
4140    #[test]
4141    fn a_trailing_newline_is_not_part_of_the_token() {
4142        let token = exposed(&fixture_token());
4143
4144        for suffix in ["\n", "\r\n", "\n\n", " ", "\t\n", ""] {
4145            let raw = format!("{token}{suffix}").into_bytes();
4146            assert_eq!(
4147                trim_trailing_ascii_whitespace(raw),
4148                token.clone().into_bytes(),
4149                "a credential written with {suffix:?} on the end yielded a different token"
4150            );
4151        }
4152
4153        // Interior whitespace is left alone. A token has none, and silently
4154        // rewriting the middle of a value would be a worse bug than the one
4155        // this fixes.
4156        let interior = b"gh u_x\n".to_vec();
4157        assert_eq!(trim_trailing_ascii_whitespace(interior), b"gh u_x".to_vec());
4158
4159        // A value that is nothing but whitespace becomes empty, which `decode`
4160        // reports as `Corrupt` rather than as absence.
4161        assert!(trim_trailing_ascii_whitespace(b"\n\n".to_vec()).is_empty());
4162    }
4163
4164    // -----------------------------------------------------------------------
4165    // Windows
4166    // -----------------------------------------------------------------------
4167
4168    #[cfg(windows)]
4169    mod windows {
4170        use super::*;
4171        use crate::secrets::sys::{merge_grants, replacement_sddl, sddl, trustees};
4172
4173        /// How much a [`DeniedReplace`] takes away.
4174        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
4175        enum AlsoDeny {
4176            /// Only what denies a *replacing rename*. Creating a file in the
4177            /// directory still works, exactly as it does for operator B, so the
4178            /// temporary is still written if the store gets that far.
4179            Nothing,
4180            /// Additionally `FILE_ADD_FILE`, so nothing can be created in the
4181            /// directory at all. What makes
4182            /// [`the_refusal_is_made_before_anything_is_written`] able to tell
4183            /// a pre-write refusal from a post-write one.
4184            Creation,
4185        }
4186
4187        /// Reproduces what a second non-administrative operator meets, without
4188        /// needing a second account, and puts the rights back on **every** path
4189        /// out — including an unwind.
4190        ///
4191        /// **Both denies are required, and finding that out was the point of
4192        /// running this against the un-fixed code.** Windows grants delete two
4193        /// ways — `DELETE` on the object, or `FILE_DELETE_CHILD` on its parent
4194        /// — and `MOVEFILE_REPLACE_EXISTING`, which is what `std::fs::rename`
4195        /// is on Windows, takes either. Operator B has neither: the file's DACL
4196        /// names `SY`, `BA` and `OW`, and a stock `%ProgramData%` grants
4197        /// `BUILTIN\Users` no `DC`. The test process, by contrast, *owns* its
4198        /// temporary directory and so does hold `FILE_DELETE_CHILD` — with only
4199        /// the file denied, the rename went through and the simulation
4200        /// reproduced nothing while looking exactly right.
4201        ///
4202        /// # Why the restore is a `Drop` and not a line at the end of the body
4203        ///
4204        /// Because a failing assertion unwinds past that line, and what it
4205        /// leaves behind is not tidy: `Everyone:(D)` denies deleting the guard
4206        /// and `Everyone:(DC)` denies deleting the directory's children, so
4207        /// `TempDir::drop` — which ignores removal errors — cannot clean up. A
4208        /// DPAPI blob of the fixture token would sit in `%TEMP%` under an ACL
4209        /// ordinary cleanup cannot remove, on exactly the run where somebody is
4210        /// already debugging a failure.
4211        struct DeniedReplace {
4212            file: std::path::PathBuf,
4213            directory: std::path::PathBuf,
4214            restored: bool,
4215        }
4216
4217        impl DeniedReplace {
4218            fn new(file: &std::path::Path, directory: &std::path::Path, also: AlsoDeny) -> Self {
4219                let denied = Self {
4220                    file: file.to_path_buf(),
4221                    directory: directory.to_path_buf(),
4222                    restored: false,
4223                };
4224                // Constructed first, so that a failure in any `icacls` below
4225                // unwinds through this guard's `Drop` and undoes the ones that
4226                // did take effect.
4227                icacls(&[&denied.file.display().to_string(), "/deny", "*S-1-1-0:(D)"]);
4228                icacls(&[
4229                    &denied.directory.display().to_string(),
4230                    "/deny",
4231                    "*S-1-1-0:(DC)",
4232                ]);
4233                if also == AlsoDeny::Creation {
4234                    icacls(&[
4235                        &denied.directory.display().to_string(),
4236                        "/deny",
4237                        "*S-1-1-0:(WD)",
4238                    ]);
4239                }
4240                denied
4241            }
4242
4243            /// Puts the rights back now, for a test that needs to go on and
4244            /// observe the store working again. Idempotent, so [`Drop`] running
4245            /// afterwards is a no-op.
4246            fn restore(&mut self) {
4247                if self.restored {
4248                    return;
4249                }
4250                self.restored = true;
4251                // `/remove:d` drops every deny ACE this SID has on the object,
4252                // so one call per object undoes all of the above.
4253                //
4254                // Deliberately not asserting: this runs on the unwind path,
4255                // where a panic would abort the process and replace a readable
4256                // test failure with one nobody can diagnose.
4257                for path in [&self.file, &self.directory] {
4258                    let arguments = [
4259                        path.display().to_string(),
4260                        "/remove:d".into(),
4261                        "*S-1-1-0".into(),
4262                    ];
4263                    match run_icacls(&arguments.each_ref().map(String::as_str)) {
4264                        Ok(output) if output.status.success() => {}
4265                        other => eprintln!(
4266                            "could not restore the ACL on {}: {other:?}; {} may survive in \
4267                             the temporary directory",
4268                            path.display(),
4269                            path.display()
4270                        ),
4271                    }
4272                }
4273            }
4274        }
4275
4276        impl Drop for DeniedReplace {
4277            fn drop(&mut self) {
4278                self.restore();
4279            }
4280        }
4281
4282        fn run_icacls(arguments: &[&str]) -> std::io::Result<std::process::Output> {
4283            std::process::Command::new("icacls.exe")
4284                .args(arguments)
4285                .output()
4286        }
4287
4288        fn icacls(arguments: &[&str]) {
4289            let output = run_icacls(arguments).expect("icacls is present on every Windows");
4290            assert!(
4291                output.status.success(),
4292                "icacls {arguments:?} failed: {}{}",
4293                String::from_utf8_lossy(&output.stdout),
4294                String::from_utf8_lossy(&output.stderr)
4295            );
4296        }
4297
4298        /// The DACL string alone, with no OS in the way.
4299        #[test]
4300        fn a_replacement_carries_the_previous_owner_and_a_first_write_does_not() {
4301            for scope in [SecretScope::Machine, SecretScope::User] {
4302                assert_eq!(
4303                    replacement_sddl(scope, &[]),
4304                    sddl(scope),
4305                    "a first write has nothing to carry, so it gets the constant DACL and \
4306                     nothing else"
4307                );
4308                assert_eq!(
4309                    replacement_sddl(scope, &["S-1-5-21-1-2-3-1001".to_owned()]),
4310                    format!("{}(A;;FA;;;S-1-5-21-1-2-3-1001)", sddl(scope)),
4311                    "one carried grant is one appended ACE"
4312                );
4313            }
4314        }
4315
4316        /// The second renewal, which is where carrying only the owner undoes
4317        /// itself.
4318        ///
4319        /// After one renewal the file is owned by `LocalSystem` and the
4320        /// operator is named by the ACE that renewal carried. A mechanism that
4321        /// rebuilds the DACL from the owner alone reads `S-1-5-18` here, drops
4322        /// the operator, and locks them out again eight hours after the fix
4323        /// appeared to work.
4324        ///
4325        /// Driving `store` cannot reach this: a test process is one account and
4326        /// cannot make the owner move. So the rule is tested where it lives.
4327        #[test]
4328        fn a_grant_survives_a_renewal_by_an_account_that_is_not_the_previous_owner() {
4329            let operator = "S-1-5-21-9-8-7-1001";
4330            let after_one_renewal = format!("{}(A;;FA;;;{operator})", sddl(SecretScope::Machine));
4331
4332            assert_eq!(
4333                merge_grants(Some("S-1-5-18"), &after_one_renewal),
4334                vec![operator.to_owned()],
4335                "the owner is now LocalSystem, which `SY` already grants; what must survive is \
4336                 the operator named in the DACL the previous renewal wrote"
4337            );
4338
4339            assert_eq!(
4340                merge_grants(Some(operator), sddl(SecretScope::Machine)),
4341                vec![operator.to_owned()],
4342                "and the first renewal, where the operator is still the owner and the DACL \
4343                 names nobody, carries the same one account"
4344            );
4345
4346            assert!(
4347                merge_grants(None, "").is_empty(),
4348                "a first write has no owner and no DACL to read, and carries nothing"
4349            );
4350
4351            assert_eq!(
4352                merge_grants(Some(operator), &after_one_renewal),
4353                vec![operator.to_owned()],
4354                "an account reachable both ways is named once, so the DACL cannot grow by an \
4355                 ACE per write"
4356            );
4357
4358            // The CI runner's own case, which an ordinary developer machine
4359            // does not reach: Windows renders a well-known account's ACE by
4360            // alias, so what the previous renewal wrote as `S-1-5-21-...-500`
4361            // reads back as `LA`. Carrying only trustees spelled `S-1-` drops
4362            // it and the operator is locked out one renewal later.
4363            let after_a_renewal_for_a_builtin =
4364                format!("{}(A;;FA;;;LA)", sddl(SecretScope::Machine));
4365            assert_eq!(
4366                merge_grants(Some("S-1-5-18"), &after_a_renewal_for_a_builtin),
4367                vec!["LA".to_owned()],
4368                "a grant is a grant whichever spelling the DACL reads back in"
4369            );
4370
4371            assert!(
4372                merge_grants(None, sddl(SecretScope::Machine)).is_empty(),
4373                "and the constant DACL's own aliases are not carried, or every write would \
4374                 double the base"
4375            );
4376        }
4377
4378        /// Every trustee, because after the first replacement one of them is
4379        /// where the operator's access lives — and Windows chooses the
4380        /// spelling, not this code.
4381        #[test]
4382        fn the_trustee_scan_reads_both_spellings() {
4383            assert_eq!(
4384                trustees("D:P(A;;FA;;;SY)(A;;FA;;;BA)(A;;FA;;;OW)(A;;FA;;;S-1-5-21-9-8-7-1001)"),
4385                vec![
4386                    "SY".to_owned(),
4387                    "BA".to_owned(),
4388                    "OW".to_owned(),
4389                    "S-1-5-21-9-8-7-1001".to_owned(),
4390                ],
4391                "the scan reads trustees; deciding which of them are already granted is \
4392                 `merge_grants`'s job and not this one's"
4393            );
4394            assert_eq!(
4395                trustees("D:P(A;;FA;;;LA)"),
4396                vec!["LA".to_owned()],
4397                "an alias is a trustee too, which is what CI's built-in Administrator account \
4398                 reads back as"
4399            );
4400        }
4401
4402        /// The lockout, as a test: renewal writes as a different account, and
4403        /// the operator who signed in must still be able to read the store.
4404        ///
4405        /// # What this can and cannot reproduce
4406        ///
4407        /// A test process is one account, so it cannot *become* `LocalSystem`
4408        /// and take ownership the way a daemon does. What it pins is the
4409        /// mechanism that makes that survivable: after a replacement, the
4410        /// previous owner is named in the DACL by SID rather than left to
4411        /// `OW` — so when the owner does move, the grant does not move with it.
4412        ///
4413        /// Un-fixed, the second description equals the first: `OW` and nothing
4414        /// else, which is exactly the state that locked an operator out of
4415        /// their own credential on 2026-08-29.
4416        ///
4417        /// # What it asserts, and why not the SID
4418        ///
4419        /// That the very first write already names somebody beyond the
4420        /// constant, and that the DACL then stops changing. Growth would be an
4421        /// ACE per write; a return to the constant would be the account
4422        /// dropped, which is the lockout.
4423        ///
4424        /// The first write counts because `OW` is not enough on its own: the
4425        /// system deletes the OWNER RIGHTS ACE whenever an owner changes, so a
4426        /// store that leans on it loses the grant to a single `takeown`. The
4427        /// writer is named by SID from the start.
4428        ///
4429        /// It deliberately does not name the account. Windows chooses the
4430        /// spelling: this machine's operator reads back as
4431        /// `S-1-5-21-…-1001`, and CI's, being the built-in Administrator,
4432        /// reads back as the alias `LA`. An earlier version of this test
4433        /// asserted the SID and failed on CI for that reason alone —
4434        /// and the same assumption was in the code, where it was a real
4435        /// defect. The spelling-sensitive rule is pinned in
4436        /// [`the_trustee_scan_reads_both_spellings`] instead.
4437        #[test]
4438        fn replacing_a_stored_credential_keeps_the_previous_owners_grant() {
4439            let root = TempDir::new().expect("a temporary directory");
4440            let store = rooted(SecretScope::Machine, &root);
4441            let base = sddl(SecretScope::Machine);
4442
4443            store.store(&fixture_token()).expect("the first write");
4444            let first = store
4445                .protection()
4446                .expect("the first file's DACL is readable")
4447                .description()
4448                .to_string();
4449            assert_ne!(
4450                first, base,
4451                "even a first write names the account that made it, because `OW` alone does \
4452                 not survive a change of owner"
4453            );
4454
4455            let mut previous: Option<String> = Some(first);
4456            for round in 1..=3 {
4457                store.store(&other_token()).expect("the replacement");
4458                let dacl = store
4459                    .protection()
4460                    .expect("the replacement's DACL is readable")
4461                    .description()
4462                    .to_string();
4463                assert_ne!(
4464                    dacl, base,
4465                    "write {round}: the account that owned what was replaced must stay granted \
4466                     explicitly, because a writer under another account takes `OW` with it"
4467                );
4468                if let Some(previous) = &previous {
4469                    assert_eq!(
4470                        &dacl, previous,
4471                        "write {round}: and the set must settle -- a DACL that keeps growing is \
4472                         an ACE per renewal, and one that shrinks back to the constant is the \
4473                         lockout returning"
4474                    );
4475                }
4476                previous = Some(dacl);
4477            }
4478
4479            assert_eq!(
4480                store
4481                    .load()
4482                    .expect("the replacement is readable")
4483                    .map(|secret| secret.expose_secret().to_string()),
4484                Some(other_token().expose_secret().to_string()),
4485                "carrying an ACE forward must not disturb what the store holds"
4486            );
4487        }
4488
4489        /// Denies *reading* the store, which is the state a renewal under a
4490        /// service account leaves an operator in, and puts the right back on
4491        /// every path out including an unwind.
4492        ///
4493        /// A deny ACE for `Everyone` binds administrators too, which is what
4494        /// makes this reproducible on CI's elevated runner as well as on an
4495        /// ordinary developer machine.
4496        struct DeniedRead {
4497            file: std::path::PathBuf,
4498            restored: bool,
4499        }
4500
4501        impl DeniedRead {
4502            fn new(file: &std::path::Path) -> Self {
4503                let denied = Self {
4504                    file: file.to_path_buf(),
4505                    restored: false,
4506                };
4507                icacls(&[&denied.file.display().to_string(), "/deny", "*S-1-1-0:(R)"]);
4508                denied
4509            }
4510
4511            fn restore(&mut self) {
4512                if self.restored {
4513                    return;
4514                }
4515                self.restored = true;
4516                let arguments = [
4517                    self.file.display().to_string(),
4518                    "/remove:d".into(),
4519                    "*S-1-1-0".into(),
4520                ];
4521                // Not asserted: this runs on the unwind path, where a panic
4522                // would replace a readable failure with an aborted process.
4523                match run_icacls(&arguments.each_ref().map(String::as_str)) {
4524                    Ok(output) if output.status.success() => {}
4525                    other => eprintln!(
4526                        "could not restore the ACL on {}: {other:?}",
4527                        self.file.display()
4528                    ),
4529                }
4530            }
4531        }
4532
4533        impl Drop for DeniedRead {
4534            fn drop(&mut self) {
4535                self.restore();
4536            }
4537        }
4538
4539        /// A store the operator may not read says how to get it back.
4540        ///
4541        /// Carrying the previous owner keeps this from *starting*, but it
4542        /// cannot end it on a host where it already happened: the file grants
4543        /// nobody but the service and has nothing left in its DACL to carry, so
4544        /// every renewal rebuilds the same DACL. Without a message the operator
4545        /// is told `Access is denied` by every command, forever, with no way to
4546        /// find out that one elevated `takeown` ends it.
4547        ///
4548        /// Watched on a real host on 2026-08-30, on 0.1.13, which had the carry
4549        /// and still could not read its own credential.
4550        #[test]
4551        fn a_store_this_account_may_not_read_names_the_command_that_gives_it_back() {
4552            let root = TempDir::new().expect("a temporary directory");
4553            let store = rooted(SecretScope::Machine, &root);
4554            store.store(&fixture_token()).expect("the first write");
4555
4556            let guard = store.guard();
4557            let _denied = DeniedRead::new(&guard);
4558
4559            let error = store
4560                .load()
4561                .expect_err("a store this account may not read is not a store it can load");
4562            let rendered = error.to_string();
4563
4564            for expected in ["icacls", "/grant", &guard.display().to_string(), "elevated"] {
4565                assert!(
4566                    rendered.contains(expected),
4567                    "the refusal must name the remedy and the file it applies to. Wanted \
4568                     {expected:?} in: {rendered}"
4569                );
4570            }
4571            assert!(
4572                !rendered.contains(fixture_token().expose_secret()),
4573                "and it must not carry the value it could not read"
4574            );
4575            assert!(
4576                rendered.contains("Do NOT use `takeown`"),
4577                "and it must warn off the repair that looks right and is not. Changing the \
4578                 owner makes Windows delete the OWNER RIGHTS ACE, so the account ends up \
4579                 owning a file it still cannot read -- permanently. Offered on a real host on \
4580                 2026-08-30, where it appeared to work only because the check that followed \
4581                 ran in the same elevated prompt. Got: {rendered}"
4582            );
4583        }
4584
4585        /// Finding 1: a second operator is refused with a remedy, before
4586        /// anything is written.
4587        ///
4588        /// The behaviour is right — one machine-scoped credential per host, and
4589        /// replacing it is an administrator's call; see the backend's module
4590        /// documentation for why widening the DACL is the wrong answer. What
4591        /// this pins is that the refusal *says so*, that it is classifiable as
4592        /// a permission problem, and that it leaves nothing on disk.
4593        #[test]
4594        fn a_second_operator_is_refused_with_a_remedy_and_writes_nothing() {
4595            let root = TempDir::new().expect("a temporary directory");
4596            let store = rooted(SecretScope::Machine, &root);
4597            store
4598                .store(&fixture_token())
4599                .expect("the first operator stores");
4600
4601            let guard = store.guard();
4602            let directory = guard
4603                .parent()
4604                .expect("the guard has a directory")
4605                .to_path_buf();
4606            let mut denied = DeniedReplace::new(&guard, &directory, AlsoDeny::Nothing);
4607
4608            let error = store
4609                .store(&other_token())
4610                .expect_err("a value this account may not replace is not a value it may store");
4611
4612            let rendered = error.to_string();
4613            for expected in [
4614                "one machine-scoped credential per host",
4615                "auth logout",
4616                "elevated",
4617                "--start-at login",
4618                "Nothing was written",
4619            ] {
4620                assert!(
4621                    rendered.contains(expected),
4622                    "the refusal does not name {expected:?}, so an operator cannot act on \
4623                     it: {rendered}"
4624                );
4625            }
4626            assert!(
4627                matches!(
4628                    &error,
4629                    SecretStoreError::Store { source, .. }
4630                        if source.kind() == std::io::ErrorKind::PermissionDenied
4631                ),
4632                "a caller cannot classify this as a permission problem: {error:?}"
4633            );
4634
4635            // Nothing was written, so the refusal did not also leave a valid
4636            // machine-decryptable blob of a live token under a name nobody
4637            // looks at. This is the half the old code got wrong: it found out
4638            // at the rename, after the blob was already on disk.
4639            let strays: Vec<_> = std::fs::read_dir(&directory)
4640                .expect("readable")
4641                .flatten()
4642                .map(|entry| entry.file_name().to_string_lossy().into_owned())
4643                .filter(|name| name.ends_with(".tmp"))
4644                .collect();
4645            assert!(strays.is_empty(), "a refused store left {strays:?}");
4646
4647            // And the first operator's value is untouched.
4648            denied.restore();
4649            assert_eq!(stored(&store), exposed(&fixture_token()));
4650
4651            // With the denial lifted, the same call succeeds -- which is what
4652            // makes the assertions above a statement about the denial rather
4653            // than about the store being broken.
4654            store
4655                .store(&other_token())
4656                .expect("stored once allowed again");
4657            assert_eq!(stored(&store), exposed(&other_token()));
4658        }
4659
4660        /// The ordering the fix is built around: the refusal is made **before**
4661        /// anything is encrypted or written.
4662        ///
4663        /// The test above cannot tell. The rename path re-derives the identical
4664        /// diagnosis — on `PermissionDenied` it calls `cannot_replace` itself —
4665        /// so moving the probe back behind the write leaves all five message
4666        /// assertions and the `kind()` assertion passing, and `discard` removes
4667        /// the temporary either way, so the `strays` assertion does not catch it
4668        /// either. The property stated at `store`'s call site and twice in the
4669        /// module documentation was asserted by nothing: the same shape as the
4670        /// zero fill that could be deleted with the suite staying green.
4671        ///
4672        /// [`AlsoDeny::Creation`] closes that. With `FILE_ADD_FILE` denied on
4673        /// the directory:
4674        ///
4675        /// - a probe that runs **first** still produces the remedy, because it
4676        ///   only reads the target's ACL, and nothing has been written;
4677        /// - a probe that runs **after** the write never runs at all, because
4678        ///   `create_protected_file` dies first with a bare denial that carries
4679        ///   no remedy in it.
4680        ///
4681        /// So this pins the ordering rather than the wording.
4682        #[test]
4683        fn the_refusal_is_made_before_anything_is_written() {
4684            let root = TempDir::new().expect("a temporary directory");
4685            let store = rooted(SecretScope::Machine, &root);
4686            store
4687                .store(&fixture_token())
4688                .expect("the first operator stores");
4689
4690            let guard = store.guard();
4691            let directory = guard
4692                .parent()
4693                .expect("the guard has a directory")
4694                .to_path_buf();
4695            let _denied = DeniedReplace::new(&guard, &directory, AlsoDeny::Creation);
4696
4697            let error = store
4698                .store(&other_token())
4699                .expect_err("nothing can be created here, so nothing can be stored");
4700
4701            let rendered = error.to_string();
4702            for expected in [
4703                "one machine-scoped credential per host",
4704                "auth logout",
4705                "elevated",
4706                "--start-at login",
4707                "Nothing was written",
4708            ] {
4709                assert!(
4710                    rendered.contains(expected),
4711                    "the refusal does not name {expected:?}. With creation denied, the only \
4712                     way to produce that text is a check that ran BEFORE the write -- so this \
4713                     message came from `create_protected_file` instead, and the store reached \
4714                     the write before it refused: {rendered}"
4715                );
4716            }
4717        }
4718
4719        /// Finding 3: the DPAPI output buffer is zeroed before it is freed.
4720        ///
4721        /// Asserted against a buffer Rust owns, because once `LocalFree` has
4722        /// run there is nothing left to look at. `copy_and_scrub` is the whole
4723        /// of what `take_blob` does to that buffer before freeing it, so this
4724        /// is the property and not a rehearsal of it.
4725        #[test]
4726        fn the_dpapi_buffer_is_scrubbed_before_it_is_freed() {
4727            let token = exposed(&fixture_token());
4728            let mut buffer = token.clone().into_bytes();
4729            let length = buffer.len();
4730
4731            // SAFETY: `buffer` is a live allocation of exactly `length` bytes
4732            // and nothing else refers to it for the duration of the call.
4733            let copy = unsafe { sys::copy_and_scrub(buffer.as_mut_ptr(), length) };
4734
4735            assert_eq!(
4736                copy,
4737                token.clone().into_bytes(),
4738                "the caller must still receive the value"
4739            );
4740            assert!(
4741                buffer.iter().all(|byte| *byte == 0),
4742                "the source buffer still holds the token after the copy, and on the \
4743                 unprotect path that buffer is handed back to the heap by LocalFree: \
4744                 {buffer:?}"
4745            );
4746        }
4747
4748        #[test]
4749        fn a_win32_error_keeps_its_kind_through_the_hresult_wrapper() {
4750            // ERROR_ACCESS_DENIED as windows-rs reports it: HRESULT 0x80070005.
4751            // Handed straight to `from_raw_os_error` this is `Uncategorized`,
4752            // and finding 1's refusal could not be classified by a caller.
4753            let denied = ::windows::core::Error::from_hresult(::windows::core::HRESULT(
4754                0x8007_0005_u32 as i32,
4755            ));
4756            assert_eq!(
4757                sys::io_error(&denied).kind(),
4758                std::io::ErrorKind::PermissionDenied
4759            );
4760
4761            // ERROR_FILE_NOT_FOUND, 0x80070002.
4762            let missing = ::windows::core::Error::from_hresult(::windows::core::HRESULT(
4763                0x8007_0002_u32 as i32,
4764            ));
4765            assert_eq!(sys::io_error(&missing).kind(), std::io::ErrorKind::NotFound);
4766        }
4767
4768        #[test]
4769        fn both_dacls_are_protected_and_name_no_broad_trustee() {
4770            for scope in [SecretScope::Machine, SecretScope::User] {
4771                let sddl = sys::sddl(scope);
4772                assert!(
4773                    sddl.starts_with("D:P"),
4774                    "an unprotected DACL inherits whatever %ProgramData% grants, which is \
4775                     Builtin Users read: {sddl}"
4776                );
4777                for broad in ["WD", "AU", "BU", "IU", "AN"] {
4778                    assert!(
4779                        !sddl.contains(&format!(";{broad})")),
4780                        "{scope}: {sddl} names the broad trustee {broad}"
4781                    );
4782                }
4783            }
4784        }
4785
4786        #[test]
4787        fn only_the_machine_dacl_carries_the_local_system_ace() {
4788            // `process.rs` argues at length that a `SY` ACE adds nothing to the
4789            // JIT handoff, and it is right there: that file's writer and reader
4790            // are one process. Here they are not -- `auth login` writes as the
4791            // operator and the daemon reads as the service account -- so `SY`
4792            // is load-bearing on the machine store and out of place on the
4793            // user store, which is deliberately not for a service.
4794            assert!(sys::sddl(SecretScope::Machine).contains("(A;;FA;;;SY)"));
4795            assert!(!sys::sddl(SecretScope::User).contains(";SY)"));
4796        }
4797
4798        #[test]
4799        fn the_dacl_on_disk_is_the_one_the_backend_asked_for() {
4800            let root = TempDir::new().expect("a temporary directory");
4801            for scope in [SecretScope::Machine, SecretScope::User] {
4802                let store = rooted(scope, &root);
4803                store.store(&fixture_token()).expect("stored");
4804
4805                let description = store.protection().expect("inspectable").description;
4806                assert!(
4807                    description.contains("D:P"),
4808                    "{scope}: the stored file did not keep its protected DACL: {description}"
4809                );
4810                assert!(
4811                    description.contains("FA;;;BA"),
4812                    "{scope}: an administrator must still be able to clean up: {description}"
4813                );
4814                // The one ACE that keeps a *non-administrative* operator able
4815                // to read back what they just stored. Nothing else in the DACL
4816                // names them, so if `CreateFileW` had quietly dropped it the
4817                // round trip would still pass on an administrator's machine and
4818                // fail on everybody else's.
4819                assert!(
4820                    description.contains(";OW)") || description.contains(";S-1-3-4)"),
4821                    "{scope}: the OWNER RIGHTS ACE did not survive to disk, so a \
4822                     non-administrative operator cannot read their own token: {description}"
4823                );
4824                if scope == SecretScope::Machine {
4825                    assert!(
4826                        description.contains("FA;;;SY"),
4827                        "a LocalSystem daemon must be able to read the machine store: \
4828                         {description}"
4829                    );
4830                }
4831            }
4832        }
4833
4834        #[test]
4835        fn the_bytes_on_disk_are_not_the_value() {
4836            let root = TempDir::new().expect("a temporary directory");
4837            let store = rooted(SecretScope::Machine, &root);
4838            store.store(&fixture_token()).expect("stored");
4839
4840            let blob = std::fs::read(store.guard()).expect("the blob is readable");
4841            let token = exposed(&fixture_token());
4842            assert!(
4843                !blob
4844                    .windows(token.len())
4845                    .any(|window| window == token.as_bytes()),
4846                "the DPAPI blob contains the plaintext token"
4847            );
4848        }
4849
4850        #[test]
4851        fn bytes_that_are_not_a_blob_are_reported_as_corrupt() {
4852            let root = TempDir::new().expect("a temporary directory");
4853            let store = rooted(SecretScope::Machine, &root);
4854            store.store(&fixture_token()).expect("stored");
4855
4856            // A blob truncated by an interrupted write, or one written by
4857            // another machine and copied here. Either way DPAPI refuses it, and
4858            // the caller must be told to purge rather than to retry.
4859            std::fs::write(store.guard(), b"this is not a DPAPI blob").expect("planted");
4860            let error = store.load().expect_err("a foreign blob is not a value");
4861            assert!(
4862                matches!(error, SecretStoreError::Corrupt { .. }),
4863                "got {error:?}"
4864            );
4865        }
4866    }
4867
4868    // -----------------------------------------------------------------------
4869    // Unix -- the mode bits, on both Unixes
4870    // -----------------------------------------------------------------------
4871
4872    #[cfg(unix)]
4873    mod unix {
4874        use super::*;
4875
4876        use std::os::unix::fs::PermissionsExt as _;
4877
4878        fn mode_of(path: &std::path::Path) -> u32 {
4879            std::fs::metadata(path)
4880                .unwrap_or_else(|error| panic!("{} is not there: {error}", path.display()))
4881                .permissions()
4882                .mode()
4883                & 0o777
4884        }
4885
4886        /// Asked before anything irreversible, so it has to agree with what a
4887        /// write would meet -- in both directions.
4888        #[test]
4889        fn ensure_writable_refuses_exactly_when_the_store_directory_is_not_writable() {
4890            // SAFETY: `geteuid` reads this process's own credentials, takes no
4891            // pointer, and cannot fail.
4892            if unsafe { libc::geteuid() } == 0 {
4893                // Modes refuse nobody running as root, so the refusal half
4894                // cannot be staged here.
4895                return;
4896            }
4897            for scope in [SecretScope::Machine, SecretScope::User] {
4898                let root = TempDir::new().expect("a temporary directory");
4899                let store = rooted(scope, &root);
4900                store
4901                    .ensure_writable()
4902                    .unwrap_or_else(|error| panic!("{scope}: nothing written yet: {error}"));
4903                store.store(&fixture_token()).expect("stored");
4904                store
4905                    .ensure_writable()
4906                    .unwrap_or_else(|error| panic!("{scope}: the writer's own store: {error}"));
4907
4908                let guard = store.guard();
4909                let directory = guard.parent().expect("the guard has a directory");
4910                std::fs::set_permissions(directory, std::fs::Permissions::from_mode(0o500))
4911                    .expect("the directory is made read-only");
4912                let refusal = store.ensure_writable();
4913                // A new entry beside the store, which is what both backends'
4914                // replacing write creates first. Not `store` itself: the Linux
4915                // backend re-applies `0700` to a directory this test's account
4916                // owns, so it would undo the staging rather than meet it. The
4917                // production case -- a directory another account owns -- is
4918                // one no chmod of ours can repair.
4919                let write = std::fs::File::create(directory.join("probe.tmp"));
4920                std::fs::set_permissions(directory, std::fs::Permissions::from_mode(0o700))
4921                    .expect("the directory is restored for cleanup");
4922
4923                let refusal = refusal.expect_err("a read-only directory refuses a write");
4924                assert!(
4925                    matches!(
4926                        &refusal,
4927                        SecretStoreError::Store { source, .. }
4928                            if source.kind() == std::io::ErrorKind::PermissionDenied
4929                    ),
4930                    "{scope}: got {refusal:?}"
4931                );
4932                assert!(
4933                    write.is_err(),
4934                    "{scope}: the check refused an entry the directory then accepted"
4935                );
4936            }
4937        }
4938
4939        #[test]
4940        fn the_guard_is_0600_and_its_directory_is_0700() {
4941            for scope in [SecretScope::Machine, SecretScope::User] {
4942                let root = TempDir::new().expect("a temporary directory");
4943                let store = rooted(scope, &root);
4944                store.store(&fixture_token()).expect("stored");
4945
4946                let guard = store.guard();
4947                assert_eq!(
4948                    mode_of(&guard),
4949                    0o600,
4950                    "{scope}: {} is not 0600",
4951                    guard.display()
4952                );
4953                let directory = guard.parent().expect("the guard has a directory");
4954                assert_eq!(
4955                    mode_of(directory),
4956                    0o700,
4957                    "{scope}: {} is not 0700",
4958                    directory.display()
4959                );
4960            }
4961        }
4962    }
4963
4964    // -----------------------------------------------------------------------
4965    // Linux -- systemd credentials
4966    // -----------------------------------------------------------------------
4967
4968    #[cfg(all(unix, not(target_os = "macos")))]
4969    mod linux {
4970        use super::*;
4971
4972        use std::os::unix::fs::PermissionsExt as _;
4973
4974        /// Writes `bytes` where systemd would have put a credential.
4975        fn plant_credential(directory: &std::path::Path, bytes: &[u8]) -> std::path::PathBuf {
4976            std::fs::create_dir_all(directory).expect("the credentials directory");
4977            let path = directory.join(SYSTEMD_CREDENTIAL);
4978            std::fs::write(&path, bytes).expect("the credential is written");
4979            // systemd mounts the credentials directory read-only and gives each
4980            // credential 0400. Reproduced so that the protection assertion sees
4981            // what production would.
4982            std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o400))
4983                .expect("the credential is tightened");
4984            path
4985        }
4986
4987        #[test]
4988        fn a_systemd_credential_is_read_in_preference_to_the_file() {
4989            let root = TempDir::new().expect("a temporary directory");
4990            let credentials = TempDir::new().expect("a credentials directory");
4991
4992            // The file first, so that reading the credential is a preference
4993            // rather than the only thing there is to read.
4994            let plain = rooted(SecretScope::Machine, &root);
4995            plain.store(&other_token()).expect("stored");
4996
4997            plant_credential(credentials.path(), exposed(&fixture_token()).as_bytes());
4998            let store =
4999                rooted(SecretScope::Machine, &root).with_credentials_directory(credentials.path());
5000
5001            assert_eq!(
5002                stored(&store),
5003                exposed(&fixture_token()),
5004                "a unit given LoadCredentialEncrypted= must not be overridden by a stale file"
5005            );
5006            assert_eq!(
5007                store.credential_path(),
5008                Some(credentials.path().join(SYSTEMD_CREDENTIAL).as_path())
5009            );
5010            assert!(
5011                store.location().contains("systemd credential"),
5012                "`host show` must say where the value is actually coming from: {}",
5013                store.location()
5014            );
5015        }
5016
5017        /// Finding 6, end to end: what an operator's `systemd-creds encrypt`
5018        /// actually produces.
5019        ///
5020        /// `echo`, `printf '%s\n'` and every text editor leave a newline. Used
5021        /// byte for byte it becomes part of the token and fails much later
5022        /// inside an `Authorization` header, where it reads as a bad credential
5023        /// rather than as a bad read — which is the failure this pins.
5024        #[test]
5025        fn a_credential_written_with_a_trailing_newline_yields_the_token_without_it() {
5026            let root = TempDir::new().expect("a temporary directory");
5027            let credentials = TempDir::new().expect("a credentials directory");
5028            let token = exposed(&fixture_token());
5029
5030            plant_credential(credentials.path(), format!("{token}\n").as_bytes());
5031            let store =
5032                rooted(SecretScope::Machine, &root).with_credentials_directory(credentials.path());
5033
5034            assert_eq!(stored(&store), token);
5035        }
5036
5037        /// The file half of the same decision, which must *not* be trimmed.
5038        ///
5039        /// `store` writes no newline, so anything trailing in its own file is
5040        /// corruption rather than formatting, and repairing it silently would
5041        /// hide the one thing `Corrupt` exists to report.
5042        #[test]
5043        fn the_stores_own_file_is_read_back_verbatim() {
5044            let root = TempDir::new().expect("a temporary directory");
5045            let store = rooted(SecretScope::Machine, &root);
5046            store.store(&fixture_token()).expect("stored");
5047
5048            let token = exposed(&fixture_token());
5049            std::fs::write(store.guard(), format!("{token}\n")).expect("planted");
5050
5051            assert_eq!(
5052                stored(&store),
5053                format!("{token}\n"),
5054                "the store's own file is used verbatim; only a systemd credential is trimmed"
5055            );
5056        }
5057
5058        #[test]
5059        fn a_credentials_directory_without_this_credential_falls_back_to_the_file() {
5060            let root = TempDir::new().expect("a temporary directory");
5061            let credentials = TempDir::new().expect("a credentials directory");
5062
5063            let plain = rooted(SecretScope::Machine, &root);
5064            plain.store(&fixture_token()).expect("stored");
5065
5066            // A unit can be given credentials without being given this one.
5067            std::fs::write(credentials.path().join("something.else"), b"x").expect("written");
5068            let store =
5069                rooted(SecretScope::Machine, &root).with_credentials_directory(credentials.path());
5070
5071            assert_eq!(stored(&store), exposed(&fixture_token()));
5072        }
5073
5074        #[test]
5075        fn the_credential_is_what_protection_inspects_when_there_is_one() {
5076            let root = TempDir::new().expect("a temporary directory");
5077            let credentials = TempDir::new().expect("a credentials directory");
5078            let planted =
5079                plant_credential(credentials.path(), exposed(&fixture_token()).as_bytes());
5080
5081            let store =
5082                rooted(SecretScope::Machine, &root).with_credentials_directory(credentials.path());
5083            let protection = store.protection().expect("inspectable");
5084
5085            assert_eq!(protection.guard(), planted);
5086            assert!(!protection.readable_by_other_local_users(), "{protection}");
5087        }
5088
5089        #[test]
5090        fn storing_under_a_systemd_credential_is_refused_rather_than_shadowed() {
5091            let root = TempDir::new().expect("a temporary directory");
5092            let credentials = TempDir::new().expect("a credentials directory");
5093            plant_credential(credentials.path(), exposed(&fixture_token()).as_bytes());
5094
5095            // The same site without the credential, so the test can name the
5096            // file the refusal must not have written.
5097            let file = rooted(SecretScope::Machine, &root).guard();
5098
5099            let store =
5100                rooted(SecretScope::Machine, &root).with_credentials_directory(credentials.path());
5101            let error = store
5102                .store(&other_token())
5103                .expect_err("a write that the next read would ignore is not a write");
5104            let rendered = error.to_string();
5105            assert!(rendered.contains(SYSTEMD_CREDENTIAL), "{rendered}");
5106
5107            // And nothing was written, so the refusal did not also leave a
5108            // second copy of a token on disk.
5109            assert!(!file.exists(), "{} was written anyway", file.display());
5110        }
5111
5112        #[test]
5113        fn purging_under_a_systemd_credential_removes_the_file_and_reports_the_remainder() {
5114            let root = TempDir::new().expect("a temporary directory");
5115            let credentials = TempDir::new().expect("a credentials directory");
5116
5117            let plain = rooted(SecretScope::Machine, &root);
5118            plain.store(&other_token()).expect("stored");
5119            let file = plain.guard();
5120            plant_credential(credentials.path(), exposed(&fixture_token()).as_bytes());
5121
5122            let store =
5123                rooted(SecretScope::Machine, &root).with_credentials_directory(credentials.path());
5124            let error = store
5125                .delete()
5126                .expect_err("this host is not purged and `auth logout` must not say it is");
5127
5128            assert!(!file.exists(), "the file it could remove was removed");
5129            assert!(
5130                error.to_string().contains(SYSTEMD_CREDENTIAL),
5131                "the operator has to be told what is still supplying a token: {error}"
5132            );
5133        }
5134
5135        #[test]
5136        #[serial_test::serial]
5137        fn the_standard_machine_store_reads_the_credentials_directory_from_the_environment() {
5138            let credentials = TempDir::new().expect("a credentials directory");
5139
5140            // SAFETY: `serial_test` guarantees no other test in this binary is
5141            // running, and this is the only test that touches this variable.
5142            unsafe {
5143                std::env::set_var(CREDENTIALS_DIRECTORY, credentials.path());
5144            }
5145            let store = PlatformSecretStore::standard(SecretScope::Machine).expect("resolves");
5146            let resolved = store.credential_path().map(std::path::Path::to_path_buf);
5147
5148            // SAFETY: as above.
5149            unsafe {
5150                std::env::remove_var(CREDENTIALS_DIRECTORY);
5151            }
5152
5153            assert_eq!(
5154                resolved,
5155                Some(credentials.path().join(SYSTEMD_CREDENTIAL)),
5156                "a daemon started by systemd gets its credential without being told to"
5157            );
5158
5159            let without = PlatformSecretStore::standard(SecretScope::Machine).expect("resolves");
5160            assert_eq!(
5161                without.credential_path(),
5162                None,
5163                "a daemon started by anything else must not invent one"
5164            );
5165        }
5166
5167        #[test]
5168        fn a_user_scoped_store_never_consults_a_service_credential() {
5169            let store = PlatformSecretStore::standard(SecretScope::User).expect("resolves");
5170            assert_eq!(store.credential_path(), None);
5171        }
5172    }
5173}