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]
212pub fn is_protected_link_target(within: &Path, resolved: &Path) -> bool {
213 protected_kind(within, resolved).is_some()
214}
215
216fn protected_kind(within: &Path, resolved: &Path) -> Option<Refusal> {
218 let below = resolved.strip_prefix(within).unwrap_or(resolved);
219 let names = || {
220 below.components().filter_map(|component| match component {
221 Component::Normal(name) => name.to_str(),
222 _ => None,
223 })
224 };
225 if names().any(|name| name.eq_ignore_ascii_case(PACKAGE_DIR)) {
226 return Some(Refusal::Packages);
227 }
228 if names().any(|name| name.eq_ignore_ascii_case(GIT_ENTRY)) {
229 return Some(Refusal::GitMetadata);
230 }
231 GitDirs::of(within)
232 .holds(resolved)
233 .then_some(Refusal::GitMetadata)
234}
235
236#[derive(Clone, Debug, Default)]
240pub struct GitDirs {
241 work_tree: Option<PathBuf>,
243 dirs: Vec<PathBuf>,
244 unknown: bool,
247}
248
249impl GitDirs {
250 #[must_use]
254 pub fn of(dir: &Path) -> Self {
255 let Some(top) = work_tree_top(dir) else {
256 return Self::default();
257 };
258 let work_tree = std::fs::canonicalize(top).ok();
259 let Some(git_dir) = git_dir_of_entry(&top.join(GIT_ENTRY)) else {
260 return Self {
261 work_tree,
262 ..Self::default()
263 };
264 };
265 let common = common_dir_of(&git_dir);
266 let unknown = common.is_none();
267 let mut dirs = vec![git_dir];
268 if let Some(common) = common
269 && !dirs.contains(&common)
270 {
271 dirs.push(common);
272 }
273 Self {
274 work_tree,
275 dirs,
276 unknown,
277 }
278 }
279
280 #[must_use]
285 pub fn holds(&self, path: &Path) -> bool {
286 if self.unknown {
287 return true;
288 }
289 let in_work_tree_of = |dir: &Path| {
290 self.work_tree
291 .as_deref()
292 .is_some_and(|tree| tree.starts_with(dir) && path.starts_with(tree))
293 };
294 self.dirs
295 .iter()
296 .any(|dir| path.starts_with(dir) && !in_work_tree_of(dir))
297 }
298}
299
300#[must_use]
303pub fn work_tree_top(dir: &Path) -> Option<&Path> {
304 dir.ancestors()
305 .find(|ancestor| ancestor.join(GIT_ENTRY).symlink_metadata().is_ok())
306}
307
308fn git_dir_of_entry(entry: &Path) -> Option<PathBuf> {
311 let meta = std::fs::metadata(entry).ok()?;
312 if meta.is_dir() {
313 return std::fs::canonicalize(entry).ok();
314 }
315 let text = std::fs::read_to_string(entry).ok()?;
316 let named = text
317 .lines()
318 .find_map(|line| line.strip_prefix(GITDIR_PREFIX))?
319 .trim();
320 let parent = entry.parent()?;
321 std::fs::canonicalize(parent.join(named)).ok()
322}
323
324fn common_dir_of(git_dir: &Path) -> Option<PathBuf> {
329 match std::fs::read_to_string(git_dir.join(COMMONDIR_FILE)) {
330 Ok(text) => std::fs::canonicalize(git_dir.join(text.trim())).ok(),
331 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Some(git_dir.to_path_buf()),
332 Err(_) => None,
333 }
334}
335
336#[must_use]
351pub fn cache_write_base(root: &Path, cache_dir: &Path) -> PathBuf {
352 let normalized = lexically_normalized(cache_dir);
353 if normalized.starts_with(root) {
354 return root.to_path_buf();
355 }
356 same_repository_top(root, &normalized).unwrap_or_else(|| cache_dir.to_path_buf())
357}
358
359fn same_repository_top(root: &Path, cache_dir: &Path) -> Option<PathBuf> {
374 let root_common = common_dir_of_work_tree(work_tree_top(root)?)?;
375 let tops: Vec<&Path> = cache_dir
376 .ancestors()
377 .skip(1)
378 .filter(|ancestor| {
379 ancestor
380 .symlink_metadata()
381 .is_ok_and(|meta| !meta.file_type().is_symlink())
382 && ancestor.join(GIT_ENTRY).symlink_metadata().is_ok()
383 && common_dir_of_work_tree(ancestor).as_ref() == Some(&root_common)
384 })
385 .collect();
386 let highest = *tops.last()?;
387 tops.into_iter()
388 .find(|top| !has_link_between(highest, top))
389 .map(Path::to_path_buf)
390}
391
392fn has_link_between(upper: &Path, lower: &Path) -> bool {
395 let Ok(relative) = lower.strip_prefix(upper) else {
396 return true;
397 };
398 let mut current = upper.to_path_buf();
399 relative.components().any(|component| {
400 current.push(component);
401 !current
402 .symlink_metadata()
403 .is_ok_and(|meta| !meta.file_type().is_symlink())
404 })
405}
406
407fn common_dir_of_work_tree(top: &Path) -> Option<PathBuf> {
409 git_dir_of_entry(&top.join(GIT_ENTRY)).and_then(|git_dir| common_dir_of(&git_dir))
410}
411
412#[must_use]
415pub fn lexically_normalized(path: &Path) -> PathBuf {
416 let mut normalized = PathBuf::new();
417 for component in path.components() {
418 match component {
419 Component::CurDir => {}
420 Component::ParentDir => {
421 normalized.pop();
422 }
423 other => normalized.push(other),
424 }
425 }
426 normalized
427}
428
429pub fn ensure_no_outside_link(base: &Path, path: &Path) -> std::io::Result<()> {
444 if base.symlink_metadata().is_err() {
445 return Ok(());
446 }
447 match find_refusal(base, path, ParentSteps::Resolve) {
448 None => Ok(()),
449 Some(refused) => Err(std::io::Error::new(
450 std::io::ErrorKind::PermissionDenied,
451 format!(
452 "refusing to write {}: {}",
453 path.display(),
454 refused.reason.describe(&refused.entry, base)
455 ),
456 )),
457 }
458}
459
460#[derive(Clone, Copy, Debug)]
465pub struct CacheTarget<'a> {
466 dir: &'a Path,
467 anchor: &'a Path,
470 root: Option<&'a Path>,
472}
473
474impl<'a> CacheTarget<'a> {
475 #[must_use]
477 pub const fn new(root: &'a Path, dir: &'a Path) -> Self {
478 Self {
479 dir,
480 anchor: dir,
481 root: Some(root),
482 }
483 }
484
485 #[must_use]
488 pub const fn inside(dir: &'a Path) -> Self {
489 Self {
490 dir,
491 anchor: dir,
492 root: None,
493 }
494 }
495
496 #[must_use]
498 pub const fn dir(&self) -> &'a Path {
499 self.dir
500 }
501
502 #[must_use]
504 pub const fn with_dir(&self, dir: &'a Path) -> Self {
505 Self {
506 dir,
507 anchor: self.anchor,
508 root: self.root,
509 }
510 }
511
512 #[must_use]
515 pub fn write_base(&self) -> PathBuf {
516 self.root.map_or_else(
517 || self.anchor.to_path_buf(),
518 |root| cache_write_base(root, self.anchor),
519 )
520 }
521
522 pub fn check(&self, path: &Path) -> std::io::Result<()> {
529 ensure_no_outside_link(&self.write_base(), path)
530 }
531
532 pub fn write_file(&self, name: &str, data: &[u8]) -> std::io::Result<()> {
541 let path = self.dir.join(name);
542 self.check(&path)?;
543 std::fs::create_dir_all(self.dir)?;
544 crate::atomic_file::write_atomic(&path, data)
545 }
546
547 pub fn write_gitignore(&self) -> std::io::Result<()> {
554 let path = self.dir.join(".gitignore");
555 self.check(&path)?;
556 if std::fs::read(&path).is_ok_and(|content| content == b"*\n") {
557 return Ok(());
558 }
559 self.write_file(".gitignore", b"*\n")
560 }
561}
562
563#[cfg(all(test, unix, not(miri)))]
564mod tests {
565 use super::*;
566 use std::os::unix::fs::symlink;
567
568 struct Fixture {
569 _dir: tempfile::TempDir,
570 root: PathBuf,
571 outside: PathBuf,
572 }
573
574 fn fixture() -> Fixture {
575 let dir = tempfile::tempdir().expect("tempdir");
576 let root = dir.path().join("project");
577 let outside = dir.path().join("outside");
578 std::fs::create_dir_all(&root).expect("root");
579 std::fs::create_dir_all(&outside).expect("outside");
580 Fixture {
581 _dir: dir,
582 root,
583 outside,
584 }
585 }
586
587 #[test]
588 fn a_plain_path_passes() {
589 let f = fixture();
590 let path = f.root.join(".fallow/cache/x/cache.bin");
591 assert_eq!(outside_link(&f.root, &path), None);
592 assert!(ensure_no_outside_link(&f.root, &path).is_ok());
593 }
594
595 #[test]
596 fn a_linked_cache_dir_is_refused() {
597 let f = fixture();
598 symlink(&f.outside, f.root.join(".fallow")).expect("link");
599 let path = f.root.join(".fallow/.gitignore");
600 assert_eq!(outside_link(&f.root, &path), Some(f.root.join(".fallow")));
601 let error = ensure_no_outside_link(&f.root, &path).expect_err("refused");
602 assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
603 }
604
605 #[test]
606 fn a_dangling_file_link_is_refused() {
607 let f = fixture();
608 std::fs::create_dir_all(f.root.join(".fallow")).expect("cache");
609 let link = f.root.join(".fallow/.gitignore");
610 symlink(f.outside.join("missing"), &link).expect("link");
611 assert_eq!(outside_link(&f.root, &link), Some(link.clone()));
612 let error = ensure_no_outside_link(&f.root, &link).expect_err("refused");
613 assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
614 }
615
616 #[test]
617 fn a_link_inside_the_base_passes() {
618 let f = fixture();
619 std::fs::create_dir_all(f.root.join("build/cache")).expect("target");
620 symlink(f.root.join("build/cache"), f.root.join(".fallow")).expect("link");
621 assert_eq!(
622 outside_link(&f.root, &f.root.join(".fallow/cache.bin")),
623 None
624 );
625 }
626
627 #[test]
628 fn a_path_outside_the_base_is_refused() {
629 let f = fixture();
630 let path = f.outside.join("cache.bin");
631 assert_eq!(outside_link(&f.root, &path), Some(path));
632 }
633
634 #[test]
635 fn the_base_follows_where_the_cache_dir_is() {
636 let root = Path::new("/p");
637 assert_eq!(cache_write_base(root, Path::new("/p/.fallow")), root);
638 assert_eq!(
639 cache_write_base(root, Path::new("/ci/cache")),
640 Path::new("/ci/cache")
641 );
642 }
643
644 #[test]
645 fn a_target_writes_the_file_and_the_gitignore() {
646 let f = fixture();
647 let dir = f.root.join(".fallow/cache");
648 let target = CacheTarget::new(&f.root, &dir);
649 target.write_gitignore().expect("gitignore");
650 target.write_file("cache.bin", b"data").expect("file");
651 assert_eq!(std::fs::read(dir.join(".gitignore")).expect("read"), b"*\n");
652 assert_eq!(std::fs::read(dir.join("cache.bin")).expect("read"), b"data");
653 }
654
655 #[test]
656 fn a_target_refuses_a_linked_cache_dir_and_writes_nothing() {
657 let f = fixture();
658 symlink(&f.outside, f.root.join(".fallow")).expect("link");
659 let dir = f.root.join(".fallow");
660 let target = CacheTarget::new(&f.root, &dir);
661 assert!(target.write_gitignore().is_err());
662 assert!(target.write_file("cache.bin", b"data").is_err());
663 assert_eq!(std::fs::read_dir(&f.outside).expect("outside").count(), 0);
664 }
665
666 #[test]
667 fn a_target_refuses_a_dangling_gitignore_link() {
668 let f = fixture();
669 let dir = f.root.join(".fallow");
670 std::fs::create_dir_all(&dir).expect("cache");
671 symlink(f.outside.join("victim"), dir.join(".gitignore")).expect("link");
672 assert!(CacheTarget::new(&f.root, &dir).write_gitignore().is_err());
673 assert!(!f.outside.join("victim").exists());
674 }
675
676 #[test]
677 fn a_relative_cache_dir_above_the_root_is_its_own_base() {
678 let root = Path::new("/p/project");
679 let shared = Path::new("/p/project/../shared");
680 assert_eq!(cache_write_base(root, shared), shared);
681 let inside = Path::new("/p/project/sub/../.fallow");
682 assert_eq!(cache_write_base(root, inside), root);
683 }
684
685 #[test]
686 fn a_relative_cache_dir_above_the_root_gets_its_cache() {
687 let f = fixture();
688 let dir = f.root.join("../shared");
689 let target = CacheTarget::new(&f.root, &dir);
690 target.write_file("cache.bin", b"data").expect("file");
691 assert!(f.outside.join("../shared/cache.bin").exists());
692 }
693
694 #[test]
695 fn a_missing_base_passes_the_check() {
696 let f = fixture();
697 let base = f.outside.join("new");
698 assert!(ensure_no_outside_link(&base, &base.join("cache.bin")).is_ok());
699 }
700
701 #[test]
702 fn a_target_writes_into_a_new_cache_dir() {
703 let f = fixture();
704 let dir = f.outside.join("new/cache");
705 CacheTarget::inside(&dir)
706 .write_gitignore()
707 .expect("gitignore");
708 assert!(dir.join(".gitignore").exists());
709 }
710
711 #[test]
712 fn a_dir_link_into_the_git_dir_below_the_base_is_refused() {
713 let f = fixture();
714 std::fs::create_dir_all(f.root.join(".git")).expect("git dir");
715 symlink(f.root.join(".git"), f.root.join("conf")).expect("link");
716 let path = f.root.join("conf/config");
717 assert_eq!(outside_link(&f.root, &path), Some(f.root.join("conf")));
718 let error = ensure_no_outside_link(&f.root, &path).expect_err("refused");
719 assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
720 assert!(error.to_string().contains("Git metadata"), "{error}");
721 }
722
723 #[test]
724 fn a_file_link_into_a_nested_git_dir_is_refused() {
725 let f = fixture();
726 std::fs::create_dir_all(f.root.join("sub/.GIT")).expect("git dir");
727 std::fs::write(f.root.join("sub/.GIT/HEAD"), "ref").expect("head");
728 symlink(f.root.join("sub/.GIT/HEAD"), f.root.join("head")).expect("link");
729 let path = f.root.join("head");
730 assert_eq!(outside_link(&f.root, &path), Some(path));
731 }
732
733 #[test]
734 fn a_link_into_the_dir_that_a_git_file_names_is_refused() {
735 let f = fixture();
736 std::fs::create_dir_all(f.root.join("meta")).expect("meta");
737 std::fs::write(f.root.join(".git"), "gitdir: meta\n").expect("git file");
738 symlink(f.root.join("meta"), f.root.join("m")).expect("link");
739 let path = f.root.join("m/config");
740 assert_eq!(outside_link(&f.root, &path), Some(f.root.join("m")));
741 }
742
743 #[test]
744 fn a_base_that_links_into_the_git_dir_is_refused() {
745 let f = fixture();
746 std::fs::create_dir_all(f.root.join(".git/hooks")).expect("git dir");
747 let base = f.root.join("alias");
748 symlink(f.root.join(".git/hooks"), &base).expect("link");
749 let path = base.join("pre-commit");
750 assert_eq!(outside_link(&base, &path), Some(base));
751 }
752
753 #[test]
754 fn a_plain_path_into_the_git_dir_passes() {
755 let f = fixture();
756 std::fs::create_dir_all(f.root.join(".git/hooks")).expect("git dir");
757 let path = f.root.join(".git/hooks/pre-commit");
758 assert_eq!(outside_link(&f.root, &path), None);
759 }
760
761 #[test]
762 fn a_link_into_node_modules_is_refused() {
763 let f = fixture();
764 std::fs::create_dir_all(f.root.join("node_modules/left-pad")).expect("package");
765 std::fs::write(f.root.join("node_modules/left-pad/index.js"), "x").expect("file");
766 let path = f.root.join(".gitignore");
767 symlink(f.root.join("node_modules/left-pad/index.js"), &path).expect("link");
768 assert_eq!(outside_link(&f.root, &path), Some(path));
769 }
770
771 #[test]
772 fn a_named_pipe_target_is_refused() {
773 let f = fixture();
774 let fifo = f.root.join("report");
775 let made = std::process::Command::new("mkfifo")
776 .arg(&fifo)
777 .status()
778 .expect("run mkfifo");
779 assert!(made.success());
780 assert_eq!(outside_link(&f.root, &fifo), Some(fifo));
781 }
782
783 #[test]
787 fn a_cache_dir_in_the_checkout_of_a_linked_worktree_is_checked_from_the_checkout() {
788 let f = fixture();
789 let host = f.root.join("host");
790 std::fs::create_dir_all(host.join(".git/worktrees/staged")).expect("host git");
791 std::fs::write(host.join(".git/worktrees/staged/commondir"), "../..\n").expect("common");
792 std::fs::create_dir_all(host.join("packages/app")).expect("host app");
793 let staged = f.root.join("staged");
794 std::fs::create_dir_all(staged.join("packages/app")).expect("staged app");
795 std::fs::write(
796 staged.join(".git"),
797 format!("gitdir: {}\n", host.join(".git/worktrees/staged").display()),
798 )
799 .expect("git file");
800 symlink(&f.outside, host.join("packages/app/buildcache")).expect("link");
801 let root = staged.join("packages/app");
802 let dir = host.join("packages/app/buildcache");
803 let target = CacheTarget::new(&root, &dir);
804 assert!(target.check(&dir.join("cache.bin")).is_err());
805 assert!(target.write_file("cache.bin", b"data").is_err());
806 assert_eq!(std::fs::read_dir(&f.outside).expect("outside").count(), 0);
807 }
808
809 #[test]
812 fn a_cache_dir_through_a_link_to_another_checkout_is_checked_from_the_checkout() {
813 let f = fixture();
814 let host = f.root.join("host");
815 std::fs::create_dir_all(host.join(".git/worktrees/staged")).expect("host git");
816 std::fs::write(host.join(".git/worktrees/staged/commondir"), "../..\n").expect("common");
817 std::fs::create_dir_all(host.join("packages/app")).expect("host app");
818 let other = f.outside.join("other");
819 std::fs::create_dir_all(other.join(".git")).expect("other git");
820 symlink(&other, host.join("packages/app/link")).expect("link");
821 let staged = f.root.join("staged");
822 std::fs::create_dir_all(staged.join("packages/app")).expect("staged app");
823 std::fs::write(
824 staged.join(".git"),
825 format!("gitdir: {}\n", host.join(".git/worktrees/staged").display()),
826 )
827 .expect("git file");
828 let root = staged.join("packages/app");
829 let dir = host.join("packages/app/link/cache");
830 let target = CacheTarget::new(&root, &dir);
831 assert!(target.write_file("cache.bin", b"data").is_err());
832 assert!(!other.join("cache").exists());
833 }
834
835 #[test]
838 fn a_cache_dir_in_a_linked_worktree_host_is_checked_from_the_worktree() {
839 let f = fixture();
840 let main = f.root.join("repo");
841 std::fs::create_dir_all(main.join(".git/worktrees/feature")).expect("main git");
842 std::fs::create_dir_all(main.join(".git/worktrees/staged")).expect("staged git");
843 for name in ["feature", "staged"] {
844 std::fs::write(
845 main.join(format!(".git/worktrees/{name}/commondir")),
846 "../..\n",
847 )
848 .expect("common");
849 }
850 let host = f.root.join("wt/feature");
851 std::fs::create_dir_all(host.join("packages/app")).expect("host app");
852 std::fs::write(
853 host.join(".git"),
854 format!(
855 "gitdir: {}\n",
856 main.join(".git/worktrees/feature").display()
857 ),
858 )
859 .expect("host git file");
860 let staged = f.root.join("staged");
861 std::fs::create_dir_all(staged.join("packages/app")).expect("staged app");
862 std::fs::write(
863 staged.join(".git"),
864 format!("gitdir: {}\n", main.join(".git/worktrees/staged").display()),
865 )
866 .expect("staged git file");
867 symlink(&f.outside, host.join("packages/app/build")).expect("link");
868 let root = staged.join("packages/app");
869 let dir = host.join("packages/app/build/cache");
870 assert!(
871 CacheTarget::new(&root, &dir)
872 .write_file("cache.bin", b"data")
873 .is_err()
874 );
875 assert_eq!(std::fs::read_dir(&f.outside).expect("outside").count(), 0);
876 }
877
878 #[test]
881 fn a_cache_dir_in_a_submodule_host_is_checked_from_the_submodule() {
882 let f = fixture();
883 let modules = f.root.join("super/.git/modules/sub");
884 std::fs::create_dir_all(modules.join("worktrees/staged")).expect("module git");
885 std::fs::write(modules.join("worktrees/staged/commondir"), "../..\n").expect("common");
886 let host = f.root.join("super/sub");
887 std::fs::create_dir_all(host.join("packages/app")).expect("host app");
888 std::fs::write(
889 host.join(".git"),
890 format!("gitdir: {}\n", modules.display()),
891 )
892 .expect("host git file");
893 let staged = f.root.join("staged");
894 std::fs::create_dir_all(staged.join("packages/app")).expect("staged app");
895 std::fs::write(
896 staged.join(".git"),
897 format!("gitdir: {}\n", modules.join("worktrees/staged").display()),
898 )
899 .expect("staged git file");
900 symlink(&f.outside, host.join("packages/app/build")).expect("link");
901 let root = staged.join("packages/app");
902 let dir = host.join("packages/app/build/cache");
903 assert!(
904 CacheTarget::new(&root, &dir)
905 .write_file("cache.bin", b"data")
906 .is_err()
907 );
908 assert_eq!(std::fs::read_dir(&f.outside).expect("outside").count(), 0);
909 }
910
911 fn linked_work_tree(common: &Path, top: &Path, name: &str) {
914 let git_dir = common.join("worktrees").join(name);
915 std::fs::create_dir_all(&git_dir).expect("linked git dir");
916 std::fs::write(git_dir.join("commondir"), "../..\n").expect("common");
917 std::fs::create_dir_all(top).expect("work tree");
918 std::fs::write(top.join(".git"), format!("gitdir: {}\n", git_dir.display()))
919 .expect("git file");
920 }
921
922 #[test]
926 fn a_link_from_a_worktree_inside_the_main_checkout_up_into_it_is_refused() {
927 let f = fixture();
928 let repo = f.root.join("repo");
929 std::fs::create_dir_all(repo.join(".git")).expect("main git");
930 let host = repo.join(".worktrees/feature");
931 linked_work_tree(&repo.join(".git"), &host, "feature");
932 let staged = f.root.join("staged");
933 linked_work_tree(&repo.join(".git"), &staged, "staged");
934 symlink("../..", host.join("build")).expect("link");
935 let dir = host.join("build/cache");
936 for root in [&staged, &host] {
937 let target = CacheTarget::new(root, &dir);
938 assert!(target.write_gitignore().is_err());
939 assert!(target.write_file("cache.bin", b"data").is_err());
940 }
941 assert!(!repo.join("cache").exists());
942 }
943
944 #[test]
947 fn a_link_from_a_nested_worktree_of_a_bare_repository_is_refused() {
948 let f = fixture();
949 let bare = f.root.join("repo.git");
950 let outer = f.root.join("trees/main");
951 linked_work_tree(&bare, &outer, "main");
952 let host = outer.join(".worktrees/feature");
953 linked_work_tree(&bare, &host, "feature");
954 let staged = f.root.join("staged");
955 linked_work_tree(&bare, &staged, "staged");
956 symlink("../..", host.join("build")).expect("link");
957 let dir = host.join("build/cache");
958 assert!(
959 CacheTarget::new(&staged, &dir)
960 .write_file("cache.bin", b"data")
961 .is_err()
962 );
963 assert!(!outer.join("cache").exists());
964 }
965
966 #[test]
969 fn a_work_tree_behind_a_link_is_not_the_base() {
970 let f = fixture();
971 let repo = f.root.join("repo");
972 std::fs::create_dir_all(repo.join(".git")).expect("main git");
973 let host = f.root.join("host");
974 linked_work_tree(&repo.join(".git"), &host, "host");
975 let other = f.outside.join("other");
976 linked_work_tree(&repo.join(".git"), &other, "other");
977 linked_work_tree(&repo.join(".git"), &other.join("nested"), "nested");
978 let staged = f.root.join("staged");
979 linked_work_tree(&repo.join(".git"), &staged, "staged");
980 symlink(&other, host.join("shared")).expect("link");
981 let dir = host.join("shared/nested/cache");
982 assert!(
983 CacheTarget::new(&staged, &dir)
984 .write_file("cache.bin", b"data")
985 .is_err()
986 );
987 assert!(!other.join("nested/cache").exists());
988 }
989
990 #[test]
993 fn a_worktree_inside_a_bare_repository_is_not_git_metadata() {
994 let f = fixture();
995 let bare = f.root.join("proj.git");
996 let main = bare.join("main");
997 linked_work_tree(&bare, &main, "main");
998 std::fs::create_dir_all(main.join("src")).expect("src");
999 std::fs::create_dir_all(bare.join("hooks")).expect("hooks");
1000 let canonical_main = std::fs::canonicalize(&main).expect("main");
1001 let canonical_bare = std::fs::canonicalize(&bare).expect("bare");
1002 assert!(!is_protected_link_target(
1003 &canonical_main,
1004 &canonical_main.join("src/a.ts")
1005 ));
1006 assert!(is_protected_link_target(
1007 &canonical_main,
1008 &canonical_bare.join("hooks/pre-commit")
1009 ));
1010 assert!(is_protected_link_target(
1011 &canonical_main,
1012 &canonical_bare.join("worktrees/main/HEAD")
1013 ));
1014 std::fs::create_dir_all(main.join("build/cache")).expect("cache");
1015 symlink("build/cache", main.join(".fallow")).expect("link");
1016 let dir = main.join(".fallow");
1017 CacheTarget::new(&main, &dir)
1018 .write_file("cache.bin", b"data")
1019 .expect("file");
1020 symlink(bare.join("hooks"), main.join("hooks")).expect("hooks link");
1021 let error =
1022 ensure_no_outside_link(&main, &main.join("hooks/pre-commit")).expect_err("refused");
1023 assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
1024 }
1025
1026 #[test]
1029 fn an_unreadable_commondir_protects_every_link_target() {
1030 let f = fixture();
1031 let repo = f.root.join("repo");
1032 std::fs::create_dir_all(repo.join(".git/worktrees/main/commondir")).expect("git dir");
1033 let main = f.root.join("main");
1034 std::fs::create_dir_all(&main).expect("main");
1035 std::fs::write(
1036 main.join(".git"),
1037 format!("gitdir: {}\n", repo.join(".git/worktrees/main").display()),
1038 )
1039 .expect("git file");
1040 let canonical = std::fs::canonicalize(&main).expect("main");
1041 assert!(is_protected_link_target(
1042 &canonical,
1043 &canonical.join("src/a.ts")
1044 ));
1045 }
1046
1047 #[test]
1051 fn a_user_cache_dir_with_a_parent_step_in_the_work_tree_writes() {
1052 let f = fixture();
1053 std::fs::create_dir_all(f.root.join(".git")).expect("git dir");
1054 let root = f.root.join("pkg");
1055 std::fs::create_dir_all(&root).expect("pkg");
1056 let dir = root.join("../shared");
1057 assert_eq!(cache_write_base(&root, &dir), f.root);
1058 CacheTarget::new(&root, &dir)
1059 .write_file("cache.bin", b"data")
1060 .expect("file");
1061 assert!(f.root.join("shared/cache.bin").exists());
1062
1063 std::fs::create_dir_all(f.outside.join("sub")).expect("sub");
1064 symlink(f.outside.join("sub"), root.join("link")).expect("link");
1065 let through = root.join("link/../elsewhere");
1066 let error = CacheTarget::new(&root, &through)
1067 .write_file("cache.bin", b"data")
1068 .expect_err("refused");
1069 assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
1070 assert!(error.to_string().contains("outside"), "{error}");
1071 assert!(!f.outside.join("elsewhere").exists());
1072 }
1073
1074 #[test]
1076 fn the_refusal_names_the_reason() {
1077 let f = fixture();
1078 std::fs::create_dir_all(f.root.join("node_modules/pkg")).expect("packages");
1079 symlink(f.root.join("node_modules/pkg"), f.root.join(".fallow")).expect("link");
1080 let error = ensure_no_outside_link(&f.root, &f.root.join(".fallow/cache.bin"))
1081 .expect_err("refused");
1082 assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
1083 assert!(error.to_string().contains("node_modules"), "{error}");
1084 assert!(!error.to_string().contains("outside"), "{error}");
1085 }
1086
1087 #[test]
1088 fn a_cache_dir_above_a_subdirectory_root_is_checked_from_the_work_tree() {
1089 let f = fixture();
1090 std::fs::create_dir_all(f.root.join(".git")).expect("git dir");
1091 std::fs::create_dir_all(f.root.join("packages/app")).expect("app");
1092 symlink(&f.outside, f.root.join(".cache")).expect("link");
1093 let root = f.root.join("packages/app");
1094 let dir = f.root.join(".cache");
1095 assert!(
1096 CacheTarget::new(&root, &dir)
1097 .check(&dir.join("cache.bin"))
1098 .is_err()
1099 );
1100 }
1101
1102 #[test]
1103 fn a_cache_dir_in_another_checkout_is_its_own_base() {
1104 let f = fixture();
1105 std::fs::create_dir_all(f.root.join(".git")).expect("git dir");
1106 let other = f.outside.join("home");
1107 std::fs::create_dir_all(other.join(".git")).expect("other git");
1108 let elsewhere = f.outside.join("disk");
1109 std::fs::create_dir_all(&elsewhere).expect("disk");
1110 symlink(&elsewhere, other.join(".cache")).expect("link");
1111 let dir = other.join(".cache/fallow");
1112 let target = CacheTarget::new(&f.root, &dir);
1113 target.write_file("cache.bin", b"data").expect("file");
1114 assert!(elsewhere.join("fallow/cache.bin").exists());
1115 }
1116
1117 #[test]
1118 fn a_user_cache_dir_outside_the_root_is_checked_from_itself() {
1119 let f = fixture();
1120 let target = CacheTarget::new(&f.root, &f.outside);
1121 target.write_file("cache.bin", b"data").expect("file");
1122 assert!(f.outside.join("cache.bin").exists());
1123 }
1124}