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
8pub 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(¤t) {
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 let canonical_target = canonicalize(¤t)?;
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
72pub fn workspace_relative_display(workspace_root: &Path, path: &Path) -> String {
83 WorkspacePathDisplay::new(workspace_root).render(path)
84}
85
86pub 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#[derive(Clone)]
108pub struct WorkspacePathDisplay {
109 workspace_root: PathBuf,
110 canonical_root: Option<PathBuf>,
112}
113
114impl WorkspacePathDisplay {
115 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 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 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 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 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 pub fn relative_lexical(&self, path: &Path) -> Option<String> {
195 self.lexical_relative(path)
196 }
197
198 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 return DisplayResolution::Unresolved;
258 };
259 for component in missing_tail.into_iter().rev() {
260 canonical.push(component);
261 }
262 DisplayResolution::Resolved(canonical)
263}
264
265pub 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
286pub fn secure_path(workspace_root: &Path, user_path: &Path) -> Result<PathBuf> {
290 resolve_workspace_path(workspace_root, user_path)
292}
293
294pub 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
314pub 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 assert_eq!(
511 display.render_entry(&root.join("src/lib.rs"), Some(file_type)),
512 display.render(&root.join("src/lib.rs"))
513 );
514 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 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 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 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 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}