1use std::path::{Component, Path, PathBuf};
11
12const GIT_ENTRY: &str = ".git";
14
15const PACKAGE_DIR: &str = "node_modules";
19
20const GITDIR_PREFIX: &str = "gitdir:";
22
23const COMMONDIR_FILE: &str = "commondir";
25
26#[derive(Clone, Copy, Debug, PartialEq, Eq)]
28enum Refusal {
29 NotBelowBase,
31 LinkOutside,
33 GitMetadata,
35 Packages,
37 NotRegular,
39 Unreadable,
41}
42
43impl Refusal {
44 fn describe(self, entry: &Path, base: &Path) -> String {
46 let entry = entry.display();
47 match self {
48 Self::NotBelowBase => format!("{entry} is not below {}", base.display()),
49 Self::LinkOutside => format!(
50 "{entry} is a symlink that resolves outside {} or does not resolve",
51 base.display()
52 ),
53 Self::GitMetadata => format!("{entry} is a symlink that resolves into Git metadata"),
54 Self::Packages => {
55 format!("{entry} is a symlink that resolves into a node_modules directory")
56 }
57 Self::NotRegular => format!("{entry} is not a regular file or directory"),
58 Self::Unreadable => format!("{entry} cannot be read"),
59 }
60 }
61}
62
63struct Refused {
65 entry: PathBuf,
66 reason: Refusal,
67}
68
69#[derive(Clone, Copy, PartialEq, Eq)]
71enum ParentSteps {
72 Refuse,
74 Resolve,
76}
77
78#[must_use]
89pub fn outside_link(base: &Path, path: &Path) -> Option<PathBuf> {
90 find_refusal(base, path, ParentSteps::Refuse).map(|refused| refused.entry)
91}
92
93fn find_refusal(base: &Path, path: &Path, steps: ParentSteps) -> Option<Refused> {
97 let refuse = |entry: &Path, reason| {
98 Some(Refused {
99 entry: entry.to_path_buf(),
100 reason,
101 })
102 };
103 let Ok(relative) = path.strip_prefix(base) else {
104 return refuse(path, Refusal::NotBelowBase);
105 };
106 let Ok(canonical_base) = std::fs::canonicalize(base) else {
107 return refuse(path, Refusal::Unreadable);
108 };
109 if let Some(reason) = base_protected_link(base, &canonical_base) {
110 return refuse(base, reason);
111 }
112 let mut current = base.to_path_buf();
113 let mut resolved = canonical_base.clone();
114 for component in relative.components() {
115 let name = match component {
116 Component::Normal(name) => name,
117 Component::CurDir if steps == ParentSteps::Resolve => continue,
118 Component::ParentDir if steps == ParentSteps::Resolve => {
119 current.push(component);
120 resolved.pop();
121 if !resolved.starts_with(&canonical_base) {
122 return refuse(¤t, Refusal::NotBelowBase);
123 }
124 continue;
125 }
126 _ => return refuse(path, Refusal::NotBelowBase),
127 };
128 current.push(name);
129 match step_into(&canonical_base, &resolved, name, steps) {
130 Ok(Some(next)) => resolved = next,
131 Ok(None) => return None,
132 Err(reason) => return refuse(¤t, reason),
133 }
134 }
135 is_special_file(&resolved).then(|| Refused {
136 entry: path.to_path_buf(),
137 reason: Refusal::NotRegular,
138 })
139}
140
141fn step_into(
144 canonical_base: &Path,
145 parent: &Path,
146 name: &std::ffi::OsStr,
147 steps: ParentSteps,
148) -> Result<Option<PathBuf>, Refusal> {
149 let candidate = parent.join(name);
150 match candidate.symlink_metadata() {
151 Ok(meta) if meta.file_type().is_symlink() => {
152 link_target_in(canonical_base, &candidate).map(Some)
153 }
154 Ok(_) => Ok(Some(candidate)),
155 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
156 Ok((steps == ParentSteps::Resolve).then_some(candidate))
157 }
158 Err(_) => Err(Refusal::Unreadable),
159 }
160}
161
162fn link_target_in(canonical_base: &Path, link: &Path) -> Result<PathBuf, Refusal> {
165 let target = std::fs::canonicalize(link).map_err(|_| Refusal::LinkOutside)?;
166 if !target.starts_with(canonical_base) {
167 return Err(Refusal::LinkOutside);
168 }
169 match protected_kind(canonical_base, &target) {
170 Some(reason) => Err(reason),
171 None => Ok(target),
172 }
173}
174
175fn is_special_file(path: &Path) -> bool {
177 std::fs::metadata(path).is_ok_and(|meta| !meta.is_file() && !meta.is_dir())
178}
179
180fn base_protected_link(base: &Path, canonical_base: &Path) -> Option<Refusal> {
183 if !base
184 .symlink_metadata()
185 .is_ok_and(|meta| meta.file_type().is_symlink())
186 {
187 return None;
188 }
189 let Some(parent) = base
190 .parent()
191 .and_then(|parent| std::fs::canonicalize(parent).ok())
192 else {
193 return Some(Refusal::Unreadable);
194 };
195 protected_kind(&parent, canonical_base)
196}
197
198#[must_use]
213pub fn is_protected_link_target(within: &Path, resolved: &Path) -> bool {
214 protected_kind(within, resolved).is_some()
215}
216
217fn protected_kind(within: &Path, resolved: &Path) -> Option<Refusal> {
219 let below = resolved.strip_prefix(within).unwrap_or(resolved);
220 let names = || {
221 below.components().filter_map(|component| match component {
222 Component::Normal(name) => name.to_str(),
223 _ => None,
224 })
225 };
226 if names().any(|name| name.eq_ignore_ascii_case(PACKAGE_DIR)) {
227 return Some(Refusal::Packages);
228 }
229 if names().any(|name| name.eq_ignore_ascii_case(GIT_ENTRY)) {
230 return Some(Refusal::GitMetadata);
231 }
232 GitDirs::of(within)
233 .holds(resolved)
234 .then_some(Refusal::GitMetadata)
235}
236
237#[derive(Clone, Debug, Default)]
243pub struct GitDirs {
244 work_tree: Option<PathBuf>,
246 dirs: Vec<PathBuf>,
247 unknown: bool,
250}
251
252impl GitDirs {
253 #[must_use]
258 pub fn of(dir: &Path) -> Self {
259 let Some(top) = work_tree_top(dir) else {
260 return Self::default();
261 };
262 let mut git_dirs = Self {
263 work_tree: std::fs::canonicalize(top).ok(),
264 ..Self::default()
265 };
266 let mut next = Some(top);
267 while let Some(tree) = next {
268 git_dirs.add_entry(&tree.join(GIT_ENTRY));
269 next = tree.parent().and_then(work_tree_top);
270 }
271 git_dirs
272 }
273
274 fn add_entry(&mut self, entry: &Path) {
277 let git_dir = match read_git_entry(entry) {
278 Ok(Some(git_dir)) => git_dir,
279 Ok(None) => return,
280 Err(Unreadable) => {
281 self.unknown = true;
282 return;
283 }
284 };
285 let common = common_dir_of(&git_dir);
286 self.add(git_dir);
287 match common {
288 Some(common) => self.add(common),
289 None => self.unknown = true,
290 }
291 }
292
293 fn add(&mut self, dir: PathBuf) {
294 if !self.dirs.contains(&dir) {
295 self.dirs.push(dir);
296 }
297 }
298
299 #[must_use]
304 pub fn holds(&self, path: &Path) -> bool {
305 if self.unknown {
306 return true;
307 }
308 let in_work_tree_of = |dir: &Path| {
309 self.work_tree
310 .as_deref()
311 .is_some_and(|tree| tree.starts_with(dir) && path.starts_with(tree))
312 };
313 self.dirs
314 .iter()
315 .any(|dir| path.starts_with(dir) && !in_work_tree_of(dir))
316 }
317}
318
319#[must_use]
322pub fn work_tree_top(dir: &Path) -> Option<&Path> {
323 dir.ancestors()
324 .find(|ancestor| ancestor.join(GIT_ENTRY).symlink_metadata().is_ok())
325}
326
327struct Unreadable;
330
331const GIT_FILE_MAX_BYTES: u64 = 64 * 1024;
334
335fn git_dir_of_entry(entry: &Path) -> Option<PathBuf> {
338 read_git_entry(entry).ok().flatten()
339}
340
341fn read_git_entry(entry: &Path) -> Result<Option<PathBuf>, Unreadable> {
345 let meta = match std::fs::metadata(entry) {
346 Ok(meta) => meta,
347 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
348 Err(_) => return Err(Unreadable),
349 };
350 if meta.is_dir() {
351 return std::fs::canonicalize(entry)
352 .map(Some)
353 .map_err(|_| Unreadable);
354 }
355 let text = crate::read_guard::read_to_string_bounded(entry, GIT_FILE_MAX_BYTES)
356 .map_err(|_| Unreadable)?;
357 let named = text
358 .lines()
359 .find_map(|line| line.strip_prefix(GITDIR_PREFIX))
360 .map(str::trim)
361 .filter(|named| !named.is_empty())
362 .ok_or(Unreadable)?;
363 let parent = entry.parent().ok_or(Unreadable)?;
364 Ok(std::fs::canonicalize(parent.join(named)).ok())
365}
366
367fn common_dir_of(git_dir: &Path) -> Option<PathBuf> {
372 match crate::read_guard::read_to_string_bounded(
373 &git_dir.join(COMMONDIR_FILE),
374 GIT_FILE_MAX_BYTES,
375 ) {
376 Ok(text) => std::fs::canonicalize(git_dir.join(text.trim())).ok(),
377 Err(error) if error.is_not_found() => Some(git_dir.to_path_buf()),
378 Err(_) => None,
379 }
380}
381
382#[must_use]
397pub fn cache_write_base(root: &Path, cache_dir: &Path) -> PathBuf {
398 let normalized = lexically_normalized(cache_dir);
399 if normalized.starts_with(root) {
400 return root.to_path_buf();
401 }
402 same_repository_top(root, &normalized).unwrap_or_else(|| cache_dir.to_path_buf())
403}
404
405fn same_repository_top(root: &Path, cache_dir: &Path) -> Option<PathBuf> {
420 let root_common = common_dir_of_work_tree(work_tree_top(root)?)?;
421 let tops: Vec<&Path> = cache_dir
422 .ancestors()
423 .skip(1)
424 .filter(|ancestor| {
425 ancestor
426 .symlink_metadata()
427 .is_ok_and(|meta| !meta.file_type().is_symlink())
428 && ancestor.join(GIT_ENTRY).symlink_metadata().is_ok()
429 && common_dir_of_work_tree(ancestor).as_ref() == Some(&root_common)
430 })
431 .collect();
432 let highest = *tops.last()?;
433 tops.into_iter()
434 .find(|top| !has_link_between(highest, top))
435 .map(Path::to_path_buf)
436}
437
438fn has_link_between(upper: &Path, lower: &Path) -> bool {
441 let Ok(relative) = lower.strip_prefix(upper) else {
442 return true;
443 };
444 let mut current = upper.to_path_buf();
445 relative.components().any(|component| {
446 current.push(component);
447 !current
448 .symlink_metadata()
449 .is_ok_and(|meta| !meta.file_type().is_symlink())
450 })
451}
452
453fn common_dir_of_work_tree(top: &Path) -> Option<PathBuf> {
455 git_dir_of_entry(&top.join(GIT_ENTRY)).and_then(|git_dir| common_dir_of(&git_dir))
456}
457
458#[must_use]
461pub fn lexically_normalized(path: &Path) -> PathBuf {
462 let mut normalized = PathBuf::new();
463 for component in path.components() {
464 match component {
465 Component::CurDir => {}
466 Component::ParentDir => {
467 normalized.pop();
468 }
469 other => normalized.push(other),
470 }
471 }
472 normalized
473}
474
475pub fn ensure_no_outside_link(base: &Path, path: &Path) -> std::io::Result<()> {
490 if base.symlink_metadata().is_err() {
491 return Ok(());
492 }
493 match find_refusal(base, path, ParentSteps::Resolve) {
494 None => Ok(()),
495 Some(refused) => Err(std::io::Error::new(
496 std::io::ErrorKind::PermissionDenied,
497 format!(
498 "refusing to write {}: {}",
499 path.display(),
500 refused.reason.describe(&refused.entry, base)
501 ),
502 )),
503 }
504}
505
506#[derive(Clone, Copy, Debug)]
511pub struct CacheTarget<'a> {
512 dir: &'a Path,
513 anchor: &'a Path,
516 root: Option<&'a Path>,
518}
519
520impl<'a> CacheTarget<'a> {
521 #[must_use]
523 pub const fn new(root: &'a Path, dir: &'a Path) -> Self {
524 Self {
525 dir,
526 anchor: dir,
527 root: Some(root),
528 }
529 }
530
531 #[must_use]
534 pub const fn inside(dir: &'a Path) -> Self {
535 Self {
536 dir,
537 anchor: dir,
538 root: None,
539 }
540 }
541
542 #[must_use]
544 pub const fn dir(&self) -> &'a Path {
545 self.dir
546 }
547
548 #[must_use]
550 pub const fn with_dir(&self, dir: &'a Path) -> Self {
551 Self {
552 dir,
553 anchor: self.anchor,
554 root: self.root,
555 }
556 }
557
558 #[must_use]
561 pub fn write_base(&self) -> PathBuf {
562 self.root.map_or_else(
563 || self.anchor.to_path_buf(),
564 |root| cache_write_base(root, self.anchor),
565 )
566 }
567
568 pub fn check(&self, path: &Path) -> std::io::Result<()> {
575 ensure_no_outside_link(&self.write_base(), path)
576 }
577
578 pub fn write_file(&self, name: &str, data: &[u8]) -> std::io::Result<()> {
587 let path = self.dir.join(name);
588 self.check(&path)?;
589 std::fs::create_dir_all(self.dir)?;
590 crate::atomic_file::write_atomic(&path, data)
591 }
592
593 pub fn write_gitignore(&self) -> std::io::Result<()> {
600 let path = self.dir.join(".gitignore");
601 self.check(&path)?;
602 if std::fs::read(&path).is_ok_and(|content| content == b"*\n") {
603 return Ok(());
604 }
605 self.write_file(".gitignore", b"*\n")
606 }
607}
608
609#[cfg(all(test, unix, not(miri)))]
610mod tests {
611 use super::*;
612 use std::os::unix::fs::symlink;
613
614 struct Fixture {
615 _dir: tempfile::TempDir,
616 root: PathBuf,
617 outside: PathBuf,
618 }
619
620 fn fixture() -> Fixture {
621 let dir = tempfile::tempdir().expect("tempdir");
622 let root = dir.path().join("project");
623 let outside = dir.path().join("outside");
624 std::fs::create_dir_all(&root).expect("root");
625 std::fs::create_dir_all(&outside).expect("outside");
626 Fixture {
627 _dir: dir,
628 root,
629 outside,
630 }
631 }
632
633 #[test]
634 fn a_plain_path_passes() {
635 let f = fixture();
636 let path = f.root.join(".fallow/cache/x/cache.bin");
637 assert_eq!(outside_link(&f.root, &path), None);
638 assert!(ensure_no_outside_link(&f.root, &path).is_ok());
639 }
640
641 #[test]
642 fn a_linked_cache_dir_is_refused() {
643 let f = fixture();
644 symlink(&f.outside, f.root.join(".fallow")).expect("link");
645 let path = f.root.join(".fallow/.gitignore");
646 assert_eq!(outside_link(&f.root, &path), Some(f.root.join(".fallow")));
647 let error = ensure_no_outside_link(&f.root, &path).expect_err("refused");
648 assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
649 }
650
651 #[test]
652 fn a_dangling_file_link_is_refused() {
653 let f = fixture();
654 std::fs::create_dir_all(f.root.join(".fallow")).expect("cache");
655 let link = f.root.join(".fallow/.gitignore");
656 symlink(f.outside.join("missing"), &link).expect("link");
657 assert_eq!(outside_link(&f.root, &link), Some(link.clone()));
658 let error = ensure_no_outside_link(&f.root, &link).expect_err("refused");
659 assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
660 }
661
662 #[test]
663 fn a_link_inside_the_base_passes() {
664 let f = fixture();
665 std::fs::create_dir_all(f.root.join("build/cache")).expect("target");
666 symlink(f.root.join("build/cache"), f.root.join(".fallow")).expect("link");
667 assert_eq!(
668 outside_link(&f.root, &f.root.join(".fallow/cache.bin")),
669 None
670 );
671 }
672
673 #[test]
674 fn a_path_outside_the_base_is_refused() {
675 let f = fixture();
676 let path = f.outside.join("cache.bin");
677 assert_eq!(outside_link(&f.root, &path), Some(path));
678 }
679
680 #[test]
681 fn the_base_follows_where_the_cache_dir_is() {
682 let root = Path::new("/p");
683 assert_eq!(cache_write_base(root, Path::new("/p/.fallow")), root);
684 assert_eq!(
685 cache_write_base(root, Path::new("/ci/cache")),
686 Path::new("/ci/cache")
687 );
688 }
689
690 #[test]
691 fn a_target_writes_the_file_and_the_gitignore() {
692 let f = fixture();
693 let dir = f.root.join(".fallow/cache");
694 let target = CacheTarget::new(&f.root, &dir);
695 target.write_gitignore().expect("gitignore");
696 target.write_file("cache.bin", b"data").expect("file");
697 assert_eq!(std::fs::read(dir.join(".gitignore")).expect("read"), b"*\n");
698 assert_eq!(std::fs::read(dir.join("cache.bin")).expect("read"), b"data");
699 }
700
701 #[test]
702 fn a_target_refuses_a_linked_cache_dir_and_writes_nothing() {
703 let f = fixture();
704 symlink(&f.outside, f.root.join(".fallow")).expect("link");
705 let dir = f.root.join(".fallow");
706 let target = CacheTarget::new(&f.root, &dir);
707 assert!(target.write_gitignore().is_err());
708 assert!(target.write_file("cache.bin", b"data").is_err());
709 assert_eq!(std::fs::read_dir(&f.outside).expect("outside").count(), 0);
710 }
711
712 #[test]
713 fn a_target_refuses_a_dangling_gitignore_link() {
714 let f = fixture();
715 let dir = f.root.join(".fallow");
716 std::fs::create_dir_all(&dir).expect("cache");
717 symlink(f.outside.join("victim"), dir.join(".gitignore")).expect("link");
718 assert!(CacheTarget::new(&f.root, &dir).write_gitignore().is_err());
719 assert!(!f.outside.join("victim").exists());
720 }
721
722 #[test]
723 fn a_relative_cache_dir_above_the_root_is_its_own_base() {
724 let root = Path::new("/p/project");
725 let shared = Path::new("/p/project/../shared");
726 assert_eq!(cache_write_base(root, shared), shared);
727 let inside = Path::new("/p/project/sub/../.fallow");
728 assert_eq!(cache_write_base(root, inside), root);
729 }
730
731 #[test]
732 fn a_relative_cache_dir_above_the_root_gets_its_cache() {
733 let f = fixture();
734 let dir = f.root.join("../shared");
735 let target = CacheTarget::new(&f.root, &dir);
736 target.write_file("cache.bin", b"data").expect("file");
737 assert!(f.outside.join("../shared/cache.bin").exists());
738 }
739
740 #[test]
741 fn a_missing_base_passes_the_check() {
742 let f = fixture();
743 let base = f.outside.join("new");
744 assert!(ensure_no_outside_link(&base, &base.join("cache.bin")).is_ok());
745 }
746
747 #[test]
748 fn a_target_writes_into_a_new_cache_dir() {
749 let f = fixture();
750 let dir = f.outside.join("new/cache");
751 CacheTarget::inside(&dir)
752 .write_gitignore()
753 .expect("gitignore");
754 assert!(dir.join(".gitignore").exists());
755 }
756
757 #[test]
758 fn a_dir_link_into_the_git_dir_below_the_base_is_refused() {
759 let f = fixture();
760 std::fs::create_dir_all(f.root.join(".git")).expect("git dir");
761 symlink(f.root.join(".git"), f.root.join("conf")).expect("link");
762 let path = f.root.join("conf/config");
763 assert_eq!(outside_link(&f.root, &path), Some(f.root.join("conf")));
764 let error = ensure_no_outside_link(&f.root, &path).expect_err("refused");
765 assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
766 assert!(error.to_string().contains("Git metadata"), "{error}");
767 }
768
769 #[test]
770 fn a_file_link_into_a_nested_git_dir_is_refused() {
771 let f = fixture();
772 std::fs::create_dir_all(f.root.join("sub/.GIT")).expect("git dir");
773 std::fs::write(f.root.join("sub/.GIT/HEAD"), "ref").expect("head");
774 symlink(f.root.join("sub/.GIT/HEAD"), f.root.join("head")).expect("link");
775 let path = f.root.join("head");
776 assert_eq!(outside_link(&f.root, &path), Some(path));
777 }
778
779 #[test]
780 fn a_link_into_the_dir_that_a_git_file_names_is_refused() {
781 let f = fixture();
782 std::fs::create_dir_all(f.root.join("meta")).expect("meta");
783 std::fs::write(f.root.join(".git"), "gitdir: meta\n").expect("git file");
784 symlink(f.root.join("meta"), f.root.join("m")).expect("link");
785 let path = f.root.join("m/config");
786 assert_eq!(outside_link(&f.root, &path), Some(f.root.join("m")));
787 }
788
789 #[test]
790 fn a_base_that_links_into_the_git_dir_is_refused() {
791 let f = fixture();
792 std::fs::create_dir_all(f.root.join(".git/hooks")).expect("git dir");
793 let base = f.root.join("alias");
794 symlink(f.root.join(".git/hooks"), &base).expect("link");
795 let path = base.join("pre-commit");
796 assert_eq!(outside_link(&base, &path), Some(base));
797 }
798
799 #[test]
800 fn a_plain_path_into_the_git_dir_passes() {
801 let f = fixture();
802 std::fs::create_dir_all(f.root.join(".git/hooks")).expect("git dir");
803 let path = f.root.join(".git/hooks/pre-commit");
804 assert_eq!(outside_link(&f.root, &path), None);
805 }
806
807 #[test]
808 fn a_link_into_node_modules_is_refused() {
809 let f = fixture();
810 std::fs::create_dir_all(f.root.join("node_modules/left-pad")).expect("package");
811 std::fs::write(f.root.join("node_modules/left-pad/index.js"), "x").expect("file");
812 let path = f.root.join(".gitignore");
813 symlink(f.root.join("node_modules/left-pad/index.js"), &path).expect("link");
814 assert_eq!(outside_link(&f.root, &path), Some(path));
815 }
816
817 #[test]
818 fn a_named_pipe_target_is_refused() {
819 let f = fixture();
820 let fifo = f.root.join("report");
821 let made = std::process::Command::new("mkfifo")
822 .arg(&fifo)
823 .status()
824 .expect("run mkfifo");
825 assert!(made.success());
826 assert_eq!(outside_link(&f.root, &fifo), Some(fifo));
827 }
828
829 #[test]
833 fn a_cache_dir_in_the_checkout_of_a_linked_worktree_is_checked_from_the_checkout() {
834 let f = fixture();
835 let host = f.root.join("host");
836 std::fs::create_dir_all(host.join(".git/worktrees/staged")).expect("host git");
837 std::fs::write(host.join(".git/worktrees/staged/commondir"), "../..\n").expect("common");
838 std::fs::create_dir_all(host.join("packages/app")).expect("host app");
839 let staged = f.root.join("staged");
840 std::fs::create_dir_all(staged.join("packages/app")).expect("staged app");
841 std::fs::write(
842 staged.join(".git"),
843 format!("gitdir: {}\n", host.join(".git/worktrees/staged").display()),
844 )
845 .expect("git file");
846 symlink(&f.outside, host.join("packages/app/buildcache")).expect("link");
847 let root = staged.join("packages/app");
848 let dir = host.join("packages/app/buildcache");
849 let target = CacheTarget::new(&root, &dir);
850 assert!(target.check(&dir.join("cache.bin")).is_err());
851 assert!(target.write_file("cache.bin", b"data").is_err());
852 assert_eq!(std::fs::read_dir(&f.outside).expect("outside").count(), 0);
853 }
854
855 #[test]
858 fn a_cache_dir_through_a_link_to_another_checkout_is_checked_from_the_checkout() {
859 let f = fixture();
860 let host = f.root.join("host");
861 std::fs::create_dir_all(host.join(".git/worktrees/staged")).expect("host git");
862 std::fs::write(host.join(".git/worktrees/staged/commondir"), "../..\n").expect("common");
863 std::fs::create_dir_all(host.join("packages/app")).expect("host app");
864 let other = f.outside.join("other");
865 std::fs::create_dir_all(other.join(".git")).expect("other git");
866 symlink(&other, host.join("packages/app/link")).expect("link");
867 let staged = f.root.join("staged");
868 std::fs::create_dir_all(staged.join("packages/app")).expect("staged app");
869 std::fs::write(
870 staged.join(".git"),
871 format!("gitdir: {}\n", host.join(".git/worktrees/staged").display()),
872 )
873 .expect("git file");
874 let root = staged.join("packages/app");
875 let dir = host.join("packages/app/link/cache");
876 let target = CacheTarget::new(&root, &dir);
877 assert!(target.write_file("cache.bin", b"data").is_err());
878 assert!(!other.join("cache").exists());
879 }
880
881 #[test]
884 fn a_cache_dir_in_a_linked_worktree_host_is_checked_from_the_worktree() {
885 let f = fixture();
886 let main = f.root.join("repo");
887 std::fs::create_dir_all(main.join(".git/worktrees/feature")).expect("main git");
888 std::fs::create_dir_all(main.join(".git/worktrees/staged")).expect("staged git");
889 for name in ["feature", "staged"] {
890 std::fs::write(
891 main.join(format!(".git/worktrees/{name}/commondir")),
892 "../..\n",
893 )
894 .expect("common");
895 }
896 let host = f.root.join("wt/feature");
897 std::fs::create_dir_all(host.join("packages/app")).expect("host app");
898 std::fs::write(
899 host.join(".git"),
900 format!(
901 "gitdir: {}\n",
902 main.join(".git/worktrees/feature").display()
903 ),
904 )
905 .expect("host git file");
906 let staged = f.root.join("staged");
907 std::fs::create_dir_all(staged.join("packages/app")).expect("staged app");
908 std::fs::write(
909 staged.join(".git"),
910 format!("gitdir: {}\n", main.join(".git/worktrees/staged").display()),
911 )
912 .expect("staged git file");
913 symlink(&f.outside, host.join("packages/app/build")).expect("link");
914 let root = staged.join("packages/app");
915 let dir = host.join("packages/app/build/cache");
916 assert!(
917 CacheTarget::new(&root, &dir)
918 .write_file("cache.bin", b"data")
919 .is_err()
920 );
921 assert_eq!(std::fs::read_dir(&f.outside).expect("outside").count(), 0);
922 }
923
924 #[test]
927 fn a_cache_dir_in_a_submodule_host_is_checked_from_the_submodule() {
928 let f = fixture();
929 let modules = f.root.join("super/.git/modules/sub");
930 std::fs::create_dir_all(modules.join("worktrees/staged")).expect("module git");
931 std::fs::write(modules.join("worktrees/staged/commondir"), "../..\n").expect("common");
932 let host = f.root.join("super/sub");
933 std::fs::create_dir_all(host.join("packages/app")).expect("host app");
934 std::fs::write(
935 host.join(".git"),
936 format!("gitdir: {}\n", modules.display()),
937 )
938 .expect("host git file");
939 let staged = f.root.join("staged");
940 std::fs::create_dir_all(staged.join("packages/app")).expect("staged app");
941 std::fs::write(
942 staged.join(".git"),
943 format!("gitdir: {}\n", modules.join("worktrees/staged").display()),
944 )
945 .expect("staged git file");
946 symlink(&f.outside, host.join("packages/app/build")).expect("link");
947 let root = staged.join("packages/app");
948 let dir = host.join("packages/app/build/cache");
949 assert!(
950 CacheTarget::new(&root, &dir)
951 .write_file("cache.bin", b"data")
952 .is_err()
953 );
954 assert_eq!(std::fs::read_dir(&f.outside).expect("outside").count(), 0);
955 }
956
957 fn linked_work_tree(common: &Path, top: &Path, name: &str) {
960 let git_dir = common.join("worktrees").join(name);
961 std::fs::create_dir_all(&git_dir).expect("linked git dir");
962 std::fs::write(git_dir.join("commondir"), "../..\n").expect("common");
963 std::fs::create_dir_all(top).expect("work tree");
964 std::fs::write(top.join(".git"), format!("gitdir: {}\n", git_dir.display()))
965 .expect("git file");
966 }
967
968 #[test]
972 fn a_link_from_a_worktree_inside_the_main_checkout_up_into_it_is_refused() {
973 let f = fixture();
974 let repo = f.root.join("repo");
975 std::fs::create_dir_all(repo.join(".git")).expect("main git");
976 let host = repo.join(".worktrees/feature");
977 linked_work_tree(&repo.join(".git"), &host, "feature");
978 let staged = f.root.join("staged");
979 linked_work_tree(&repo.join(".git"), &staged, "staged");
980 symlink("../..", host.join("build")).expect("link");
981 let dir = host.join("build/cache");
982 for root in [&staged, &host] {
983 let target = CacheTarget::new(root, &dir);
984 assert!(target.write_gitignore().is_err());
985 assert!(target.write_file("cache.bin", b"data").is_err());
986 }
987 assert!(!repo.join("cache").exists());
988 }
989
990 #[test]
993 fn a_link_from_a_nested_worktree_of_a_bare_repository_is_refused() {
994 let f = fixture();
995 let bare = f.root.join("repo.git");
996 let outer = f.root.join("trees/main");
997 linked_work_tree(&bare, &outer, "main");
998 let host = outer.join(".worktrees/feature");
999 linked_work_tree(&bare, &host, "feature");
1000 let staged = f.root.join("staged");
1001 linked_work_tree(&bare, &staged, "staged");
1002 symlink("../..", host.join("build")).expect("link");
1003 let dir = host.join("build/cache");
1004 assert!(
1005 CacheTarget::new(&staged, &dir)
1006 .write_file("cache.bin", b"data")
1007 .is_err()
1008 );
1009 assert!(!outer.join("cache").exists());
1010 }
1011
1012 #[test]
1015 fn a_work_tree_behind_a_link_is_not_the_base() {
1016 let f = fixture();
1017 let repo = f.root.join("repo");
1018 std::fs::create_dir_all(repo.join(".git")).expect("main git");
1019 let host = f.root.join("host");
1020 linked_work_tree(&repo.join(".git"), &host, "host");
1021 let other = f.outside.join("other");
1022 linked_work_tree(&repo.join(".git"), &other, "other");
1023 linked_work_tree(&repo.join(".git"), &other.join("nested"), "nested");
1024 let staged = f.root.join("staged");
1025 linked_work_tree(&repo.join(".git"), &staged, "staged");
1026 symlink(&other, host.join("shared")).expect("link");
1027 let dir = host.join("shared/nested/cache");
1028 assert!(
1029 CacheTarget::new(&staged, &dir)
1030 .write_file("cache.bin", b"data")
1031 .is_err()
1032 );
1033 assert!(!other.join("nested/cache").exists());
1034 }
1035
1036 #[test]
1039 fn a_worktree_inside_a_bare_repository_is_not_git_metadata() {
1040 let f = fixture();
1041 let bare = f.root.join("proj.git");
1042 let main = bare.join("main");
1043 linked_work_tree(&bare, &main, "main");
1044 std::fs::create_dir_all(main.join("src")).expect("src");
1045 std::fs::create_dir_all(bare.join("hooks")).expect("hooks");
1046 let canonical_main = std::fs::canonicalize(&main).expect("main");
1047 let canonical_bare = std::fs::canonicalize(&bare).expect("bare");
1048 assert!(!is_protected_link_target(
1049 &canonical_main,
1050 &canonical_main.join("src/a.ts")
1051 ));
1052 assert!(is_protected_link_target(
1053 &canonical_main,
1054 &canonical_bare.join("hooks/pre-commit")
1055 ));
1056 assert!(is_protected_link_target(
1057 &canonical_main,
1058 &canonical_bare.join("worktrees/main/HEAD")
1059 ));
1060 std::fs::create_dir_all(main.join("build/cache")).expect("cache");
1061 symlink("build/cache", main.join(".fallow")).expect("link");
1062 let dir = main.join(".fallow");
1063 CacheTarget::new(&main, &dir)
1064 .write_file("cache.bin", b"data")
1065 .expect("file");
1066 symlink(bare.join("hooks"), main.join("hooks")).expect("hooks link");
1067 let error =
1068 ensure_no_outside_link(&main, &main.join("hooks/pre-commit")).expect_err("refused");
1069 assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
1070 }
1071
1072 #[test]
1075 fn an_unreadable_commondir_protects_every_link_target() {
1076 let f = fixture();
1077 let repo = f.root.join("repo");
1078 std::fs::create_dir_all(repo.join(".git/worktrees/main/commondir")).expect("git dir");
1079 let main = f.root.join("main");
1080 std::fs::create_dir_all(&main).expect("main");
1081 std::fs::write(
1082 main.join(".git"),
1083 format!("gitdir: {}\n", repo.join(".git/worktrees/main").display()),
1084 )
1085 .expect("git file");
1086 let canonical = std::fs::canonicalize(&main).expect("main");
1087 assert!(is_protected_link_target(
1088 &canonical,
1089 &canonical.join("src/a.ts")
1090 ));
1091 }
1092
1093 #[test]
1097 fn a_user_cache_dir_with_a_parent_step_in_the_work_tree_writes() {
1098 let f = fixture();
1099 std::fs::create_dir_all(f.root.join(".git")).expect("git dir");
1100 let root = f.root.join("pkg");
1101 std::fs::create_dir_all(&root).expect("pkg");
1102 let dir = root.join("../shared");
1103 assert_eq!(cache_write_base(&root, &dir), f.root);
1104 CacheTarget::new(&root, &dir)
1105 .write_file("cache.bin", b"data")
1106 .expect("file");
1107 assert!(f.root.join("shared/cache.bin").exists());
1108
1109 std::fs::create_dir_all(f.outside.join("sub")).expect("sub");
1110 symlink(f.outside.join("sub"), root.join("link")).expect("link");
1111 let through = root.join("link/../elsewhere");
1112 let error = CacheTarget::new(&root, &through)
1113 .write_file("cache.bin", b"data")
1114 .expect_err("refused");
1115 assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
1116 assert!(error.to_string().contains("outside"), "{error}");
1117 assert!(!f.outside.join("elsewhere").exists());
1118 }
1119
1120 #[test]
1122 fn the_refusal_names_the_reason() {
1123 let f = fixture();
1124 std::fs::create_dir_all(f.root.join("node_modules/pkg")).expect("packages");
1125 symlink(f.root.join("node_modules/pkg"), f.root.join(".fallow")).expect("link");
1126 let error = ensure_no_outside_link(&f.root, &f.root.join(".fallow/cache.bin"))
1127 .expect_err("refused");
1128 assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
1129 assert!(error.to_string().contains("node_modules"), "{error}");
1130 assert!(!error.to_string().contains("outside"), "{error}");
1131 }
1132
1133 #[test]
1134 fn a_cache_dir_above_a_subdirectory_root_is_checked_from_the_work_tree() {
1135 let f = fixture();
1136 std::fs::create_dir_all(f.root.join(".git")).expect("git dir");
1137 std::fs::create_dir_all(f.root.join("packages/app")).expect("app");
1138 symlink(&f.outside, f.root.join(".cache")).expect("link");
1139 let root = f.root.join("packages/app");
1140 let dir = f.root.join(".cache");
1141 assert!(
1142 CacheTarget::new(&root, &dir)
1143 .check(&dir.join("cache.bin"))
1144 .is_err()
1145 );
1146 }
1147
1148 #[test]
1149 fn a_cache_dir_in_another_checkout_is_its_own_base() {
1150 let f = fixture();
1151 std::fs::create_dir_all(f.root.join(".git")).expect("git dir");
1152 let other = f.outside.join("home");
1153 std::fs::create_dir_all(other.join(".git")).expect("other git");
1154 let elsewhere = f.outside.join("disk");
1155 std::fs::create_dir_all(&elsewhere).expect("disk");
1156 symlink(&elsewhere, other.join(".cache")).expect("link");
1157 let dir = other.join(".cache/fallow");
1158 let target = CacheTarget::new(&f.root, &dir);
1159 target.write_file("cache.bin", b"data").expect("file");
1160 assert!(elsewhere.join("fallow/cache.bin").exists());
1161 }
1162
1163 #[test]
1164 fn a_user_cache_dir_outside_the_root_is_checked_from_itself() {
1165 let f = fixture();
1166 let target = CacheTarget::new(&f.root, &f.outside);
1167 target.write_file("cache.bin", b"data").expect("file");
1168 assert!(f.outside.join("cache.bin").exists());
1169 }
1170
1171 fn submodule_of_separate_git_dir(f: &Fixture) -> (PathBuf, PathBuf) {
1177 let git_dir = f.outside.join("super.git");
1178 let module = git_dir.join("modules/lib");
1179 std::fs::create_dir_all(git_dir.join("hooks")).expect("super hooks");
1180 std::fs::create_dir_all(module.join("hooks")).expect("module hooks");
1181 let superproject = f.root.join("super");
1182 let submodule = superproject.join("vendor/lib");
1183 std::fs::create_dir_all(submodule.join("src")).expect("submodule");
1184 std::fs::write(
1185 superproject.join(".git"),
1186 format!("gitdir: {}\n", git_dir.display()),
1187 )
1188 .expect("super git file");
1189 std::fs::write(
1190 submodule.join(".git"),
1191 format!("gitdir: {}\n", module.display()),
1192 )
1193 .expect("submodule git file");
1194 (
1195 std::fs::canonicalize(&submodule).expect("submodule"),
1196 std::fs::canonicalize(&git_dir).expect("super git dir"),
1197 )
1198 }
1199
1200 #[test]
1203 fn a_link_into_the_git_dir_of_the_superproject_is_refused() {
1204 let f = fixture();
1205 let (submodule, git_dir) = submodule_of_separate_git_dir(&f);
1206 assert!(is_protected_link_target(
1207 &submodule,
1208 &git_dir.join("hooks/pre-commit")
1209 ));
1210 assert!(is_protected_link_target(
1211 &submodule.join("src"),
1212 &git_dir.join("config")
1213 ));
1214 }
1215
1216 #[test]
1219 fn a_submodule_root_protects_its_own_git_dir_only() {
1220 let f = fixture();
1221 let (submodule, git_dir) = submodule_of_separate_git_dir(&f);
1222 assert!(is_protected_link_target(
1223 &submodule,
1224 &git_dir.join("modules/lib/hooks/pre-commit")
1225 ));
1226 assert!(!is_protected_link_target(
1227 &submodule,
1228 &submodule.join("src/a.ts")
1229 ));
1230 let other = std::fs::canonicalize(&f.outside).expect("outside");
1231 assert!(!is_protected_link_target(
1232 &submodule,
1233 &other.join("report.json")
1234 ));
1235 }
1236
1237 #[test]
1240 fn a_link_into_the_common_dir_of_the_superproject_is_refused() {
1241 let f = fixture();
1242 let common = f.outside.join("super.git");
1243 std::fs::create_dir_all(common.join("hooks")).expect("hooks");
1244 let superproject = f.root.join("wt");
1245 linked_work_tree(&common, &superproject, "wt");
1246 let submodule = superproject.join("lib");
1247 let module = common.join("worktrees/wt/modules/lib");
1248 std::fs::create_dir_all(&module).expect("module");
1249 std::fs::create_dir_all(&submodule).expect("submodule");
1250 std::fs::write(
1251 submodule.join(".git"),
1252 format!("gitdir: {}\n", module.display()),
1253 )
1254 .expect("git file");
1255 let submodule = std::fs::canonicalize(&submodule).expect("submodule");
1256 let common = std::fs::canonicalize(&common).expect("common");
1257 assert!(is_protected_link_target(
1258 &submodule,
1259 &common.join("hooks/pre-commit")
1260 ));
1261 }
1262
1263 #[test]
1267 fn a_git_file_without_a_gitdir_line_protects_every_link_target() {
1268 let f = fixture();
1269 let superproject = f.root.join("super");
1270 let submodule = superproject.join("lib");
1271 std::fs::create_dir_all(&submodule).expect("submodule");
1272 std::fs::create_dir_all(submodule.join(".git")).expect("submodule git dir");
1273 std::fs::write(superproject.join(".git"), "not a git file\n").expect("git file");
1274 let submodule = std::fs::canonicalize(&submodule).expect("submodule");
1275 assert!(is_protected_link_target(
1276 &submodule,
1277 &submodule.join("src/a.ts")
1278 ));
1279 }
1280
1281 #[test]
1283 fn an_unreadable_git_file_protects_every_link_target() {
1284 let f = fixture();
1285 let root = f.root.join("repo");
1286 std::fs::create_dir_all(&root).expect("repo");
1287 std::fs::write(root.join(".git"), [0xff, 0xfe, b'\n']).expect("git file");
1288 let root = std::fs::canonicalize(&root).expect("repo");
1289 assert!(is_protected_link_target(&root, &root.join("src/a.ts")));
1290 }
1291
1292 #[test]
1295 fn a_named_pipe_git_entry_protects_every_link_target() {
1296 let f = fixture();
1297 let root = f.root.join("repo");
1298 std::fs::create_dir_all(&root).expect("repo");
1299 let made = std::process::Command::new("mkfifo")
1300 .arg(root.join(".git"))
1301 .status()
1302 .expect("run mkfifo");
1303 assert!(made.success());
1304 let root = std::fs::canonicalize(&root).expect("repo");
1305 assert!(is_protected_link_target(&root, &root.join("src/a.ts")));
1306 }
1307}