Skip to main content

shep_core/
paths.rs

1//! On-disk layout of `$SHEP_HOME`
2//!
3//! One resolver, no hidden `std::env` reads — the environment comes in as a
4//! closure so tests and the daemon share one code path.
5
6use std::path::{Path, PathBuf};
7
8/// Drops the `\\?\` extended-length prefix Windows' `canonicalize` adds
9///
10/// `std::fs::canonicalize` returns a verbatim path on Windows, so a binary at
11/// `C:\tools\dog.exe` comes back as `\\?\C:\tools\dog.exe`. That form is
12/// correct and every Win32 call accepts it, which is exactly why it leaks
13/// quietly: nothing inside shep breaks, and it surfaces only once the path
14/// reaches something that is not Win32. Two such places are already known.
15/// Node's `require` reads the leading `\\` as a UNC share and fails on `C:`.
16/// And `shep adopt` records the vetted binary in `shep.toml`, where the prefix
17/// is simply noise in a file an operator edits by hand.
18///
19/// So this is for paths that LEAVE shep: written to config, shown to an
20/// operator, or handed to another program. Paths that stay inside and are
21/// compared against each other must not use it. `serve`'s docroot containment
22/// check is the case that matters, where both sides being canonical is the
23/// security property, and rewriting one side would weaken it.
24///
25/// Only `\\?\C:\` is unwrapped, because that is the one shape `canonicalize`
26/// produces for a local file. A verbatim UNC path (`\\?\UNC\server\share`)
27/// is left alone: no host here can mount a share to test that branch, and an
28/// unexercised guess is worth less than a documented gap.
29///
30/// **A path long enough to need the prefix is out of scope.** Above `MAX_PATH`
31/// the prefix is load-bearing rather than decorative, and stripping it can
32/// produce a path that no longer opens. Nothing in shep's own layout comes
33/// close, and the alternative is a conditional rule whose behavior changes at
34/// a length nobody can see, so the simple rule is the one kept.
35#[cfg(windows)]
36#[must_use]
37pub fn strip_verbatim_prefix(path: &Path) -> std::borrow::Cow<'_, Path> {
38    use std::path::{Component, Prefix};
39
40    let mut components = path.components();
41    let Some(Component::Prefix(prefix)) = components.next() else {
42        return std::borrow::Cow::Borrowed(path);
43    };
44    let Prefix::VerbatimDisk(letter) = prefix.kind() else {
45        return std::borrow::Cow::Borrowed(path);
46    };
47
48    let mut rebuilt = PathBuf::from(format!("{}:\\", char::from(letter)));
49    rebuilt.extend(components.filter(|part| !matches!(part, Component::RootDir)));
50    std::borrow::Cow::Owned(rebuilt)
51}
52
53/// Passes the path through: only Windows' `canonicalize` prefixes its output
54///
55/// See the Windows sibling for what this exists to undo.
56#[cfg(not(windows))]
57#[must_use]
58pub fn strip_verbatim_prefix(path: &Path) -> std::borrow::Cow<'_, Path> {
59    std::borrow::Cow::Borrowed(path)
60}
61
62/// Resolved filesystem layout for one shep home
63///
64/// All paths are derived from `$SHEP_HOME` (default `<home>/.shep`); nothing
65/// here touches the filesystem. The root itself is created by the CLI's own
66/// `ensure_home`, for the commands that need it before any daemon exists
67/// (`startup` above all), and everything under it by
68/// `shep_daemon::boot::init_dirs` on each boot.
69#[derive(Debug, Clone, PartialEq, Eq)]
70pub struct ShepPaths {
71    /// Root: `$SHEP_HOME`
72    pub home: PathBuf,
73    /// Daemon config: `shep.toml`
74    pub daemon_config: PathBuf,
75    /// Flock snapshot (muster roll): `flock.json`
76    pub snapshot: PathBuf,
77    /// Log directory
78    pub logs: PathBuf,
79    /// Pid-file directory
80    pub pids: PathBuf,
81    /// Runtime dir (sockets; created 0700)
82    pub run: PathBuf,
83    /// The control address the client dials and the daemon answers on.
84    ///
85    /// **Two different kinds of thing behind one field, on purpose.** On
86    /// unix it is a filesystem path, `run/shep.sock`, and a real AF_UNIX
87    /// socket file lives there. On Windows it is [`Self::pipe_name`] — a
88    /// named pipe's `\\.\pipe\...` name, which is path-*shaped* but names an
89    /// object in the kernel's pipe namespace rather than a file on any
90    /// volume.
91    ///
92    /// One field rather than two because every consumer in the workspace
93    /// treats this as an opaque address it hands to `Client::connect`, and a
94    /// second field would make all of them choose. The one place the
95    /// difference is load-bearing is a caller that treats this as a *file* —
96    /// `shep-cli`'s `wait_for_socket_to_disappear` is the only one, and it
97    /// carries its own Windows arm because a pipe has no directory entry to
98    /// watch: it stops existing when its last handle closes, so "has the
99    /// daemon gone" is a connect attempt there, not a `Path::exists`.
100    ///
101    /// A corollary worth stating because it silently breaks otherwise:
102    /// `socket.parent()` is `$SHEP_HOME/run` on unix and the meaningless
103    /// `\\.\pipe` on Windows. Nothing may derive a directory from this field.
104    pub socket: PathBuf,
105    /// Bark history ring: `barks.jsonl`
106    pub barks: PathBuf,
107    /// Key/value store: `kv.json`
108    pub kv: PathBuf,
109    /// Operator override store: `overrides.json`
110    pub overrides: PathBuf,
111}
112
113/// FNV-1a, 64-bit, over `bytes`
114///
115/// Hand-rolled rather than reached for from `std`: [`std::hash::DefaultHasher`]
116/// does not promise a stable value across toolchains, and the daemon and a
117/// client built separately have to derive one pipe name and agree on it.
118fn fnv1a64(bytes: &[u8]) -> u64 {
119    bytes.iter().fold(0xcbf2_9ce4_8422_2325, |hash, &byte| {
120        (hash ^ u64::from(byte)).wrapping_mul(0x0000_0100_0000_01b3)
121    })
122}
123
124impl ShepPaths {
125    /// Windows named-pipe identity for this home:
126    /// `\\.\pipe\shep-<sanitized>-<digest>`
127    ///
128    /// The readable half is the home path with every non-alphanumeric
129    /// character collapsed to `-`, capped, so an operator reading a pipe name
130    /// can tell which home it belongs to. **That half alone does not identify
131    /// a home**: `\`, `:`, `.`, `_` and a literal `-` all become `-`, so
132    /// `C:\a\b` and `C:\a-b` sanitize to one string. The pipe namespace is
133    /// machine-global and [`crate::transport::Listener::bind`] asks for
134    /// `first_pipe_instance`, so a collision does not surface as an error: the
135    /// second home's daemon is refused as already running, and that home's CLI
136    /// then drives the first home's flock. No handshake field carries a home,
137    /// so nothing downstream would catch it.
138    ///
139    /// The appended digest of the full home path is what makes the name
140    /// distinct. Changing this derivation is a breaking change for any
141    /// already-running daemon: it stays bound under a name a client built
142    /// afterward would never dial.
143    #[must_use]
144    pub fn pipe_name(&self) -> String {
145        // Bounds the readable half; a pipe name may be 256 characters.
146        const MAX_STEM: usize = 64;
147
148        let home = self.home.to_string_lossy();
149        let sanitized: String = home
150            .chars()
151            .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
152            .collect();
153        let trimmed = sanitized.trim_matches('-');
154        // Every character above is ASCII, so this cut cannot split one.
155        let stem = trimmed[..trimmed.len().min(MAX_STEM)].trim_end_matches('-');
156        let digest = fnv1a64(home.as_bytes());
157        format!(r"\\.\pipe\shep-{stem}-{digest:016x}")
158    }
159
160    /// Resolves the layout from an environment lookup and the user's home dir
161    ///
162    /// [`Self::socket`] resolves per-platform — a socket file under `run/` on
163    /// unix, a `\\.\pipe\...` name on Windows — for the reason that field's
164    /// own doc gives. Everything else is identical on both.
165    #[must_use]
166    pub fn resolve(env: &dyn Fn(&str) -> Option<String>, home_dir: &Path) -> Self {
167        let home = env("SHEP_HOME")
168            .map(PathBuf::from)
169            .unwrap_or_else(|| home_dir.join(".shep"));
170        let run = home.join("run");
171        // `mut` is read only by the `cfg(windows)` block below; on unix the
172        // value is returned exactly as built.
173        #[cfg_attr(not(windows), allow(unused_mut))]
174        let mut paths = Self {
175            daemon_config: home.join("shep.toml"),
176            snapshot: home.join("flock.json"),
177            logs: home.join("logs"),
178            pids: home.join("pids"),
179            socket: run.join("shep.sock"),
180            barks: home.join("barks.jsonl"),
181            kv: home.join("kv.json"),
182            overrides: home.join("overrides.json"),
183            run,
184            home,
185        };
186        // Computed from the already-built value rather than inline above,
187        // because `pipe_name` reads `self.home` and the struct is what owns
188        // that derivation — duplicating the sanitizer here is exactly how
189        // the two would drift.
190        #[cfg(windows)]
191        {
192            paths.socket = PathBuf::from(paths.pipe_name());
193        }
194        paths
195    }
196}
197
198#[cfg(test)]
199mod tests {
200    /// Pins the strip directly, because no end-to-end case can. Node resolves
201    /// a `\\?\` path on some versions and not others, so the `.js` flockfile
202    /// cases passed on the development machine both before this existed and
203    /// after, while failing on the CI runner both times. Asserting on the
204    /// rewritten path is the part that holds either way.
205    #[cfg(windows)]
206    #[test]
207    fn a_verbatim_prefix_is_stripped() {
208        let rewritten = super::strip_verbatim_prefix(std::path::Path::new(r"\\?\C:\tmp\flock.js"));
209        assert_eq!(
210            rewritten.as_os_str(),
211            std::ffi::OsStr::new(r"C:\tmp\flock.js"),
212            "node reads the leading `\\\\` as a UNC share and lstats `C:`, so \
213             the verbatim prefix must not reach it"
214        );
215
216        let plain = std::path::Path::new(r"C:\tmp\flock.js");
217        assert_eq!(
218            super::strip_verbatim_prefix(plain).as_os_str(),
219            plain.as_os_str(),
220            "a path with no verbatim prefix must pass through untouched"
221        );
222    }
223
224    /// Guards the assumption the strip rests on: that `canonicalize` really
225    /// does hand back a prefixed path, and that the rewrite clears it without
226    /// breaking what it points at. If a future Windows or std stops adding
227    /// the prefix, this stays green and the strip becomes a no-op rather
228    /// than a wrong answer.
229    #[cfg(windows)]
230    #[test]
231    fn a_real_canonicalized_path_comes_back_free_of_the_prefix() {
232        let dir = tempfile::tempdir().expect("temp dir");
233        let file = dir.path().join("dog.exe");
234        std::fs::write(&file, b"not really an exe").expect("write file");
235
236        let canonical = std::fs::canonicalize(&file).expect("canonicalize");
237        let rewritten = super::strip_verbatim_prefix(&canonical);
238        let shown = rewritten.display().to_string();
239
240        assert!(
241            !shown.starts_with(r"\\?\"),
242            "the path an operator will read still carries a verbatim prefix: {shown}"
243        );
244        assert!(
245            std::path::Path::new(&shown).is_file(),
246            "stripping the prefix must not break the path: {shown}"
247        );
248    }
249
250    /// The unix build has nothing to strip, and the helper exists there only
251    /// so call sites do not each carry a `cfg`. Pinned so it stays that way.
252    #[cfg(not(windows))]
253    #[test]
254    fn a_unix_path_passes_through_untouched() {
255        let plain = std::path::Path::new("/tmp/flock.js");
256        assert_eq!(
257            super::strip_verbatim_prefix(plain).as_os_str(),
258            plain.as_os_str(),
259            "the non-Windows arm must be an identity"
260        );
261    }
262
263    use super::*;
264    use std::path::Path;
265
266    fn no_env(_: &str) -> Option<String> {
267        None
268    }
269
270    #[test]
271    fn default_layout_under_home_dir() {
272        let p = ShepPaths::resolve(&no_env, Path::new("/home/ada"));
273        assert_eq!(p.home, Path::new("/home/ada/.shep"));
274        assert_eq!(p.daemon_config, Path::new("/home/ada/.shep/shep.toml"));
275        assert_eq!(p.snapshot, Path::new("/home/ada/.shep/flock.json"));
276        assert_eq!(p.logs, Path::new("/home/ada/.shep/logs"));
277        assert_eq!(p.pids, Path::new("/home/ada/.shep/pids"));
278        assert_eq!(p.run, Path::new("/home/ada/.shep/run"));
279        assert_eq!(p.barks, Path::new("/home/ada/.shep/barks.jsonl"));
280        assert_eq!(p.kv, Path::new("/home/ada/.shep/kv.json"));
281        assert_eq!(p.overrides, Path::new("/home/ada/.shep/overrides.json"));
282    }
283
284    /// The one field that is not the same kind of thing on both platforms —
285    /// see [`ShepPaths::socket`]'s own doc. Asserted per-platform rather
286    /// than skipped on Windows, because "the socket resolves to the pipe
287    /// name" IS the Windows transport's identity and a silent fallback to
288    /// `run/shep.sock` there would produce a daemon that binds a pipe and a
289    /// client that dials a file that does not exist.
290    #[test]
291    fn the_control_address_is_a_socket_file_on_unix_and_a_pipe_name_on_windows() {
292        let p = ShepPaths::resolve(&no_env, Path::new("/home/ada"));
293        #[cfg(unix)]
294        assert_eq!(p.socket, Path::new("/home/ada/.shep/run/shep.sock"));
295        #[cfg(windows)]
296        assert_eq!(
297            p.socket,
298            Path::new(r"\\.\pipe\shep-home-ada--shep-fd394cfc5c93ad12")
299        );
300        #[cfg(windows)]
301        assert_eq!(
302            p.socket,
303            Path::new(&p.pipe_name()),
304            "the resolved address and `pipe_name` must not drift"
305        );
306    }
307
308    #[test]
309    fn shep_home_env_overrides_root() {
310        let env = |key: &str| (key == "SHEP_HOME").then(|| "/srv/shep".to_string());
311        let p = ShepPaths::resolve(&env, Path::new("/home/ada"));
312        assert_eq!(p.home, Path::new("/srv/shep"));
313        #[cfg(unix)]
314        assert_eq!(p.socket, Path::new("/srv/shep/run/shep.sock"));
315        #[cfg(windows)]
316        assert_eq!(
317            p.socket,
318            Path::new(r"\\.\pipe\shep-srv-shep-23b467803966a71a")
319        );
320    }
321
322    #[test]
323    fn pipe_name_is_per_home_and_sanitized() {
324        // Windows transport identity (spec §6): derived from SHEP_HOME so
325        // two homes never share a pipe; non-alphanumerics collapse to '-',
326        // then a digest of the whole home path. Both homes come from the env
327        // rather than the default join, whose separator is the host's and
328        // would give the digest a different value per platform.
329        let env = |key: &str| (key == "SHEP_HOME").then(|| "/home/ada/.shep".to_string());
330        let p = ShepPaths::resolve(&env, Path::new("/home/ada"));
331        assert_eq!(
332            p.pipe_name(),
333            r"\\.\pipe\shep-home-ada--shep-626b4d544f86fe95"
334        );
335        let env = |key: &str| (key == "SHEP_HOME").then(|| "/srv/shep".to_string());
336        let q = ShepPaths::resolve(&env, Path::new("/home/ada"));
337        assert_eq!(q.pipe_name(), r"\\.\pipe\shep-srv-shep-23b467803966a71a");
338    }
339
340    /// The sanitizer is not injective (`\`, `:` and a literal `-` all become
341    /// `-`), and a shared name is the one failure that reaches nobody: the
342    /// second daemon is refused as already running and its CLI then drives the
343    /// first home's flock in silence.
344    #[test]
345    fn two_homes_that_sanitize_alike_get_distinct_pipe_names() {
346        let nested = |key: &str| (key == "SHEP_HOME").then(|| r"C:\a\b".to_string());
347        let dashed = |key: &str| (key == "SHEP_HOME").then(|| r"C:\a-b".to_string());
348        let n = ShepPaths::resolve(&nested, Path::new("/home/ada"));
349        let d = ShepPaths::resolve(&dashed, Path::new("/home/ada"));
350        assert!(
351            n.pipe_name().starts_with(r"\\.\pipe\shep-C--a-b-")
352                && d.pipe_name().starts_with(r"\\.\pipe\shep-C--a-b-"),
353            "the readable stem is what collides, and it stays readable: {} vs {}",
354            n.pipe_name(),
355            d.pipe_name()
356        );
357        assert_ne!(
358            n.pipe_name(),
359            d.pipe_name(),
360            "only the digest keeps two homes that sanitize alike off one pipe"
361        );
362    }
363}