Skip to main content

vtcode_commons/paths/
containment.rs

1use super::canonicalize::{canonicalize, canonicalize_async};
2use super::normalize::normalize_path;
3use anyhow::{Context, Result, anyhow, bail};
4use std::fs::FileType;
5use std::path::{Component, Path, PathBuf};
6use tracing::warn;
7
8/// Validate every existing path component and reject escaping symlinks.
9///
10/// Platform aliases such as macOS `/tmp -> /private/tmp` are accepted when a
11/// symlink resolves beneath its containing directory. Missing trailing
12/// components are allowed when `allow_missing_tail` is set so callers can
13/// create them safely afterwards. A symlinked leaf always fails: callers
14/// must decide explicitly whether to follow, replace, or reject it.
15///
16/// # Errors
17///
18/// Returns an error when the path contains `..`, when any existing
19/// component is a symlink escaping its containing directory (including a
20/// symlinked leaf), when a non-leaf component is not a directory, or when
21/// a component is missing and `allow_missing_tail` is false.
22pub fn validate_no_escaping_symlink_ancestors(path: &Path, allow_missing_tail: bool) -> std::io::Result<()> {
23    use std::fs;
24
25    let components = path.components().collect::<Vec<_>>();
26    let mut current = PathBuf::new();
27    for (index, component) in components.iter().enumerate() {
28        if matches!(component, Component::ParentDir) {
29            return Err(std::io::Error::other(format!("path contains traversal: {}", path.display())));
30        }
31        if matches!(component, Component::CurDir) {
32            continue;
33        }
34        current.push(component.as_os_str());
35        let is_leaf = index + 1 == components.len();
36        let metadata = match fs::symlink_metadata(&current) {
37            Ok(metadata) => metadata,
38            Err(error) if allow_missing_tail && error.kind() == std::io::ErrorKind::NotFound => break,
39            Err(error) => return Err(error),
40        };
41        if metadata.file_type().is_symlink() {
42            if is_leaf {
43                return Err(std::io::Error::other(format!("refusing symlink path {}", current.display())));
44            }
45            let parent = current
46                .parent()
47                .filter(|parent| !parent.as_os_str().is_empty())
48                .unwrap_or_else(|| Path::new("."));
49            let canonical_parent = canonicalize(parent)?;
50            // Keep the single resolution of `current`: it answers both the
51            // containment question and the "is a directory" question. Re-stating
52            // `current` afterwards would observe a path a concurrent actor can
53            // swap between the two calls, so the verdict could describe a
54            // different entry than the one whose target we just validated.
55            let canonical_target = canonicalize(&current)?;
56            if !canonical_target.starts_with(&canonical_parent) {
57                return Err(std::io::Error::other(format!(
58                    "path component {} escapes its containing directory",
59                    current.display()
60                )));
61            }
62            if !canonical_target.is_dir() {
63                return Err(std::io::Error::other(format!("path component {} is not a directory", current.display())));
64            }
65        } else if !is_leaf && !metadata.is_dir() {
66            return Err(std::io::Error::other(format!("path component {} is not a directory", current.display())));
67        }
68    }
69    Ok(())
70}
71
72/// Render a path relative to the workspace when it belongs to that workspace.
73///
74/// Paths outside the workspace remain absolute (or otherwise unchanged) so a
75/// diagnostic never hides that it refers to an external location. The
76/// filesystem-resolved comparison handles workspace aliases and symlink
77/// escapes without requiring callers to canonicalize their candidate first.
78///
79/// This is the one-shot form. Loops that render many entries should build a
80/// [`WorkspacePathDisplay`] once instead, so the workspace root is
81/// canonicalized a single time rather than once per entry.
82pub fn workspace_relative_display(workspace_root: &Path, path: &Path) -> String {
83    WorkspacePathDisplay::new(workspace_root).render(path)
84}
85
86/// Render a working directory for tool metadata: workspace-relative, `/`-separated.
87///
88/// Session backends report the directory they run in, and the shape is a user-visible
89/// contract shared by the PTY and pipe executors: paths inside the workspace are
90/// relative, the workspace root itself is `"."`, separators are always `/` so the
91/// value is stable across platforms, and paths outside the workspace stay absolute.
92pub fn workspace_relative_slash(workspace_root: &Path, path: &Path) -> String {
93    match path.strip_prefix(workspace_root) {
94        Ok(relative) if relative.as_os_str().is_empty() => ".".into(),
95        Ok(relative) => relative.to_string_lossy().replace('\\', "/"),
96        Err(_) => path.to_string_lossy().into_owned(),
97    }
98}
99
100/// Renders workspace-relative display paths for many entries under one root.
101///
102/// [`workspace_relative_display`] canonicalizes the workspace root on every
103/// call. That is invisible for a single diagnostic, but directory listings and
104/// tree walks render one path per entry, so the repeated `realpath` dominates
105/// the loop while always producing the same answer. This type resolves the
106/// root once and reuses it.
107#[derive(Clone)]
108pub struct WorkspacePathDisplay {
109    workspace_root: PathBuf,
110    /// Workspace root as resolved on the filesystem, when it exists.
111    canonical_root: Option<PathBuf>,
112}
113
114impl WorkspacePathDisplay {
115    /// Resolve the workspace root once, reusing it for every later [`Self::render`].
116    pub fn new(workspace_root: &Path) -> Self {
117        let canonical_root = canonicalize(workspace_root).ok();
118        Self {
119            workspace_root: workspace_root.to_path_buf(),
120            canonical_root,
121        }
122    }
123
124    /// Render `path` relative to the workspace, matching
125    /// [`workspace_relative_display`] exactly.
126    pub fn render(&self, path: &Path) -> String {
127        let candidate = if path.is_absolute() {
128            path.to_path_buf()
129        } else {
130            self.workspace_root.join(path)
131        };
132
133        if let Some(canonical_workspace) = self.canonical_root.as_ref() {
134            // A successful canonicalization is authoritative: a path that
135            // resolves outside the workspace must not fall back to lexical
136            // containment through an escaping symlink.
137            match canonicalize_for_display(&candidate) {
138                DisplayResolution::Resolved(canonical_candidate) => {
139                    return canonical_candidate
140                        .strip_prefix(canonical_workspace)
141                        .map(|relative| relative.to_string_lossy().into_owned())
142                        .unwrap_or_else(|_| path.to_string_lossy().into_owned());
143                }
144                DisplayResolution::Unresolved => return path.to_string_lossy().into_owned(),
145            }
146        }
147
148        // If the candidate cannot be resolved yet (for example, a new file with a
149        // missing tail), retain the cheap lexical behavior for paths that are
150        // clearly under the workspace.
151        let normalized_candidate = normalize_path(&candidate);
152        let normalized_workspace = normalize_path(&self.workspace_root);
153        if let Ok(relative) = normalized_candidate.strip_prefix(normalized_workspace) {
154            return relative.to_string_lossy().into_owned();
155        }
156        path.to_string_lossy().into_owned()
157    }
158
159    /// Render a path produced by a traversal that cannot cross a symlink.
160    ///
161    /// # Preconditions
162    ///
163    /// The caller must know both of the following, which hold for entries from
164    /// [`build_default_walker`](crate::walk::build_default_walker) (it does not
165    /// follow links) and for direct children of an already canonical directory:
166    ///
167    /// - `file_type` is the entry's own type, or `None` when unknown;
168    /// - no ancestor between the workspace root and `path` is a symlink.
169    ///
170    /// Under those conditions the resolved path equals the lexically stripped
171    /// path, so the per-entry `realpath` is redundant. Anything else — an
172    /// unknown type, or a symlinked leaf that may point outside the workspace —
173    /// falls back to [`Self::render`], which stays authoritative.
174    pub fn render_entry(&self, path: &Path, file_type: Option<FileType>) -> String {
175        if file_type.is_some_and(|file_type| !file_type.is_symlink())
176            && let Some(relative) = self.lexical_relative(path)
177        {
178            return relative;
179        }
180        self.render(path)
181    }
182
183    /// Strip whichever known root `path` lexically sits under, without any syscall.
184    ///
185    /// This is [`Self::render_entry`]'s core, exposed for callers that must
186    /// build *keys* rather than display strings (for example indexing children
187    /// by parent directory). It carries the same preconditions documented on
188    /// [`Self::render_entry`]: the caller must know the path came from a
189    /// traversal that cannot cross a symlink.
190    ///
191    /// Returns `None` for relative paths and for any `.`/`..` component, where
192    /// lexical stripping would disagree with the resolved form; callers fall
193    /// back to [`Self::render`].
194    pub fn relative_lexical(&self, path: &Path) -> Option<String> {
195        self.lexical_relative(path)
196    }
197
198    /// Strip whichever of the two known roots the path lexically sits under.
199    ///
200    /// Rejects relative paths and any `.`/`..` component: stripping is lexical
201    /// while [`Self::render`] resolves those components, so a path containing
202    /// them can strip to a different answer than the resolved form.
203    fn lexical_relative(&self, path: &Path) -> Option<String> {
204        if !path.is_absolute()
205            || path
206                .components()
207                .any(|component| matches!(component, Component::CurDir | Component::ParentDir))
208        {
209            return None;
210        }
211        let candidate = path;
212
213        self.canonical_root
214            .iter()
215            .chain(std::iter::once(&self.workspace_root))
216            .find_map(|root| {
217                candidate
218                    .strip_prefix(normalize_path(root))
219                    .ok()
220                    .map(|relative| relative.to_string_lossy().into_owned())
221            })
222    }
223}
224
225enum DisplayResolution {
226    Resolved(PathBuf),
227    Unresolved,
228}
229
230fn canonicalize_for_display(path: &Path) -> DisplayResolution {
231    if let Ok(canonical) = canonicalize(path) {
232        return DisplayResolution::Resolved(canonical);
233    }
234
235    let mut missing_tail = Vec::new();
236    let mut existing_prefix = path;
237    loop {
238        match std::fs::symlink_metadata(existing_prefix) {
239            Ok(_) => break,
240            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
241                let Some(file_name) = existing_prefix.file_name() else {
242                    return DisplayResolution::Unresolved;
243                };
244                let Some(parent) = existing_prefix.parent() else {
245                    return DisplayResolution::Unresolved;
246                };
247                missing_tail.push(PathBuf::from(file_name));
248                existing_prefix = parent;
249            }
250            Err(_) => return DisplayResolution::Unresolved,
251        }
252    }
253
254    let Ok(mut canonical) = canonicalize(existing_prefix) else {
255        // This includes dangling symlinks and inaccessible existing paths.
256        // Do not fall back to lexical containment for either case.
257        return DisplayResolution::Unresolved;
258    };
259    for component in missing_tail.into_iter().rev() {
260        canonical.push(component);
261    }
262    DisplayResolution::Resolved(canonical)
263}
264
265/// Resolve a path relative to a workspace root and ensure it stays within it.
266pub fn resolve_workspace_path(workspace_root: &Path, user_path: &Path) -> Result<PathBuf> {
267    let candidate = if user_path.is_absolute() {
268        user_path.to_path_buf()
269    } else {
270        workspace_root.join(user_path)
271    };
272
273    let canonical =
274        canonicalize(&candidate).with_context(|| format!("Failed to canonicalize path {}", candidate.display()))?;
275
276    let workspace_canonical = canonicalize(workspace_root)
277        .with_context(|| format!("Failed to canonicalize workspace root {}", workspace_root.display()))?;
278
279    if !canonical.starts_with(&workspace_canonical) {
280        return Err(anyhow!("Path {} escapes workspace root {}", canonical.display(), workspace_canonical.display()));
281    }
282
283    Ok(canonical)
284}
285
286/// Return a canonicalised absolute path that is guaranteed to reside inside the
287/// provided `workspace_root`.  If the path is outside the workspace an error is
288/// returned.
289pub fn secure_path(workspace_root: &Path, user_path: &Path) -> Result<PathBuf> {
290    // Resolve relative paths against the workspace root.
291    resolve_workspace_path(workspace_root, user_path)
292}
293
294/// Ensure a candidate path is inside the workspace root after lexical
295/// normalization.
296///
297/// This is the cheap, filesystem-free tier of workspace containment: it
298/// resolves `.`/`..` components lexically but does not follow symlinks. Use
299/// [`ensure_path_within_workspace_resolved`] when the candidate may traverse
300/// symlinks that point outside the workspace.
301///
302/// Returns the normalized candidate path on success.
303pub fn ensure_path_within_workspace(candidate: &Path, workspace_root: &Path) -> Result<PathBuf> {
304    let normalized_candidate = normalize_path(candidate);
305    let normalized_workspace = normalize_path(workspace_root);
306
307    if !normalized_candidate.starts_with(&normalized_workspace) {
308        bail!("Path '{}' escapes workspace '{}'", candidate.display(), workspace_root.display());
309    }
310
311    Ok(normalized_candidate)
312}
313
314/// Ensure a candidate path is inside the workspace root, resolving symlinks
315/// component by component.
316///
317/// This is the strict, filesystem-aware tier of workspace containment. On top
318/// of the lexical check performed by [`ensure_path_within_workspace`], it
319/// walks each component of the candidate below the workspace root and:
320///
321/// - canonicalizes every existing component and verifies the resolved path
322///   still starts with the canonical workspace root (catches symlinks that
323///   point outside the workspace);
324/// - tolerates nonexistent tail components (paths about to be created);
325/// - rejects traversal through a file component (e.g. `file.txt/child`).
326///
327/// The candidate must already be lexically inside `workspace_root` (both
328/// sides are normalized before comparison).
329///
330/// Returns the normalized candidate path on success.
331pub async fn ensure_path_within_workspace_resolved(candidate: &Path, workspace_root: &Path) -> Result<PathBuf> {
332    let normalized_root = normalize_path(workspace_root);
333    let normalized_candidate = normalize_path(candidate);
334
335    let canonical_root = match canonicalize_async(&normalized_root).await {
336        Ok(resolved) => resolved,
337        Err(error) => {
338            warn!(
339                path = %normalized_root.display(),
340                %error,
341                "Failed to canonicalize workspace root; falling back to provided path"
342            );
343            normalized_root.clone()
344        }
345    };
346
347    if normalized_root == normalized_candidate {
348        return Ok(normalized_candidate);
349    }
350
351    let relative = normalized_candidate
352        .strip_prefix(&normalized_root)
353        .map_err(|_error| anyhow!("path '{}' escapes the workspace root", candidate.display()))?
354        .to_path_buf();
355
356    let mut prefix = normalized_root.clone();
357    let mut components = relative.components().peekable();
358
359    while let Some(component) = components.next() {
360        prefix.push(component.as_os_str());
361
362        let metadata = match tokio::fs::symlink_metadata(&prefix).await {
363            Ok(metadata) => metadata,
364            Err(error) => {
365                if error.kind() == std::io::ErrorKind::NotFound {
366                    break;
367                }
368                return Err(error).with_context(|| format!("failed to inspect path component '{}'", prefix.display()));
369            }
370        };
371
372        let resolved = canonicalize_async(&prefix)
373            .await
374            .with_context(|| format!("failed to canonicalize path component '{}'", prefix.display()))?;
375
376        if metadata.file_type().is_symlink() {
377            if !resolved.starts_with(&canonical_root) {
378                return Err(anyhow!(
379                    "path '{}' escapes the workspace root via symlink '{}'",
380                    candidate.display(),
381                    prefix.display()
382                ));
383            }
384        } else {
385            if !resolved.starts_with(&canonical_root) {
386                return Err(anyhow!(
387                    "path '{}' escapes the workspace root via component '{}'",
388                    candidate.display(),
389                    prefix.display()
390                ));
391            }
392
393            if metadata.is_file() && components.peek().is_some() {
394                return Err(anyhow!(
395                    "path '{}' traverses through file component '{}'",
396                    candidate.display(),
397                    prefix.display()
398                ));
399            }
400        }
401    }
402
403    Ok(normalized_candidate)
404}
405
406#[cfg(test)]
407mod tests {
408    use super::super::canonicalize::canonicalize;
409    use super::*;
410    use std::path::{Path, PathBuf};
411
412    #[test]
413    fn workspace_relative_display_uses_workspace_relative_paths() {
414        let workspace = Path::new("/workspace");
415        let path = Path::new("/workspace/src/main.rs");
416
417        assert_eq!(workspace_relative_display(workspace, path), "src/main.rs");
418    }
419
420    #[test]
421    fn workspace_relative_display_preserves_external_paths() {
422        let workspace = Path::new("/workspace");
423        let path = Path::new("/tmp/external.txt");
424
425        assert_eq!(workspace_relative_display(workspace, path), "/tmp/external.txt");
426    }
427
428    #[test]
429    fn workspace_relative_display_handles_canonical_workspace_paths() {
430        let workspace = tempfile::tempdir().unwrap();
431        let workspace_path = canonicalize(workspace.path()).unwrap();
432        let path = workspace_path.join("docs").join("guide.md");
433
434        assert_eq!(workspace_relative_display(workspace.path(), &path), "docs/guide.md");
435    }
436
437    #[cfg(unix)]
438    #[test]
439    fn workspace_relative_display_resolves_workspace_aliases() {
440        use std::os::unix::fs::symlink;
441
442        let temp = tempfile::tempdir().unwrap();
443        let workspace = temp.path().join("workspace");
444        std::fs::create_dir_all(workspace.join("src")).unwrap();
445        let alias = temp.path().join("workspace-alias");
446        symlink(&workspace, &alias).unwrap();
447
448        let path = alias.join("src").join("main.rs");
449        assert_eq!(workspace_relative_display(&workspace, &path), "src/main.rs");
450    }
451
452    #[cfg(unix)]
453    #[test]
454    fn workspace_relative_display_preserves_symlink_escape() {
455        use std::os::unix::fs::symlink;
456
457        let temp = tempfile::tempdir().unwrap();
458        let workspace = temp.path().join("workspace");
459        let outside = temp.path().join("outside");
460        std::fs::create_dir_all(&workspace).unwrap();
461        std::fs::create_dir_all(&outside).unwrap();
462        std::fs::write(outside.join("secret.txt"), "secret").unwrap();
463        symlink(&outside, workspace.join("linked-outside")).unwrap();
464
465        let path = workspace.join("linked-outside").join("secret.txt");
466        assert_eq!(workspace_relative_display(&workspace, &path), path.to_string_lossy());
467    }
468
469    #[cfg(unix)]
470    #[test]
471    fn workspace_relative_display_fails_closed_for_dangling_symlink() {
472        use std::os::unix::fs::symlink;
473
474        let temp = tempfile::tempdir().unwrap();
475        let workspace = temp.path().join("workspace");
476        std::fs::create_dir_all(&workspace).unwrap();
477        let path = workspace.join("dangling-link");
478        symlink(temp.path().join("missing-target"), &path).unwrap();
479
480        assert_eq!(workspace_relative_display(&workspace, &path), path.to_string_lossy());
481    }
482
483    #[test]
484    fn path_display_matches_one_shot_render_for_many_entries() {
485        let workspace = tempfile::tempdir().unwrap();
486        let root = canonicalize(workspace.path()).unwrap();
487        std::fs::create_dir_all(root.join("src/nested")).unwrap();
488        std::fs::write(root.join("src/nested/lib.rs"), "x").unwrap();
489
490        let display = WorkspacePathDisplay::new(workspace.path());
491        for relative in ["src", "src/nested", "src/nested/lib.rs"] {
492            let path = root.join(relative);
493            assert_eq!(display.render(&path), workspace_relative_display(workspace.path(), &path));
494            assert_eq!(display.render(&path), relative);
495        }
496    }
497
498    #[test]
499    fn path_display_entry_fast_path_agrees_with_render() {
500        let workspace = tempfile::tempdir().unwrap();
501        let root = canonicalize(workspace.path()).unwrap();
502        std::fs::create_dir_all(root.join("src")).unwrap();
503        std::fs::write(root.join("src/lib.rs"), "x").unwrap();
504
505        let display = WorkspacePathDisplay::new(workspace.path());
506        let file_type = std::fs::symlink_metadata(root.join("src/lib.rs")).unwrap().file_type();
507
508        assert_eq!(display.render_entry(&root.join("src/lib.rs"), Some(file_type)), "src/lib.rs");
509        // Identity: the fast path must never disagree with the authoritative form.
510        assert_eq!(
511            display.render_entry(&root.join("src/lib.rs"), Some(file_type)),
512            display.render(&root.join("src/lib.rs"))
513        );
514        // Unknown type must fall back rather than guess.
515        assert_eq!(display.render_entry(&root.join("src/lib.rs"), None), display.render(&root.join("src/lib.rs")));
516    }
517
518    #[test]
519    fn path_display_entry_fast_path_rejects_dot_components() {
520        let workspace = tempfile::tempdir().unwrap();
521        let root = canonicalize(workspace.path()).unwrap();
522        std::fs::create_dir_all(root.join("src")).unwrap();
523
524        let display = WorkspacePathDisplay::new(workspace.path());
525        let dotted = root.join("src").join("..").join("src").join("lib.rs");
526        let file_type = std::fs::symlink_metadata(root.join("src")).unwrap().file_type();
527
528        // Stripping is lexical but `render` resolves, so the fast path must
529        // defer instead of emitting `src/../src/lib.rs`.
530        assert_eq!(display.render_entry(&dotted, Some(file_type)), display.render(&dotted));
531    }
532
533    #[cfg(unix)]
534    #[test]
535    fn path_display_entry_fast_path_defers_for_symlinks() {
536        use std::os::unix::fs::symlink;
537
538        let temp = tempfile::tempdir().unwrap();
539        let workspace = temp.path().join("workspace");
540        let outside = temp.path().join("outside");
541        std::fs::create_dir_all(&workspace).unwrap();
542        std::fs::create_dir_all(&outside).unwrap();
543        std::fs::write(outside.join("secret.txt"), "secret").unwrap();
544        let link = workspace.join("linked-outside");
545        symlink(&outside, &link).unwrap();
546
547        let display = WorkspacePathDisplay::new(&workspace);
548        let link_type = std::fs::symlink_metadata(&link).unwrap().file_type();
549        assert!(link_type.is_symlink());
550
551        // A symlinked leaf can leave the workspace, so it must not take the
552        // lexical fast path even though it lexically starts with the root.
553        assert_eq!(display.render_entry(&link, Some(link_type)), display.render(&link));
554        assert_eq!(display.render_entry(&link, Some(link_type)), link.to_string_lossy());
555    }
556
557    #[test]
558    fn ensures_path_within_workspace_accepts_nested_path() {
559        let workspace = Path::new("/tmp/project");
560        let candidate = Path::new("/tmp/project/src/../src/lib.rs");
561        let normalized = ensure_path_within_workspace(candidate, workspace).unwrap();
562        assert_eq!(normalized, PathBuf::from("/tmp/project/src/lib.rs"));
563    }
564
565    #[test]
566    fn ensures_path_within_workspace_rejects_escape() {
567        let workspace = Path::new("/tmp/project");
568        let candidate = Path::new("/tmp/project/../../etc/passwd");
569        assert!(ensure_path_within_workspace(candidate, workspace).is_err());
570    }
571
572    #[tokio::test]
573    async fn resolved_check_accepts_nested_existing_path() {
574        let workspace = tempfile::tempdir().unwrap();
575        let root = canonicalize(workspace.path()).unwrap();
576        let nested = root.join("src");
577        tokio::fs::create_dir_all(&nested).await.unwrap();
578        let file = nested.join("lib.rs");
579        tokio::fs::write(&file, b"test").await.unwrap();
580
581        let result = ensure_path_within_workspace_resolved(&file, &root).await;
582        assert_eq!(result.unwrap(), file);
583    }
584
585    #[tokio::test]
586    async fn resolved_check_accepts_missing_tail_components() {
587        let workspace = tempfile::tempdir().unwrap();
588        let root = canonicalize(workspace.path()).unwrap();
589        let missing = root.join("new_dir/new_file.txt");
590
591        let result = ensure_path_within_workspace_resolved(&missing, &root).await;
592        assert_eq!(result.unwrap(), missing);
593    }
594
595    #[tokio::test]
596    async fn resolved_check_rejects_lexical_escape() {
597        let workspace = tempfile::tempdir().unwrap();
598        let root = canonicalize(workspace.path()).unwrap();
599        let escape = root.join("../outside.txt");
600
601        assert!(ensure_path_within_workspace_resolved(&escape, &root).await.is_err());
602    }
603
604    #[cfg(unix)]
605    #[tokio::test]
606    async fn resolved_check_rejects_symlink_escape() {
607        let workspace = tempfile::tempdir().unwrap();
608        let outside = tempfile::tempdir().unwrap();
609        let root = canonicalize(workspace.path()).unwrap();
610        let outside_dir = canonicalize(outside.path()).unwrap();
611
612        let link = root.join("escape");
613        tokio::fs::symlink(&outside_dir, &link).await.unwrap();
614
615        let candidate = link.join("secret.txt");
616        assert!(ensure_path_within_workspace_resolved(&candidate, &root).await.is_err());
617    }
618
619    #[cfg(unix)]
620    #[tokio::test]
621    async fn resolved_check_accepts_symlink_within_workspace() {
622        let workspace = tempfile::tempdir().unwrap();
623        let root = canonicalize(workspace.path()).unwrap();
624        let target = root.join("real");
625        tokio::fs::create_dir_all(&target).await.unwrap();
626        let link = root.join("alias");
627        tokio::fs::symlink(&target, &link).await.unwrap();
628
629        let candidate = link.join("file.txt");
630        assert!(ensure_path_within_workspace_resolved(&candidate, &root).await.is_ok());
631    }
632
633    #[tokio::test]
634    async fn resolved_check_rejects_traversal_through_file() {
635        let workspace = tempfile::tempdir().unwrap();
636        let root = canonicalize(workspace.path()).unwrap();
637        let file = root.join("data.txt");
638        tokio::fs::write(&file, b"test").await.unwrap();
639
640        let candidate = file.join("child.txt");
641        assert!(ensure_path_within_workspace_resolved(&candidate, &root).await.is_err());
642    }
643
644    #[test]
645    fn symlink_ancestor_validation_rejects_traversal_and_missing_tail() {
646        let temp = tempfile::tempdir().expect("tempdir");
647        let missing = temp.path().join("absent").join("child");
648        assert!(validate_no_escaping_symlink_ancestors(&missing, true).is_ok());
649        assert!(validate_no_escaping_symlink_ancestors(&missing, false).is_err());
650        assert!(validate_no_escaping_symlink_ancestors(Path::new("a/../b"), false).is_err());
651        assert!(validate_no_escaping_symlink_ancestors(temp.path(), false).is_ok());
652    }
653
654    #[cfg(unix)]
655    #[test]
656    fn symlink_ancestor_validation_rejects_escaping_links_but_allows_in_parent_aliases() {
657        use std::os::unix::fs::symlink;
658
659        let temp = tempfile::tempdir().expect("tempdir");
660        let outside = tempfile::tempdir().expect("outside tempdir");
661        let escape = temp.path().join("escape");
662        symlink(outside.path(), &escape).expect("symlink");
663        let error = validate_no_escaping_symlink_ancestors(&escape.join("child"), false)
664            .expect_err("escaping ancestor must fail");
665        assert!(error.to_string().contains("escapes its containing directory"), "{error}");
666        let leaf_error = validate_no_escaping_symlink_ancestors(&escape, false).expect_err("symlinked leaf must fail");
667        assert!(leaf_error.to_string().contains("refusing symlink path"), "{leaf_error}");
668
669        let inner = temp.path().join("inner");
670        std::fs::create_dir(&inner).expect("mkdir");
671        symlink(&inner, temp.path().join("alias")).expect("symlink");
672        // An in-parent alias as a non-leaf ancestor is tolerated (this is
673        // how platform aliases like /tmp survive validation); as a leaf it
674        // still fails closed.
675        assert!(validate_no_escaping_symlink_ancestors(&temp.path().join("alias").join("child"), true).is_ok());
676        assert!(validate_no_escaping_symlink_ancestors(&temp.path().join("alias"), false).is_err());
677    }
678
679    #[cfg(unix)]
680    #[test]
681    fn symlink_ancestor_validation_rejects_link_to_regular_file() {
682        use std::os::unix::fs::symlink;
683
684        let temp = tempfile::tempdir().expect("tempdir");
685        let file = temp.path().join("plain-file");
686        std::fs::write(&file, b"data").expect("write file");
687        let link = temp.path().join("link-to-file");
688        symlink(&file, &link).expect("symlink");
689
690        // Checks the directory verdict is derived from the single resolved
691        // target rather than a second stat of the (swappable) link path.
692        let error = validate_no_escaping_symlink_ancestors(&link.join("child"), false)
693            .expect_err("non-directory symlink ancestor must fail");
694        assert!(error.to_string().contains("is not a directory"), "{error}");
695    }
696}