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}
110
111/// FNV-1a, 64-bit, over `bytes`
112///
113/// Hand-rolled rather than reached for from `std`: [`std::hash::DefaultHasher`]
114/// does not promise a stable value across toolchains, and the daemon and a
115/// client built separately have to derive one pipe name and agree on it.
116fn fnv1a64(bytes: &[u8]) -> u64 {
117    bytes.iter().fold(0xcbf2_9ce4_8422_2325, |hash, &byte| {
118        (hash ^ u64::from(byte)).wrapping_mul(0x0000_0100_0000_01b3)
119    })
120}
121
122impl ShepPaths {
123    /// Windows named-pipe identity for this home:
124    /// `\\.\pipe\shep-<sanitized>-<digest>`
125    ///
126    /// The readable half is the home path with every non-alphanumeric
127    /// character collapsed to `-`, capped, so an operator reading a pipe name
128    /// can tell which home it belongs to. **That half alone does not identify
129    /// a home**: `\`, `:`, `.`, `_` and a literal `-` all become `-`, so
130    /// `C:\a\b` and `C:\a-b` sanitize to one string. The pipe namespace is
131    /// machine-global and [`crate::transport::Listener::bind`] asks for
132    /// `first_pipe_instance`, so a collision does not surface as an error: the
133    /// second home's daemon is refused as already running, and that home's CLI
134    /// then drives the first home's flock. No handshake field carries a home,
135    /// so nothing downstream would catch it.
136    ///
137    /// The appended digest of the full home path is what makes the name
138    /// distinct. Changing this derivation is a breaking change for any
139    /// already-running daemon: it stays bound under a name a client built
140    /// afterward would never dial.
141    #[must_use]
142    pub fn pipe_name(&self) -> String {
143        // Bounds the readable half; a pipe name may be 256 characters.
144        const MAX_STEM: usize = 64;
145
146        let home = self.home.to_string_lossy();
147        let sanitized: String = home
148            .chars()
149            .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
150            .collect();
151        let trimmed = sanitized.trim_matches('-');
152        // Every character above is ASCII, so this cut cannot split one.
153        let stem = trimmed[..trimmed.len().min(MAX_STEM)].trim_end_matches('-');
154        let digest = fnv1a64(home.as_bytes());
155        format!(r"\\.\pipe\shep-{stem}-{digest:016x}")
156    }
157
158    /// Resolves the layout from an environment lookup and the user's home dir
159    ///
160    /// [`Self::socket`] resolves per-platform — a socket file under `run/` on
161    /// unix, a `\\.\pipe\...` name on Windows — for the reason that field's
162    /// own doc gives. Everything else is identical on both.
163    #[must_use]
164    pub fn resolve(env: &dyn Fn(&str) -> Option<String>, home_dir: &Path) -> Self {
165        let home = env("SHEP_HOME")
166            .map(PathBuf::from)
167            .unwrap_or_else(|| home_dir.join(".shep"));
168        let run = home.join("run");
169        // `mut` is read only by the `cfg(windows)` block below; on unix the
170        // value is returned exactly as built.
171        #[cfg_attr(not(windows), allow(unused_mut))]
172        let mut paths = Self {
173            daemon_config: home.join("shep.toml"),
174            snapshot: home.join("flock.json"),
175            logs: home.join("logs"),
176            pids: home.join("pids"),
177            socket: run.join("shep.sock"),
178            barks: home.join("barks.jsonl"),
179            kv: home.join("kv.json"),
180            run,
181            home,
182        };
183        // Computed from the already-built value rather than inline above,
184        // because `pipe_name` reads `self.home` and the struct is what owns
185        // that derivation — duplicating the sanitizer here is exactly how
186        // the two would drift.
187        #[cfg(windows)]
188        {
189            paths.socket = PathBuf::from(paths.pipe_name());
190        }
191        paths
192    }
193}
194
195#[cfg(test)]
196mod tests {
197    /// Pins the strip directly, because no end-to-end case can. Node resolves
198    /// a `\\?\` path on some versions and not others, so the `.js` flockfile
199    /// cases passed on the development machine both before this existed and
200    /// after, while failing on the CI runner both times. Asserting on the
201    /// rewritten path is the part that holds either way.
202    #[cfg(windows)]
203    #[test]
204    fn a_verbatim_prefix_is_stripped() {
205        let rewritten = super::strip_verbatim_prefix(std::path::Path::new(r"\\?\C:\tmp\flock.js"));
206        assert_eq!(
207            rewritten.as_os_str(),
208            std::ffi::OsStr::new(r"C:\tmp\flock.js"),
209            "node reads the leading `\\\\` as a UNC share and lstats `C:`, so \
210             the verbatim prefix must not reach it"
211        );
212
213        let plain = std::path::Path::new(r"C:\tmp\flock.js");
214        assert_eq!(
215            super::strip_verbatim_prefix(plain).as_os_str(),
216            plain.as_os_str(),
217            "a path with no verbatim prefix must pass through untouched"
218        );
219    }
220
221    /// Guards the assumption the strip rests on: that `canonicalize` really
222    /// does hand back a prefixed path, and that the rewrite clears it without
223    /// breaking what it points at. If a future Windows or std stops adding
224    /// the prefix, this stays green and the strip becomes a no-op rather
225    /// than a wrong answer.
226    #[cfg(windows)]
227    #[test]
228    fn a_real_canonicalized_path_comes_back_free_of_the_prefix() {
229        let dir = tempfile::tempdir().expect("temp dir");
230        let file = dir.path().join("dog.exe");
231        std::fs::write(&file, b"not really an exe").expect("write file");
232
233        let canonical = std::fs::canonicalize(&file).expect("canonicalize");
234        let rewritten = super::strip_verbatim_prefix(&canonical);
235        let shown = rewritten.display().to_string();
236
237        assert!(
238            !shown.starts_with(r"\\?\"),
239            "the path an operator will read still carries a verbatim prefix: {shown}"
240        );
241        assert!(
242            std::path::Path::new(&shown).is_file(),
243            "stripping the prefix must not break the path: {shown}"
244        );
245    }
246
247    /// The unix build has nothing to strip, and the helper exists there only
248    /// so call sites do not each carry a `cfg`. Pinned so it stays that way.
249    #[cfg(not(windows))]
250    #[test]
251    fn a_unix_path_passes_through_untouched() {
252        let plain = std::path::Path::new("/tmp/flock.js");
253        assert_eq!(
254            super::strip_verbatim_prefix(plain).as_os_str(),
255            plain.as_os_str(),
256            "the non-Windows arm must be an identity"
257        );
258    }
259
260    use super::*;
261    use std::path::Path;
262
263    fn no_env(_: &str) -> Option<String> {
264        None
265    }
266
267    #[test]
268    fn default_layout_under_home_dir() {
269        let p = ShepPaths::resolve(&no_env, Path::new("/home/ada"));
270        assert_eq!(p.home, Path::new("/home/ada/.shep"));
271        assert_eq!(p.daemon_config, Path::new("/home/ada/.shep/shep.toml"));
272        assert_eq!(p.snapshot, Path::new("/home/ada/.shep/flock.json"));
273        assert_eq!(p.logs, Path::new("/home/ada/.shep/logs"));
274        assert_eq!(p.pids, Path::new("/home/ada/.shep/pids"));
275        assert_eq!(p.run, Path::new("/home/ada/.shep/run"));
276        assert_eq!(p.barks, Path::new("/home/ada/.shep/barks.jsonl"));
277        assert_eq!(p.kv, Path::new("/home/ada/.shep/kv.json"));
278    }
279
280    /// The one field that is not the same kind of thing on both platforms —
281    /// see [`ShepPaths::socket`]'s own doc. Asserted per-platform rather
282    /// than skipped on Windows, because "the socket resolves to the pipe
283    /// name" IS the Windows transport's identity and a silent fallback to
284    /// `run/shep.sock` there would produce a daemon that binds a pipe and a
285    /// client that dials a file that does not exist.
286    #[test]
287    fn the_control_address_is_a_socket_file_on_unix_and_a_pipe_name_on_windows() {
288        let p = ShepPaths::resolve(&no_env, Path::new("/home/ada"));
289        #[cfg(unix)]
290        assert_eq!(p.socket, Path::new("/home/ada/.shep/run/shep.sock"));
291        #[cfg(windows)]
292        assert_eq!(
293            p.socket,
294            Path::new(r"\\.\pipe\shep-home-ada--shep-fd394cfc5c93ad12")
295        );
296        #[cfg(windows)]
297        assert_eq!(
298            p.socket,
299            Path::new(&p.pipe_name()),
300            "the resolved address and `pipe_name` must not drift"
301        );
302    }
303
304    #[test]
305    fn shep_home_env_overrides_root() {
306        let env = |key: &str| (key == "SHEP_HOME").then(|| "/srv/shep".to_string());
307        let p = ShepPaths::resolve(&env, Path::new("/home/ada"));
308        assert_eq!(p.home, Path::new("/srv/shep"));
309        #[cfg(unix)]
310        assert_eq!(p.socket, Path::new("/srv/shep/run/shep.sock"));
311        #[cfg(windows)]
312        assert_eq!(
313            p.socket,
314            Path::new(r"\\.\pipe\shep-srv-shep-23b467803966a71a")
315        );
316    }
317
318    #[test]
319    fn pipe_name_is_per_home_and_sanitized() {
320        // Windows transport identity (spec §6): derived from SHEP_HOME so
321        // two homes never share a pipe; non-alphanumerics collapse to '-',
322        // then a digest of the whole home path. Both homes come from the env
323        // rather than the default join, whose separator is the host's and
324        // would give the digest a different value per platform.
325        let env = |key: &str| (key == "SHEP_HOME").then(|| "/home/ada/.shep".to_string());
326        let p = ShepPaths::resolve(&env, Path::new("/home/ada"));
327        assert_eq!(
328            p.pipe_name(),
329            r"\\.\pipe\shep-home-ada--shep-626b4d544f86fe95"
330        );
331        let env = |key: &str| (key == "SHEP_HOME").then(|| "/srv/shep".to_string());
332        let q = ShepPaths::resolve(&env, Path::new("/home/ada"));
333        assert_eq!(q.pipe_name(), r"\\.\pipe\shep-srv-shep-23b467803966a71a");
334    }
335
336    /// The sanitizer is not injective (`\`, `:` and a literal `-` all become
337    /// `-`), and a shared name is the one failure that reaches nobody: the
338    /// second daemon is refused as already running and its CLI then drives the
339    /// first home's flock in silence.
340    #[test]
341    fn two_homes_that_sanitize_alike_get_distinct_pipe_names() {
342        let nested = |key: &str| (key == "SHEP_HOME").then(|| r"C:\a\b".to_string());
343        let dashed = |key: &str| (key == "SHEP_HOME").then(|| r"C:\a-b".to_string());
344        let n = ShepPaths::resolve(&nested, Path::new("/home/ada"));
345        let d = ShepPaths::resolve(&dashed, Path::new("/home/ada"));
346        assert!(
347            n.pipe_name().starts_with(r"\\.\pipe\shep-C--a-b-")
348                && d.pipe_name().starts_with(r"\\.\pipe\shep-C--a-b-"),
349            "the readable stem is what collides, and it stays readable: {} vs {}",
350            n.pipe_name(),
351            d.pipe_name()
352        );
353        assert_ne!(
354            n.pipe_name(),
355            d.pipe_name(),
356            "only the digest keeps two homes that sanitize alike off one pipe"
357        );
358    }
359}