Skip to main content

khive_runtime/daemon/
run_daemon.rs

1#![cfg(unix)]
2use super::*;
3
4#[cfg(test)]
5pub(super) static DEFAULT_RENDEZVOUS_PREBIND_HOOK: std::sync::Mutex<
6    Option<Box<dyn FnOnce() + Send>>,
7> = std::sync::Mutex::new(None);
8
9/// Run the daemon: bind the socket, warm in the background, serve request
10/// frames until SIGTERM/SIGINT.
11///
12/// Fatally acquires its own startup lock, which only protects
13/// cleanup→pid-claim→bind — `dispatcher` has already run migrations and
14/// applied pack schema plans while constructing itself, unguarded. Production
15/// boot must go through [`run_daemon_with_boot_guard`] instead, which extends
16/// the same lock back over construction. This entry point is for callers
17/// (and tests) that build the dispatcher and start serving as one atomic
18/// step with no separate boot-guard window to protect.
19#[cfg(unix)]
20pub async fn run_daemon<D: DaemonDispatch>(dispatcher: D) -> anyhow::Result<()> {
21    let boot_guard = Some(acquire_daemon_boot_guard()?);
22    run_daemon_with_boot_guard_inner(
23        dispatcher,
24        boot_guard,
25        false,
26        DaemonOptions::default(),
27        |_| DaemonStartupReport::default(),
28    )
29    .await
30}
31
32/// Run a real daemon server for an in-process multi-launch test.
33///
34/// Separate production daemon candidates have distinct PIDs, so the boot fence
35/// recognizes a live incumbent and makes later candidates exit. Parallel
36/// test launchers share one OS process and therefore one PID; this explicit
37/// fault-injection entry point preserves the production fence semantics by
38/// allowing a live same-PID incumbent to win. Ordinary daemon startup
39/// continues to treat a same-PID rendezvous as stale, protecting PID-reuse
40/// cleanup behavior.
41///
42/// A losing candidate still follows the ordinary daemon-exit path and cancels
43/// the process-wide component shutdown token. Callers must therefore use a
44/// component-free dispatcher; this seam validates socket/PID ownership, not
45/// multi-candidate component lifecycle.
46#[cfg(all(unix, any(test, feature = "fault-injection")))]
47#[doc(hidden)]
48pub async fn run_daemon_in_process_test<D: DaemonDispatch>(dispatcher: D) -> anyhow::Result<()> {
49    let boot_guard = Some(acquire_daemon_boot_guard()?);
50    run_daemon_with_boot_guard_inner(
51        dispatcher,
52        boot_guard,
53        true,
54        DaemonOptions::default(),
55        |_| DaemonStartupReport::default(),
56    )
57    .await
58}
59
60#[cfg(unix)]
61#[derive(Clone, Copy, PartialEq, Eq)]
62pub(super) enum RendezvousPathRole<'a> {
63    Socket,
64    PidFile,
65    Store(&'a std::path::Path),
66}
67
68#[cfg(unix)]
69impl RendezvousPathRole<'_> {
70    pub(super) fn refusal(
71        self,
72        rendezvous: std::fmt::Arguments<'_>,
73        store: std::fmt::Arguments<'_>,
74    ) -> anyhow::Error {
75        match self {
76            Self::Store(db_path) => anyhow::anyhow!(
77                "refusing to open events database {}: {store}. Check the offending directory's \
78                 ownership and permissions (remove group/other write access), or move the store \
79                 to a location trusted end to end. Only the first offending component is \
80                 reported; further untrusted ancestors or components may remain.",
81                db_path.display()
82            ),
83            Self::Socket | Self::PidFile => anyhow::anyhow!("{rendezvous}"),
84        }
85    }
86
87    pub(super) fn env_name(self) -> &'static str {
88        match self {
89            Self::Socket => SOCKET_PATH_ENV,
90            Self::PidFile => PID_PATH_ENV,
91            Self::Store(_) => "events database",
92        }
93    }
94
95    pub(super) fn directory_name(self) -> &'static str {
96        match self {
97            Self::Socket => "socket directory",
98            Self::PidFile => "PID-file directory",
99            Self::Store(_) => "store directory",
100        }
101    }
102
103    pub(super) fn path_name(self) -> &'static str {
104        match self {
105            Self::Socket => "socket path",
106            Self::PidFile => "PID-file path",
107            Self::Store(_) => "store path",
108        }
109    }
110
111    pub(super) fn path_component_name(self) -> &'static str {
112        match self {
113            Self::Socket => "socket-path",
114            Self::PidFile => "PID-file-path",
115            Self::Store(_) => "store-path",
116        }
117    }
118}
119
120/// Vet the socket's parent directory, re-permissioning it only when it is the
121/// directory khive owns by convention.
122///
123/// `KHIVE_SOCKET` takes an arbitrary path, and the previous unconditional
124/// chmod-0700 of its parent was wrong in both directions: pointed at a shared
125/// parent like `/tmp` it either failed outright for an ordinary user, or —
126/// worse — succeeded when privileged and stripped access for every other
127/// process on the machine. A directory we did not create is never modified.
128///
129/// What the directory must actually prevent is a *takeover of the socket
130/// path*: the connection gate is the 0600 socket plus the accept-time
131/// peer-uid check, but both defend the daemon's own socket — neither helps
132/// once another local user can put *their* listener at the path clients
133/// resolve. There are two ways a shared directory allows that, and the
134/// sticky bit closes neither: a writer can *pre-bind* the predictable path
135/// before this daemon starts (the sticky bit restricts unlinking, not
136/// creating), and the directory's *owner* can unlink and rebind even in a
137/// 1777 directory (sticky exempts the directory owner). So a caller-chosen
138/// directory is served only when it is trusted end to end: owned by this
139/// daemon's euid or root, and not writable by group or other at all. The
140/// umask-default 0755 stays acceptable; shared sticky directories like
141/// `/tmp` do not.
142#[cfg(unix)]
143pub(crate) fn ensure_socket_dir_is_trusted(parent: &std::path::Path) -> anyhow::Result<()> {
144    // SAFETY: `geteuid` is always successful and takes no arguments.
145    let daemon_euid = unsafe { libc::geteuid() } as u32;
146    let default_rendezvous = super::lifecycle::path_override(SOCKET_PATH_ENV).is_none()
147        && super::lifecycle::path_override(PID_PATH_ENV).is_none();
148    ensure_rendezvous_dir_is_trusted(
149        parent,
150        RendezvousPathRole::Socket,
151        daemon_euid,
152        default_rendezvous,
153    )
154}
155
156/// Apply the existing directory trust and default-root repair rules to an events store.
157#[cfg(unix)]
158pub(crate) fn ensure_store_dir_is_trusted(
159    parent: &std::path::Path,
160    db_path: &std::path::Path,
161) -> anyhow::Result<()> {
162    // SAFETY: `geteuid` is always successful and takes no arguments.
163    let daemon_euid = unsafe { libc::geteuid() } as u32;
164    ensure_rendezvous_dir_is_trusted(
165        parent,
166        RendezvousPathRole::Store(db_path),
167        daemon_euid,
168        true,
169    )
170}
171
172/// Vet the parent directory of a PID file before reading, locking, or writing
173/// it. The file's lock only protects the inode currently named by its path;
174/// every directory component must therefore be as swap-resistant as the
175/// socket rendezvous.
176#[cfg(unix)]
177pub fn ensure_pid_file_dir_is_trusted(pid_file: &std::path::Path) -> anyhow::Result<()> {
178    let parent = pid_file
179        .parent()
180        .filter(|parent| !parent.as_os_str().is_empty())
181        .unwrap_or_else(|| std::path::Path::new("."));
182    // SAFETY: `geteuid` is always successful and takes no arguments.
183    let daemon_euid = unsafe { libc::geteuid() } as u32;
184    ensure_rendezvous_dir_is_trusted(parent, RendezvousPathRole::PidFile, daemon_euid, false)
185}
186
187/// Secure the default rendezvous directory during a mutating recovery attempt.
188/// Read-only daemon probes must use `ensure_pid_file_dir_is_trusted` instead.
189#[cfg(unix)]
190pub fn prepare_default_rendezvous_for_recovery() -> anyhow::Result<()> {
191    let explicit_rendezvous = super::lifecycle::path_override(PID_PATH_ENV).is_some()
192        || super::lifecycle::path_override(SOCKET_PATH_ENV).is_some();
193    let parent = khive_dir();
194    let mut marker_lock = supervisor_marker_path().into_os_string();
195    marker_lock.push(".lock");
196    let locks = [
197        lock_path(),
198        recoverer_lock_path(),
199        std::path::PathBuf::from(marker_lock),
200    ];
201    for lock in &locks {
202        if lock.file_name().is_none() {
203            anyhow::bail!(
204                "refusing recovery lock {} without a filename",
205                lock.display()
206            );
207        }
208    }
209    if explicit_rendezvous
210        && !locks
211            .iter()
212            .any(|lock| lock.parent() == Some(parent.as_path()))
213    {
214        return Ok(());
215    }
216    if !prepare_default_rendezvous_directory()? {
217        return Ok(());
218    }
219    // SAFETY: `geteuid` is always successful and takes no arguments.
220    let daemon_euid = unsafe { libc::geteuid() } as u32;
221    for lock in locks {
222        if lock.parent() == Some(parent.as_path()) {
223            tighten_owned_recovery_lock(&lock, daemon_euid)?;
224        }
225    }
226    Ok(())
227}
228
229/// Prepare the default parent only when this particular recovery lock needs it.
230#[cfg(unix)]
231pub fn prepare_default_rendezvous_for_lock(lock: &std::path::Path) -> anyhow::Result<()> {
232    let parent = khive_dir();
233    if lock.parent() != Some(parent.as_path()) {
234        return Ok(());
235    }
236    if lock.file_name().is_none() {
237        anyhow::bail!(
238            "refusing recovery lock {} without a filename",
239            lock.display()
240        );
241    }
242    if prepare_default_rendezvous_directory()? {
243        // SAFETY: `geteuid` is always successful and takes no arguments.
244        let daemon_euid = unsafe { libc::geteuid() } as u32;
245        tighten_owned_recovery_lock(lock, daemon_euid)?;
246    }
247    Ok(())
248}
249
250/// Prepare the default directory without touching any lock in it.
251#[cfg(unix)]
252pub(super) fn prepare_default_rendezvous_directory() -> anyhow::Result<bool> {
253    use std::os::unix::fs::DirBuilderExt;
254
255    let explicit_rendezvous = super::lifecycle::path_override(PID_PATH_ENV).is_some()
256        || super::lifecycle::path_override(SOCKET_PATH_ENV).is_some();
257    let parent = khive_dir();
258    // An explicitly selected rendezvous is not ours to repair. If a default
259    // lock still needs this parent, create it only when absent; an existing
260    // parent must already pass the normal trust checks at the checked opener.
261    if explicit_rendezvous {
262        if let Ok(metadata) = std::fs::symlink_metadata(&parent) {
263            use std::os::unix::fs::MetadataExt;
264            // SAFETY: geteuid takes no arguments and always succeeds.
265            let uid = unsafe { libc::geteuid() } as u32;
266            if metadata.is_dir() && metadata.uid() == uid && metadata.mode() & 0o7777 == 0 {
267                anyhow::bail!("cannot access default lock directory {} (mode 0000); verify ownership and set this directory to mode 0700 by hand, then retry", parent.display());
268            }
269            return Ok(false);
270        }
271    }
272    // SAFETY: `geteuid` is always successful and takes no arguments.
273    let daemon_euid = unsafe { libc::geteuid() } as u32;
274    let ancestors = parent
275        .parent()
276        .filter(|path| !path.as_os_str().is_empty())
277        .unwrap_or_else(|| std::path::Path::new("."));
278    ensure_rendezvous_path_is_swap_resistant(ancestors, daemon_euid, RendezvousPathRole::PidFile)?;
279    let mut builder = std::fs::DirBuilder::new();
280    builder.mode(0o700);
281    let created = match builder.create(&parent) {
282        Ok(()) => true,
283        Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists && explicit_rendezvous => {
284            return Ok(false)
285        }
286        Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => false,
287        Err(error) => {
288            return Err(anyhow::anyhow!(
289                "refusing to inspect default rendezvous directory {}: {error}",
290                parent.display()
291            ))
292        }
293    };
294    repair_default_dir_with_recovery_guidance(&parent, daemon_euid, created)?;
295
296    Ok(true)
297}
298
299#[cfg(unix)]
300fn repair_default_dir_with_recovery_guidance(
301    parent: &std::path::Path,
302    daemon_euid: u32,
303    created: bool,
304) -> anyhow::Result<()> {
305    use std::os::unix::fs::MetadataExt;
306    repair_owned_default_dir(parent, RendezvousPathRole::PidFile, daemon_euid).map_err(|error| {
307        let owned_inaccessible = std::fs::symlink_metadata(parent).is_ok_and(|metadata| {
308            metadata.is_dir() && metadata.uid() == daemon_euid && metadata.mode() & 0o7777 == 0
309        });
310        if owned_inaccessible {
311            let context = if created { "newly created" } else { "existing" };
312            anyhow::anyhow!(
313                "failed to prepare {context} default directory {}: {error:#}; verify ownership and set this directory to mode 0700 by hand, then retry",
314                parent.display()
315            )
316        } else {
317            error
318        }
319    })
320}
321
322#[cfg(unix)]
323fn tighten_owned_recovery_lock(lock: &std::path::Path, daemon_euid: u32) -> anyhow::Result<()> {
324    tighten_owned_recovery_lock_with_hook(lock, daemon_euid, || {})
325}
326
327#[cfg(unix)]
328fn tighten_owned_recovery_lock_with_hook(
329    lock: &std::path::Path,
330    daemon_euid: u32,
331    after_validation: impl FnOnce(),
332) -> anyhow::Result<()> {
333    use std::os::unix::fs::MetadataExt;
334
335    let observed = match std::fs::symlink_metadata(lock) {
336        Ok(metadata) => metadata,
337        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
338        Err(error) => anyhow::bail!("cannot inspect recovery lock {}: {error}", lock.display()),
339    };
340    let mode = observed.permissions().mode() & 0o7777;
341    if !observed.is_file() || observed.uid() != daemon_euid || observed.nlink() != 1 {
342        anyhow::bail!(
343            "refusing recovery lock {}: expected a single-link regular file owned by uid {daemon_euid}, found uid {} and mode {mode:04o}",
344            lock.display(),
345            observed.uid()
346        );
347    }
348    super::locks::checked_open_lock_with_hooks(lock, false, false, true, || {}, after_validation)?
349        .ok_or_else(|| anyhow::anyhow!("recovery lock {} disappeared", lock.display()))?;
350    Ok(())
351}
352
353#[cfg(unix)]
354fn repair_owned_default_dir(
355    parent: &std::path::Path,
356    role: RendezvousPathRole<'_>,
357    daemon_euid: u32,
358) -> anyhow::Result<()> {
359    repair_owned_default_dir_with_hooks(parent, role, daemon_euid, || {}, || {})
360}
361
362#[cfg(unix)]
363fn repair_owned_default_dir_with_hooks(
364    parent: &std::path::Path,
365    role: RendezvousPathRole<'_>,
366    daemon_euid: u32,
367    before_open: impl FnOnce(),
368    after_validation: impl FnOnce(),
369) -> anyhow::Result<()> {
370    use std::os::unix::fs::{MetadataExt, OpenOptionsExt};
371
372    let ancestors = parent
373        .parent()
374        .filter(|path| !path.as_os_str().is_empty())
375        .unwrap_or_else(|| std::path::Path::new("."));
376    ensure_rendezvous_path_is_swap_resistant(ancestors, daemon_euid, role)?;
377
378    let observed = std::fs::symlink_metadata(parent).map_err(|error| {
379        anyhow::anyhow!(
380            "refusing to stat default rendezvous directory {}: {error}",
381            parent.display()
382        )
383    })?;
384    let observed_mode = observed.permissions().mode() & 0o7777;
385    if !observed.is_dir() {
386        anyhow::bail!(
387            "refusing non-directory or symlink default rendezvous path {} (mode {observed_mode:04o})",
388            parent.display()
389        );
390    }
391    before_open();
392    // The metadata check and permission change operate on this exact opened
393    // directory; opening the leaf with NOFOLLOW refuses a symlink.
394    let directory = std::fs::OpenOptions::new()
395        .read(true)
396        .custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW)
397        .open(parent)
398        .map_err(|error| anyhow::anyhow!(
399            "refusing to open default rendezvous directory {} (observed mode {observed_mode:04o}) without following a symlink: {error}",
400            parent.display()
401        ))?;
402    let metadata = directory.metadata().map_err(|error| {
403        anyhow::anyhow!(
404            "refusing to stat default rendezvous directory {}: {error}",
405            parent.display()
406        )
407    })?;
408    if observed.dev() != metadata.dev() || observed.ino() != metadata.ino() {
409        anyhow::bail!(
410            "default rendezvous directory {} changed before it was opened",
411            parent.display()
412        );
413    }
414    let mode = metadata.permissions().mode() & 0o7777;
415    if !metadata.is_dir() || metadata.uid() != daemon_euid {
416        anyhow::bail!(
417            "refusing to repair default rendezvous directory {}: owner uid {}, mode {mode:04o}; expected uid {daemon_euid}",
418            parent.display(),
419            metadata.uid()
420        );
421    }
422    after_validation();
423    let latest = directory.metadata().map_err(|error| {
424        anyhow::anyhow!(
425            "refusing to restat default rendezvous directory {}: {error}",
426            parent.display()
427        )
428    })?;
429    let latest_mode = latest.permissions().mode() & 0o7777;
430    if !latest.is_dir() || latest.uid() != daemon_euid {
431        anyhow::bail!(
432            "refusing to repair default rendezvous directory {}: owner uid {}, mode {latest_mode:04o}; expected uid {daemon_euid}",
433            parent.display(),
434            latest.uid()
435        );
436    }
437    // The daemon creates its lock, pid and socket files here, so the owner keeps
438    // full access and every other bit is cleared.
439    let tightened = 0o700;
440    if tightened != latest_mode {
441        directory
442            .set_permissions(std::fs::Permissions::from_mode(tightened))
443            .map_err(|error| anyhow::anyhow!(
444                "refusing to tighten default rendezvous directory {} from mode {latest_mode:04o}: {error}",
445                parent.display()
446            ))?;
447    }
448    let current = std::fs::symlink_metadata(parent).map_err(|error| {
449        anyhow::anyhow!(
450            "refusing changed default rendezvous directory {}: {error}",
451            parent.display()
452        )
453    })?;
454    if !current.is_dir() || metadata.dev() != current.dev() || metadata.ino() != current.ino() {
455        anyhow::bail!(
456            "default rendezvous directory {} changed during repair",
457            parent.display()
458        );
459    }
460    ensure_rendezvous_path_is_swap_resistant(parent, daemon_euid, role)
461}
462
463#[cfg(unix)]
464pub(super) fn ensure_rendezvous_dir_is_trusted(
465    parent: &std::path::Path,
466    role: RendezvousPathRole<'_>,
467    daemon_euid: u32,
468    repair_owned_default: bool,
469) -> anyhow::Result<()> {
470    let env_name = role.env_name();
471    let directory_name = role.directory_name();
472
473    if repair_owned_default && parent == khive_dir() {
474        return repair_owned_default_dir(parent, role, daemon_euid).map_err(|error| {
475            role.refusal(
476                format_args!("{error:#}"),
477                format_args!(
478                    "cannot safely repair default store directory {}: {error:#}",
479                    parent.display()
480                ),
481            )
482        });
483    }
484
485    // Fail closed on the stat itself: not being able to read the metadata is
486    // not the same as the directory passing.
487    let meta = std::fs::metadata(parent).map_err(|e| {
488        role.refusal(
489            format_args!(
490                "refusing to start: cannot stat {directory_name} {} for {env_name}: {e}. \
491             It gates rendezvous-path safety, and unreadable metadata is not a passing state.",
492                parent.display()
493            ),
494            format_args!(
495                "cannot stat store directory {}: {e}; unreadable metadata is not a passing state",
496                parent.display()
497            ),
498        )
499    })?;
500
501    use std::os::unix::fs::MetadataExt;
502    let owner = meta.uid();
503    if owner != daemon_euid && owner != 0 {
504        return Err(role.refusal(
505            format_args!(
506                "refusing to start: {directory_name} {} for {env_name} is owned by uid {owner}, \
507             not this daemon's uid ({daemon_euid}) or root. A directory owner can replace \
508             the rendezvous path regardless of mode bits. Point {env_name} at a directory \
509             you own, or unset it for the default.",
510                parent.display()
511            ),
512            format_args!(
513                "store directory {} is owned by uid {owner}, not this process's uid \
514                 ({daemon_euid}) or root; its owner can replace the database path",
515                parent.display()
516            ),
517        ));
518    }
519
520    let mode = meta.permissions().mode();
521    if mode & 0o022 != 0 {
522        if role == RendezvousPathRole::PidFile
523            && super::lifecycle::path_override(PID_PATH_ENV).is_none()
524            && parent == khive_dir()
525        {
526            anyhow::bail!(
527                "refusing to start: default PID-file directory {} is mode {:04o} — writable by group or other",
528                parent.display(),
529                mode & 0o7777
530            );
531        }
532        return Err(role.refusal(
533            format_args!(
534                "refusing to start: {directory_name} {} for {env_name} is mode {:04o} — writable \
535             by group or other, so another local user could replace the rendezvous path. \
536             Use a directory only you can write, or unset {env_name} for the default. \
537             This daemon is not changing the permissions of a directory it does not own.",
538                parent.display(),
539                mode & 0o7777
540            ),
541            format_args!(
542                "store directory {} is mode {:04o}, writable by group or other, so another local \
543                 user could replace the database path",
544                parent.display(),
545                mode & 0o7777
546            ),
547        ));
548    }
549
550    ensure_rendezvous_path_is_swap_resistant(parent, daemon_euid, role)
551}
552
553/// Socket-role form of [`ensure_rendezvous_path_is_swap_resistant`], used by the
554/// socket-path tests.
555#[cfg(all(unix, test))]
556pub(super) fn ensure_socket_path_is_swap_resistant(
557    parent: &std::path::Path,
558    daemon_euid: u32,
559) -> anyhow::Result<()> {
560    ensure_rendezvous_path_is_swap_resistant(parent, daemon_euid, RendezvousPathRole::Socket)
561}
562
563/// Walk the socket directory path exactly as the kernel will traverse it at
564/// bind time — component by component, following symlinks — and refuse any
565/// node another local user could swap after this validation.
566///
567/// Checking only the canonicalized result is not enough: bind and every
568/// client traverse the *original* path, so a symlink component owned by
569/// another user can resolve somewhere trusted while it is being validated
570/// and be retargeted before the socket is bound. Validating the nodes the
571/// traversal actually visits closes that gap: a symlink component is
572/// acceptable only when its owner — the only party besides root who can
573/// retarget it — is this daemon's euid or root, and every directory
574/// component is held to the ancestor rule below.
575///
576/// The directory rule is deliberately weaker than the immediate parent's.
577/// The parent hosts the socket file, where the threat is *creation* of the
578/// predictable path — the sticky bit does not restrict creating, so no
579/// sticky exception is sound there. An ancestor only threatens via
580/// *rename/unlink of an existing entry we own*, which the sticky bit does
581/// restrict: in a sticky directory, only the entry's owner, the directory's
582/// owner, or root may rename it. So a root-owned `/tmp` (1777) is an
583/// acceptable ancestor of a user-owned 0700 socket directory, while a
584/// non-sticky group/other-writable ancestor, or one owned by a third uid
585/// (who could rename the entry, or chmod the directory first), is refused.
586/// Every stat failure fails closed.
587#[cfg(unix)]
588pub(super) fn ensure_rendezvous_path_is_swap_resistant(
589    parent: &std::path::Path,
590    daemon_euid: u32,
591    role: RendezvousPathRole<'_>,
592) -> anyhow::Result<()> {
593    use std::os::unix::fs::MetadataExt;
594
595    let env_name = role.env_name();
596    let directory_name = role.directory_name();
597    let path_name = role.path_name();
598    let component_name = role.path_component_name();
599
600    let absolute = if parent.is_absolute() {
601        parent.to_path_buf()
602    } else {
603        std::env::current_dir()
604            .map_err(|e| {
605                role.refusal(
606                    format_args!(
607                        "refusing to start: cannot resolve the working directory to absolutize \
608                     {directory_name} {} for {env_name}: {e}.",
609                        parent.display()
610                    ),
611                    format_args!(
612                        "cannot resolve the working directory for store directory {}: {e}",
613                        parent.display()
614                    ),
615                )
616            })?
617            .join(parent)
618    };
619
620    fn push_components(stack: &mut Vec<std::ffi::OsString>, path: &std::path::Path) {
621        let components: Vec<_> = path
622            .components()
623            .map(|c| c.as_os_str().to_os_string())
624            .collect();
625        stack.extend(components.into_iter().rev());
626    }
627
628    let mut stack: Vec<std::ffi::OsString> = Vec::new();
629    push_components(&mut stack, &absolute);
630    let mut resolved = std::path::PathBuf::new();
631    let mut symlinks_followed = 0u32;
632
633    while let Some(component) = stack.pop() {
634        if component == "/" {
635            resolved = std::path::PathBuf::from("/");
636            continue;
637        }
638        if component == "." {
639            continue;
640        }
641        if component == ".." {
642            resolved.pop();
643            continue;
644        }
645        let candidate = resolved.join(&component);
646        let meta = std::fs::symlink_metadata(&candidate).map_err(|e| {
647            role.refusal(
648                format_args!(
649                    "refusing to start: cannot stat {component_name} component {} for {env_name}: \
650                 {e}. An unreadable component is not a passing one.",
651                    candidate.display()
652                ),
653                format_args!(
654                    "cannot stat store-path component {}: {e}; unreadable metadata is not a \
655                     passing state",
656                    candidate.display()
657                ),
658            )
659        })?;
660        let owner = meta.uid();
661
662        if meta.file_type().is_symlink() {
663            symlinks_followed += 1;
664            if symlinks_followed > 40 {
665                return Err(role.refusal(
666                    format_args!(
667                        "refusing to start: {path_name} for {env_name} resolves through more than \
668                     40 symlinks at {} — treating this as a loop.",
669                        candidate.display()
670                    ),
671                    format_args!(
672                        "store path resolves through more than 40 symlinks at {}; treating this as \
673                         a loop",
674                        candidate.display()
675                    ),
676                ));
677            }
678            if owner != daemon_euid && owner != 0 {
679                return Err(role.refusal(
680                    format_args!(
681                        "refusing to start: {component_name} symlink component {} for {env_name} \
682                     is owned by uid {owner}, not this daemon's uid ({daemon_euid}) or root — \
683                     its owner could retarget it after this check and re-root the {path_name}. \
684                     Point {env_name} somewhere trusted end to end, or unset it for the default.",
685                        candidate.display()
686                    ),
687                    format_args!(
688                        "store-path symlink component {} is owned by uid {owner}, not this \
689                         process's uid ({daemon_euid}) or root; its owner could retarget the \
690                         database path",
691                        candidate.display()
692                    ),
693                ));
694            }
695            let target = std::fs::read_link(&candidate).map_err(|e| {
696                role.refusal(
697                    format_args!(
698                        "refusing to start: cannot read {component_name} symlink component {} \
699                     for {env_name}: {e}.",
700                        candidate.display()
701                    ),
702                    format_args!(
703                        "cannot read store-path symlink component {}: {e}",
704                        candidate.display()
705                    ),
706                )
707            })?;
708            push_components(&mut stack, &target);
709            continue;
710        }
711
712        if meta.is_dir() {
713            let mode = meta.permissions().mode();
714            let sticky = mode & 0o1000 != 0;
715            if owner != daemon_euid && owner != 0 {
716                return Err(role.refusal(
717                    format_args!(
718                    "refusing to start: {component_name} ancestor {} for {env_name} is owned by \
719                     uid {owner}, not this daemon's uid ({daemon_euid}) or root — its owner \
720                     could rename the next path component and re-root the {path_name}. Point \
721                     {env_name} somewhere trusted end to end, or unset it for the default.",
722                    candidate.display()
723                    ),
724                    format_args!(
725                        "store-path ancestor {} is owned by uid {owner}, not this process's uid \
726                         ({daemon_euid}) or root; its owner could rename the next path component",
727                        candidate.display()
728                    ),
729                ));
730            }
731            if mode & 0o022 != 0 && !sticky {
732                return Err(role.refusal(
733                    format_args!(
734                        "refusing to start: {component_name} ancestor {} for {env_name} is mode \
735                     {:04o} — writable by group or other without the sticky bit, so another \
736                     local user could rename the next path component and re-root the {path_name}. \
737                     Point {env_name} somewhere trusted end to end, or unset it for the default.",
738                        candidate.display(),
739                        mode & 0o7777
740                    ),
741                    format_args!(
742                        "store-path ancestor {} is mode {:04o}, writable by group or other without \
743                         the sticky bit, so another local user could rename the next path \
744                         component",
745                        candidate.display(), mode & 0o7777
746                    ),
747                ));
748            }
749            resolved = candidate;
750            continue;
751        }
752
753        return Err(role.refusal(
754            format_args!(
755                "refusing to start: {component_name} component {} for {env_name} is neither a \
756             directory nor a symlink — the {path_name} cannot traverse it.",
757                candidate.display()
758            ),
759            format_args!(
760                "store-path component {} is neither a directory nor a symlink; the database path \
761                 cannot traverse it",
762                candidate.display()
763            ),
764        ));
765    }
766
767    Ok(())
768}
769
770#[cfg(all(test, unix))]
771mod default_directory_repair_tests {
772    use super::{
773        ensure_pid_file_dir_is_trusted, ensure_socket_dir_is_trusted,
774        repair_default_dir_with_recovery_guidance, repair_owned_default_dir,
775        repair_owned_default_dir_with_hooks, tighten_owned_recovery_lock,
776        tighten_owned_recovery_lock_with_hook, RendezvousPathRole,
777    };
778    use std::os::unix::fs::{MetadataExt, PermissionsExt};
779    use std::os::unix::io::AsRawFd;
780
781    fn hold_lock(file: &std::fs::File) {
782        // SAFETY: the fixture owns this live file descriptor.
783        assert_eq!(
784            unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
785            0
786        );
787    }
788
789    #[derive(Clone)]
790    struct EmptyDispatcher;
791
792    #[async_trait::async_trait]
793    impl super::super::DaemonDispatch for EmptyDispatcher {
794        fn plan(&self, _ops: &str) -> String {
795            String::new()
796        }
797
798        async fn dispatch(
799            &self,
800            _ops: String,
801            _presentation: Option<String>,
802            _presentation_per_op: Option<Vec<Option<String>>>,
803            _format: Option<String>,
804            _format_per_op: Option<Vec<Option<String>>>,
805            _from_wire: bool,
806            _identity: Option<super::super::RequestIdentity>,
807        ) -> Result<String, String> {
808            Ok("{}".to_owned())
809        }
810
811        async fn warm_all(&self) {}
812        fn namespace(&self) -> &str {
813            "test"
814        }
815        fn config_id(&self) -> &str {
816            "test"
817        }
818    }
819
820    #[test]
821    #[serial_test::serial]
822    fn pid_directory_diagnostic_depends_on_the_checked_path_and_override() {
823        if crate::test_process::run_in_child() {
824            return;
825        }
826        let root = tempfile::Builder::new()
827            .prefix("khive-pid-diagnostic-")
828            .tempdir_in("/tmp")
829            .unwrap();
830        let home = root.path().join("home");
831        let default = home.join(".khive");
832        let other = root.path().join("other");
833        std::fs::create_dir_all(&default).unwrap();
834        std::fs::create_dir(&other).unwrap();
835        std::fs::set_permissions(&default, std::fs::Permissions::from_mode(0o775)).unwrap();
836        std::fs::set_permissions(&other, std::fs::Permissions::from_mode(0o775)).unwrap();
837        std::env::set_var("HOME", &home);
838        std::env::remove_var("KHIVE_PID");
839        std::env::remove_var("KHIVE_SOCKET");
840
841        let other_message = ensure_pid_file_dir_is_trusted(&other.join("daemon.pid"))
842            .unwrap_err()
843            .to_string();
844        assert!(
845            other_message.contains("PID-file directory") && other_message.contains("for KHIVE_PID"),
846            "{other_message}"
847        );
848        let default_message = ensure_pid_file_dir_is_trusted(&default.join("khived.pid"))
849            .unwrap_err()
850            .to_string();
851        assert!(
852            default_message.contains("default PID-file directory"),
853            "{default_message}"
854        );
855
856        std::env::set_var("KHIVE_PID", default.join("khived.pid"));
857        let explicit_message = ensure_pid_file_dir_is_trusted(&default.join("khived.pid"))
858            .unwrap_err()
859            .to_string();
860        assert!(
861            explicit_message.contains("for KHIVE_PID"),
862            "{explicit_message}"
863        );
864        assert!(
865            !explicit_message.contains("default PID-file directory"),
866            "{explicit_message}"
867        );
868        assert_eq!(
869            std::fs::metadata(&other).unwrap().permissions().mode() & 0o777,
870            0o775
871        );
872        assert_eq!(
873            std::fs::metadata(&default).unwrap().permissions().mode() & 0o777,
874            0o775
875        );
876    }
877
878    #[test]
879    #[serial_test::serial]
880    fn explicit_boot_lock_does_not_prepare_an_unrelated_default_home() {
881        if crate::test_process::run_in_child() {
882            return;
883        }
884        let root = tempfile::Builder::new()
885            .prefix("khive-explicit-boot-")
886            .tempdir_in("/tmp")
887            .unwrap();
888        let home = root.path().join("missing-home");
889        let lock = root.path().join("boot.lock");
890        std::env::set_var("HOME", &home);
891        std::env::set_var("KHIVE_PID", root.path().join("daemon.pid"));
892        std::env::set_var("KHIVE_SOCKET", root.path().join("daemon.sock"));
893        std::env::set_var("KHIVE_LOCK", &lock);
894        std::env::remove_var("KHIVE_RECOVERER_LOCK");
895        std::env::remove_var("KHIVE_SUPERVISOR_MARKER");
896        let opened = super::super::locks::open_mutating_daemon_lock(&lock, false)
897            .expect("the explicit lock parent exists and is trusted");
898        assert!(lock.exists());
899        assert!(
900            !home.exists(),
901            "an unrelated default HOME must remain absent"
902        );
903        drop(opened);
904
905        let unsafe_parent = root.path().join("unsafe-parent");
906        std::fs::create_dir(&unsafe_parent).unwrap();
907        std::fs::set_permissions(&unsafe_parent, std::fs::Permissions::from_mode(0o775)).unwrap();
908        let unsafe_lock = unsafe_parent.join("boot.lock");
909        assert!(super::super::locks::open_mutating_daemon_lock(&unsafe_lock, false).is_err());
910        assert!(
911            !unsafe_lock.exists(),
912            "an untrusted explicit parent must remain refused"
913        );
914        assert!(!home.exists());
915    }
916
917    #[test]
918    #[serial_test::serial]
919    fn explicit_boot_lock_creates_its_missing_pid_parent() {
920        if crate::test_process::run_in_child() {
921            return;
922        }
923        let root = tempfile::Builder::new()
924            .prefix("khive-explicit-missing-parent-")
925            .tempdir_in("/tmp")
926            .unwrap();
927        let home = root.path().join("missing-home");
928        let parent = root.path().join("new").join("rendezvous");
929        let lock = parent.join("boot.lock");
930        std::env::set_var("HOME", &home);
931        std::env::set_var("KHIVE_PID", parent.join("daemon.pid"));
932        std::env::set_var("KHIVE_SOCKET", parent.join("daemon.sock"));
933        std::env::set_var("KHIVE_LOCK", &lock);
934        std::env::remove_var("KHIVE_RECOVERER_LOCK");
935        std::env::remove_var("KHIVE_SUPERVISOR_MARKER");
936        assert!(!parent.exists());
937        // SAFETY: this fixture runs alone in a dedicated child process.
938        let previous_umask = unsafe { libc::umask(0o077) };
939        let opened = super::super::locks::open_mutating_daemon_lock(&lock, false);
940        // SAFETY: restore the process umask immediately after the operation.
941        unsafe { libc::umask(previous_umask) };
942        let opened = opened.expect("the explicitly selected lock parent is created");
943        assert!(parent.is_dir());
944        assert!(lock.is_file());
945        assert!(!home.exists());
946        drop(opened);
947    }
948
949    #[test]
950    #[serial_test::serial]
951    fn private_lock_with_default_rendezvous_does_not_prepare_home() {
952        if crate::test_process::run_in_child() {
953            return;
954        }
955        let root = tempfile::Builder::new()
956            .prefix("khive-private-lock-default-rendezvous-")
957            .tempdir_in("/tmp")
958            .unwrap();
959        let home = root.path().join("home");
960        std::fs::create_dir(&home).unwrap();
961        let lock = root.path().join("boot.lock");
962        std::env::set_var("HOME", &home);
963        std::env::remove_var("KHIVE_PID");
964        std::env::remove_var("KHIVE_SOCKET");
965        std::env::set_var("KHIVE_LOCK", &lock);
966        std::env::remove_var("KHIVE_RECOVERER_LOCK");
967        std::env::remove_var("KHIVE_SUPERVISOR_MARKER");
968        let opened = super::super::locks::open_mutating_daemon_lock(&lock, false)
969            .expect("the private lock must open");
970        hold_lock(&opened);
971        assert!(lock.is_file());
972        assert!(
973            std::fs::read_dir(&home).unwrap().next().is_none(),
974            "opening a private lock must not prepare the default rendezvous"
975        );
976        drop(opened);
977    }
978
979    #[test]
980    #[serial_test::serial]
981    fn default_lock_preparation_only_inspects_the_selected_lock() {
982        if crate::test_process::run_in_child() {
983            return;
984        }
985        let root = tempfile::Builder::new()
986            .prefix("khive-selected-default-lock-")
987            .tempdir_in("/tmp")
988            .unwrap();
989        let home = root.path().join("home");
990        let default = home.join(".khive");
991        std::fs::create_dir_all(&default).unwrap();
992        std::fs::set_permissions(&default, std::fs::Permissions::from_mode(0o700)).unwrap();
993        std::env::set_var("HOME", &home);
994        std::env::remove_var("KHIVE_PID");
995        std::env::remove_var("KHIVE_SOCKET");
996        std::env::remove_var("KHIVE_LOCK");
997        std::env::remove_var("KHIVE_RECOVERER_LOCK");
998        std::env::remove_var("KHIVE_SUPERVISOR_MARKER");
999        let unrelated = default.join("khived.recoverer.lock");
1000        std::os::unix::fs::symlink(root.path().join("missing"), &unrelated).unwrap();
1001        let selected = default.join("khived.recovery.lock");
1002        super::prepare_default_rendezvous_for_lock(&selected)
1003            .expect("unrelated recovery lock must not be examined");
1004        let opened = super::super::locks::open_mutating_daemon_lock(&selected, false)
1005            .expect("selected default lock must open");
1006        hold_lock(&opened);
1007        assert_eq!(
1008            opened.metadata().unwrap().permissions().mode() & 0o777,
1009            0o600
1010        );
1011        assert!(std::fs::symlink_metadata(unrelated)
1012            .unwrap()
1013            .file_type()
1014            .is_symlink());
1015    }
1016
1017    #[tokio::test]
1018    #[serial_test::serial]
1019    async fn default_rendezvous_is_prepared_with_an_external_boot_lock() {
1020        if crate::test_process::run_in_child() {
1021            return;
1022        }
1023        let root = tempfile::Builder::new()
1024            .prefix("khive-default-with-external-lock-")
1025            .tempdir_in("/tmp")
1026            .unwrap();
1027        let home = root.path().join("home");
1028        std::fs::create_dir(&home).unwrap();
1029        let lock = root.path().join("boot.lock");
1030        std::env::set_var("HOME", &home);
1031        std::env::remove_var("KHIVE_PID");
1032        std::env::remove_var("KHIVE_SOCKET");
1033        std::env::set_var("KHIVE_LOCK", &lock);
1034        std::env::remove_var("KHIVE_RECOVERER_LOCK");
1035        std::env::remove_var("KHIVE_SUPERVISOR_MARKER");
1036        // SAFETY: the test runs in a dedicated child process.
1037        let previous_umask = unsafe { libc::umask(0o002) };
1038        let default = home.join(".khive");
1039        let guard = super::super::acquire_daemon_boot_guard().expect("external boot guard");
1040        assert_eq!(
1041            std::fs::metadata(&default).unwrap().permissions().mode() & 0o777,
1042            0o700,
1043            "the default rendezvous must be private before boot"
1044        );
1045        let daemon = tokio::spawn(super::super::run_daemon_with_boot_guard_and_start(
1046            EmptyDispatcher,
1047            Some(guard),
1048            |_| {},
1049        ));
1050        let pid = default.join("khived.pid");
1051        let socket = default.join("khived.sock");
1052        let ready = tokio::time::timeout(std::time::Duration::from_secs(5), async {
1053            loop {
1054                assert!(!daemon.is_finished(), "daemon exited before boot");
1055                if lock.exists() && pid.exists() && socket.exists() {
1056                    break;
1057                }
1058                tokio::time::sleep(std::time::Duration::from_millis(10)).await;
1059            }
1060        })
1061        .await;
1062        // SAFETY: restore the process umask immediately after the boot witness.
1063        unsafe { libc::umask(previous_umask) };
1064        ready.expect("default daemon must bind with its external boot lock");
1065        assert_eq!(
1066            std::fs::metadata(default).unwrap().permissions().mode() & 0o777,
1067            0o700
1068        );
1069        daemon.abort();
1070        assert!(daemon
1071            .await
1072            .expect_err("daemon task must be cancelled")
1073            .is_cancelled());
1074    }
1075
1076    #[tokio::test]
1077    #[serial_test::serial]
1078    async fn supplied_external_guard_boots_with_private_default_rendezvous() {
1079        use std::os::unix::fs::FileTypeExt;
1080
1081        if crate::test_process::run_in_child() {
1082            return;
1083        }
1084        let root = tempfile::Builder::new()
1085            .prefix("khive-supplied-guard-default-")
1086            .tempdir_in("/tmp")
1087            .unwrap();
1088        let home = root.path().join("home");
1089        std::fs::create_dir(&home).unwrap();
1090        let lock = root.path().join("boot.lock");
1091        std::env::set_var("HOME", &home);
1092        std::env::remove_var("KHIVE_PID");
1093        std::env::remove_var("KHIVE_SOCKET");
1094        std::env::set_var("KHIVE_LOCK", &lock);
1095        std::env::remove_var("KHIVE_RECOVERER_LOCK");
1096        std::env::remove_var("KHIVE_SUPERVISOR_MARKER");
1097        let guard = super::super::locks::open_mutating_daemon_lock(&lock, false)
1098            .expect("external guard file must open");
1099        hold_lock(&guard);
1100        assert!(std::fs::read_dir(&home).unwrap().next().is_none());
1101
1102        let default = home.join(".khive");
1103        let pid = default.join("khived.pid");
1104        let socket = default.join("khived.sock");
1105        let entered = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
1106        let entered_at_hook = std::sync::Arc::clone(&entered);
1107        let observed_mode = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(u32::MAX));
1108        let mode_at_hook = std::sync::Arc::clone(&observed_mode);
1109        let socket_absent = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
1110        let socket_absent_at_hook = std::sync::Arc::clone(&socket_absent);
1111        let directory_at_hook = default.clone();
1112        let socket_at_hook = socket.clone();
1113        *super::DEFAULT_RENDEZVOUS_PREBIND_HOOK.lock().unwrap() = Some(Box::new(move || {
1114            let mode = std::fs::metadata(&directory_at_hook)
1115                .map(|metadata| metadata.permissions().mode() & 0o777)
1116                .unwrap_or(u32::MAX);
1117            mode_at_hook.store(mode, std::sync::atomic::Ordering::SeqCst);
1118            socket_absent_at_hook.store(
1119                !socket_at_hook.exists(),
1120                std::sync::atomic::Ordering::SeqCst,
1121            );
1122            entered_at_hook.store(true, std::sync::atomic::Ordering::SeqCst);
1123        }));
1124        // SAFETY: the test runs in a dedicated child process.
1125        let previous_umask = unsafe { libc::umask(0o002) };
1126        let daemon = tokio::spawn(super::super::run_daemon_with_boot_guard_and_start(
1127            EmptyDispatcher,
1128            Some(guard),
1129            |_| {},
1130        ));
1131        let hook_reached = tokio::time::timeout(std::time::Duration::from_secs(5), async {
1132            while !entered.load(std::sync::atomic::Ordering::SeqCst) && !daemon.is_finished() {
1133                tokio::time::sleep(std::time::Duration::from_millis(10)).await;
1134            }
1135        })
1136        .await;
1137        assert!(hook_reached.is_ok(), "daemon must reach pre-bind observer");
1138        assert!(
1139            entered.load(std::sync::atomic::Ordering::SeqCst),
1140            "pre-bind observer must execute"
1141        );
1142        assert_eq!(
1143            observed_mode.load(std::sync::atomic::Ordering::SeqCst),
1144            0o700,
1145            "default rendezvous must be private before binding; u32::MAX means absent or unreadable"
1146        );
1147        assert!(
1148            socket_absent.load(std::sync::atomic::Ordering::SeqCst),
1149            "witness must precede socket bind"
1150        );
1151        let ready = tokio::time::timeout(std::time::Duration::from_secs(5), async {
1152            loop {
1153                assert!(!daemon.is_finished(), "daemon exited before boot");
1154                if pid.exists() && socket.exists() {
1155                    break;
1156                }
1157                tokio::time::sleep(std::time::Duration::from_millis(10)).await;
1158            }
1159        })
1160        .await;
1161        // SAFETY: restore the process umask immediately after the boot witness.
1162        unsafe { libc::umask(previous_umask) };
1163        ready.expect("daemon must bind with the caller-supplied guard");
1164        assert!(std::fs::metadata(&socket).unwrap().file_type().is_socket());
1165        assert_eq!(
1166            std::fs::metadata(default).unwrap().permissions().mode() & 0o777,
1167            0o700
1168        );
1169        daemon.abort();
1170        assert!(daemon
1171            .await
1172            .expect_err("daemon task must be cancelled")
1173            .is_cancelled());
1174    }
1175
1176    #[tokio::test]
1177    #[serial_test::serial]
1178    async fn explicit_daemon_boot_keeps_private_home_empty() {
1179        use std::os::unix::fs::FileTypeExt;
1180
1181        if crate::test_process::run_in_child() {
1182            return;
1183        }
1184        let root = tempfile::Builder::new()
1185            .prefix("khive-explicit-daemon-")
1186            .tempdir_in("/tmp")
1187            .expect("private synthetic root");
1188        let home = root.path().join("home");
1189        let rendezvous = root.path().join("run");
1190        std::fs::create_dir(&home).unwrap();
1191        std::fs::create_dir(&rendezvous).unwrap();
1192        std::fs::set_permissions(&home, std::fs::Permissions::from_mode(0o700)).unwrap();
1193        std::fs::set_permissions(&rendezvous, std::fs::Permissions::from_mode(0o700)).unwrap();
1194        let lock = rendezvous.join("boot.lock");
1195        let pid = rendezvous.join("daemon.pid");
1196        let socket = rendezvous.join("daemon.sock");
1197        std::env::set_var("HOME", &home);
1198        std::env::set_var("KHIVE_LOCK", &lock);
1199        std::env::set_var("KHIVE_PID", &pid);
1200        std::env::set_var("KHIVE_SOCKET", &socket);
1201        std::env::remove_var("KHIVE_RECOVERER_LOCK");
1202        std::env::remove_var("KHIVE_SUPERVISOR_MARKER");
1203        assert!(std::fs::read_dir(&home).unwrap().next().is_none());
1204
1205        let daemon = tokio::spawn(super::run_daemon(EmptyDispatcher));
1206        tokio::time::timeout(std::time::Duration::from_secs(5), async {
1207            loop {
1208                assert!(
1209                    !daemon.is_finished(),
1210                    "daemon exited before the boot witness"
1211                );
1212                if lock.exists() && pid.exists() && socket.exists() {
1213                    break;
1214                }
1215                tokio::time::sleep(std::time::Duration::from_millis(10)).await;
1216            }
1217        })
1218        .await
1219        .expect("daemon must create its explicit boot lock, PID and socket");
1220        assert!(std::fs::metadata(&socket).unwrap().file_type().is_socket());
1221        assert!(
1222            std::fs::read_dir(&home).unwrap().next().is_none(),
1223            "explicit daemon boot must leave its private HOME empty"
1224        );
1225        daemon.abort();
1226        let error = daemon.await.expect_err("the daemon task must be cancelled");
1227        assert!(
1228            error.is_cancelled(),
1229            "daemon task failed before cancellation: {error}"
1230        );
1231    }
1232
1233    #[tokio::test]
1234    #[serial_test::serial]
1235    async fn direct_daemon_boot_refuses_unsafe_ancestor_before_lock_creation() {
1236        if crate::test_process::run_in_child() {
1237            return;
1238        }
1239        let root = tempfile::Builder::new()
1240            .prefix("khive-boot-unsafe-")
1241            .tempdir_in("/tmp")
1242            .expect("private synthetic root");
1243        let unsafe_ancestor = root.path().join("unsafe");
1244        let home = unsafe_ancestor.join("home");
1245        std::fs::create_dir_all(&home).unwrap();
1246        std::fs::set_permissions(&unsafe_ancestor, std::fs::Permissions::from_mode(0o775)).unwrap();
1247        std::fs::set_permissions(&home, std::fs::Permissions::from_mode(0o700)).unwrap();
1248        std::env::set_var("HOME", &home);
1249        for key in [
1250            "KHIVE_PID",
1251            "KHIVE_SOCKET",
1252            "KHIVE_LOCK",
1253            "KHIVE_RECOVERER_LOCK",
1254            "KHIVE_SUPERVISOR_MARKER",
1255        ] {
1256            std::env::remove_var(key);
1257        }
1258        let directory = home.join(".khive");
1259        assert!(!directory.exists());
1260
1261        let outcome = tokio::time::timeout(
1262            std::time::Duration::from_secs(2),
1263            super::run_daemon(EmptyDispatcher),
1264        )
1265        .await;
1266
1267        assert!(
1268            matches!(outcome, Ok(Err(_))),
1269            "unsafe direct boot must refuse promptly"
1270        );
1271        assert!(
1272            !directory.exists(),
1273            "no lock directory may be created under an unsafe ancestor"
1274        );
1275        assert_eq!(
1276            std::fs::metadata(&unsafe_ancestor)
1277                .unwrap()
1278                .permissions()
1279                .mode()
1280                & 0o777,
1281            0o775
1282        );
1283
1284        std::fs::set_permissions(&unsafe_ancestor, std::fs::Permissions::from_mode(0o700)).unwrap();
1285        std::fs::create_dir(&directory).unwrap();
1286        std::fs::set_permissions(&directory, std::fs::Permissions::from_mode(0o700)).unwrap();
1287        let existing_lock = directory.join("khived.recovery.lock");
1288        std::fs::write(&existing_lock, b"").unwrap();
1289        std::fs::set_permissions(&existing_lock, std::fs::Permissions::from_mode(0o644)).unwrap();
1290        let guard = super::super::acquire_daemon_boot_guard().expect("trusted boot-lock baseline");
1291        assert_eq!(
1292            guard.metadata().unwrap().permissions().mode() & 0o777,
1293            0o600
1294        );
1295        assert_eq!(
1296            std::fs::metadata(&existing_lock)
1297                .unwrap()
1298                .permissions()
1299                .mode()
1300                & 0o777,
1301            0o600
1302        );
1303        drop(guard);
1304    }
1305
1306    #[test]
1307    #[serial_test::serial]
1308    fn foreign_owner_is_refused_before_permissions_change() {
1309        let directory = tempfile::Builder::new()
1310            .prefix("khive-foreign-owner-")
1311            .tempdir_in("/tmp")
1312            .expect("private synthetic directory");
1313        std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o775)).unwrap();
1314        let actual_owner = std::fs::metadata(directory.path()).unwrap().uid();
1315        let other_owner = actual_owner.wrapping_add(1);
1316        let tmp_owner = std::fs::metadata("/tmp").unwrap().uid();
1317
1318        let error =
1319            repair_owned_default_dir(directory.path(), RendezvousPathRole::PidFile, other_owner)
1320                .expect_err("directory owned by a different uid must not be repaired");
1321
1322        let message = error.to_string();
1323        if tmp_owner != 0 && tmp_owner != other_owner {
1324            assert!(
1325                message.contains(&format!(
1326                    "PID-file-path ancestor /tmp for KHIVE_PID is owned by uid {tmp_owner}, not this daemon's uid ({other_owner}) or root"
1327                )),
1328                "{message}"
1329            );
1330        } else {
1331            assert!(
1332                message.contains(&format!(
1333                    "refusing to repair default rendezvous directory {}: owner uid {actual_owner}, mode 0775; expected uid {other_owner}",
1334                    directory.path().display()
1335                )),
1336                "{message}"
1337            );
1338        }
1339        assert_eq!(
1340            std::fs::metadata(directory.path())
1341                .unwrap()
1342                .permissions()
1343                .mode()
1344                & 0o777,
1345            0o775
1346        );
1347    }
1348
1349    #[test]
1350    #[serial_test::serial]
1351    fn repair_does_not_chmod_a_replacement_path() {
1352        let root = tempfile::Builder::new()
1353            .prefix("khive-default-swap-")
1354            .tempdir_in("/tmp")
1355            .expect("private synthetic directory");
1356        let directory = root.path().join("rendezvous");
1357        let original = root.path().join("original");
1358        let replacement = root.path().join("replacement");
1359        std::fs::create_dir(&directory).unwrap();
1360        std::fs::create_dir(&replacement).unwrap();
1361        std::fs::set_permissions(&directory, std::fs::Permissions::from_mode(0o775)).unwrap();
1362        std::fs::set_permissions(&replacement, std::fs::Permissions::from_mode(0o755)).unwrap();
1363        let owner = std::fs::metadata(&directory).unwrap().uid();
1364
1365        let outcome = repair_owned_default_dir_with_hooks(
1366            &directory,
1367            RendezvousPathRole::PidFile,
1368            owner,
1369            || {},
1370            || {
1371                std::fs::rename(&directory, &original).unwrap();
1372                std::fs::rename(&replacement, &directory).unwrap();
1373            },
1374        );
1375
1376        assert!(outcome.is_err(), "a path replacement must be reported");
1377        assert_eq!(
1378            std::fs::metadata(&directory).unwrap().permissions().mode() & 0o777,
1379            0o755
1380        );
1381        assert_eq!(
1382            std::fs::metadata(&original).unwrap().permissions().mode() & 0o777,
1383            0o700
1384        );
1385    }
1386
1387    #[test]
1388    #[serial_test::serial]
1389    fn repair_does_not_follow_symlink_replacing_the_leaf_before_open() {
1390        use std::os::unix::fs::symlink;
1391
1392        let root = tempfile::Builder::new()
1393            .prefix("khive-default-symlink-")
1394            .tempdir_in("/tmp")
1395            .expect("private synthetic directory");
1396        let directory = root.path().join("rendezvous");
1397        let target = root.path().join("target");
1398        std::fs::create_dir(&directory).unwrap();
1399        std::fs::create_dir(&target).unwrap();
1400        std::fs::set_permissions(&directory, std::fs::Permissions::from_mode(0o775)).unwrap();
1401        std::fs::set_permissions(&target, std::fs::Permissions::from_mode(0o775)).unwrap();
1402        let owner = std::fs::metadata(&directory).unwrap().uid();
1403
1404        let outcome = repair_owned_default_dir_with_hooks(
1405            &directory,
1406            RendezvousPathRole::PidFile,
1407            owner,
1408            || {
1409                std::fs::remove_dir(&directory).unwrap();
1410                symlink(&target, &directory).unwrap();
1411            },
1412            || {},
1413        );
1414
1415        assert!(outcome.is_err(), "a replacement symlink must be refused");
1416        assert_eq!(
1417            std::fs::metadata(&target).unwrap().permissions().mode() & 0o777,
1418            0o775
1419        );
1420    }
1421
1422    #[test]
1423    #[serial_test::serial]
1424    fn repair_refuses_directory_replaced_before_open_without_chmod() {
1425        let root = tempfile::Builder::new()
1426            .prefix("khive-default-before-open-")
1427            .tempdir_in("/tmp")
1428            .expect("private synthetic directory");
1429        let directory = root.path().join("rendezvous");
1430        let original = root.path().join("original");
1431        let replacement = root.path().join("replacement");
1432        std::fs::create_dir(&directory).unwrap();
1433        std::fs::create_dir(&replacement).unwrap();
1434        std::fs::set_permissions(&directory, std::fs::Permissions::from_mode(0o775)).unwrap();
1435        std::fs::set_permissions(&replacement, std::fs::Permissions::from_mode(0o775)).unwrap();
1436        let owner = std::fs::metadata(&directory).unwrap().uid();
1437
1438        let outcome = repair_owned_default_dir_with_hooks(
1439            &directory,
1440            RendezvousPathRole::PidFile,
1441            owner,
1442            || {
1443                std::fs::rename(&directory, &original).unwrap();
1444                std::fs::rename(&replacement, &directory).unwrap();
1445            },
1446            || {},
1447        );
1448
1449        assert!(
1450            outcome.is_err(),
1451            "a directory swapped before open must be refused"
1452        );
1453        assert_eq!(
1454            std::fs::metadata(&directory).unwrap().permissions().mode() & 0o777,
1455            0o775
1456        );
1457        assert_eq!(
1458            std::fs::metadata(&original).unwrap().permissions().mode() & 0o777,
1459            0o775
1460        );
1461    }
1462
1463    #[test]
1464    #[serial_test::serial]
1465    fn repair_restores_owner_access_removed_after_validation() {
1466        let root = tempfile::Builder::new()
1467            .prefix("khive-default-chmod-")
1468            .tempdir_in("/tmp")
1469            .expect("private synthetic directory");
1470        let directory = root.path().join("rendezvous");
1471        std::fs::create_dir(&directory).unwrap();
1472        std::fs::set_permissions(&directory, std::fs::Permissions::from_mode(0o775)).unwrap();
1473        let owner = std::fs::metadata(&directory).unwrap().uid();
1474
1475        let outcome = repair_owned_default_dir_with_hooks(
1476            &directory,
1477            RendezvousPathRole::PidFile,
1478            owner,
1479            || {},
1480            || {
1481                std::fs::set_permissions(&directory, std::fs::Permissions::from_mode(0o500))
1482                    .unwrap()
1483            },
1484        );
1485
1486        let mode = std::fs::metadata(&directory).unwrap().permissions().mode() & 0o777;
1487        let created = std::fs::File::create(directory.join("daemon.lock"));
1488        std::fs::set_permissions(&directory, std::fs::Permissions::from_mode(0o700)).unwrap();
1489        assert!(
1490            outcome.is_ok(),
1491            "an owned directory is repaired: {outcome:?}"
1492        );
1493        assert_eq!(mode, 0o700);
1494        assert!(
1495            created.is_ok(),
1496            "the daemon can create its files after repair: {created:?}"
1497        );
1498    }
1499
1500    #[test]
1501    #[serial_test::serial]
1502    fn repair_makes_an_owner_read_only_directory_writable() {
1503        let root = tempfile::Builder::new()
1504            .prefix("khive-default-read-only-")
1505            .tempdir_in("/tmp")
1506            .expect("private synthetic directory");
1507        let directory = root.path().join("rendezvous");
1508        std::fs::create_dir(&directory).unwrap();
1509        std::fs::set_permissions(&directory, std::fs::Permissions::from_mode(0o550)).unwrap();
1510        let owner = std::fs::metadata(&directory).unwrap().uid();
1511
1512        let outcome = repair_owned_default_dir(&directory, RendezvousPathRole::PidFile, owner);
1513
1514        let mode = std::fs::metadata(&directory).unwrap().permissions().mode() & 0o777;
1515        let created = std::fs::File::create(directory.join("daemon.pid"));
1516        std::fs::set_permissions(&directory, std::fs::Permissions::from_mode(0o700)).unwrap();
1517        assert!(
1518            outcome.is_ok(),
1519            "an owned directory is repaired: {outcome:?}"
1520        );
1521        assert_eq!(mode, 0o700);
1522        assert!(
1523            created.is_ok(),
1524            "the daemon can create its files after repair: {created:?}"
1525        );
1526    }
1527
1528    #[test]
1529    #[serial_test::serial]
1530    fn newly_created_inaccessible_default_dir_reports_manual_recovery() {
1531        let root = tempfile::Builder::new()
1532            .prefix("khive-dir-recovery-")
1533            .tempdir_in("/tmp")
1534            .unwrap();
1535        let directory = root.path().join("rendezvous");
1536        std::fs::create_dir(&directory).unwrap();
1537        let uid = std::fs::metadata(&directory).unwrap().uid();
1538        std::fs::set_permissions(&directory, std::fs::Permissions::from_mode(0o000)).unwrap();
1539        // This is a fixture qualification, not semantic evidence on a privileged host.
1540        let denied = std::fs::File::open(&directory)
1541            .expect_err("fixture requires an unprivileged owner unable to open mode 0000");
1542        assert_eq!(denied.kind(), std::io::ErrorKind::PermissionDenied);
1543        let error = repair_default_dir_with_recovery_guidance(&directory, uid, true).unwrap_err();
1544        let message = format!("{error:#}");
1545        assert!(message.contains(&directory.display().to_string()));
1546        assert!(message.contains("0700") && message.contains("by hand"));
1547        let retry = repair_default_dir_with_recovery_guidance(&directory, uid, false).unwrap_err();
1548        let retry_message = format!("{retry:#}");
1549        assert!(retry_message.contains(&directory.display().to_string()));
1550        assert!(retry_message.contains("0700") && retry_message.contains("by hand"));
1551        let foreign =
1552            repair_default_dir_with_recovery_guidance(&directory, uid.wrapping_add(1), false)
1553                .unwrap_err();
1554        assert!(!format!("{foreign:#}").contains("by hand"));
1555        assert_eq!(
1556            std::fs::metadata(&directory).unwrap().permissions().mode() & 0o777,
1557            0
1558        );
1559        std::fs::set_permissions(&directory, std::fs::Permissions::from_mode(0o700)).unwrap();
1560        repair_default_dir_with_recovery_guidance(&directory, uid, false).unwrap();
1561    }
1562
1563    #[test]
1564    #[serial_test::serial]
1565    fn concurrent_lock_creation_reopens_the_validated_existing_entry() {
1566        let root = tempfile::Builder::new()
1567            .prefix("khive-lock-create-race-")
1568            .tempdir_in("/tmp")
1569            .unwrap();
1570        let lock = root.path().join("recovery.lock");
1571
1572        let opened = super::super::locks::checked_open_lock_with_observe_hook(
1573            &lock,
1574            true,
1575            false,
1576            true,
1577            || {},
1578            || {},
1579            (false, false, || {
1580                std::fs::write(&lock, b"incumbent").unwrap();
1581                std::fs::set_permissions(&lock, std::fs::Permissions::from_mode(0o644)).unwrap();
1582            }),
1583        )
1584        .expect("concurrent valid lock must be reopened")
1585        .unwrap();
1586
1587        let on_disk = std::fs::metadata(&lock).unwrap();
1588        assert_eq!(opened.metadata().unwrap().ino(), on_disk.ino());
1589        assert_eq!(on_disk.permissions().mode() & 0o777, 0o600);
1590        assert_eq!(std::fs::read(&lock).unwrap(), b"incumbent");
1591    }
1592
1593    #[test]
1594    #[serial_test::serial]
1595    fn concurrent_lock_symlink_is_refused_before_opening_its_target() {
1596        use std::os::unix::fs::symlink;
1597        let root = tempfile::Builder::new()
1598            .prefix("khive-lock-create-symlink-")
1599            .tempdir_in("/tmp")
1600            .unwrap();
1601        let lock = root.path().join("recovery.lock");
1602        let target = root.path().join("target");
1603        std::fs::write(&target, b"untouched").unwrap();
1604        std::fs::set_permissions(&target, std::fs::Permissions::from_mode(0o644)).unwrap();
1605
1606        let error = super::super::locks::checked_open_lock_with_observe_hook(
1607            &lock,
1608            true,
1609            false,
1610            true,
1611            || {},
1612            || {},
1613            (false, false, || symlink(&target, &lock).unwrap()),
1614        )
1615        .unwrap_err();
1616
1617        assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
1618        assert_eq!(std::fs::read(&target).unwrap(), b"untouched");
1619        assert_eq!(
1620            std::fs::metadata(&target).unwrap().permissions().mode() & 0o777,
1621            0o644
1622        );
1623    }
1624
1625    #[test]
1626    #[serial_test::serial]
1627    fn created_lock_failures_leave_entry_and_report_manual_recovery() {
1628        let root = tempfile::Builder::new()
1629            .prefix("khive-lock-failure-")
1630            .tempdir_in("/tmp")
1631            .unwrap();
1632        for (label, fail_metadata, fail_chmod) in
1633            [("metadata", true, false), ("chmod", false, true)]
1634        {
1635            let lock = root.path().join(label);
1636            let error = super::super::locks::checked_open_lock_with_faults(
1637                &lock,
1638                true,
1639                false,
1640                true,
1641                || {},
1642                || {
1643                    if fail_chmod {
1644                        std::fs::set_permissions(&lock, std::fs::Permissions::from_mode(0o000))
1645                            .unwrap();
1646                    }
1647                },
1648                (fail_metadata, fail_chmod),
1649            )
1650            .unwrap_err();
1651            let message = error.to_string();
1652            assert!(message.contains(&lock.display().to_string()));
1653            assert!(
1654                message.contains("confirming no daemon")
1655                    && message.contains("verifying the entry is the leftover lock")
1656            );
1657            assert!(lock.exists(), "failure must not unlink the created entry");
1658            std::fs::remove_file(&lock).unwrap();
1659            let file = super::super::locks::checked_open_lock(&lock, true, false, true)
1660                .unwrap()
1661                .unwrap();
1662            assert_eq!(file.metadata().unwrap().permissions().mode() & 0o777, 0o600);
1663        }
1664    }
1665
1666    #[test]
1667    #[serial_test::serial]
1668    fn created_lock_replacement_reports_inspection_without_removal_advice() {
1669        let root = tempfile::Builder::new()
1670            .prefix("khive-lock-created-swap-")
1671            .tempdir_in("/tmp")
1672            .unwrap();
1673        let lock = root.path().join("lock");
1674        let original = root.path().join("original");
1675        let replacement = root.path().join("replacement");
1676        std::fs::write(&replacement, b"replacement").unwrap();
1677        let error = super::super::locks::checked_open_lock_with_hooks(
1678            &lock,
1679            true,
1680            false,
1681            true,
1682            || {},
1683            || {
1684                std::fs::rename(&lock, &original).unwrap();
1685                std::fs::rename(&replacement, &lock).unwrap();
1686            },
1687        )
1688        .unwrap_err();
1689        let message = error.to_string();
1690        assert!(message.contains(&lock.display().to_string()));
1691        assert!(
1692            message.contains("inspect the path")
1693                && message.contains("do not remove the replacement")
1694        );
1695        assert!(!message.contains("remove it and retry"));
1696        assert_eq!(std::fs::read(&lock).unwrap(), b"replacement");
1697        assert!(original.exists());
1698    }
1699
1700    #[test]
1701    #[serial_test::serial]
1702    fn newly_created_recovery_lock_is_owner_only_under_restrictive_umask() {
1703        if crate::test_process::run_in_child() {
1704            return;
1705        }
1706        let root = tempfile::Builder::new()
1707            .prefix("khive-lock-mode-")
1708            .tempdir_in("/tmp")
1709            .expect("private synthetic directory");
1710        std::env::set_var("HOME", root.path());
1711        std::env::set_var("KHIVE_PID", root.path().join("khived.pid"));
1712        std::env::set_var("KHIVE_SOCKET", root.path().join("khived.sock"));
1713        let lock = root.path().join("recovery.lock");
1714        // SAFETY: this test runs in an isolated child process.
1715        let old_umask = unsafe { libc::umask(0o777) };
1716        let opened = super::super::locks::open_lock_file(&lock);
1717        // SAFETY: restore the umask returned in this isolated process.
1718        unsafe { libc::umask(old_umask) };
1719
1720        let file = opened.expect("create new recovery lock");
1721        assert_eq!(file.metadata().unwrap().permissions().mode() & 0o777, 0o600);
1722    }
1723
1724    #[test]
1725    #[serial_test::serial]
1726    fn recovery_lock_opener_refuses_a_symlink() {
1727        use std::os::unix::fs::symlink;
1728
1729        let root = tempfile::Builder::new()
1730            .prefix("khive-lock-symlink-")
1731            .tempdir_in("/tmp")
1732            .expect("private synthetic directory");
1733        if crate::test_process::run_in_child() {
1734            return;
1735        }
1736        std::env::set_var("HOME", root.path());
1737        std::env::set_var("KHIVE_PID", root.path().join("khived.pid"));
1738        std::env::set_var("KHIVE_SOCKET", root.path().join("khived.sock"));
1739        let lock = root.path().join("lock");
1740        let target = root.path().join("not-a-lock");
1741        symlink(&target, &lock).unwrap();
1742
1743        let error = super::super::locks::open_lock_file(&lock).unwrap_err();
1744
1745        assert!(error.to_string().contains(&lock.display().to_string()));
1746        assert!(
1747            !target.exists(),
1748            "opening a lock must not create a symlink target"
1749        );
1750    }
1751
1752    #[test]
1753    #[serial_test::serial]
1754    fn foreign_owned_lock_is_refused_without_chmod() {
1755        let root = tempfile::Builder::new()
1756            .prefix("khive-foreign-lock-")
1757            .tempdir_in("/tmp")
1758            .expect("private synthetic directory");
1759        let lock = root.path().join("lock");
1760        std::fs::write(&lock, b"").unwrap();
1761        std::fs::set_permissions(&lock, std::fs::Permissions::from_mode(0o644)).unwrap();
1762        let owner = std::fs::metadata(&lock).unwrap().uid();
1763
1764        let error = tighten_owned_recovery_lock(&lock, owner.wrapping_add(1)).unwrap_err();
1765
1766        assert!(error.to_string().contains(&lock.display().to_string()));
1767        assert!(error.to_string().contains("0644"));
1768        assert_eq!(
1769            std::fs::metadata(&lock).unwrap().permissions().mode() & 0o777,
1770            0o644
1771        );
1772        tighten_owned_recovery_lock(&lock, owner).unwrap();
1773        assert_eq!(
1774            std::fs::metadata(&lock).unwrap().permissions().mode() & 0o777,
1775            0o600
1776        );
1777    }
1778
1779    #[test]
1780    #[serial_test::serial]
1781    fn lock_tightening_does_not_chmod_a_replacement_path() {
1782        let root = tempfile::Builder::new()
1783            .prefix("khive-lock-swap-")
1784            .tempdir_in("/tmp")
1785            .expect("private synthetic directory");
1786        let lock = root.path().join("lock");
1787        let original = root.path().join("original");
1788        let replacement = root.path().join("replacement");
1789        std::fs::write(&lock, b"").unwrap();
1790        std::fs::write(&replacement, b"").unwrap();
1791        std::fs::set_permissions(&lock, std::fs::Permissions::from_mode(0o644)).unwrap();
1792        std::fs::set_permissions(&replacement, std::fs::Permissions::from_mode(0o644)).unwrap();
1793        let owner = std::fs::metadata(&lock).unwrap().uid();
1794
1795        let outcome = tighten_owned_recovery_lock_with_hook(&lock, owner, || {
1796            std::fs::rename(&lock, &original).unwrap();
1797            std::fs::rename(&replacement, &lock).unwrap();
1798        });
1799
1800        assert!(outcome.is_err());
1801        assert_eq!(
1802            std::fs::metadata(&lock).unwrap().permissions().mode() & 0o777,
1803            0o644
1804        );
1805        assert_eq!(
1806            std::fs::metadata(&original).unwrap().permissions().mode() & 0o777,
1807            0o644
1808        );
1809    }
1810
1811    #[test]
1812    #[serial_test::serial]
1813    fn lock_open_refuses_parent_replaced_after_directory_fd_check() {
1814        let root = tempfile::Builder::new()
1815            .prefix("khive-lock-parent-swap-")
1816            .tempdir_in("/tmp")
1817            .expect("private synthetic directory");
1818        let directory = root.path().join("parent");
1819        let original = root.path().join("original");
1820        let replacement = root.path().join("replacement");
1821        std::fs::create_dir(&directory).unwrap();
1822        std::fs::create_dir(&replacement).unwrap();
1823        std::fs::set_permissions(&directory, std::fs::Permissions::from_mode(0o700)).unwrap();
1824        std::fs::set_permissions(&replacement, std::fs::Permissions::from_mode(0o700)).unwrap();
1825        let lock = directory.join("lock");
1826
1827        let outcome = super::super::locks::checked_open_lock_with_hooks(
1828            &lock,
1829            true,
1830            false,
1831            true,
1832            || {
1833                std::fs::rename(&directory, &original).unwrap();
1834                std::fs::rename(&replacement, &directory).unwrap();
1835            },
1836            || {},
1837        );
1838
1839        assert!(outcome.is_err());
1840        assert!(!lock.exists(), "replacement parent must not receive a lock");
1841        assert!(
1842            !original.join("lock").exists(),
1843            "detected change must refuse before create"
1844        );
1845        std::fs::rename(&directory, &replacement).unwrap();
1846        std::fs::rename(&original, &directory).unwrap();
1847        let positive = super::super::locks::checked_open_lock(&lock, true, false, true)
1848            .expect("trusted-parent positive control")
1849            .expect("mutating opener creates the lock");
1850        assert_eq!(
1851            positive.metadata().unwrap().permissions().mode() & 0o777,
1852            0o600
1853        );
1854    }
1855
1856    #[test]
1857    #[serial_test::serial]
1858    fn explicitly_selected_default_socket_directory_is_not_repaired_on_boot() {
1859        if crate::test_process::run_in_child() {
1860            return;
1861        }
1862        let home = tempfile::Builder::new()
1863            .prefix("khive-explicit-default-")
1864            .tempdir_in("/tmp")
1865            .expect("private synthetic home");
1866        std::env::set_var("HOME", home.path());
1867        let directory = home.path().join(".khive");
1868        std::fs::create_dir(&directory).unwrap();
1869        std::fs::set_permissions(&directory, std::fs::Permissions::from_mode(0o775)).unwrap();
1870        std::env::set_var("KHIVE_PID", directory.join("khived.pid"));
1871        std::env::set_var("KHIVE_SOCKET", directory.join("khived.sock"));
1872
1873        let outcome = ensure_socket_dir_is_trusted(&directory);
1874
1875        assert!(outcome.is_err());
1876        assert_eq!(
1877            std::fs::metadata(&directory).unwrap().permissions().mode() & 0o777,
1878            0o775
1879        );
1880    }
1881}