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,
47 shared_dirs: Vec<PathBuf>,
48}
49
50enum Refusal {
52 Outside,
54 Link {
57 link: PathBuf,
58 target: PathBuf,
59 kind: LinkTarget,
60 },
61 Special,
64}
65
66#[derive(Clone, Copy)]
68enum LinkTarget {
69 Outside,
71 Packages,
73 GitMetadata,
75}
76
77impl LinkTarget {
78 const fn phrase(self) -> &'static str {
80 match self {
81 Self::Outside => "outside the project",
82 Self::Packages => "into a node_modules directory",
83 Self::GitMetadata => "into Git metadata",
84 }
85 }
86
87 fn of(within: Option<&Path>, target: &Path) -> Option<Self> {
88 let Some(within) = within else {
89 return Some(Self::Outside);
90 };
91 if !fallow_types::path_guard::is_protected_link_target(within, target) {
92 return None;
93 }
94 let below = target.strip_prefix(within).unwrap_or(target);
95 let in_packages = below.components().any(|component| {
96 component
97 .as_os_str()
98 .to_str()
99 .is_some_and(|name| name.eq_ignore_ascii_case("node_modules"))
100 });
101 Some(if in_packages {
102 Self::Packages
103 } else {
104 Self::GitMetadata
105 })
106 }
107}
108
109impl WriteScope {
110 pub fn new(root: &Path, cwd: &Path, shared_dirs: Vec<PathBuf>) -> Result<Self, String> {
122 let root = root.canonicalize().map_err(|err| {
123 format!(
124 "the project root {} cannot be resolved ({err})",
125 root.display()
126 )
127 })?;
128 let cwd = cwd.canonicalize().unwrap_or_else(|_| cwd.to_path_buf());
129 let checkout = fallow_types::path_guard::work_tree_top(&root).map(Path::to_path_buf);
130 let work_tree = checkout.clone().filter(|tree| cwd.starts_with(tree));
131 let git_dirs = fallow_types::path_guard::GitDirs::of(&root);
132 Ok(Self {
133 root,
134 work_tree,
135 checkout,
136 git_dirs,
137 shared_dirs,
138 })
139 }
140
141 #[must_use]
144 pub fn contains(&self, path: &Path) -> bool {
145 walk(path).is_ok_and(|walk| self.refusal(&walk).is_none())
146 }
147
148 #[must_use]
169 pub fn check(&self, flag: &str, path: &Path, cwd: &Path) -> Option<String> {
170 if is_null_device(path) {
171 return None;
172 }
173 let walk = match walk(&cwd.join(path)) {
174 Ok(walk) => walk,
175 Err(err) => {
176 return Some(format!(
177 "{flag} {} cannot be resolved ({err}). Choose a path that fallow can read.",
178 path.display()
179 ));
180 }
181 };
182 let refusal = self.refusal(&walk)?;
183 Some(match refusal {
184 Refusal::Outside => format!(
185 "{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).",
186 path.display(),
187 walk.resolved.display(),
188 self.root.display(),
189 self.work_tree
190 .as_deref()
191 .filter(|tree| *tree != self.root)
192 .map(|tree| format!(" or its Git work tree {}", tree.display()))
193 .unwrap_or_default(),
194 ),
195 Refusal::Link { link, target, kind } => format!(
196 "{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.",
197 path.display(),
198 link.display(),
199 kind.phrase(),
200 target.display(),
201 ),
202 Refusal::Special => format!(
203 "{flag} {} resolves to {}, which is not a regular file. Choose a path to a regular file.",
204 path.display(),
205 walk.resolved.display(),
206 ),
207 })
208 }
209
210 fn refusal(&self, walk: &Walk) -> Option<Refusal> {
211 let mut through_project_link = false;
212 for link in &walk.links {
213 let kind = if self.git_dirs.holds(&link.target) {
214 Some(LinkTarget::GitMetadata)
215 } else if self.in_checkout(&link.location) {
216 through_project_link = true;
217 let within = if link.target.starts_with(&self.root) {
218 Some(self.root.as_path())
219 } else {
220 self.work_tree
221 .as_deref()
222 .filter(|tree| link.target.starts_with(tree))
223 };
224 LinkTarget::of(within, &link.target)
225 } else {
226 LinkTarget::of(Some(self.protected_scope_for(link)), &link.target)
229 .filter(|kind| !matches!(kind, LinkTarget::Outside))
230 };
231 if let Some(kind) = kind {
232 return Some(Refusal::Link {
233 link: link.location.clone(),
234 target: link.target.clone(),
235 kind,
236 });
237 }
238 }
239 match std::fs::metadata(&walk.resolved) {
240 Ok(meta) if !meta.is_file() && !meta.is_dir() => {
241 return (through_project_link || !is_stream_target(&walk.resolved))
242 .then_some(Refusal::Special);
243 }
244 Ok(_) => {}
245 Err(error) if error.kind() == io::ErrorKind::NotFound => {}
246 Err(_) => return Some(Refusal::Special),
247 }
248 let path = walk.resolved.as_path();
249 let inside = path.starts_with(&self.root)
250 || self
251 .work_tree
252 .as_deref()
253 .is_some_and(|tree| path.starts_with(tree))
254 || self.shared_dirs.iter().any(|dir| path.starts_with(dir));
255 (!inside).then_some(Refusal::Outside)
256 }
257
258 #[must_use]
262 pub fn refusal_reason(&self, path: &Path) -> Option<&'static str> {
263 let Ok(walk) = walk(path) else {
264 return Some("to a path that cannot be read");
265 };
266 Some(match self.refusal(&walk)? {
267 Refusal::Outside => "outside the project",
268 Refusal::Link { kind, .. } => kind.phrase(),
269 Refusal::Special => "to a file that is not a regular file",
270 })
271 }
272
273 fn protected_scope_for<'a>(&'a self, link: &'a Link) -> &'a Path {
277 if link.target.starts_with(&self.root) {
278 return &self.root;
279 }
280 if let Some(tree) = self
281 .checkout
282 .as_deref()
283 .filter(|tree| link.target.starts_with(tree))
284 {
285 return tree;
286 }
287 link.location.parent().unwrap_or(&link.location)
288 }
289
290 fn in_checkout(&self, path: &Path) -> bool {
291 path.starts_with(&self.root)
292 || self
293 .checkout
294 .as_deref()
295 .is_some_and(|tree| path.starts_with(tree))
296 }
297
298 fn refusal_error(&self, requested: &Path, walk: &Walk) -> Option<io::Error> {
299 let reason = match self.refusal(walk)? {
300 Refusal::Outside => format!(
301 "{} resolves to {}, which is outside the directories this run may write to",
302 requested.display(),
303 walk.resolved.display()
304 ),
305 Refusal::Link { link, target, kind } => format!(
306 "{} goes through the symlink {}, which resolves {} ({}), so fallow did not write it",
307 requested.display(),
308 link.display(),
309 kind.phrase(),
310 target.display()
311 ),
312 Refusal::Special => format!(
313 "{} resolves to {}, which is not a regular file, so fallow did not write it",
314 requested.display(),
315 walk.resolved.display()
316 ),
317 };
318 Some(io::Error::new(io::ErrorKind::PermissionDenied, reason))
319 }
320}
321
322const SHARED_DIR_VARIABLES: [&str; 3] = ["GITHUB_WORKSPACE", "CI_PROJECT_DIR", "RUNNER_TEMP"];
326
327#[must_use]
334pub fn shared_dirs() -> Vec<PathBuf> {
335 shared_dirs_for(std::env::temp_dir())
336}
337
338fn shared_dirs_for(temp_dir: PathBuf) -> Vec<PathBuf> {
339 SHARED_DIR_VARIABLES
340 .iter()
341 .filter_map(std::env::var_os)
342 .filter(|value| !value.is_empty())
343 .map(PathBuf::from)
344 .chain(temp_dirs_with(temp_dir))
345 .filter_map(|dir| dir.canonicalize().ok())
346 .collect()
347}
348
349const UNIX_SYSTEM_TEMP_DIR: &str = "/tmp";
353
354#[must_use]
358pub fn system_temp_dirs() -> Vec<PathBuf> {
359 temp_dirs_with(std::env::temp_dir())
360}
361
362fn temp_dirs_with(temp_dir: PathBuf) -> Vec<PathBuf> {
363 let mut dirs = vec![temp_dir];
364 if cfg!(unix) {
365 dirs.push(PathBuf::from(UNIX_SYSTEM_TEMP_DIR));
366 }
367 dirs
368}
369
370#[cfg(unix)]
373fn is_stream_target(path: &Path) -> bool {
374 use std::os::unix::fs::FileTypeExt;
375 std::fs::metadata(path).is_ok_and(|meta| {
376 let file_type = meta.file_type();
377 file_type.is_char_device() || file_type.is_fifo()
378 })
379}
380
381#[cfg(not(unix))]
382const fn is_stream_target(_path: &Path) -> bool {
383 false
384}
385
386#[cfg(windows)]
388const WINDOWS_NULL_DEVICE: &str = r"\\.\NUL";
389
390fn is_null_device(path: &Path) -> bool {
395 cfg!(windows) && names_windows_null_device(path)
396}
397
398fn names_windows_null_device(path: &Path) -> bool {
405 let Some(text) = path.to_str() else {
406 return false;
407 };
408 let name = text
409 .strip_prefix(r"\\.\")
410 .or_else(|| text.strip_prefix("//./"))
411 .unwrap_or_else(|| text.strip_suffix(':').unwrap_or(text));
412 name.eq_ignore_ascii_case("NUL")
413}
414
415#[derive(Debug, Clone, Copy, PartialEq, Eq)]
418pub enum WriteTarget {
419 Path,
421 DiscoveredConfig,
424}
425
426#[derive(Debug)]
428struct Confinement {
429 cwd: PathBuf,
430 paths: WriteScope,
431 config: WriteScope,
432}
433
434static CONFINEMENT: OnceLock<Confinement> = OnceLock::new();
435
436pub fn confine(cwd: PathBuf, paths: WriteScope, config: WriteScope) {
441 let _ = CONFINEMENT.set(Confinement { cwd, paths, config });
442}
443
444#[derive(Debug)]
446pub enum WriteFailure {
447 Directory(io::Error),
449 File(io::Error),
453}
454
455impl WriteFailure {
456 #[must_use]
459 pub const fn is_directory(&self) -> bool {
460 matches!(self, Self::Directory(_))
461 }
462}
463
464impl std::fmt::Display for WriteFailure {
465 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
466 match self {
467 Self::Directory(error) | Self::File(error) => error.fmt(f),
468 }
469 }
470}
471
472impl std::error::Error for WriteFailure {}
473
474impl From<WriteFailure> for io::Error {
475 fn from(failure: WriteFailure) -> Self {
476 match failure {
477 WriteFailure::Directory(error) | WriteFailure::File(error) => error,
478 }
479 }
480}
481
482pub fn create_file(path: &Path, target: WriteTarget) -> Result<File, WriteFailure> {
494 let confinement = CONFINEMENT.get();
495 let absolute = match confinement {
496 Some(confinement) => confinement.cwd.join(path),
497 None => std::env::current_dir().map_or_else(|_| path.to_path_buf(), |cwd| cwd.join(path)),
498 };
499 let scope = confinement.map(|confinement| match target {
500 WriteTarget::Path => &confinement.paths,
501 WriteTarget::DiscoveredConfig => &confinement.config,
502 });
503 create_checked(path, &absolute, scope)
504}
505
506pub fn write_file(path: &Path, contents: &[u8], target: WriteTarget) -> Result<(), WriteFailure> {
513 let mut file = create_file(path, target)?;
514 file.write_all(contents).map_err(WriteFailure::File)?;
515 file.flush().map_err(WriteFailure::File)
516}
517
518fn create_checked(
519 requested: &Path,
520 absolute: &Path,
521 scope: Option<&WriteScope>,
522) -> Result<File, WriteFailure> {
523 if is_null_device(requested) {
524 return open_null_device().map_err(WriteFailure::File);
525 }
526 let walk = walk(absolute).map_err(WriteFailure::File)?;
527 if let Some(error) = scope.and_then(|scope| scope.refusal_error(requested, &walk)) {
528 return Err(WriteFailure::File(error));
529 }
530 let resolved = walk.resolved;
531 if is_stream_target(&resolved) {
532 return open_stream(&resolved).map_err(WriteFailure::File);
533 }
534 if let Some(parent) = resolved.parent()
535 && !parent.as_os_str().is_empty()
536 {
537 std::fs::create_dir_all(parent).map_err(WriteFailure::Directory)?;
538 let real_parent = parent.canonicalize().map_err(WriteFailure::File)?;
541 if real_parent != parent {
542 return Err(WriteFailure::File(io::Error::new(
543 io::ErrorKind::PermissionDenied,
544 format!(
545 "{} changed while fallow prepared the write, so fallow did not write it",
546 requested.display()
547 ),
548 )));
549 }
550 }
551 open_no_follow(&resolved).map_err(WriteFailure::File)
552}
553
554fn open_stream(path: &Path) -> io::Result<File> {
559 let mut options = std::fs::OpenOptions::new();
560 options.write(true);
561 #[cfg(unix)]
562 {
563 use std::os::unix::fs::OpenOptionsExt;
564 options.custom_flags(libc::O_NOFOLLOW);
565 }
566 let file = options.open(path)?;
567 #[cfg(unix)]
568 ensure_stream_handle(&file, path)?;
569 Ok(file)
570}
571
572#[cfg(windows)]
574fn open_null_device() -> io::Result<File> {
575 std::fs::OpenOptions::new()
576 .write(true)
577 .open(WINDOWS_NULL_DEVICE)
578}
579
580#[cfg(not(windows))]
582fn open_null_device() -> io::Result<File> {
583 Err(io::Error::new(
584 io::ErrorKind::Unsupported,
585 "only Windows has a null device name",
586 ))
587}
588
589#[cfg(unix)]
591fn ensure_stream_handle(file: &File, path: &Path) -> io::Result<()> {
592 use std::os::unix::fs::FileTypeExt;
593 let file_type = file.metadata()?.file_type();
594 if file_type.is_char_device() || file_type.is_fifo() {
595 return Ok(());
596 }
597 Err(io::Error::new(
598 io::ErrorKind::PermissionDenied,
599 format!(
600 "{} is no longer a device or a named pipe, so fallow did not write it",
601 path.display()
602 ),
603 ))
604}
605
606fn open_no_follow(path: &Path) -> io::Result<File> {
610 let mut options = std::fs::OpenOptions::new();
611 options.write(true).create(true).truncate(true);
612 #[cfg(unix)]
613 {
614 use std::os::unix::fs::OpenOptionsExt;
615 options.custom_flags(libc::O_NOFOLLOW);
616 }
617 #[cfg(not(unix))]
620 if path
621 .symlink_metadata()
622 .is_ok_and(|meta| meta.file_type().is_symlink())
623 {
624 return Err(io::Error::new(
625 io::ErrorKind::PermissionDenied,
626 format!(
627 "{} became a symlink after fallow checked it, so fallow did not write it",
628 path.display()
629 ),
630 ));
631 }
632 options.open(path)
633}
634
635const MAX_LINK_HOPS: usize = 40;
637
638#[must_use]
645pub fn resolve(path: &Path) -> PathBuf {
646 walk(path).map_or_else(|_| canonical_form(path, 0), |walk| walk.resolved)
647}
648
649struct Link {
651 location: PathBuf,
653 target: PathBuf,
655}
656
657struct Walk {
659 resolved: PathBuf,
660 links: Vec<Link>,
661}
662
663fn walk(path: &Path) -> io::Result<Walk> {
672 let absolute;
673 let path = if path.is_absolute() {
674 path
675 } else {
676 absolute = std::env::current_dir()?.join(path);
677 &absolute
678 };
679 let mut links = Vec::new();
680 let mut hops = 0;
681 let walked = walk_components(path, &mut links, &mut hops)?;
682 Ok(Walk {
683 resolved: canonical_form(&walked, 0),
684 links,
685 })
686}
687
688fn walk_components(path: &Path, links: &mut Vec<Link>, hops: &mut usize) -> io::Result<PathBuf> {
689 let mut resolved = PathBuf::new();
690 for component in path.components() {
691 let name = match component {
692 Component::Prefix(_) | Component::RootDir => {
693 resolved.push(component.as_os_str());
694 continue;
695 }
696 Component::CurDir => continue,
697 Component::ParentDir => {
698 resolved.pop();
699 continue;
700 }
701 Component::Normal(name) => name,
702 };
703 let candidate = resolved.join(name);
704 match candidate.symlink_metadata() {
705 Ok(meta) if meta.file_type().is_symlink() => {
706 *hops += 1;
707 if *hops > MAX_LINK_HOPS {
708 return Err(io::Error::new(
709 io::ErrorKind::InvalidInput,
710 format!("{} goes through too many symlinks", path.display()),
711 ));
712 }
713 let target = std::fs::read_link(&candidate)?;
714 let followed = walk_components(&resolved.join(target), links, hops)?;
715 links.push(Link {
716 location: canonical_form(&resolved, 0).join(name),
717 target: canonical_form(&followed, 0),
718 });
719 resolved = followed;
720 }
721 Ok(_) => resolved = candidate,
722 Err(error) if error.kind() == io::ErrorKind::NotFound => resolved = candidate,
723 Err(error) => return Err(error),
724 }
725 }
726 Ok(resolved)
727}
728
729fn canonical_form(path: &Path, hops: usize) -> PathBuf {
734 let mut existing = path;
735 let mut missing = Vec::new();
736 loop {
737 if let Ok(real) = existing.canonicalize() {
738 return append_missing(real, &missing);
739 }
740 if hops < MAX_LINK_HOPS
741 && let Ok(target) = std::fs::read_link(existing)
742 {
743 let base = existing.parent().unwrap_or_else(|| Path::new(""));
744 let followed = canonical_form(&base.join(target), hops + 1);
745 return append_missing(followed, &missing);
746 }
747 let (Some(parent), Some(last)) = (existing.parent(), existing.components().next_back())
748 else {
749 return append_missing(PathBuf::new(), &missing);
750 };
751 missing.push(last);
752 existing = parent;
753 }
754}
755
756fn append_missing(mut resolved: PathBuf, missing: &[Component<'_>]) -> PathBuf {
758 for component in missing.iter().rev() {
759 match component {
760 Component::ParentDir => {
761 resolved.pop();
762 }
763 Component::CurDir => {}
764 other => resolved.push(other.as_os_str()),
765 }
766 }
767 resolved
768}
769
770#[cfg(test)]
771mod tests {
772 use std::path::Path;
773
774 use super::{WriteScope, create_checked, names_windows_null_device, resolve};
775
776 #[cfg(unix)]
780 #[test]
781 fn scope_accepts_the_unix_system_temp_dir_when_tmpdir_names_another_folder() {
782 use super::shared_dirs_for;
783
784 let project = tempfile::tempdir().expect("project dir");
785 let other_temp = tempfile::tempdir().expect("temp dir");
786 let scope = WriteScope::new(
787 project.path(),
788 project.path(),
789 shared_dirs_for(other_temp.path().to_path_buf()),
790 )
791 .expect("scope");
792 assert_eq!(
793 scope.check("--save-baseline", Path::new("/tmp/x.json"), project.path()),
794 None
795 );
796 }
797
798 #[test]
802 fn the_windows_null_device_is_named_by_nul_alone() {
803 for name in [
804 "NUL", "nul", "Nul", "NUL:", r"\\.\NUL", r"\\.\nul", "//./NUL",
805 ] {
806 assert!(names_windows_null_device(Path::new(name)), "{name}");
807 }
808 for name in [
809 "NUL.txt",
810 "nul.sarif",
811 "null",
812 "NULL",
813 "report",
814 r"dir\NUL",
815 "dir/nul",
816 r".\NUL",
817 r"C:\NUL",
818 "",
819 ] {
820 assert!(!names_windows_null_device(Path::new(name)), "{name}");
821 }
822 }
823
824 #[test]
825 fn resolve_normalises_the_missing_part() {
826 let dir = tempfile::tempdir().expect("temp dir");
827 let base = dir.path().canonicalize().unwrap();
828 assert_eq!(
829 resolve(&base.join("a/b/../c.json")),
830 base.join("a").join("c.json")
831 );
832 assert_eq!(
833 resolve(&base.join("a/../../x.json")),
834 base.parent().unwrap().join("x.json")
835 );
836 }
837
838 #[cfg(unix)]
839 #[test]
840 fn a_dangling_link_resolves_to_its_target() {
841 let dir = tempfile::tempdir().expect("temp dir");
842 let base = dir.path().canonicalize().unwrap();
843 let root = base.join("project");
844 std::fs::create_dir_all(&root).unwrap();
845 std::os::unix::fs::symlink(base.join("elsewhere.json"), root.join("b.json")).unwrap();
846 assert_eq!(resolve(&root.join("b.json")), base.join("elsewhere.json"));
847 }
848
849 #[test]
850 fn scope_accepts_a_temp_dir_through_a_symlinked_spelling() {
851 let dir = tempfile::tempdir().expect("temp dir");
852 let root = dir.path().join("project");
853 let temp = dir.path().join("temp");
854 std::fs::create_dir_all(&root).unwrap();
855 std::fs::create_dir_all(&temp).unwrap();
856 let scope =
857 WriteScope::new(&root, &root, vec![temp.canonicalize().unwrap()]).expect("scope");
858 assert!(
861 scope
862 .check("--save-baseline", &temp.join("b.json"), &root)
863 .is_none()
864 );
865 assert!(
866 scope
867 .check("--save-baseline", &dir.path().join("b.json"), &root)
868 .is_some()
869 );
870 }
871
872 #[test]
873 fn a_root_that_cannot_be_resolved_fails_closed() {
874 let dir = tempfile::tempdir().expect("temp dir");
875 let missing = dir.path().join("missing");
876 assert!(WriteScope::new(&missing, dir.path(), Vec::new()).is_err());
877 }
878
879 #[test]
880 fn the_work_tree_needs_the_working_directory_inside_it() {
881 let dir = tempfile::tempdir().expect("temp dir");
882 let home = dir.path().join("home");
883 let root = home.join("project");
884 let elsewhere = dir.path().join("elsewhere");
885 std::fs::create_dir_all(&root).unwrap();
886 std::fs::create_dir_all(&elsewhere).unwrap();
887 std::fs::create_dir_all(home.join(".git")).unwrap();
888 let target = home.join(".config").join("x.json");
889 let from_outside = WriteScope::new(&root, &elsewhere, Vec::new()).expect("scope");
890 assert!(
891 from_outside
892 .check("--save-baseline", &target, &elsewhere)
893 .is_some()
894 );
895 let from_inside = WriteScope::new(&root, &home, Vec::new()).expect("scope");
896 assert!(
897 from_inside
898 .check("--save-baseline", &target, &home)
899 .is_none()
900 );
901 }
902
903 #[test]
904 fn scope_accepts_the_root_and_rejects_a_sibling() {
905 let dir = tempfile::tempdir().expect("temp dir");
906 let root = dir.path().join("project");
907 std::fs::create_dir_all(&root).unwrap();
908 let scope = WriteScope::new(&root, &root, Vec::new()).expect("scope");
909 assert!(
910 scope
911 .check("--save-baseline", "nested/b.json".as_ref(), &root)
912 .is_none()
913 );
914 let message = scope
915 .check("--save-baseline", "../b.json".as_ref(), &root)
916 .expect("outside");
917 assert!(message.contains("outside the project root"), "{message}");
918 }
919
920 #[test]
921 fn scope_accepts_the_git_work_tree_of_the_root() {
922 let dir = tempfile::tempdir().expect("temp dir");
923 let repo = dir.path().join("repo");
924 let root = repo.join("packages/app");
925 std::fs::create_dir_all(&root).unwrap();
926 std::fs::create_dir_all(repo.join(".git")).unwrap();
927 let scope = WriteScope::new(&root, &repo, Vec::new()).expect("scope");
928 assert!(
929 scope
930 .check("--save-baseline", "baselines/b.json".as_ref(), &repo)
931 .is_none()
932 );
933 let message = scope
934 .check("--save-baseline", "../b.json".as_ref(), &repo)
935 .expect("outside");
936 assert!(message.contains("Git work tree"), "{message}");
937 }
938
939 #[test]
940 fn a_checked_write_lands_inside_the_scope() {
941 let dir = tempfile::tempdir().expect("temp dir");
942 let root = dir.path().join("project");
943 std::fs::create_dir_all(&root).unwrap();
944 let scope = WriteScope::new(&root, &root, Vec::new()).expect("scope");
945 let target = root.join("out/nested/report.json");
946 assert!(scope.check("--output-file", &target, &root).is_none());
947 let file = create_checked(&target, &target, Some(&scope)).expect("write inside");
948 drop(file);
949 assert!(target.is_file());
950 }
951
952 #[cfg(unix)]
954 #[test]
955 fn a_character_device_is_allowed_outside_the_scope() {
956 let dir = tempfile::tempdir().expect("temp dir");
957 let root = dir.path().join("project");
958 std::fs::create_dir_all(&root).unwrap();
959 let scope = WriteScope::new(&root, &root, Vec::new()).expect("scope");
960 let null = std::path::Path::new("/dev/null");
961 assert!(scope.check("--output-file", null, &root).is_none());
962 let file = create_checked(null, null, Some(&scope)).expect("write to /dev/null");
963 drop(file);
964 }
965
966 #[cfg(unix)]
969 #[test]
970 fn a_named_pipe_is_allowed_outside_the_scope() {
971 use std::io::Write as _;
972 let dir = tempfile::tempdir().expect("temp dir");
973 let root = dir.path().join("project");
974 std::fs::create_dir_all(&root).unwrap();
975 let fifo = dir.path().join("report.fifo");
976 let made = std::process::Command::new("mkfifo")
977 .arg(&fifo)
978 .status()
979 .expect("run mkfifo");
980 assert!(made.success());
981 let scope = WriteScope::new(&root, &root, Vec::new()).expect("scope");
982 assert!(scope.check("--sarif-file", &fifo, &root).is_none());
983 let reader_path = fifo.clone();
984 let reader = std::thread::spawn(move || std::fs::read_to_string(reader_path));
985 let mut file = create_checked(&fifo, &fifo, Some(&scope)).expect("write to fifo");
986 file.write_all(b"sarif").unwrap();
987 drop(file);
988 assert_eq!(reader.join().unwrap().unwrap(), "sarif");
989 }
990
991 #[cfg(unix)]
994 #[test]
995 fn a_stream_target_swapped_after_the_check_is_refused() {
996 use super::{ensure_stream_handle, open_stream};
997 let dir = tempfile::tempdir().expect("temp dir");
998 let link = dir.path().join("null-link");
999 std::os::unix::fs::symlink("/dev/null", &link).unwrap();
1000 assert!(open_stream(&link).is_err(), "a symlink is not followed");
1001
1002 let regular = dir.path().join("regular.json");
1003 std::fs::write(®ular, "keep").unwrap();
1004 assert!(open_stream(®ular).is_err(), "a regular file is refused");
1005 let handle = std::fs::File::open(®ular).unwrap();
1006 assert!(ensure_stream_handle(&handle, ®ular).is_err());
1007 assert_eq!(std::fs::read_to_string(®ular).unwrap(), "keep");
1008
1009 let null = std::fs::File::open("/dev/null").unwrap();
1010 assert!(ensure_stream_handle(&null, std::path::Path::new("/dev/null")).is_ok());
1011 }
1012
1013 #[cfg(unix)]
1016 #[test]
1017 fn a_directory_swapped_for_a_symlink_after_the_check_is_refused() {
1018 let dir = tempfile::tempdir().expect("temp dir");
1019 let root = dir.path().join("project");
1020 let elsewhere = dir.path().join("elsewhere");
1021 std::fs::create_dir_all(root.join("out")).unwrap();
1022 std::fs::create_dir_all(&elsewhere).unwrap();
1023 let scope = WriteScope::new(&root, &root, Vec::new()).expect("scope");
1024 let target = root.join("out/report.json");
1025 assert!(scope.check("--output-file", &target, &root).is_none());
1026
1027 std::fs::remove_dir(root.join("out")).unwrap();
1028 std::os::unix::fs::symlink(&elsewhere, root.join("out")).unwrap();
1029
1030 let error = std::io::Error::from(
1031 create_checked(&target, &target, Some(&scope)).expect_err("refused"),
1032 );
1033 assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
1034 assert!(!elsewhere.join("report.json").exists());
1035 }
1036
1037 #[cfg(unix)]
1040 #[test]
1041 fn a_file_swapped_for_a_symlink_after_the_check_is_refused() {
1042 let dir = tempfile::tempdir().expect("temp dir");
1043 let root = dir.path().join("project");
1044 std::fs::create_dir_all(&root).unwrap();
1045 let outside = dir.path().join("outside.json");
1046 let scope = WriteScope::new(&root, &root, Vec::new()).expect("scope");
1047 let target = root.join("report.json");
1048 assert!(scope.check("--output-file", &target, &root).is_none());
1049
1050 std::os::unix::fs::symlink(&outside, &target).unwrap();
1051
1052 assert!(create_checked(&target, &target, Some(&scope)).is_err());
1053 assert!(!outside.exists());
1054 }
1055
1056 #[cfg(unix)]
1060 #[test]
1061 fn a_link_after_a_parent_step_is_resolved() {
1062 let dir = tempfile::tempdir().expect("temp dir");
1063 let root = dir.path().join("project");
1064 let elsewhere = dir.path().join("elsewhere");
1065 std::fs::create_dir_all(&root).unwrap();
1066 std::fs::create_dir_all(&elsewhere).unwrap();
1067 std::os::unix::fs::symlink(&elsewhere, root.join("away")).unwrap();
1068 let scope = WriteScope::new(&root, &root, Vec::new()).expect("scope");
1069 let requested = Path::new("build/../away/x/r.json");
1070 assert!(scope.check("--output-file", requested, &root).is_some());
1071 let absolute = root.join(requested);
1072 assert!(create_checked(requested, &absolute, Some(&scope)).is_err());
1073 assert!(!elsewhere.join("x").exists());
1074 assert!(!root.join("build").exists());
1075 }
1076
1077 #[cfg(unix)]
1080 #[test]
1081 fn a_project_link_into_a_shared_dir_is_refused() {
1082 let dir = tempfile::tempdir().expect("temp dir");
1083 let root = dir.path().join("project");
1084 let shared = dir.path().join("workspace");
1085 std::fs::create_dir_all(&root).unwrap();
1086 std::fs::create_dir_all(&shared).unwrap();
1087 std::fs::write(shared.join("run.sh"), "keep").unwrap();
1088 std::os::unix::fs::symlink(shared.join("run.sh"), root.join("report.sarif")).unwrap();
1089 let scope =
1090 WriteScope::new(&root, &root, vec![shared.canonicalize().unwrap()]).expect("scope");
1091 let target = root.join("report.sarif");
1092 assert!(scope.check("--sarif-file", &target, &root).is_some());
1093 assert!(create_checked(&target, &target, Some(&scope)).is_err());
1094 assert_eq!(
1095 std::fs::read_to_string(shared.join("run.sh")).unwrap(),
1096 "keep"
1097 );
1098 assert!(
1099 scope
1100 .check("--sarif-file", &shared.join("report.sarif"), &root)
1101 .is_none()
1102 );
1103 }
1104
1105 #[cfg(unix)]
1108 #[test]
1109 fn a_project_link_to_a_named_pipe_is_refused() {
1110 let dir = tempfile::tempdir().expect("temp dir");
1111 let root = dir.path().join("project");
1112 std::fs::create_dir_all(&root).unwrap();
1113 let fifo = dir.path().join("report.fifo");
1114 let made = std::process::Command::new("mkfifo")
1115 .arg(&fifo)
1116 .status()
1117 .expect("run mkfifo");
1118 assert!(made.success());
1119 std::os::unix::fs::symlink(&fifo, root.join("report.json")).unwrap();
1120 let scope = WriteScope::new(&root, &root, Vec::new()).expect("scope");
1121 assert!(
1122 scope
1123 .check("--output-file", &root.join("report.json"), &root)
1124 .is_some()
1125 );
1126 assert!(scope.check("--output-file", &fifo, &root).is_none());
1127 }
1128
1129 #[cfg(unix)]
1132 #[test]
1133 fn a_project_link_into_git_or_node_modules_is_refused() {
1134 let dir = tempfile::tempdir().expect("temp dir");
1135 let root = dir.path().join("project");
1136 std::fs::create_dir_all(root.join(".git")).unwrap();
1137 std::fs::create_dir_all(root.join("node_modules/pkg")).unwrap();
1138 std::fs::create_dir_all(root.join("reports")).unwrap();
1139 std::os::unix::fs::symlink(root.join(".git"), root.join("meta")).unwrap();
1140 std::os::unix::fs::symlink(root.join("node_modules/pkg"), root.join("pkg")).unwrap();
1141 std::os::unix::fs::symlink(root.join("reports"), root.join("out")).unwrap();
1142 let scope = WriteScope::new(&root, &root, Vec::new()).expect("scope");
1143 for refused in ["meta/config", "pkg/index.js"] {
1144 assert!(
1145 scope
1146 .check("--output-file", Path::new(refused), &root)
1147 .is_some(),
1148 "{refused}"
1149 );
1150 let absolute = root.join(refused);
1151 assert!(create_checked(Path::new(refused), &absolute, Some(&scope)).is_err());
1152 }
1153 assert!(!root.join(".git/config").exists());
1154 assert!(
1155 scope
1156 .check("--output-file", Path::new("out/r.json"), &root)
1157 .is_none()
1158 );
1159 }
1160
1161 #[cfg(unix)]
1164 #[test]
1165 fn an_outside_link_into_git_metadata_is_refused() {
1166 let dir = tempfile::tempdir().expect("temp dir");
1167 let root = dir.path().join("project");
1168 let shared = dir.path().join("shared");
1169 std::fs::create_dir_all(root.join(".git/hooks")).unwrap();
1170 std::fs::create_dir_all(&shared).unwrap();
1171 let hook = root.join(".git/hooks/pre-commit");
1172 std::fs::write(&hook, "keep").unwrap();
1173 let link = shared.join("r.json");
1174 std::os::unix::fs::symlink(&hook, &link).unwrap();
1175 let scope =
1176 WriteScope::new(&root, &root, vec![shared.canonicalize().unwrap()]).expect("scope");
1177 assert!(scope.check("--output-file", &link, &root).is_some());
1178 assert!(create_checked(&link, &link, Some(&scope)).is_err());
1179 assert_eq!(std::fs::read_to_string(&hook).unwrap(), "keep");
1180 }
1181
1182 #[cfg(unix)]
1186 #[test]
1187 fn an_outside_link_into_a_separate_git_dir_is_refused() {
1188 let dir = tempfile::tempdir().expect("temp dir");
1189 let root = dir.path().join("project");
1190 let shared = dir.path().join("shared");
1191 let git_dir = shared.join("gd");
1192 std::fs::create_dir_all(git_dir.join("hooks")).unwrap();
1193 std::fs::create_dir_all(&root).unwrap();
1194 std::fs::write(
1195 root.join(".git"),
1196 format!("gitdir: {}\n", git_dir.display()),
1197 )
1198 .unwrap();
1199 let hook = git_dir.join("hooks/pre-commit");
1200 std::fs::write(&hook, "keep").unwrap();
1201 let link = shared.join("r.json");
1202 std::os::unix::fs::symlink(&hook, &link).unwrap();
1203 let scope =
1204 WriteScope::new(&root, &root, vec![shared.canonicalize().unwrap()]).expect("scope");
1205 assert!(scope.check("--output-file", &link, &root).is_some());
1206 assert!(!scope.contains(&link));
1207 assert!(create_checked(&link, &link, Some(&scope)).is_err());
1208 assert_eq!(std::fs::read_to_string(&hook).unwrap(), "keep");
1209 }
1210
1211 #[cfg(unix)]
1214 #[test]
1215 fn an_outside_link_into_the_common_git_dir_of_a_worktree_is_refused() {
1216 let dir = tempfile::tempdir().expect("temp dir");
1217 let shared = dir.path().join("shared");
1218 let bare = shared.join("repo.git");
1219 let linked = bare.join("worktrees/project");
1220 std::fs::create_dir_all(&linked).unwrap();
1221 std::fs::create_dir_all(bare.join("hooks")).unwrap();
1222 std::fs::write(linked.join("commondir"), "../..\n").unwrap();
1223 let root = dir.path().join("project");
1224 std::fs::create_dir_all(&root).unwrap();
1225 std::fs::write(root.join(".git"), format!("gitdir: {}\n", linked.display())).unwrap();
1226 let hook = bare.join("hooks/pre-commit");
1227 std::fs::write(&hook, "keep").unwrap();
1228 let link = shared.join("r.json");
1229 std::os::unix::fs::symlink(&hook, &link).unwrap();
1230 let scope =
1231 WriteScope::new(&root, &root, vec![shared.canonicalize().unwrap()]).expect("scope");
1232 assert!(scope.check("--output-file", &link, &root).is_some());
1233 assert_eq!(std::fs::read_to_string(&hook).unwrap(), "keep");
1234 }
1235
1236 #[cfg(unix)]
1240 #[test]
1241 fn a_link_inside_a_worktree_of_a_bare_repository_is_allowed() {
1242 let dir = tempfile::tempdir().expect("temp dir");
1243 let bare = dir.path().join("proj.git");
1244 let linked = bare.join("worktrees/main");
1245 std::fs::create_dir_all(&linked).unwrap();
1246 std::fs::create_dir_all(bare.join("hooks")).unwrap();
1247 std::fs::write(linked.join("commondir"), "../..\n").unwrap();
1248 let root = bare.join("main");
1249 std::fs::create_dir_all(root.join("reports")).unwrap();
1250 std::fs::write(root.join(".git"), format!("gitdir: {}\n", linked.display())).unwrap();
1251 std::os::unix::fs::symlink(root.join("reports"), root.join("out")).unwrap();
1252 std::os::unix::fs::symlink(bare.join("hooks"), root.join("hooks")).unwrap();
1253 let scope = WriteScope::new(&root, &root, Vec::new()).expect("scope");
1254 assert!(scope.contains(&root.join("out/r.json")));
1255 assert!(scope.contains(&root.join("reports/r.json")));
1256 assert!(!scope.contains(&root.join("hooks/pre-commit")));
1257 }
1258
1259 #[cfg(unix)]
1262 #[test]
1263 fn a_dangling_git_link_marks_the_checkout() {
1264 let dir = tempfile::tempdir().expect("temp dir");
1265 let repo = dir.path().join("repo");
1266 std::fs::create_dir_all(repo.join("pkg")).unwrap();
1267 std::os::unix::fs::symlink(dir.path().join("missing"), repo.join(".git")).unwrap();
1268 let scope = WriteScope::new(&repo.join("pkg"), &repo, Vec::new()).expect("scope");
1269 assert!(scope.contains(&repo.join("r.json")));
1270 }
1271
1272 #[cfg(unix)]
1274 #[test]
1275 fn a_socket_target_is_refused() {
1276 let dir = tempfile::tempdir().expect("temp dir");
1277 let root = dir.path().join("project");
1278 std::fs::create_dir_all(&root).unwrap();
1279 let socket = root.join("s.sock");
1280 let _listener = std::os::unix::net::UnixListener::bind(&socket).expect("bind");
1281 let scope = WriteScope::new(&root, &root, Vec::new()).expect("scope");
1282 assert!(scope.check("--output-file", &socket, &root).is_some());
1283 }
1284
1285 #[cfg(unix)]
1288 #[test]
1289 fn a_component_that_cannot_be_read_is_refused() {
1290 use std::os::unix::fs::PermissionsExt;
1291 let dir = tempfile::tempdir().expect("temp dir");
1292 let root = dir.path().join("project");
1293 let closed = root.join("closed");
1294 std::fs::create_dir_all(&closed).unwrap();
1295 std::fs::set_permissions(&closed, std::fs::Permissions::from_mode(0o000)).unwrap();
1296 let readable = closed.join("probe").symlink_metadata();
1297 let scope = WriteScope::new(&root, &root, Vec::new()).expect("scope");
1298 let result = scope.check("--output-file", Path::new("closed/sub/r.json"), &root);
1299 std::fs::set_permissions(&closed, std::fs::Permissions::from_mode(0o755)).unwrap();
1300 if readable.is_err_and(|error| error.kind() == std::io::ErrorKind::PermissionDenied) {
1302 assert!(result.is_some());
1303 }
1304 }
1305
1306 #[cfg(unix)]
1309 #[test]
1310 fn the_open_does_not_follow_a_final_symlink() {
1311 let dir = tempfile::tempdir().expect("temp dir");
1312 let real = dir.path().join("real.json");
1313 std::fs::write(&real, "keep").unwrap();
1314 let link = dir.path().join("link.json");
1315 std::os::unix::fs::symlink(&real, &link).unwrap();
1316
1317 assert!(super::open_no_follow(&link).is_err());
1318 assert_eq!(std::fs::read_to_string(&real).unwrap(), "keep");
1319 }
1320
1321 #[cfg(unix)]
1323 fn git(dir: &Path, args: &[&str]) {
1324 let output = crate::git_fixture::fixture_git_command(dir)
1325 .args([
1326 "-c",
1327 "protocol.file.allow=always",
1328 "-c",
1329 "init.defaultBranch=main",
1330 ])
1331 .args(args)
1332 .output()
1333 .expect("run git");
1334 assert!(
1335 output.status.success(),
1336 "git {args:?}: {}",
1337 String::from_utf8_lossy(&output.stderr)
1338 );
1339 }
1340
1341 #[cfg(unix)]
1345 fn submodule_with_separate_superproject_git_dir(
1346 dir: &Path,
1347 shared: &Path,
1348 ) -> (std::path::PathBuf, std::path::PathBuf) {
1349 let lib = dir.join("lib");
1350 std::fs::create_dir_all(&lib).unwrap();
1351 git(&lib, &["init", "-q"]);
1352 std::fs::write(lib.join("index.ts"), "export const a = 1;\n").unwrap();
1353 git(&lib, &["add", "."]);
1354 git(&lib, &["commit", "-q", "-m", "lib"]);
1355 let superproject = dir.join("super");
1356 let git_dir = shared.join("super.git");
1357 std::fs::create_dir_all(&superproject).unwrap();
1358 git(
1359 &superproject,
1360 &[
1361 "init",
1362 "-q",
1363 "--separate-git-dir",
1364 git_dir.to_str().unwrap(),
1365 ],
1366 );
1367 git(
1368 &superproject,
1369 &[
1370 "submodule",
1371 "add",
1372 "-q",
1373 lib.to_str().unwrap(),
1374 "vendor/lib",
1375 ],
1376 );
1377 (superproject.join("vendor/lib"), git_dir)
1378 }
1379
1380 #[cfg(unix)]
1384 #[test]
1385 fn an_outside_link_into_the_git_dir_of_the_superproject_is_refused() {
1386 let dir = tempfile::tempdir().expect("temp dir");
1387 let shared = dir.path().join("shared");
1388 std::fs::create_dir_all(&shared).unwrap();
1389 let (root, git_dir) = submodule_with_separate_superproject_git_dir(dir.path(), &shared);
1390 let hook = git_dir.join("hooks/pre-commit");
1391 std::fs::write(&hook, "keep").unwrap();
1392 let link = shared.join("r.json");
1393 std::os::unix::fs::symlink(&hook, &link).unwrap();
1394 let config_link = shared.join("c.json");
1395 std::os::unix::fs::symlink(git_dir.join("config"), &config_link).unwrap();
1396 let module_link = shared.join("m.json");
1397 std::os::unix::fs::symlink(git_dir.join("modules/vendor/lib/config"), &module_link)
1398 .unwrap();
1399 let scope =
1400 WriteScope::new(&root, &root, vec![shared.canonicalize().unwrap()]).expect("scope");
1401 assert!(scope.check("--output-file", &link, &root).is_some());
1402 assert!(scope.check("--output-file", &config_link, &root).is_some());
1403 assert!(scope.check("--output-file", &module_link, &root).is_some());
1404 assert!(create_checked(&link, &link, Some(&scope)).is_err());
1405 assert_eq!(std::fs::read_to_string(&hook).unwrap(), "keep");
1406 }
1407
1408 #[cfg(unix)]
1411 #[test]
1412 fn a_link_inside_a_submodule_is_allowed() {
1413 let dir = tempfile::tempdir().expect("temp dir");
1414 let shared = dir.path().join("shared");
1415 std::fs::create_dir_all(&shared).unwrap();
1416 let (root, _) = submodule_with_separate_superproject_git_dir(dir.path(), &shared);
1417 std::fs::create_dir_all(root.join("reports")).unwrap();
1418 std::os::unix::fs::symlink("reports", root.join("out")).unwrap();
1419 let scope =
1420 WriteScope::new(&root, &root, vec![shared.canonicalize().unwrap()]).expect("scope");
1421 assert_eq!(
1422 scope.check("--output-file", Path::new("out/r.json"), &root),
1423 None
1424 );
1425 assert!(scope.contains(&shared.join("r.json")));
1426 }
1427}