Skip to main content

tinyharness_lib/
path_guard.rs

1//! Path containment guard for the built-in file tools.
2//!
3//! The built-in tools (`ls`, `read`, `write`, `edit`, `grep`, `glob`) run
4//! in-process, so they cannot be confined by an OS-level sandbox the way the
5//! shell tools can. Their containment is therefore a *path* check performed
6//! before the tool handler executes: every path argument must resolve inside
7//! the workspace root (or an explicitly allowed extra root).
8//!
9//! [`PathGuard`] is always active — there is no flag to turn it off. The
10//! workspace root is trusted; everything else is unreachable unless the user
11//! adds it to `allowed_paths`. Resolution handles:
12//!
13//! - relative paths (joined with the workspace root),
14//! - `..` traversal,
15//! - symlink escapes, including a `..` *after* a symlink (resolved component
16//!   by component, in the order `open(2)` uses),
17//! - glob patterns (only the static prefix can be checked, so `glob` also
18//!   filters its results — see [`crate::tools::glob`]).
19//!
20//! Checks fail closed: a path that cannot be *proven* to be inside an allowed
21//! root is rejected, and the rejection is reported as a tool error regardless
22//! of auto-accept mode. Callers must act on the **returned** path rather than
23//! the raw argument — a relative argument means "relative to the workspace
24//! root" here, but "relative to the process cwd" to `std::fs`.
25
26use std::collections::VecDeque;
27use std::ffi::OsString;
28use std::path::{Component, Path, PathBuf};
29
30/// Prefixes that extra allowed roots may never cover.
31///
32/// The workspace root is exempt from this list (opening TinyHarness inside,
33/// say, `/etc` has to keep working); it applies to paths reached through
34/// `allowed_paths`, so a too-broad entry like `"/"` cannot be used to write
35/// system configuration.
36pub const DEFAULT_BLOCKED_PREFIXES: &[&str] = &[
37    "/etc", "/usr", "/boot", "/sys", "/proc", "/dev", "/root", "/var/log", "/var/run", "/run",
38];
39
40/// Maximum symlink hops tolerated while resolving a path, matching the
41/// kernel's `ELOOP` limit. Beyond it the resolution fails closed.
42const MAX_SYMLINK_HOPS: usize = 40;
43
44/// Normalize a path lexically: resolve `.` and `..` components without
45/// touching the filesystem. The input should be absolute; a `..` that would
46/// escape the filesystem root is clamped at the root.
47///
48/// Only for paths that do not exist yet (configuration prefixes, where there
49/// is nothing to canonicalize). Containment of a *tool call* must go through
50/// [`PathGuard::resolve_contained`], because lexical `..` and the kernel's
51/// left-to-right resolution disagree whenever a symlink is involved:
52/// `<root>/link/../etc/passwd` (with `link -> /usr`) normalizes lexically to
53/// `<root>/etc/passwd` but the kernel opens `/etc/passwd`.
54fn normalize_lexical(path: &Path) -> PathBuf {
55    let mut out = PathBuf::new();
56    for comp in path.components() {
57        match comp {
58            Component::CurDir => {}
59            Component::ParentDir => {
60                // pop() returns false at the root — we stay clamped there.
61                let _ = out.pop();
62            }
63            other => out.push(other.as_os_str()),
64        }
65    }
66    out
67}
68
69/// Reassemble a component stack produced by [`PathGuard::resolve_kernel_order`].
70///
71/// The stack always starts with the `"/"` marker, so the result is absolute.
72fn join_components(parts: &[OsString]) -> PathBuf {
73    let mut path = PathBuf::new();
74    for part in parts {
75        path.push(part);
76    }
77    path
78}
79
80/// Extract the static (non-wildcard) directory prefix of a glob pattern.
81///
82/// Everything before the first glob metacharacter (`*`, `?`, `[`), trimmed
83/// back to the last `/`, is a literal path prefix. Patterns without any `/`
84/// before the first metacharacter are anchored at the current directory.
85///
86/// Examples: `**/*.rs` → `.`, `src/**/*.toml` → `src`, `/etc/**` → `/etc`,
87/// `../foo/*.rs` → `../foo`, `/abs/file.txt` → `/abs`.
88pub(crate) fn glob_static_prefix(pattern: &str) -> &str {
89    let meta_idx = pattern.find(['*', '?', '[']).unwrap_or(pattern.len());
90    let prefix = &pattern[..meta_idx];
91    match prefix.rfind('/') {
92        Some(i) if i > 0 => &pattern[..i],
93        Some(_) => "/", // pattern anchored at filesystem root — static prefix is `/`
94        None => ".",
95    }
96}
97
98/// Canonicalize the existing prefix of `p` and re-attach the non-existent
99/// tail, so a path spelled through a symlink (macOS `/var` -> `/private/var`)
100/// matches the canonical forms `resolve_contained` produces even when the
101/// final components do not exist yet (an `allowed_paths` entry naming a
102/// directory the user has not created).
103fn canonicalize_prefix(p: &Path) -> PathBuf {
104    let mut tail: Vec<OsString> = Vec::new();
105    let mut ancestor = p;
106    while !ancestor.exists() {
107        match (ancestor.file_name(), ancestor.parent()) {
108            (Some(name), Some(parent)) if parent != ancestor => {
109                tail.push(name.to_os_string());
110                ancestor = parent;
111            }
112            _ => return normalize_lexical(p),
113        }
114    }
115    let mut out = ancestor
116        .canonicalize()
117        .unwrap_or_else(|_| normalize_lexical(ancestor));
118    for comp in tail.iter().rev() {
119        out.push(comp);
120    }
121    out
122}
123
124/// Expand a leading `~` using the injected home directory.
125///
126/// Only `~` and `~/…` are supported — a `~user` form would need a passwd
127/// lookup, and an absolute path is the clearer spelling there anyway. Errors
128/// when no home directory was injected rather than silently resolving against
129/// the workspace root.
130fn expand_tilde(raw: &str, home: Option<&Path>) -> Result<PathBuf, String> {
131    if raw == "~" {
132        return home
133            .map(|p| p.to_path_buf())
134            .ok_or_else(|| format!("allowed_paths entry '{raw}' needs a home directory"));
135    }
136    let Some(rest) = raw.strip_prefix("~/") else {
137        return Err(format!(
138            "allowed_paths entry '{raw}' uses an unsupported '~user' form; use '~/…' or an absolute path"
139        ));
140    };
141    home.map(|p| p.join(rest))
142        .ok_or_else(|| format!("allowed_paths entry '{raw}' needs a home directory"))
143}
144
145/// Builder for [`PathGuard`] that resolves user-configured extra roots.
146///
147/// Everything is injectable (no ambient `HOME`) to match the [`Paths`]
148/// discipline: pass the home directory explicitly when `allowed_paths` may
149/// contain `~`.
150///
151/// [`Paths`]: crate::paths::Paths
152#[derive(Debug)]
153pub struct PathGuardBuilder {
154    root: PathBuf,
155    allowed_raw: Vec<String>,
156    extra_blocked: Vec<String>,
157    blocked_override: Option<Vec<String>>,
158    home: Option<PathBuf>,
159}
160
161impl PathGuardBuilder {
162    /// Add the raw `allowed_paths` entries (absolute, `~`-prefixed, or
163    /// relative to the workspace root).
164    pub fn allowed_paths<I, S>(mut self, paths: I) -> Self
165    where
166        I: IntoIterator<Item = S>,
167        S: Into<String>,
168    {
169        self.allowed_raw.extend(paths.into_iter().map(Into::into));
170        self
171    }
172
173    /// Append prefixes to the default blocked list.
174    pub fn extra_blocked_paths<I, S>(mut self, paths: I) -> Self
175    where
176        I: IntoIterator<Item = S>,
177        S: Into<String>,
178    {
179        self.extra_blocked.extend(paths.into_iter().map(Into::into));
180        self
181    }
182
183    /// Replace the blocked-prefix list entirely, dropping the defaults.
184    ///
185    /// Only for callers that need a bespoke policy — the defaults exist to
186    /// stop an over-broad `allowed_paths` entry like `"/"` from reaching
187    /// system configuration.
188    pub fn blocked_paths<I, S>(mut self, paths: I) -> Self
189    where
190        I: IntoIterator<Item = S>,
191        S: Into<String>,
192    {
193        self.blocked_override = Some(paths.into_iter().map(Into::into).collect());
194        self
195    }
196
197    /// The home directory used to expand `~` in configured paths.
198    pub fn home(mut self, home: Option<&Path>) -> Self {
199        self.home = home.map(|p| p.to_path_buf());
200        self
201    }
202
203    /// The effective blocked prefixes: the override if given, otherwise the
204    /// defaults plus any extras.
205    fn effective_blocked(&self) -> Vec<PathBuf> {
206        let raw: Vec<String> = match &self.blocked_override {
207            Some(list) => list.clone(),
208            None => DEFAULT_BLOCKED_PREFIXES
209                .iter()
210                .map(|s| (*s).to_string())
211                .chain(self.extra_blocked.iter().cloned())
212                .collect(),
213        };
214        raw.iter()
215            .map(|s| normalize_lexical(Path::new(s)))
216            .collect()
217    }
218
219    /// Resolve everything and build the guard.
220    ///
221    /// Returns `Err` for a configuration entry that cannot be resolved (bad
222    /// `~` expansion) so a typo in `settings.json` surfaces at startup rather
223    /// than as a confusing tool error mid-session. Entries swallowed by a
224    /// blocked prefix are dropped with a warning — they're pointless, not
225    /// dangerous.
226    pub fn build(self) -> Result<PathGuard, String> {
227        let canonical_root = self.root.canonicalize().map_err(|e| {
228            format!(
229                "Failed to canonicalize workspace root '{}': {}",
230                self.root.display(),
231                e
232            )
233        })?;
234        if !canonical_root.is_dir() {
235            return Err(format!(
236                "Workspace root '{}' is not a directory",
237                self.root.display()
238            ));
239        }
240
241        let blocked = self.effective_blocked();
242        let home = self.home.as_deref();
243        let mut allowed = Vec::new();
244        for entry in &self.allowed_raw {
245            let trimmed = entry.trim();
246            if trimmed.is_empty() {
247                continue;
248            }
249            let expanded = if trimmed.starts_with('~') {
250                expand_tilde(trimmed, home)
251                    .map_err(|e| format!("invalid allowed_paths entry '{entry}': {e}"))?
252            } else if Path::new(trimmed).is_absolute() {
253                PathBuf::from(trimmed)
254            } else {
255                canonical_root.join(trimmed)
256            };
257            let normalized = normalize_lexical(&expanded);
258            // Canonicalize entries (including their existing prefix), so a
259            // path reached through a symlink (macOS: `/var` -> `/private/var`,
260            // `/tmp` -> `/private/tmp`) is stored in the same form
261            // `resolve_contained` produces and `covers` can match against the
262            // canonical root. Non-existent tails stay lexical — they are
263            // prefixes for files a tool may create.
264            let resolved_entry = canonicalize_prefix(&expanded);
265            // Reject in both directions: an entry *inside* a blocked prefix
266            // (`/etc/ssl`) is pointless, and an entry that *contains* one
267            // (`/`, `/var`) would let the blocked paths through the back
268            // door, because `covers()` only checks the blocked list against
269            // paths outside the workspace root. `starts_with` is
270            // component-wise, so `/root` does not match `/rootfoo`. Check
271            // both the lexical and the canonical form — a symlink entry
272            // pointing into a blocked prefix must not slip through either.
273            if blocked.iter().any(|b| {
274                normalized.starts_with(b)
275                    || b.starts_with(&normalized)
276                    || resolved_entry.starts_with(b)
277                    || b.starts_with(&resolved_entry)
278            }) {
279                tracing::warn!(
280                    "allowed_paths entry '{}' overlaps a blocked prefix — ignoring it",
281                    entry
282                );
283                continue;
284            }
285            allowed.push(resolved_entry);
286        }
287
288        Ok(PathGuard {
289            root: canonical_root,
290            allowed,
291            blocked,
292        })
293    }
294}
295
296/// Confines file-tool path access to the workspace root plus any explicitly
297/// allowed extra roots.
298#[derive(Debug, Clone)]
299pub struct PathGuard {
300    /// Canonicalized absolute workspace root.
301    root: PathBuf,
302    /// Extra absolute roots the user allowed (lexically normalized).
303    allowed: Vec<PathBuf>,
304    /// Prefixes that extra roots may never cover.
305    blocked: Vec<PathBuf>,
306}
307
308impl PathGuard {
309    /// Start building a guard rooted at `root`, with the default blocked
310    /// prefixes and no extra allowed roots.
311    pub fn builder(root: &Path) -> PathGuardBuilder {
312        PathGuardBuilder {
313            root: root.to_path_buf(),
314            allowed_raw: Vec::new(),
315            extra_blocked: Vec::new(),
316            blocked_override: None,
317            home: None,
318        }
319    }
320
321    /// Minimal guard with no extra allowed roots — the workspace root only.
322    ///
323    /// Shorthand for `PathGuard::builder(root).build()`; this is the form used
324    /// by tests and by callers with no path configuration.
325    pub fn new(root: &Path) -> Result<Self, String> {
326        Self::builder(root).build()
327    }
328
329    /// Build a guard from already-resolved configuration in one call.
330    ///
331    /// `allowed` entries follow the same rules as the `allowed_paths` setting:
332    /// absolute, `~`-prefixed (expanded with `home`), or relative to `root`.
333    /// `extra_blocked` is appended to [`DEFAULT_BLOCKED_PREFIXES`].
334    pub fn configured(
335        root: &Path,
336        allowed: &[String],
337        home: Option<&Path>,
338        extra_blocked: &[String],
339    ) -> Result<Self, String> {
340        Self::builder(root)
341            .allowed_paths(allowed.iter().cloned())
342            .extra_blocked_paths(extra_blocked.iter().cloned())
343            .home(home)
344            .build()
345    }
346
347    /// The canonicalized workspace root.
348    pub fn root(&self) -> &Path {
349        &self.root
350    }
351
352    /// The extra allowed roots (the workspace root is implicit and first).
353    pub fn allowed_roots(&self) -> &[PathBuf] {
354        &self.allowed
355    }
356
357    /// The blocked prefixes consulted for non-root paths.
358    pub fn blocked_prefixes(&self) -> &[PathBuf] {
359        &self.blocked
360    }
361
362    /// Is `p` (already lexically normalized and absolute) inside an allowed
363    /// root?
364    ///
365    /// The workspace root is trusted outright; extra roots must clear the
366    /// blocked list first.
367    fn covers(&self, p: &Path) -> bool {
368        if p.starts_with(&self.root) {
369            return true;
370        }
371        if self.blocked.iter().any(|b| p.starts_with(b)) {
372            return false;
373        }
374        self.allowed.iter().any(|a| p.starts_with(a))
375    }
376
377    /// Resolve `raw` (a path as supplied by a tool call) and verify it stays
378    /// within an allowed root.
379    ///
380    /// Returns `Ok(resolved)` with the fully resolved absolute path on
381    /// success, or `Err(message)` describing the violation. Callers must use
382    /// the returned path rather than the raw argument: the raw string may be
383    /// relative, and a relative path means different things to this guard
384    /// (resolved against the workspace root) and to `std::fs` (resolved
385    /// against the process cwd).
386    pub fn resolve_contained(&self, raw: &str) -> Result<PathBuf, String> {
387        if raw.trim().is_empty() {
388            return Err(self.violation_message(raw));
389        }
390
391        let candidate = Path::new(raw);
392        let joined = if candidate.is_absolute() {
393            candidate.to_path_buf()
394        } else {
395            self.root.join(candidate)
396        };
397
398        // Fast path: a purely lexical rejection needs no filesystem access, and
399        // it is the common case for an obvious escape (`../x`, `/etc/passwd`).
400        // But when the root itself passes through a symlink (macOS:
401        // `/var` -> `/private/var`), the lexical form of an in-root path does
402        // not start with the canonical root, so a lexical miss is not yet a
403        // rejection — resolve in kernel order first and only then fail.
404        let lexical = normalize_lexical(&joined);
405        if !self.covers(&lexical) {
406            let resolved = self
407                .resolve_kernel_order(&joined)
408                .ok_or_else(|| self.violation_message(raw))?;
409            if !self.covers(&resolved) {
410                return Err(self.violation_message(raw));
411            }
412            return Ok(resolved);
413        }
414
415        // Real resolution, in the order the kernel uses. The lexical check
416        // above is *not* sufficient: `<root>/link/../etc/passwd` with
417        // `link -> /usr` normalizes to `<root>/etc/passwd` (inside the root)
418        // but opens `/etc/passwd`.
419        let resolved = self
420            .resolve_kernel_order(&joined)
421            .ok_or_else(|| self.violation_message(raw))?;
422
423        if !self.covers(&resolved) {
424            return Err(self.violation_message(raw));
425        }
426
427        Ok(resolved)
428    }
429
430    /// Walk `joined` component by component, following symlinks as they are
431    /// encountered, so a `..` applies to the *link's target* rather than to
432    /// the textual path — the semantics `open(2)` uses.
433    ///
434    /// Components that do not exist yet are appended literally and the walk
435    /// continues (a `write` legitimately names a new file; its not-yet-existing
436    /// parents cannot be symlinks). Exceeding [`MAX_SYMLINK_HOPS`], or a
437    /// symlink that cannot be read, returns `None` — callers fail closed.
438    fn resolve_kernel_order(&self, joined: &Path) -> Option<PathBuf> {
439        debug_assert!(joined.is_absolute());
440
441        // The resolved component stack. Always begins with the root marker.
442        let mut out: Vec<OsString> = vec![OsString::from("/")];
443        // Components still to process; symlink targets are spliced at the front.
444        let mut rest: VecDeque<OsString> = joined
445            .components()
446            .filter(|c| !matches!(c, Component::RootDir))
447            .map(|c| OsString::from(c.as_os_str()))
448            .collect();
449
450        let mut hops = 0;
451        while let Some(comp) = rest.pop_front() {
452            match comp.to_str() {
453                Some(".") => continue,
454                Some("..") => {
455                    // Pop, but never past the root marker.
456                    if out.len() > 1 {
457                        out.pop();
458                    }
459                    continue;
460                }
461                _ => {}
462            }
463
464            out.push(comp);
465            let candidate = join_components(&out);
466            let meta = match std::fs::symlink_metadata(&candidate) {
467                Ok(meta) => meta,
468                // Missing: nothing below it can exist either, so the remaining
469                // components are appended literally by subsequent iterations.
470                Err(_) => continue,
471            };
472            if !meta.file_type().is_symlink() {
473                continue;
474            }
475
476            hops += 1;
477            if hops > MAX_SYMLINK_HOPS {
478                return None;
479            }
480            let target = std::fs::read_link(&candidate).ok()?;
481            out.pop();
482            if target.is_absolute() {
483                out.clear();
484                out.push(OsString::from("/"));
485            }
486            let splice = target
487                .components()
488                .filter(|c| !matches!(c, Component::RootDir))
489                .map(|c| OsString::from(c.as_os_str()))
490                .collect::<Vec<_>>();
491            for item in splice.into_iter().rev() {
492                rest.push_front(item);
493            }
494        }
495
496        Some(join_components(&out))
497    }
498
499    /// Returns `true` if `raw` resolves to a path inside an allowed root.
500    pub fn contains(&self, raw: &str) -> bool {
501        self.resolve_contained(raw).is_ok()
502    }
503
504    /// Open `path` for reading, then verify the open descriptor is contained.
505    ///
506    /// `resolve_contained` proves containment at check time, but the handler
507    /// opens the path later, and the kernel re-resolves every component at
508    /// `open(2)` — a racing process can swap a directory for a symlink in
509    /// between (the process sandbox mounts the workspace read-write, so a
510    /// sandboxed command can do exactly that). Verifying the descriptor's
511    /// real path after the open closes that race.
512    pub fn open_read_contained(&self, path: &Path) -> Result<std::fs::File, String> {
513        let file = std::fs::File::open(path)
514            .map_err(|e| format!("Error opening '{}': {}", path.display(), e))?;
515        self.verify_open_file(&file, path)?;
516        Ok(file)
517    }
518
519    /// Open `path` for writing (create/truncate), then verify containment.
520    pub fn create_contained(&self, path: &Path) -> Result<std::fs::File, String> {
521        let file = std::fs::OpenOptions::new()
522            .write(true)
523            .create(true)
524            .truncate(true)
525            .open(path)
526            .map_err(|e| format!("Error opening '{}' for writing: {}", path.display(), e))?;
527        self.verify_open_file(&file, path)?;
528        Ok(file)
529    }
530
531    /// Open `path` as a directory, then verify the open descriptor.
532    pub fn open_dir_contained(&self, path: &Path) -> Result<std::fs::File, String> {
533        let file = std::fs::File::open(path)
534            .map_err(|e| format!("Error opening directory '{}': {}", path.display(), e))?;
535        self.verify_open_file(&file, path)?;
536        Ok(file)
537    }
538
539    /// Read a file to a string through a verified descriptor.
540    pub fn read_contained(&self, path: &Path) -> Result<String, String> {
541        use std::io::Read;
542        let mut file = self.open_read_contained(path)?;
543        let mut buf = String::new();
544        file.read_to_string(&mut buf)
545            .map_err(|e| format!("Error reading '{}': {}", path.display(), e))?;
546        Ok(buf)
547    }
548
549    /// Write a file through a verified descriptor, creating parent
550    /// directories one component at a time with each new directory verified
551    /// the same way (a plain `create_dir_all` would follow a symlink swapped
552    /// into place after the guard's check).
553    pub fn write_contained(&self, path: &Path, content: &str) -> Result<(), String> {
554        use std::io::Write;
555        if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
556            self.create_dir_all_contained(parent)?;
557        }
558        let mut file = self.create_contained(path)?;
559        file.write_all(content.as_bytes())
560            .map_err(|e| format!("Error writing '{}': {}", path.display(), e))?;
561        Ok(())
562    }
563
564    /// `create_dir_all` with per-component descriptor verification, so a
565    /// symlink swapped in after the guard's check cannot redirect directory
566    /// creation outside an allowed root.
567    pub fn create_dir_all_contained(&self, dir: &Path) -> Result<(), String> {
568        let mut missing: Vec<OsString> = Vec::new();
569        let mut ancestor = dir;
570        while !ancestor.exists() {
571            match (ancestor.file_name(), ancestor.parent()) {
572                (Some(name), Some(parent)) if parent != ancestor => {
573                    missing.push(name.to_os_string());
574                    ancestor = parent;
575                }
576                _ => return Err(self.violation_message(&dir.to_string_lossy())),
577            }
578        }
579        // Verify the existing ancestor itself, then build downward.
580        self.verify_open_file(
581            &std::fs::File::open(ancestor)
582                .map_err(|e| format!("Error opening directory '{}': {}", ancestor.display(), e))?,
583            dir,
584        )?;
585        let mut cur = ancestor.to_path_buf();
586        for comp in missing.iter().rev() {
587            cur.push(comp);
588            // `create_dir` fails if the component already exists (e.g. a
589            // racing process created it) — that is fine, the descriptor
590            // check below is what decides whether it is safe to use.
591            let _ = std::fs::create_dir(&cur);
592            let f = std::fs::File::open(&cur)
593                .map_err(|e| format!("Error opening directory '{}': {}", cur.display(), e))?;
594            self.verify_open_file(&f, dir)?;
595        }
596        Ok(())
597    }
598
599    /// Verify `file`'s descriptor resolves inside an allowed root.
600    #[cfg(all(unix, not(target_os = "macos")))]
601    fn verify_open_file(&self, file: &std::fs::File, display: &Path) -> Result<(), String> {
602        use std::os::unix::io::AsRawFd;
603        let link = format!("/proc/self/fd/{}", file.as_raw_fd());
604        let real = std::fs::read_link(&link).map_err(|e| {
605            format!(
606                "Error: cannot verify opened file '{}' ({}); refusing it",
607                display.display(),
608                e
609            )
610        })?;
611        if !self.covers(&real) {
612            return Err(self.violation_message(&real.to_string_lossy()));
613        }
614        Ok(())
615    }
616
617    /// macOS has no `/proc`; `F_GETPATH` returns the descriptor's real path.
618    #[cfg(target_os = "macos")]
619    fn verify_open_file(&self, file: &std::fs::File, display: &Path) -> Result<(), String> {
620        use std::os::unix::ffi::OsStringExt;
621        use std::os::unix::io::AsRawFd;
622        let mut buf = vec![0u8; libc::PATH_MAX as usize];
623        let ret = unsafe { libc::fcntl(file.as_raw_fd(), libc::F_GETPATH, buf.as_mut_ptr()) };
624        if ret != 0 {
625            return Err(format!(
626                "Error: cannot verify opened file '{}' (F_GETPATH failed); refusing it",
627                display.display()
628            ));
629        }
630        let len = buf.iter().position(|&b| b == 0).unwrap_or(buf.len());
631        let real = PathBuf::from(std::ffi::OsString::from_vec(buf[..len].to_vec()));
632        if !self.covers(&real) {
633            return Err(self.violation_message(&real.to_string_lossy()));
634        }
635        Ok(())
636    }
637
638    /// Non-Unix platforms have no descriptor-path query; the pre-open
639    /// `resolve_contained` check is the containment there.
640    #[cfg(not(unix))]
641    fn verify_open_file(&self, _file: &std::fs::File, _display: &Path) -> Result<(), String> {
642        Ok(())
643    }
644
645    /// Check a glob pattern against the guard: the static (non-wildcard)
646    /// prefix of the pattern must resolve inside an allowed root.
647    ///
648    /// Bare patterns like `**/*.rs` are anchored at the workspace root and
649    /// always pass. Absolute or `..`-escaping prefixes are rejected.
650    pub fn check_glob_pattern(&self, pattern: &str) -> Result<(), String> {
651        let base = glob_static_prefix(pattern);
652        self.resolve_contained(base).map(|_| ())
653    }
654
655    /// Standard error message for a violation, usable as a tool result.
656    pub fn violation_message(&self, raw: &str) -> String {
657        let mut msg = format!(
658            "Error: Path '{}' is outside the workspace root '{}'. \
659             File-tool access is confined to the workspace",
660            raw,
661            self.root.display()
662        );
663        if self.allowed.is_empty() {
664            msg.push_str(". Add directories to `allowed_paths` in settings.json to widen it.");
665        } else {
666            let roots: Vec<String> = self
667                .allowed
668                .iter()
669                .map(|p| format!("'{}'", p.display()))
670                .collect();
671            msg.push_str(&format!(" (also allowed: {}).", roots.join(", ")));
672        }
673        msg
674    }
675}
676
677// The guard is pure path arithmetic, but its symlink tests need POSIX
678// semantics (Windows has 8.3 short names and `\\?\` verbatim prefixes).
679#[cfg(all(test, unix))]
680mod tests {
681    use super::*;
682
683    fn guard_in(tmp: &Path) -> PathGuard {
684        PathGuard::new(tmp).unwrap()
685    }
686
687    /// The check-then-open race: `resolve_contained` authorizes a path while
688    /// `sub` is a real directory, then a racing process swaps `sub` for a
689    /// symlink to an outside directory. The open must still fail, because the
690    /// descriptor's real path is verified after `open(2)`.
691    #[cfg(all(unix, not(target_os = "macos")))]
692    #[test]
693    fn open_descriptor_is_verified_after_the_race() {
694        let tmp = tempfile::tempdir().unwrap();
695        let outside = tempfile::tempdir().unwrap();
696        std::fs::write(outside.path().join("secret.txt"), "CANARY").unwrap();
697        let root = tmp.path().join("root");
698        std::fs::create_dir_all(root.join("sub")).unwrap();
699        std::fs::write(root.join("sub/secret.txt"), "local").unwrap();
700        let sb = guard_in(&root);
701
702        // Authorized while `sub` is a real directory.
703        let resolved = sb.resolve_contained("sub/secret.txt").unwrap();
704        assert_eq!(sb.read_contained(&resolved).unwrap(), "local");
705
706        // The race: `sub` becomes a symlink to the outside directory.
707        std::fs::remove_dir_all(root.join("sub")).unwrap();
708        std::os::unix::fs::symlink(outside.path(), root.join("sub")).unwrap();
709
710        // The descriptor now resolves outside, so both read and write of the
711        // previously-authorized path must fail closed.
712        let err = sb.open_read_contained(&resolved).unwrap_err();
713        assert!(err.contains("outside the workspace"), "err: {err}");
714        assert!(sb.read_contained(&resolved).is_err());
715        assert!(sb.write_contained(&resolved, "PWN").is_err());
716        // Nothing was written through the swapped symlink.
717        assert_eq!(
718            std::fs::read_to_string(outside.path().join("secret.txt")).unwrap(),
719            "CANARY"
720        );
721    }
722
723    /// Parent-directory creation through the guard must not follow a symlink
724    /// swapped in for a not-yet-existing component.
725    #[cfg(all(unix, not(target_os = "macos")))]
726    #[test]
727    fn create_dir_all_contained_verifies_each_new_directory() {
728        let tmp = tempfile::tempdir().unwrap();
729        let outside = tempfile::tempdir().unwrap();
730        let root = tmp.path().join("root");
731        std::fs::create_dir_all(&root).unwrap();
732        let sb = guard_in(&root);
733
734        // `sub` does not exist yet; create it as a symlink to the outside
735        // dir, simulating a swap after the guard resolved the write path.
736        std::os::unix::fs::symlink(outside.path(), root.join("sub")).unwrap();
737
738        let target = root.join("sub/new-dir/file.txt");
739        assert!(sb.write_contained(&target, "PWN").is_err());
740        assert!(!outside.path().join("new-dir").exists());
741    }
742
743    #[test]
744    fn normalize_lexical_resolves_dotdot() {
745        let p = normalize_lexical(Path::new("/a/b/../c/./d"));
746        assert_eq!(p, PathBuf::from("/a/c/d"));
747    }
748
749    #[test]
750    fn normalize_lexical_clamps_at_root() {
751        let p = normalize_lexical(Path::new("/a/../../etc/passwd"));
752        assert_eq!(p, PathBuf::from("/etc/passwd"));
753    }
754
755    #[test]
756    fn new_requires_existing_dir() {
757        assert!(PathGuard::new(Path::new("/definitely/not/a/real/dir")).is_err());
758    }
759
760    #[test]
761    fn contains_absolute_inside() {
762        let tmp = tempfile::tempdir().unwrap();
763        let sb = guard_in(tmp.path());
764        let inside = sb.root().join("file.txt");
765        assert!(sb.contains(inside.to_str().unwrap()));
766    }
767
768    #[test]
769    fn contains_absolute_outside() {
770        let tmp = tempfile::tempdir().unwrap();
771        let sb = guard_in(tmp.path());
772        assert!(!sb.contains("/etc/passwd"));
773        let other = tempfile::tempdir().unwrap();
774        assert!(!sb.contains(other.path().join("x.txt").to_str().unwrap()));
775    }
776
777    #[test]
778    fn contains_relative_paths() {
779        let tmp = tempfile::tempdir().unwrap();
780        let sb = guard_in(tmp.path());
781        assert!(sb.contains("file.txt"));
782        assert!(sb.contains("./sub/dir/file.txt"));
783        assert!(sb.contains("sub/../other.txt"));
784    }
785
786    #[test]
787    fn rejects_dotdot_traversal() {
788        let tmp = tempfile::tempdir().unwrap();
789        let sb = guard_in(tmp.path());
790        assert!(!sb.contains("../escape.txt"));
791        assert!(!sb.contains("sub/../../escape.txt"));
792        let traversal = format!("{}/../outside.txt", sb.root().display());
793        assert!(!sb.contains(&traversal));
794    }
795
796    #[test]
797    fn allows_nonexistent_paths_inside_root() {
798        // write tool creates files that don't exist yet — those must pass.
799        let tmp = tempfile::tempdir().unwrap();
800        let sb = guard_in(tmp.path());
801        assert!(sb.contains("does/not/exist/yet.txt"));
802        let resolved = sb.resolve_contained("new/nested/file.rs").unwrap();
803        assert!(resolved.starts_with(sb.root()));
804        assert!(resolved.ends_with("new/nested/file.rs"));
805    }
806
807    #[test]
808    fn rejects_nonexistent_paths_outside_root() {
809        let tmp = tempfile::tempdir().unwrap();
810        let sb = guard_in(tmp.path());
811        assert!(!sb.contains("/tmp/path-guard-evil-dir-xyz/new.txt"));
812    }
813
814    #[test]
815    fn rejects_symlink_escape() {
816        let tmp = tempfile::tempdir().unwrap();
817        let outside = tempfile::tempdir().unwrap();
818        let sb = guard_in(tmp.path());
819
820        // Create a symlink inside the workspace pointing outside.
821        let link = tmp.path().join("evil_link");
822        std::os::unix::fs::symlink(outside.path(), &link).unwrap();
823
824        assert!(!sb.contains("evil_link/secret.txt"));
825        assert!(!sb.contains(link.to_str().unwrap()));
826    }
827
828    #[test]
829    fn violation_message_mentions_path_and_root() {
830        let tmp = tempfile::tempdir().unwrap();
831        let sb = guard_in(tmp.path());
832        let msg = sb.violation_message("/etc/passwd");
833        assert!(msg.contains("/etc/passwd"));
834        assert!(msg.contains(&sb.root().display().to_string()));
835        assert!(msg.starts_with("Error: Path '"));
836    }
837
838    #[test]
839    fn rejects_empty_path() {
840        let tmp = tempfile::tempdir().unwrap();
841        let sb = guard_in(tmp.path());
842        assert!(!sb.contains(""));
843        assert!(!sb.contains("   "));
844    }
845
846    #[test]
847    fn allowed_paths_widen_the_guard() {
848        let tmp = tempfile::tempdir().unwrap();
849        let extra = tempfile::tempdir().unwrap();
850        let sb = PathGuard::configured(
851            tmp.path(),
852            &[extra.path().to_string_lossy().to_string()],
853            None,
854            &[],
855        )
856        .unwrap();
857        assert!(sb.contains(extra.path().join("file.txt").to_str().unwrap()));
858        // A sibling of the allowed root is still out of bounds.
859        assert!(!sb.contains("/etc/hosts"));
860    }
861
862    #[test]
863    fn relative_allowed_path_is_joined_with_root() {
864        let tmp = tempfile::tempdir().unwrap();
865        std::fs::create_dir_all(tmp.path().join("shared")).unwrap();
866        let sb = PathGuard::configured(tmp.path(), &["shared".to_string()], None, &[]).unwrap();
867        assert!(sb.contains("shared/a.txt"));
868        assert!(sb.contains(tmp.path().join("shared/b.txt").to_str().unwrap()));
869    }
870
871    #[test]
872    fn tilde_allowed_path_needs_home() {
873        let tmp = tempfile::tempdir().unwrap();
874        // No home injected → `~` entry is a configuration error, not a silent
875        // resolution to the workspace root.
876        let err =
877            PathGuard::configured(tmp.path(), &["~/.cargo".to_string()], None, &[]).unwrap_err();
878        assert!(err.contains("home directory"), "{err}");
879
880        let home = tempfile::tempdir().unwrap();
881        let sb = PathGuard::configured(
882            tmp.path(),
883            &["~/.cargo".to_string()],
884            Some(home.path()),
885            &[],
886        )
887        .unwrap();
888        let cargo = home.path().join(".cargo");
889        assert!(sb.contains(cargo.join("registry/index").to_str().unwrap()));
890    }
891
892    #[test]
893    fn blocked_prefix_defeats_overbroad_allowed_root() {
894        let tmp = tempfile::tempdir().unwrap();
895        // Allowing "/" is rejected outright now: it contains every blocked
896        // prefix, and accepting it would still expose /home, /var/lib, etc.
897        // to the in-process write tools.
898        let sb = PathGuard::configured(tmp.path(), &["/".to_string()], None, &[]).unwrap();
899        assert!(sb.allowed_roots().is_empty());
900        assert!(!sb.contains("/etc/passwd"));
901        assert!(!sb.contains("/usr/lib/libc.so"));
902        // ...and nothing else outside the workspace is reachable either.
903        let other = tempfile::tempdir().unwrap();
904        assert!(!sb.contains(other.path().join("x.txt").to_str().unwrap()));
905    }
906
907    #[test]
908    fn workspace_root_is_exempt_from_blocked_prefixes() {
909        // Opening the harness inside a blocked prefix still has to work.
910        let tmp = tempfile::tempdir().unwrap();
911        let sb = PathGuard::configured(tmp.path(), &["/".to_string()], None, &[]).unwrap();
912        assert!(sb.contains("inside-me/etc/passwd"));
913    }
914
915    #[test]
916    fn overbroad_allowed_entry_is_reported_not_fatal() {
917        let tmp = tempfile::tempdir().unwrap();
918        // `/etc` is blocked, so the entry is dropped with a warning; the guard
919        // still builds and still confines everything else.
920        let sb = PathGuard::configured(tmp.path(), &["/etc".to_string()], None, &[]).unwrap();
921        assert!(sb.allowed_roots().is_empty());
922        assert!(!sb.contains("/etc/passwd"));
923    }
924
925    /// An allowed entry that *contains* a blocked prefix must be dropped too:
926    /// `"/"` covers `/etc`, and `"/var"` covers `/var/log`, so accepting them
927    /// would let `covers()` wave blocked system paths through.
928    #[test]
929    fn ancestor_of_a_blocked_prefix_is_not_allowed() {
930        let tmp = tempfile::tempdir().unwrap();
931        for entry in ["/", "/var", "/run/.."] {
932            let sb = PathGuard::configured(tmp.path(), &[entry.to_string()], None, &[]).unwrap();
933            assert!(
934                sb.allowed_roots().is_empty(),
935                "entry {entry:?} must be dropped, got {:?}",
936                sb.allowed_roots()
937            );
938        }
939        let sb = PathGuard::configured(tmp.path(), &["/".to_string()], None, &[]).unwrap();
940        assert!(!sb.contains("/etc/passwd"));
941        assert!(!sb.contains("/var/log/auth.log"));
942        assert!(!sb.contains("/home/user/.bashrc"));
943    }
944
945    /// A sibling of a blocked prefix is fine: `/var/lib` does not contain
946    /// `/var/log`, and component-wise matching means `/root` does not cover
947    /// `/rootfoo`.
948    #[test]
949    fn sibling_of_a_blocked_prefix_is_allowed() {
950        let tmp = tempfile::tempdir().unwrap();
951        let sb = PathGuard::configured(tmp.path(), &["/var/lib".to_string()], None, &[]).unwrap();
952        assert_eq!(sb.allowed_roots().len(), 1);
953        assert!(!sb.contains("/var/log/auth.log"));
954    }
955
956    #[test]
957    fn glob_pattern_uses_static_prefix() {
958        let tmp = tempfile::tempdir().unwrap();
959        let sb = guard_in(tmp.path());
960        assert!(sb.check_glob_pattern("**/*.rs").is_ok());
961        assert!(sb.check_glob_pattern("src/**/*.toml").is_ok());
962        assert!(sb.check_glob_pattern("/etc/**").is_err());
963        assert!(sb.check_glob_pattern("../secret/*.txt").is_err());
964    }
965
966    /// The `link -> /usr` + `..` case: lexical normalization collapses
967    /// `<root>/link/../etc/passwd` to `<root>/etc/passwd`, which is *inside*
968    /// the root, while the kernel opens `/etc/passwd`. Resolution must follow
969    /// the kernel's order, not the textual one.
970    #[test]
971    fn rejects_symlink_then_dotdot_reaching_outside() {
972        let tmp = tempfile::tempdir().unwrap();
973        let link = tmp.path().join("link");
974        std::os::unix::fs::symlink(Path::new("/usr"), &link).unwrap();
975        let sb = guard_in(tmp.path());
976
977        assert!(!sb.contains("link/../etc/passwd"));
978        assert!(!sb.contains(&format!("{}/link/../etc/passwd", tmp.path().display())));
979        assert!(!sb.contains("link/../outside_me.txt"));
980    }
981
982    /// Same shape, but the symlink points at a *sibling* directory rather than
983    /// a system path — the escape is the traversal, not the target.
984    #[test]
985    fn rejects_symlink_then_dotdot_into_sibling() {
986        let tmp = tempfile::tempdir().unwrap();
987        let parent = tmp.path().parent().unwrap();
988        let link = tmp.path().join("link");
989        std::os::unix::fs::symlink(parent, &link).unwrap();
990        let sb = guard_in(tmp.path());
991
992        // `<root>/link/..` is `<root>` lexically, but the kernel resolves the
993        // link first, making it the workspace's *parent*.
994        assert!(!sb.contains("link/../sibling-secret.txt"));
995    }
996
997    /// A single in-workspace symlink must not defeat `DEFAULT_BLOCKED_PREFIXES`
998    /// by way of `..` — the blocked list is the last line of defence for an
999    /// over-broad `allowed_paths`, so it has to hold here too.
1000    #[test]
1001    fn symlink_dotdot_cannot_reach_a_blocked_prefix() {
1002        let tmp = tempfile::tempdir().unwrap();
1003        std::os::unix::fs::symlink(Path::new("/usr"), tmp.path().join("link")).unwrap();
1004        let sb = PathGuard::configured(tmp.path(), &["/".to_string()], None, &[]).unwrap();
1005
1006        assert!(!sb.contains("link/../etc/passwd"));
1007        assert!(!sb.contains("link/../usr/lib"));
1008    }
1009
1010    /// Chains of relative symlinks resolve in the same order the kernel uses.
1011    #[test]
1012    fn follows_relative_symlink_chains_in_kernel_order() {
1013        let tmp = tempfile::tempdir().unwrap();
1014        std::fs::create_dir_all(tmp.path().join("a")).unwrap();
1015        std::fs::create_dir_all(tmp.path().join("b")).unwrap();
1016        std::fs::write(tmp.path().join("b/target.txt"), "x").unwrap();
1017        // a/one -> ../b, i.e. a *relative* link: its meaning depends on the
1018        // directory it is reached through, so only kernel-order resolution can
1019        // place it correctly.
1020        std::os::unix::fs::symlink(Path::new("../b"), tmp.path().join("a/one")).unwrap();
1021        let sb = guard_in(tmp.path());
1022
1023        // a/one resolves to <root>/b, so the target is reachable and in bounds.
1024        assert!(sb.contains("a/one/target.txt"));
1025        // a/one/.. is <root> for the kernel (the link is resolved first) but
1026        // <root>/a for a lexical collapse — the two disagree, and the kernel
1027        // is the one that will open the file.
1028        let resolved = sb.resolve_contained("a/one/../target.txt").unwrap();
1029        assert_eq!(resolved, sb.root().join("target.txt"));
1030    }
1031
1032    /// A symlink loop must fail closed rather than hang or accept.
1033    #[test]
1034    fn rejects_symlink_loop() {
1035        let tmp = tempfile::tempdir().unwrap();
1036        let a = tmp.path().join("a");
1037        let b = tmp.path().join("b");
1038        std::os::unix::fs::symlink(&b, &a).unwrap();
1039        std::os::unix::fs::symlink(&a, &b).unwrap();
1040        let sb = guard_in(tmp.path());
1041
1042        assert!(!sb.contains("a/x.txt"));
1043        assert!(!sb.contains("b/x.txt"));
1044    }
1045
1046    /// macOS spells temp dirs `/var/folders/...` while `/var` is a symlink to
1047    /// `/private/var`, so the workspace root as *spelled* passes through a
1048    /// symlink but canonicalizes elsewhere. Absolute arguments and allowed
1049    /// entries spelled through that symlink must still match the canonical
1050    /// root. Simulated here with an explicit link.
1051    #[test]
1052    fn root_and_allowed_entries_reached_through_a_symlink_still_match() {
1053        let tmp = tempfile::tempdir().unwrap();
1054        let real = tmp.path().join("real");
1055        std::fs::create_dir_all(real.join("proj")).unwrap();
1056        std::fs::create_dir_all(real.join("extra")).unwrap();
1057        let link = tmp.path().join("link");
1058        std::os::unix::fs::symlink(&real, &link).unwrap();
1059
1060        let spelled_root = link.join("proj");
1061        let spelled_extra = link.join("extra");
1062        let sb = PathGuard::configured(
1063            &spelled_root,
1064            &[spelled_extra.to_string_lossy().to_string()],
1065            None,
1066            &[],
1067        )
1068        .unwrap();
1069        // The root is stored canonical.
1070        assert_eq!(sb.root(), real.join("proj").canonicalize().unwrap());
1071
1072        // Absolute arguments spelled through the symlink resolve to the
1073        // canonical form and are contained.
1074        assert!(sb.contains(spelled_root.join("file.txt").to_str().unwrap()));
1075        assert!(sb.contains(spelled_extra.join("f.txt").to_str().unwrap()));
1076        // The canonical spelling works too.
1077        assert!(sb.contains(real.join("proj/file.txt").to_str().unwrap()));
1078        assert!(sb.contains(real.join("extra/f.txt").to_str().unwrap()));
1079        // And something genuinely outside is still rejected.
1080        assert!(!sb.contains("/etc/passwd"));
1081        assert!(!sb.contains(link.join("../outside.txt").to_str().unwrap()));
1082    }
1083
1084    #[test]
1085    fn glob_pattern_honours_allowed_root() {
1086        let tmp = tempfile::tempdir().unwrap();
1087        let extra = tempfile::tempdir().unwrap();
1088        let sb = PathGuard::configured(
1089            tmp.path(),
1090            &[extra.path().to_string_lossy().to_string()],
1091            None,
1092            &[],
1093        )
1094        .unwrap();
1095        let pattern = format!("{}/**/*.rs", extra.path().display());
1096        assert!(sb.check_glob_pattern(&pattern).is_ok());
1097    }
1098}