1use std::fs::File;
31use std::io::{self, Write};
32use std::path::{Component, Path, PathBuf};
33use std::sync::OnceLock;
34
35#[derive(Debug, Clone)]
37pub struct WriteScope {
38 root: PathBuf,
39 work_tree: Option<PathBuf>,
40 checkout: Option<PathBuf>,
43 git_dirs: fallow_types::path_guard::GitDirs,
46 shared_dirs: Vec<PathBuf>,
47}
48
49enum Refusal {
51 Outside,
53 Link {
56 link: PathBuf,
57 target: PathBuf,
58 kind: LinkTarget,
59 },
60 Special,
63}
64
65#[derive(Clone, Copy)]
67enum LinkTarget {
68 Outside,
70 Packages,
72 GitMetadata,
74}
75
76impl LinkTarget {
77 const fn phrase(self) -> &'static str {
79 match self {
80 Self::Outside => "outside the project",
81 Self::Packages => "into a node_modules directory",
82 Self::GitMetadata => "into Git metadata",
83 }
84 }
85
86 fn of(within: Option<&Path>, target: &Path) -> Option<Self> {
87 let Some(within) = within else {
88 return Some(Self::Outside);
89 };
90 if !fallow_types::path_guard::is_protected_link_target(within, target) {
91 return None;
92 }
93 let below = target.strip_prefix(within).unwrap_or(target);
94 let in_packages = below.components().any(|component| {
95 component
96 .as_os_str()
97 .to_str()
98 .is_some_and(|name| name.eq_ignore_ascii_case("node_modules"))
99 });
100 Some(if in_packages {
101 Self::Packages
102 } else {
103 Self::GitMetadata
104 })
105 }
106}
107
108impl WriteScope {
109 pub fn new(root: &Path, cwd: &Path, shared_dirs: Vec<PathBuf>) -> Result<Self, String> {
121 let root = root.canonicalize().map_err(|err| {
122 format!(
123 "the project root {} cannot be resolved ({err})",
124 root.display()
125 )
126 })?;
127 let cwd = cwd.canonicalize().unwrap_or_else(|_| cwd.to_path_buf());
128 let checkout = fallow_types::path_guard::work_tree_top(&root).map(Path::to_path_buf);
129 let work_tree = checkout.clone().filter(|tree| cwd.starts_with(tree));
130 let git_dirs = fallow_types::path_guard::GitDirs::of(&root);
131 Ok(Self {
132 root,
133 work_tree,
134 checkout,
135 git_dirs,
136 shared_dirs,
137 })
138 }
139
140 #[must_use]
143 pub fn contains(&self, path: &Path) -> bool {
144 walk(path).is_ok_and(|walk| self.refusal(&walk).is_none())
145 }
146
147 #[must_use]
167 pub fn check(&self, flag: &str, path: &Path, cwd: &Path) -> Option<String> {
168 if is_null_device(path) {
169 return None;
170 }
171 let walk = match walk(&cwd.join(path)) {
172 Ok(walk) => walk,
173 Err(err) => {
174 return Some(format!(
175 "{flag} {} cannot be resolved ({err}). Choose a path that fallow can read.",
176 path.display()
177 ));
178 }
179 };
180 let refusal = self.refusal(&walk)?;
181 Some(match refusal {
182 Refusal::Outside => format!(
183 "{flag} {} resolves to {}, which is outside the project root {}. Choose a path inside the project root{}, or inside the CI workspace (GITHUB_WORKSPACE or CI_PROJECT_DIR) or a temp directory (RUNNER_TEMP, the system temp directory, or /tmp on Unix).",
184 path.display(),
185 walk.resolved.display(),
186 self.root.display(),
187 self.work_tree
188 .as_deref()
189 .filter(|tree| *tree != self.root)
190 .map(|tree| format!(" or its Git work tree {}", tree.display()))
191 .unwrap_or_default(),
192 ),
193 Refusal::Link { link, target, kind } => format!(
194 "{flag} {} goes through the symlink {}, which resolves {} ({}). No symlink on the path may resolve into a .git or node_modules directory, and a symlink in the project must resolve inside the project. Choose a path without the symlink.",
195 path.display(),
196 link.display(),
197 kind.phrase(),
198 target.display(),
199 ),
200 Refusal::Special => format!(
201 "{flag} {} resolves to {}, which is not a regular file. Choose a path to a regular file.",
202 path.display(),
203 walk.resolved.display(),
204 ),
205 })
206 }
207
208 fn refusal(&self, walk: &Walk) -> Option<Refusal> {
209 let mut through_project_link = false;
210 for link in &walk.links {
211 let kind = if self.git_dirs.holds(&link.target) {
212 Some(LinkTarget::GitMetadata)
213 } else if self.in_checkout(&link.location) {
214 through_project_link = true;
215 let within = if link.target.starts_with(&self.root) {
216 Some(self.root.as_path())
217 } else {
218 self.work_tree
219 .as_deref()
220 .filter(|tree| link.target.starts_with(tree))
221 };
222 LinkTarget::of(within, &link.target)
223 } else {
224 LinkTarget::of(Some(self.protected_scope_for(link)), &link.target)
227 .filter(|kind| !matches!(kind, LinkTarget::Outside))
228 };
229 if let Some(kind) = kind {
230 return Some(Refusal::Link {
231 link: link.location.clone(),
232 target: link.target.clone(),
233 kind,
234 });
235 }
236 }
237 match std::fs::metadata(&walk.resolved) {
238 Ok(meta) if !meta.is_file() && !meta.is_dir() => {
239 return (through_project_link || !is_stream_target(&walk.resolved))
240 .then_some(Refusal::Special);
241 }
242 Ok(_) => {}
243 Err(error) if error.kind() == io::ErrorKind::NotFound => {}
244 Err(_) => return Some(Refusal::Special),
245 }
246 let path = walk.resolved.as_path();
247 let inside = path.starts_with(&self.root)
248 || self
249 .work_tree
250 .as_deref()
251 .is_some_and(|tree| path.starts_with(tree))
252 || self.shared_dirs.iter().any(|dir| path.starts_with(dir));
253 (!inside).then_some(Refusal::Outside)
254 }
255
256 #[must_use]
260 pub fn refusal_reason(&self, path: &Path) -> Option<&'static str> {
261 let Ok(walk) = walk(path) else {
262 return Some("to a path that cannot be read");
263 };
264 Some(match self.refusal(&walk)? {
265 Refusal::Outside => "outside the project",
266 Refusal::Link { kind, .. } => kind.phrase(),
267 Refusal::Special => "to a file that is not a regular file",
268 })
269 }
270
271 fn protected_scope_for<'a>(&'a self, link: &'a Link) -> &'a Path {
275 if link.target.starts_with(&self.root) {
276 return &self.root;
277 }
278 if let Some(tree) = self
279 .checkout
280 .as_deref()
281 .filter(|tree| link.target.starts_with(tree))
282 {
283 return tree;
284 }
285 link.location.parent().unwrap_or(&link.location)
286 }
287
288 fn in_checkout(&self, path: &Path) -> bool {
289 path.starts_with(&self.root)
290 || self
291 .checkout
292 .as_deref()
293 .is_some_and(|tree| path.starts_with(tree))
294 }
295
296 fn refusal_error(&self, requested: &Path, walk: &Walk) -> Option<io::Error> {
297 let reason = match self.refusal(walk)? {
298 Refusal::Outside => format!(
299 "{} resolves to {}, which is outside the directories this run may write to",
300 requested.display(),
301 walk.resolved.display()
302 ),
303 Refusal::Link { link, target, kind } => format!(
304 "{} goes through the symlink {}, which resolves {} ({}), so fallow did not write it",
305 requested.display(),
306 link.display(),
307 kind.phrase(),
308 target.display()
309 ),
310 Refusal::Special => format!(
311 "{} resolves to {}, which is not a regular file, so fallow did not write it",
312 requested.display(),
313 walk.resolved.display()
314 ),
315 };
316 Some(io::Error::new(io::ErrorKind::PermissionDenied, reason))
317 }
318}
319
320const SHARED_DIR_VARIABLES: [&str; 3] = ["GITHUB_WORKSPACE", "CI_PROJECT_DIR", "RUNNER_TEMP"];
324
325#[must_use]
332pub fn shared_dirs() -> Vec<PathBuf> {
333 shared_dirs_for(std::env::temp_dir())
334}
335
336fn shared_dirs_for(temp_dir: PathBuf) -> Vec<PathBuf> {
337 SHARED_DIR_VARIABLES
338 .iter()
339 .filter_map(std::env::var_os)
340 .filter(|value| !value.is_empty())
341 .map(PathBuf::from)
342 .chain(temp_dirs_with(temp_dir))
343 .filter_map(|dir| dir.canonicalize().ok())
344 .collect()
345}
346
347const UNIX_SYSTEM_TEMP_DIR: &str = "/tmp";
351
352#[must_use]
356pub fn system_temp_dirs() -> Vec<PathBuf> {
357 temp_dirs_with(std::env::temp_dir())
358}
359
360fn temp_dirs_with(temp_dir: PathBuf) -> Vec<PathBuf> {
361 let mut dirs = vec![temp_dir];
362 if cfg!(unix) {
363 dirs.push(PathBuf::from(UNIX_SYSTEM_TEMP_DIR));
364 }
365 dirs
366}
367
368#[cfg(unix)]
371fn is_stream_target(path: &Path) -> bool {
372 use std::os::unix::fs::FileTypeExt;
373 std::fs::metadata(path).is_ok_and(|meta| {
374 let file_type = meta.file_type();
375 file_type.is_char_device() || file_type.is_fifo()
376 })
377}
378
379#[cfg(not(unix))]
380const fn is_stream_target(_path: &Path) -> bool {
381 false
382}
383
384#[cfg(windows)]
386const WINDOWS_NULL_DEVICE: &str = r"\\.\NUL";
387
388fn is_null_device(path: &Path) -> bool {
393 cfg!(windows) && names_windows_null_device(path)
394}
395
396fn names_windows_null_device(path: &Path) -> bool {
403 let Some(text) = path.to_str() else {
404 return false;
405 };
406 let name = text
407 .strip_prefix(r"\\.\")
408 .or_else(|| text.strip_prefix("//./"))
409 .unwrap_or_else(|| text.strip_suffix(':').unwrap_or(text));
410 name.eq_ignore_ascii_case("NUL")
411}
412
413#[derive(Debug, Clone, Copy, PartialEq, Eq)]
416pub enum WriteTarget {
417 Path,
419 DiscoveredConfig,
422}
423
424#[derive(Debug)]
426struct Confinement {
427 cwd: PathBuf,
428 paths: WriteScope,
429 config: WriteScope,
430}
431
432static CONFINEMENT: OnceLock<Confinement> = OnceLock::new();
433
434pub fn confine(cwd: PathBuf, paths: WriteScope, config: WriteScope) {
439 let _ = CONFINEMENT.set(Confinement { cwd, paths, config });
440}
441
442#[derive(Debug)]
444pub enum WriteFailure {
445 Directory(io::Error),
447 File(io::Error),
451}
452
453impl WriteFailure {
454 #[must_use]
457 pub const fn is_directory(&self) -> bool {
458 matches!(self, Self::Directory(_))
459 }
460}
461
462impl std::fmt::Display for WriteFailure {
463 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
464 match self {
465 Self::Directory(error) | Self::File(error) => error.fmt(f),
466 }
467 }
468}
469
470impl std::error::Error for WriteFailure {}
471
472impl From<WriteFailure> for io::Error {
473 fn from(failure: WriteFailure) -> Self {
474 match failure {
475 WriteFailure::Directory(error) | WriteFailure::File(error) => error,
476 }
477 }
478}
479
480pub fn create_file(path: &Path, target: WriteTarget) -> Result<File, WriteFailure> {
492 let confinement = CONFINEMENT.get();
493 let absolute = match confinement {
494 Some(confinement) => confinement.cwd.join(path),
495 None => std::env::current_dir().map_or_else(|_| path.to_path_buf(), |cwd| cwd.join(path)),
496 };
497 let scope = confinement.map(|confinement| match target {
498 WriteTarget::Path => &confinement.paths,
499 WriteTarget::DiscoveredConfig => &confinement.config,
500 });
501 create_checked(path, &absolute, scope)
502}
503
504pub fn write_file(path: &Path, contents: &[u8], target: WriteTarget) -> Result<(), WriteFailure> {
511 let mut file = create_file(path, target)?;
512 file.write_all(contents).map_err(WriteFailure::File)?;
513 file.flush().map_err(WriteFailure::File)
514}
515
516fn create_checked(
517 requested: &Path,
518 absolute: &Path,
519 scope: Option<&WriteScope>,
520) -> Result<File, WriteFailure> {
521 if is_null_device(requested) {
522 return open_null_device().map_err(WriteFailure::File);
523 }
524 let walk = walk(absolute).map_err(WriteFailure::File)?;
525 if let Some(error) = scope.and_then(|scope| scope.refusal_error(requested, &walk)) {
526 return Err(WriteFailure::File(error));
527 }
528 let resolved = walk.resolved;
529 if is_stream_target(&resolved) {
530 return open_stream(&resolved).map_err(WriteFailure::File);
531 }
532 if let Some(parent) = resolved.parent()
533 && !parent.as_os_str().is_empty()
534 {
535 std::fs::create_dir_all(parent).map_err(WriteFailure::Directory)?;
536 let real_parent = parent.canonicalize().map_err(WriteFailure::File)?;
539 if real_parent != parent {
540 return Err(WriteFailure::File(io::Error::new(
541 io::ErrorKind::PermissionDenied,
542 format!(
543 "{} changed while fallow prepared the write, so fallow did not write it",
544 requested.display()
545 ),
546 )));
547 }
548 }
549 open_no_follow(&resolved).map_err(WriteFailure::File)
550}
551
552fn open_stream(path: &Path) -> io::Result<File> {
557 let mut options = std::fs::OpenOptions::new();
558 options.write(true);
559 #[cfg(unix)]
560 {
561 use std::os::unix::fs::OpenOptionsExt;
562 options.custom_flags(libc::O_NOFOLLOW);
563 }
564 let file = options.open(path)?;
565 #[cfg(unix)]
566 ensure_stream_handle(&file, path)?;
567 Ok(file)
568}
569
570#[cfg(windows)]
572fn open_null_device() -> io::Result<File> {
573 std::fs::OpenOptions::new()
574 .write(true)
575 .open(WINDOWS_NULL_DEVICE)
576}
577
578#[cfg(not(windows))]
580fn open_null_device() -> io::Result<File> {
581 Err(io::Error::new(
582 io::ErrorKind::Unsupported,
583 "only Windows has a null device name",
584 ))
585}
586
587#[cfg(unix)]
589fn ensure_stream_handle(file: &File, path: &Path) -> io::Result<()> {
590 use std::os::unix::fs::FileTypeExt;
591 let file_type = file.metadata()?.file_type();
592 if file_type.is_char_device() || file_type.is_fifo() {
593 return Ok(());
594 }
595 Err(io::Error::new(
596 io::ErrorKind::PermissionDenied,
597 format!(
598 "{} is no longer a device or a named pipe, so fallow did not write it",
599 path.display()
600 ),
601 ))
602}
603
604fn open_no_follow(path: &Path) -> io::Result<File> {
608 let mut options = std::fs::OpenOptions::new();
609 options.write(true).create(true).truncate(true);
610 #[cfg(unix)]
611 {
612 use std::os::unix::fs::OpenOptionsExt;
613 options.custom_flags(libc::O_NOFOLLOW);
614 }
615 #[cfg(not(unix))]
618 if path
619 .symlink_metadata()
620 .is_ok_and(|meta| meta.file_type().is_symlink())
621 {
622 return Err(io::Error::new(
623 io::ErrorKind::PermissionDenied,
624 format!(
625 "{} became a symlink after fallow checked it, so fallow did not write it",
626 path.display()
627 ),
628 ));
629 }
630 options.open(path)
631}
632
633const MAX_LINK_HOPS: usize = 40;
635
636#[must_use]
643pub fn resolve(path: &Path) -> PathBuf {
644 walk(path).map_or_else(|_| canonical_form(path, 0), |walk| walk.resolved)
645}
646
647struct Link {
649 location: PathBuf,
651 target: PathBuf,
653}
654
655struct Walk {
657 resolved: PathBuf,
658 links: Vec<Link>,
659}
660
661fn walk(path: &Path) -> io::Result<Walk> {
670 let absolute;
671 let path = if path.is_absolute() {
672 path
673 } else {
674 absolute = std::env::current_dir()?.join(path);
675 &absolute
676 };
677 let mut links = Vec::new();
678 let mut hops = 0;
679 let walked = walk_components(path, &mut links, &mut hops)?;
680 Ok(Walk {
681 resolved: canonical_form(&walked, 0),
682 links,
683 })
684}
685
686fn walk_components(path: &Path, links: &mut Vec<Link>, hops: &mut usize) -> io::Result<PathBuf> {
687 let mut resolved = PathBuf::new();
688 for component in path.components() {
689 let name = match component {
690 Component::Prefix(_) | Component::RootDir => {
691 resolved.push(component.as_os_str());
692 continue;
693 }
694 Component::CurDir => continue,
695 Component::ParentDir => {
696 resolved.pop();
697 continue;
698 }
699 Component::Normal(name) => name,
700 };
701 let candidate = resolved.join(name);
702 match candidate.symlink_metadata() {
703 Ok(meta) if meta.file_type().is_symlink() => {
704 *hops += 1;
705 if *hops > MAX_LINK_HOPS {
706 return Err(io::Error::new(
707 io::ErrorKind::InvalidInput,
708 format!("{} goes through too many symlinks", path.display()),
709 ));
710 }
711 let target = std::fs::read_link(&candidate)?;
712 let followed = walk_components(&resolved.join(target), links, hops)?;
713 links.push(Link {
714 location: canonical_form(&resolved, 0).join(name),
715 target: canonical_form(&followed, 0),
716 });
717 resolved = followed;
718 }
719 Ok(_) => resolved = candidate,
720 Err(error) if error.kind() == io::ErrorKind::NotFound => resolved = candidate,
721 Err(error) => return Err(error),
722 }
723 }
724 Ok(resolved)
725}
726
727fn canonical_form(path: &Path, hops: usize) -> PathBuf {
732 let mut existing = path;
733 let mut missing = Vec::new();
734 loop {
735 if let Ok(real) = existing.canonicalize() {
736 return append_missing(real, &missing);
737 }
738 if hops < MAX_LINK_HOPS
739 && let Ok(target) = std::fs::read_link(existing)
740 {
741 let base = existing.parent().unwrap_or_else(|| Path::new(""));
742 let followed = canonical_form(&base.join(target), hops + 1);
743 return append_missing(followed, &missing);
744 }
745 let (Some(parent), Some(last)) = (existing.parent(), existing.components().next_back())
746 else {
747 return append_missing(PathBuf::new(), &missing);
748 };
749 missing.push(last);
750 existing = parent;
751 }
752}
753
754fn append_missing(mut resolved: PathBuf, missing: &[Component<'_>]) -> PathBuf {
756 for component in missing.iter().rev() {
757 match component {
758 Component::ParentDir => {
759 resolved.pop();
760 }
761 Component::CurDir => {}
762 other => resolved.push(other.as_os_str()),
763 }
764 }
765 resolved
766}
767
768#[cfg(test)]
769mod tests {
770 use std::path::Path;
771
772 use super::{WriteScope, create_checked, names_windows_null_device, resolve};
773
774 #[cfg(unix)]
778 #[test]
779 fn scope_accepts_the_unix_system_temp_dir_when_tmpdir_names_another_folder() {
780 use super::shared_dirs_for;
781
782 let project = tempfile::tempdir().expect("project dir");
783 let other_temp = tempfile::tempdir().expect("temp dir");
784 let scope = WriteScope::new(
785 project.path(),
786 project.path(),
787 shared_dirs_for(other_temp.path().to_path_buf()),
788 )
789 .expect("scope");
790 assert_eq!(
791 scope.check("--save-baseline", Path::new("/tmp/x.json"), project.path()),
792 None
793 );
794 }
795
796 #[test]
800 fn the_windows_null_device_is_named_by_nul_alone() {
801 for name in [
802 "NUL", "nul", "Nul", "NUL:", r"\\.\NUL", r"\\.\nul", "//./NUL",
803 ] {
804 assert!(names_windows_null_device(Path::new(name)), "{name}");
805 }
806 for name in [
807 "NUL.txt",
808 "nul.sarif",
809 "null",
810 "NULL",
811 "report",
812 r"dir\NUL",
813 "dir/nul",
814 r".\NUL",
815 r"C:\NUL",
816 "",
817 ] {
818 assert!(!names_windows_null_device(Path::new(name)), "{name}");
819 }
820 }
821
822 #[test]
823 fn resolve_normalises_the_missing_part() {
824 let dir = tempfile::tempdir().expect("temp dir");
825 let base = dir.path().canonicalize().unwrap();
826 assert_eq!(
827 resolve(&base.join("a/b/../c.json")),
828 base.join("a").join("c.json")
829 );
830 assert_eq!(
831 resolve(&base.join("a/../../x.json")),
832 base.parent().unwrap().join("x.json")
833 );
834 }
835
836 #[cfg(unix)]
837 #[test]
838 fn a_dangling_link_resolves_to_its_target() {
839 let dir = tempfile::tempdir().expect("temp dir");
840 let base = dir.path().canonicalize().unwrap();
841 let root = base.join("project");
842 std::fs::create_dir_all(&root).unwrap();
843 std::os::unix::fs::symlink(base.join("elsewhere.json"), root.join("b.json")).unwrap();
844 assert_eq!(resolve(&root.join("b.json")), base.join("elsewhere.json"));
845 }
846
847 #[test]
848 fn scope_accepts_a_temp_dir_through_a_symlinked_spelling() {
849 let dir = tempfile::tempdir().expect("temp dir");
850 let root = dir.path().join("project");
851 let temp = dir.path().join("temp");
852 std::fs::create_dir_all(&root).unwrap();
853 std::fs::create_dir_all(&temp).unwrap();
854 let scope =
855 WriteScope::new(&root, &root, vec![temp.canonicalize().unwrap()]).expect("scope");
856 assert!(
859 scope
860 .check("--save-baseline", &temp.join("b.json"), &root)
861 .is_none()
862 );
863 assert!(
864 scope
865 .check("--save-baseline", &dir.path().join("b.json"), &root)
866 .is_some()
867 );
868 }
869
870 #[test]
871 fn a_root_that_cannot_be_resolved_fails_closed() {
872 let dir = tempfile::tempdir().expect("temp dir");
873 let missing = dir.path().join("missing");
874 assert!(WriteScope::new(&missing, dir.path(), Vec::new()).is_err());
875 }
876
877 #[test]
878 fn the_work_tree_needs_the_working_directory_inside_it() {
879 let dir = tempfile::tempdir().expect("temp dir");
880 let home = dir.path().join("home");
881 let root = home.join("project");
882 let elsewhere = dir.path().join("elsewhere");
883 std::fs::create_dir_all(&root).unwrap();
884 std::fs::create_dir_all(&elsewhere).unwrap();
885 std::fs::create_dir_all(home.join(".git")).unwrap();
886 let target = home.join(".config").join("x.json");
887 let from_outside = WriteScope::new(&root, &elsewhere, Vec::new()).expect("scope");
888 assert!(
889 from_outside
890 .check("--save-baseline", &target, &elsewhere)
891 .is_some()
892 );
893 let from_inside = WriteScope::new(&root, &home, Vec::new()).expect("scope");
894 assert!(
895 from_inside
896 .check("--save-baseline", &target, &home)
897 .is_none()
898 );
899 }
900
901 #[test]
902 fn scope_accepts_the_root_and_rejects_a_sibling() {
903 let dir = tempfile::tempdir().expect("temp dir");
904 let root = dir.path().join("project");
905 std::fs::create_dir_all(&root).unwrap();
906 let scope = WriteScope::new(&root, &root, Vec::new()).expect("scope");
907 assert!(
908 scope
909 .check("--save-baseline", "nested/b.json".as_ref(), &root)
910 .is_none()
911 );
912 let message = scope
913 .check("--save-baseline", "../b.json".as_ref(), &root)
914 .expect("outside");
915 assert!(message.contains("outside the project root"), "{message}");
916 }
917
918 #[test]
919 fn scope_accepts_the_git_work_tree_of_the_root() {
920 let dir = tempfile::tempdir().expect("temp dir");
921 let repo = dir.path().join("repo");
922 let root = repo.join("packages/app");
923 std::fs::create_dir_all(&root).unwrap();
924 std::fs::create_dir_all(repo.join(".git")).unwrap();
925 let scope = WriteScope::new(&root, &repo, Vec::new()).expect("scope");
926 assert!(
927 scope
928 .check("--save-baseline", "baselines/b.json".as_ref(), &repo)
929 .is_none()
930 );
931 let message = scope
932 .check("--save-baseline", "../b.json".as_ref(), &repo)
933 .expect("outside");
934 assert!(message.contains("Git work tree"), "{message}");
935 }
936
937 #[test]
938 fn a_checked_write_lands_inside_the_scope() {
939 let dir = tempfile::tempdir().expect("temp dir");
940 let root = dir.path().join("project");
941 std::fs::create_dir_all(&root).unwrap();
942 let scope = WriteScope::new(&root, &root, Vec::new()).expect("scope");
943 let target = root.join("out/nested/report.json");
944 assert!(scope.check("--output-file", &target, &root).is_none());
945 let file = create_checked(&target, &target, Some(&scope)).expect("write inside");
946 drop(file);
947 assert!(target.is_file());
948 }
949
950 #[cfg(unix)]
952 #[test]
953 fn a_character_device_is_allowed_outside_the_scope() {
954 let dir = tempfile::tempdir().expect("temp dir");
955 let root = dir.path().join("project");
956 std::fs::create_dir_all(&root).unwrap();
957 let scope = WriteScope::new(&root, &root, Vec::new()).expect("scope");
958 let null = std::path::Path::new("/dev/null");
959 assert!(scope.check("--output-file", null, &root).is_none());
960 let file = create_checked(null, null, Some(&scope)).expect("write to /dev/null");
961 drop(file);
962 }
963
964 #[cfg(unix)]
967 #[test]
968 fn a_named_pipe_is_allowed_outside_the_scope() {
969 use std::io::Write as _;
970 let dir = tempfile::tempdir().expect("temp dir");
971 let root = dir.path().join("project");
972 std::fs::create_dir_all(&root).unwrap();
973 let fifo = dir.path().join("report.fifo");
974 let made = std::process::Command::new("mkfifo")
975 .arg(&fifo)
976 .status()
977 .expect("run mkfifo");
978 assert!(made.success());
979 let scope = WriteScope::new(&root, &root, Vec::new()).expect("scope");
980 assert!(scope.check("--sarif-file", &fifo, &root).is_none());
981 let reader_path = fifo.clone();
982 let reader = std::thread::spawn(move || std::fs::read_to_string(reader_path));
983 let mut file = create_checked(&fifo, &fifo, Some(&scope)).expect("write to fifo");
984 file.write_all(b"sarif").unwrap();
985 drop(file);
986 assert_eq!(reader.join().unwrap().unwrap(), "sarif");
987 }
988
989 #[cfg(unix)]
992 #[test]
993 fn a_stream_target_swapped_after_the_check_is_refused() {
994 use super::{ensure_stream_handle, open_stream};
995 let dir = tempfile::tempdir().expect("temp dir");
996 let link = dir.path().join("null-link");
997 std::os::unix::fs::symlink("/dev/null", &link).unwrap();
998 assert!(open_stream(&link).is_err(), "a symlink is not followed");
999
1000 let regular = dir.path().join("regular.json");
1001 std::fs::write(®ular, "keep").unwrap();
1002 assert!(open_stream(®ular).is_err(), "a regular file is refused");
1003 let handle = std::fs::File::open(®ular).unwrap();
1004 assert!(ensure_stream_handle(&handle, ®ular).is_err());
1005 assert_eq!(std::fs::read_to_string(®ular).unwrap(), "keep");
1006
1007 let null = std::fs::File::open("/dev/null").unwrap();
1008 assert!(ensure_stream_handle(&null, std::path::Path::new("/dev/null")).is_ok());
1009 }
1010
1011 #[cfg(unix)]
1014 #[test]
1015 fn a_directory_swapped_for_a_symlink_after_the_check_is_refused() {
1016 let dir = tempfile::tempdir().expect("temp dir");
1017 let root = dir.path().join("project");
1018 let elsewhere = dir.path().join("elsewhere");
1019 std::fs::create_dir_all(root.join("out")).unwrap();
1020 std::fs::create_dir_all(&elsewhere).unwrap();
1021 let scope = WriteScope::new(&root, &root, Vec::new()).expect("scope");
1022 let target = root.join("out/report.json");
1023 assert!(scope.check("--output-file", &target, &root).is_none());
1024
1025 std::fs::remove_dir(root.join("out")).unwrap();
1026 std::os::unix::fs::symlink(&elsewhere, root.join("out")).unwrap();
1027
1028 let error = std::io::Error::from(
1029 create_checked(&target, &target, Some(&scope)).expect_err("refused"),
1030 );
1031 assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
1032 assert!(!elsewhere.join("report.json").exists());
1033 }
1034
1035 #[cfg(unix)]
1038 #[test]
1039 fn a_file_swapped_for_a_symlink_after_the_check_is_refused() {
1040 let dir = tempfile::tempdir().expect("temp dir");
1041 let root = dir.path().join("project");
1042 std::fs::create_dir_all(&root).unwrap();
1043 let outside = dir.path().join("outside.json");
1044 let scope = WriteScope::new(&root, &root, Vec::new()).expect("scope");
1045 let target = root.join("report.json");
1046 assert!(scope.check("--output-file", &target, &root).is_none());
1047
1048 std::os::unix::fs::symlink(&outside, &target).unwrap();
1049
1050 assert!(create_checked(&target, &target, Some(&scope)).is_err());
1051 assert!(!outside.exists());
1052 }
1053
1054 #[cfg(unix)]
1058 #[test]
1059 fn a_link_after_a_parent_step_is_resolved() {
1060 let dir = tempfile::tempdir().expect("temp dir");
1061 let root = dir.path().join("project");
1062 let elsewhere = dir.path().join("elsewhere");
1063 std::fs::create_dir_all(&root).unwrap();
1064 std::fs::create_dir_all(&elsewhere).unwrap();
1065 std::os::unix::fs::symlink(&elsewhere, root.join("away")).unwrap();
1066 let scope = WriteScope::new(&root, &root, Vec::new()).expect("scope");
1067 let requested = Path::new("build/../away/x/r.json");
1068 assert!(scope.check("--output-file", requested, &root).is_some());
1069 let absolute = root.join(requested);
1070 assert!(create_checked(requested, &absolute, Some(&scope)).is_err());
1071 assert!(!elsewhere.join("x").exists());
1072 assert!(!root.join("build").exists());
1073 }
1074
1075 #[cfg(unix)]
1078 #[test]
1079 fn a_project_link_into_a_shared_dir_is_refused() {
1080 let dir = tempfile::tempdir().expect("temp dir");
1081 let root = dir.path().join("project");
1082 let shared = dir.path().join("workspace");
1083 std::fs::create_dir_all(&root).unwrap();
1084 std::fs::create_dir_all(&shared).unwrap();
1085 std::fs::write(shared.join("run.sh"), "keep").unwrap();
1086 std::os::unix::fs::symlink(shared.join("run.sh"), root.join("report.sarif")).unwrap();
1087 let scope =
1088 WriteScope::new(&root, &root, vec![shared.canonicalize().unwrap()]).expect("scope");
1089 let target = root.join("report.sarif");
1090 assert!(scope.check("--sarif-file", &target, &root).is_some());
1091 assert!(create_checked(&target, &target, Some(&scope)).is_err());
1092 assert_eq!(
1093 std::fs::read_to_string(shared.join("run.sh")).unwrap(),
1094 "keep"
1095 );
1096 assert!(
1097 scope
1098 .check("--sarif-file", &shared.join("report.sarif"), &root)
1099 .is_none()
1100 );
1101 }
1102
1103 #[cfg(unix)]
1106 #[test]
1107 fn a_project_link_to_a_named_pipe_is_refused() {
1108 let dir = tempfile::tempdir().expect("temp dir");
1109 let root = dir.path().join("project");
1110 std::fs::create_dir_all(&root).unwrap();
1111 let fifo = dir.path().join("report.fifo");
1112 let made = std::process::Command::new("mkfifo")
1113 .arg(&fifo)
1114 .status()
1115 .expect("run mkfifo");
1116 assert!(made.success());
1117 std::os::unix::fs::symlink(&fifo, root.join("report.json")).unwrap();
1118 let scope = WriteScope::new(&root, &root, Vec::new()).expect("scope");
1119 assert!(
1120 scope
1121 .check("--output-file", &root.join("report.json"), &root)
1122 .is_some()
1123 );
1124 assert!(scope.check("--output-file", &fifo, &root).is_none());
1125 }
1126
1127 #[cfg(unix)]
1130 #[test]
1131 fn a_project_link_into_git_or_node_modules_is_refused() {
1132 let dir = tempfile::tempdir().expect("temp dir");
1133 let root = dir.path().join("project");
1134 std::fs::create_dir_all(root.join(".git")).unwrap();
1135 std::fs::create_dir_all(root.join("node_modules/pkg")).unwrap();
1136 std::fs::create_dir_all(root.join("reports")).unwrap();
1137 std::os::unix::fs::symlink(root.join(".git"), root.join("meta")).unwrap();
1138 std::os::unix::fs::symlink(root.join("node_modules/pkg"), root.join("pkg")).unwrap();
1139 std::os::unix::fs::symlink(root.join("reports"), root.join("out")).unwrap();
1140 let scope = WriteScope::new(&root, &root, Vec::new()).expect("scope");
1141 for refused in ["meta/config", "pkg/index.js"] {
1142 assert!(
1143 scope
1144 .check("--output-file", Path::new(refused), &root)
1145 .is_some(),
1146 "{refused}"
1147 );
1148 let absolute = root.join(refused);
1149 assert!(create_checked(Path::new(refused), &absolute, Some(&scope)).is_err());
1150 }
1151 assert!(!root.join(".git/config").exists());
1152 assert!(
1153 scope
1154 .check("--output-file", Path::new("out/r.json"), &root)
1155 .is_none()
1156 );
1157 }
1158
1159 #[cfg(unix)]
1162 #[test]
1163 fn an_outside_link_into_git_metadata_is_refused() {
1164 let dir = tempfile::tempdir().expect("temp dir");
1165 let root = dir.path().join("project");
1166 let shared = dir.path().join("shared");
1167 std::fs::create_dir_all(root.join(".git/hooks")).unwrap();
1168 std::fs::create_dir_all(&shared).unwrap();
1169 let hook = root.join(".git/hooks/pre-commit");
1170 std::fs::write(&hook, "keep").unwrap();
1171 let link = shared.join("r.json");
1172 std::os::unix::fs::symlink(&hook, &link).unwrap();
1173 let scope =
1174 WriteScope::new(&root, &root, vec![shared.canonicalize().unwrap()]).expect("scope");
1175 assert!(scope.check("--output-file", &link, &root).is_some());
1176 assert!(create_checked(&link, &link, Some(&scope)).is_err());
1177 assert_eq!(std::fs::read_to_string(&hook).unwrap(), "keep");
1178 }
1179
1180 #[cfg(unix)]
1184 #[test]
1185 fn an_outside_link_into_a_separate_git_dir_is_refused() {
1186 let dir = tempfile::tempdir().expect("temp dir");
1187 let root = dir.path().join("project");
1188 let shared = dir.path().join("shared");
1189 let git_dir = shared.join("gd");
1190 std::fs::create_dir_all(git_dir.join("hooks")).unwrap();
1191 std::fs::create_dir_all(&root).unwrap();
1192 std::fs::write(
1193 root.join(".git"),
1194 format!("gitdir: {}\n", git_dir.display()),
1195 )
1196 .unwrap();
1197 let hook = git_dir.join("hooks/pre-commit");
1198 std::fs::write(&hook, "keep").unwrap();
1199 let link = shared.join("r.json");
1200 std::os::unix::fs::symlink(&hook, &link).unwrap();
1201 let scope =
1202 WriteScope::new(&root, &root, vec![shared.canonicalize().unwrap()]).expect("scope");
1203 assert!(scope.check("--output-file", &link, &root).is_some());
1204 assert!(!scope.contains(&link));
1205 assert!(create_checked(&link, &link, Some(&scope)).is_err());
1206 assert_eq!(std::fs::read_to_string(&hook).unwrap(), "keep");
1207 }
1208
1209 #[cfg(unix)]
1212 #[test]
1213 fn an_outside_link_into_the_common_git_dir_of_a_worktree_is_refused() {
1214 let dir = tempfile::tempdir().expect("temp dir");
1215 let shared = dir.path().join("shared");
1216 let bare = shared.join("repo.git");
1217 let linked = bare.join("worktrees/project");
1218 std::fs::create_dir_all(&linked).unwrap();
1219 std::fs::create_dir_all(bare.join("hooks")).unwrap();
1220 std::fs::write(linked.join("commondir"), "../..\n").unwrap();
1221 let root = dir.path().join("project");
1222 std::fs::create_dir_all(&root).unwrap();
1223 std::fs::write(root.join(".git"), format!("gitdir: {}\n", linked.display())).unwrap();
1224 let hook = bare.join("hooks/pre-commit");
1225 std::fs::write(&hook, "keep").unwrap();
1226 let link = shared.join("r.json");
1227 std::os::unix::fs::symlink(&hook, &link).unwrap();
1228 let scope =
1229 WriteScope::new(&root, &root, vec![shared.canonicalize().unwrap()]).expect("scope");
1230 assert!(scope.check("--output-file", &link, &root).is_some());
1231 assert_eq!(std::fs::read_to_string(&hook).unwrap(), "keep");
1232 }
1233
1234 #[cfg(unix)]
1238 #[test]
1239 fn a_link_inside_a_worktree_of_a_bare_repository_is_allowed() {
1240 let dir = tempfile::tempdir().expect("temp dir");
1241 let bare = dir.path().join("proj.git");
1242 let linked = bare.join("worktrees/main");
1243 std::fs::create_dir_all(&linked).unwrap();
1244 std::fs::create_dir_all(bare.join("hooks")).unwrap();
1245 std::fs::write(linked.join("commondir"), "../..\n").unwrap();
1246 let root = bare.join("main");
1247 std::fs::create_dir_all(root.join("reports")).unwrap();
1248 std::fs::write(root.join(".git"), format!("gitdir: {}\n", linked.display())).unwrap();
1249 std::os::unix::fs::symlink(root.join("reports"), root.join("out")).unwrap();
1250 std::os::unix::fs::symlink(bare.join("hooks"), root.join("hooks")).unwrap();
1251 let scope = WriteScope::new(&root, &root, Vec::new()).expect("scope");
1252 assert!(scope.contains(&root.join("out/r.json")));
1253 assert!(scope.contains(&root.join("reports/r.json")));
1254 assert!(!scope.contains(&root.join("hooks/pre-commit")));
1255 }
1256
1257 #[cfg(unix)]
1260 #[test]
1261 fn a_dangling_git_link_marks_the_checkout() {
1262 let dir = tempfile::tempdir().expect("temp dir");
1263 let repo = dir.path().join("repo");
1264 std::fs::create_dir_all(repo.join("pkg")).unwrap();
1265 std::os::unix::fs::symlink(dir.path().join("missing"), repo.join(".git")).unwrap();
1266 let scope = WriteScope::new(&repo.join("pkg"), &repo, Vec::new()).expect("scope");
1267 assert!(scope.contains(&repo.join("r.json")));
1268 }
1269
1270 #[cfg(unix)]
1272 #[test]
1273 fn a_socket_target_is_refused() {
1274 let dir = tempfile::tempdir().expect("temp dir");
1275 let root = dir.path().join("project");
1276 std::fs::create_dir_all(&root).unwrap();
1277 let socket = root.join("s.sock");
1278 let _listener = std::os::unix::net::UnixListener::bind(&socket).expect("bind");
1279 let scope = WriteScope::new(&root, &root, Vec::new()).expect("scope");
1280 assert!(scope.check("--output-file", &socket, &root).is_some());
1281 }
1282
1283 #[cfg(unix)]
1286 #[test]
1287 fn a_component_that_cannot_be_read_is_refused() {
1288 use std::os::unix::fs::PermissionsExt;
1289 let dir = tempfile::tempdir().expect("temp dir");
1290 let root = dir.path().join("project");
1291 let closed = root.join("closed");
1292 std::fs::create_dir_all(&closed).unwrap();
1293 std::fs::set_permissions(&closed, std::fs::Permissions::from_mode(0o000)).unwrap();
1294 let readable = closed.join("probe").symlink_metadata();
1295 let scope = WriteScope::new(&root, &root, Vec::new()).expect("scope");
1296 let result = scope.check("--output-file", Path::new("closed/sub/r.json"), &root);
1297 std::fs::set_permissions(&closed, std::fs::Permissions::from_mode(0o755)).unwrap();
1298 if readable.is_err_and(|error| error.kind() == std::io::ErrorKind::PermissionDenied) {
1300 assert!(result.is_some());
1301 }
1302 }
1303
1304 #[cfg(unix)]
1307 #[test]
1308 fn the_open_does_not_follow_a_final_symlink() {
1309 let dir = tempfile::tempdir().expect("temp dir");
1310 let real = dir.path().join("real.json");
1311 std::fs::write(&real, "keep").unwrap();
1312 let link = dir.path().join("link.json");
1313 std::os::unix::fs::symlink(&real, &link).unwrap();
1314
1315 assert!(super::open_no_follow(&link).is_err());
1316 assert_eq!(std::fs::read_to_string(&real).unwrap(), "keep");
1317 }
1318}