1use std::collections::VecDeque;
27use std::ffi::OsString;
28use std::path::{Component, Path, PathBuf};
29
30pub const DEFAULT_BLOCKED_PREFIXES: &[&str] = &[
37 "/etc", "/usr", "/boot", "/sys", "/proc", "/dev", "/root", "/var/log", "/var/run", "/run",
38];
39
40const MAX_SYMLINK_HOPS: usize = 40;
43
44fn 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 let _ = out.pop();
62 }
63 other => out.push(other.as_os_str()),
64 }
65 }
66 out
67}
68
69fn 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
80pub(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(_) => "/", None => ".",
95 }
96}
97
98fn 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
124fn 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#[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 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 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 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 pub fn home(mut self, home: Option<&Path>) -> Self {
199 self.home = home.map(|p| p.to_path_buf());
200 self
201 }
202
203 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 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 let resolved_entry = canonicalize_prefix(&expanded);
265 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#[derive(Debug, Clone)]
299pub struct PathGuard {
300 root: PathBuf,
302 allowed: Vec<PathBuf>,
304 blocked: Vec<PathBuf>,
306}
307
308impl PathGuard {
309 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 pub fn new(root: &Path) -> Result<Self, String> {
326 Self::builder(root).build()
327 }
328
329 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 pub fn root(&self) -> &Path {
349 &self.root
350 }
351
352 pub fn allowed_roots(&self) -> &[PathBuf] {
354 &self.allowed
355 }
356
357 pub fn blocked_prefixes(&self) -> &[PathBuf] {
359 &self.blocked
360 }
361
362 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 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 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 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 fn resolve_kernel_order(&self, joined: &Path) -> Option<PathBuf> {
439 debug_assert!(joined.is_absolute());
440
441 let mut out: Vec<OsString> = vec![OsString::from("/")];
443 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 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 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 pub fn contains(&self, raw: &str) -> bool {
501 self.resolve_contained(raw).is_ok()
502 }
503
504 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 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 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 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 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 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 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 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 #[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 #[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 #[cfg(not(unix))]
641 fn verify_open_file(&self, _file: &std::fs::File, _display: &Path) -> Result<(), String> {
642 Ok(())
643 }
644
645 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 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#[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 #[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 let resolved = sb.resolve_contained("sub/secret.txt").unwrap();
704 assert_eq!(sb.read_contained(&resolved).unwrap(), "local");
705
706 std::fs::remove_dir_all(root.join("sub")).unwrap();
708 std::os::unix::fs::symlink(outside.path(), root.join("sub")).unwrap();
709
710 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 assert_eq!(
718 std::fs::read_to_string(outside.path().join("secret.txt")).unwrap(),
719 "CANARY"
720 );
721 }
722
723 #[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 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 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 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 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 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 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 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 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 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 #[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 #[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 #[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 #[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 assert!(!sb.contains("link/../sibling-secret.txt"));
995 }
996
997 #[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 #[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 std::os::unix::fs::symlink(Path::new("../b"), tmp.path().join("a/one")).unwrap();
1021 let sb = guard_in(tmp.path());
1022
1023 assert!(sb.contains("a/one/target.txt"));
1025 let resolved = sb.resolve_contained("a/one/../target.txt").unwrap();
1029 assert_eq!(resolved, sb.root().join("target.txt"));
1030 }
1031
1032 #[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 #[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 assert_eq!(sb.root(), real.join("proj").canonicalize().unwrap());
1071
1072 assert!(sb.contains(spelled_root.join("file.txt").to_str().unwrap()));
1075 assert!(sb.contains(spelled_extra.join("f.txt").to_str().unwrap()));
1076 assert!(sb.contains(real.join("proj/file.txt").to_str().unwrap()));
1078 assert!(sb.contains(real.join("extra/f.txt").to_str().unwrap()));
1079 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}