Skip to main content

vtcode_commons/paths/
canonicalize.rs

1use anyhow::{Result, anyhow};
2use std::path::{Path, PathBuf};
3use tracing::warn;
4
5/// Canonicalize a filesystem path without the Windows `\\?\` verbatim prefix.
6///
7/// `std::fs::canonicalize` returns verbatim (`\\?\`) paths on Windows, which
8/// break path comparisons, round-tripping through user config, and some APIs
9/// that reject verbatim paths. `dunce::canonicalize` strips the prefix when it
10/// is safe to do so and is a perfect drop-in on non-Windows platforms.
11///
12/// This is the single canonical entry point for path canonicalization in the
13/// workspace. All call sites should use this (or `canonicalize_workspace`) rather
14/// than `std::fs::canonicalize` / `Path::canonicalize`, which are banned by
15/// `clippy.toml`'s `disallowed-methods`.
16pub fn canonicalize(path: impl AsRef<Path>) -> std::io::Result<PathBuf> {
17    dunce::canonicalize(path)
18}
19
20/// Async canonicalize via `dunce`, using `spawn_blocking` to avoid blocking the
21/// runtime. Equivalent to `tokio::fs::canonicalize` but without the Windows
22/// `\\?\` verbatim prefix. Use this in async contexts instead of the sync
23/// [`canonicalize`] when the path may require I/O.
24pub async fn canonicalize_async(path: impl AsRef<Path> + Send) -> std::io::Result<PathBuf> {
25    let path = path.as_ref().to_path_buf();
26    match tokio::task::spawn_blocking(move || dunce::canonicalize(&path)).await {
27        Ok(inner) => inner,
28        Err(join_error) => Err(std::io::Error::other(join_error)),
29    }
30}
31
32/// Canonicalize a path with fallback to the original path if canonicalization fails.
33pub fn canonicalize_workspace(workspace_root: &Path) -> PathBuf {
34    canonicalize(workspace_root).unwrap_or_else(|error| {
35        warn!(
36            path = %workspace_root.display(),
37            %error,
38            "Failed to canonicalize workspace root; falling back to provided path"
39        );
40        workspace_root.to_path_buf()
41    })
42}
43
44/// Canonicalize a path, walking up to find the nearest existing ancestor for new files.
45///
46/// This function handles paths to files that may not yet exist by finding the
47/// nearest existing parent directory, canonicalizing that, and then appending
48/// the remaining path components.
49///
50/// # Security
51/// This function is critical for security. It prevents symlink escapes by:
52/// 1. Finding the nearest existing ancestor directory
53/// 2. Canonicalizing that directory (resolves symlinks)
54/// 3. Appending the remaining path components
55///
56/// # Arguments
57/// * `normalized` - A normalized path (output from `normalize_path`)
58///
59/// # Returns
60/// The canonical path, or the normalized path if no parent exists. Existing
61/// symlinks must resolve, including symlinks whose targets do not yet exist.
62pub async fn canonicalize_allow_missing(normalized: &Path) -> Result<PathBuf> {
63    // Use the canonicalize result directly instead of probing with
64    // `symlink_metadata` first and re-deriving the answer with a second call.
65    // Two calls on the same path let a component change in between (the
66    // validate-then-rederive trap), and the probe is redundant work on the
67    // common path where the component exists.
68    let mut current = normalized.to_path_buf();
69    loop {
70        match canonicalize_async(&current).await {
71            Ok(canonical_parent) => {
72                let remainder = normalized.strip_prefix(&current).unwrap_or_else(|_| Path::new(""));
73
74                // Return the canonical parent + remaining components
75                return if remainder.as_os_str().is_empty() {
76                    Ok(canonical_parent)
77                } else {
78                    Ok(canonical_parent.join(remainder))
79                };
80            }
81            // `canonicalize` reports NotFound both for missing components and
82            // for dangling symlinks. Only the latter needs a second look: probe
83            // the link itself so a dangling symlink fails closed instead of
84            // being silently treated as a missing path component.
85            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
86                match tokio::fs::symlink_metadata(&current).await {
87                    Ok(_) => {
88                        return Err(anyhow!("Failed to resolve canonical path for '{}': {}", current.display(), error));
89                    }
90                    Err(metadata_error) if metadata_error.kind() == std::io::ErrorKind::NotFound => {}
91                    Err(metadata_error) => {
92                        return Err(anyhow!("Failed to inspect path '{}': {}", current.display(), metadata_error));
93                    }
94                }
95            }
96            Err(error) => {
97                return Err(anyhow!("Failed to resolve canonical path for '{}': {}", current.display(), error));
98            }
99        }
100        let Some(parent) = current.parent() else { break };
101        current = parent.to_path_buf();
102    }
103
104    // No existing parent found, return normalized path as-is
105    Ok(normalized.to_path_buf())
106}
107
108#[cfg(test)]
109mod tests {
110    use super::*;
111
112    #[tokio::test]
113    async fn test_canonicalize_existing_file() {
114        // Create a temporary directory and file
115        let temp_dir = std::env::temp_dir();
116        let test_file = temp_dir.join("vtcode_test_existing.txt");
117        tokio::fs::write(&test_file, b"test").await.unwrap();
118
119        let canonical = canonicalize_allow_missing(&test_file).await.unwrap();
120
121        // Should get the canonical path
122        assert!(canonical.is_absolute());
123        assert!(canonical.exists());
124
125        // Cleanup
126        drop(tokio::fs::remove_file(&test_file).await);
127    }
128
129    #[tokio::test]
130    async fn test_canonicalize_missing_file() {
131        // Use a path that doesn't exist but has an existing parent
132        let temp_dir = std::env::temp_dir();
133        let missing_file = temp_dir.join("vtcode_test_missing_dir/missing_file.txt");
134
135        let canonical = canonicalize_allow_missing(&missing_file).await.unwrap();
136
137        // Should get canonical parent + missing components
138        assert!(canonical.is_absolute());
139        assert!(canonical.to_string_lossy().contains("missing_file.txt"));
140    }
141
142    #[tokio::test]
143    async fn test_canonicalize_deeply_missing_path() {
144        // Use a path with multiple missing parent directories
145        let temp_dir = std::env::temp_dir();
146        let deep_missing = temp_dir.join("vtcode_test_a/b/c/d/file.txt");
147
148        let canonical = canonicalize_allow_missing(&deep_missing).await.unwrap();
149
150        // Should get canonical temp_dir + missing components
151        assert!(canonical.is_absolute());
152        assert!(canonical.to_string_lossy().contains("vtcode_test_a"));
153    }
154
155    #[tokio::test]
156    async fn test_canonicalize_missing_file_with_existing_parent() {
157        // Create a parent directory
158        let temp_dir = std::env::temp_dir();
159        let test_dir = temp_dir.join("vtcode_test_parent");
160        tokio::fs::create_dir_all(&test_dir).await.unwrap();
161
162        let missing_file = test_dir.join("missing.txt");
163        let canonical = canonicalize_allow_missing(&missing_file).await.unwrap();
164
165        // Should get canonical parent + missing filename
166        assert!(canonical.is_absolute());
167        assert!(canonical.to_string_lossy().ends_with("missing.txt"));
168
169        // Cleanup
170        drop(tokio::fs::remove_dir(&test_dir).await);
171    }
172
173    #[cfg(unix)]
174    #[tokio::test]
175    async fn dangling_symlink_is_not_treated_as_a_missing_component() {
176        let workspace = tempfile::tempdir().unwrap();
177        let outside = tempfile::tempdir().unwrap();
178        let link = workspace.path().join("link");
179        std::os::unix::fs::symlink(outside.path().join("missing"), &link).unwrap();
180        assert!(canonicalize_allow_missing(&link).await.is_err());
181        assert!(canonicalize_allow_missing(&link.join("child")).await.is_err());
182        assert!(canonicalize_allow_missing(&workspace.path().join("new/child")).await.is_ok());
183        let valid_link = workspace.path().join("valid");
184        std::os::unix::fs::symlink(outside.path(), &valid_link).unwrap();
185        let resolved = canonicalize_allow_missing(&valid_link.join("new/child")).await.unwrap();
186        assert_eq!(resolved, canonicalize_async(outside.path()).await.unwrap().join("new/child"));
187    }
188
189    #[cfg(unix)]
190    #[tokio::test]
191    async fn existing_symlink_resolves_to_its_target_on_the_success_path() {
192        let workspace = tempfile::tempdir().unwrap();
193        let outside = tempfile::tempdir().unwrap();
194        let target = outside.path().join("target");
195        std::fs::create_dir(&target).unwrap();
196
197        // Canonicalize succeeds on the first call, so its result is reused
198        // directly: the symlink must resolve to the target, not the link path.
199        let link = workspace.path().join("link");
200        std::os::unix::fs::symlink(&target, &link).unwrap();
201        let resolved = canonicalize_allow_missing(&link.join("new/child")).await.unwrap();
202        assert_eq!(resolved, canonicalize_async(&target).await.unwrap().join("new/child"));
203
204        // Asymmetric case: the same shape with a missing target must fail
205        // closed, proving the follow-up probe only distinguishes dangling links.
206        let dangling = workspace.path().join("dangling");
207        std::os::unix::fs::symlink(outside.path().join("missing"), &dangling).unwrap();
208        assert!(canonicalize_allow_missing(&dangling.join("child")).await.is_err());
209    }
210}