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 shared_dirs: Vec<PathBuf>,
41}
42
43impl WriteScope {
44 pub fn new(root: &Path, cwd: &Path, shared_dirs: Vec<PathBuf>) -> Result<Self, String> {
56 let root = root.canonicalize().map_err(|err| {
57 format!(
58 "the project root {} cannot be resolved ({err})",
59 root.display()
60 )
61 })?;
62 let cwd = cwd.canonicalize().unwrap_or_else(|_| cwd.to_path_buf());
63 let work_tree = root
64 .ancestors()
65 .find(|dir| dir.join(".git").exists())
66 .filter(|tree| cwd.starts_with(tree))
67 .map(Path::to_path_buf);
68 Ok(Self {
69 root,
70 work_tree,
71 shared_dirs,
72 })
73 }
74
75 #[must_use]
78 pub fn contains(&self, path: &Path) -> bool {
79 is_stream_target(path)
80 || path.starts_with(&self.root)
81 || self
82 .work_tree
83 .as_deref()
84 .is_some_and(|tree| path.starts_with(tree))
85 || self.shared_dirs.iter().any(|dir| path.starts_with(dir))
86 }
87
88 #[must_use]
92 pub fn check(&self, flag: &str, path: &Path, cwd: &Path) -> Option<String> {
93 if is_null_device(path) {
94 return None;
95 }
96 let resolved = resolve(&cwd.join(path));
97 if self.contains(&resolved) {
98 return None;
99 }
100 Some(format!(
101 "{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).",
102 path.display(),
103 resolved.display(),
104 self.root.display(),
105 self.work_tree
106 .as_deref()
107 .filter(|tree| *tree != self.root)
108 .map(|tree| format!(" or its Git work tree {}", tree.display()))
109 .unwrap_or_default(),
110 ))
111 }
112}
113
114const SHARED_DIR_VARIABLES: [&str; 3] = ["GITHUB_WORKSPACE", "CI_PROJECT_DIR", "RUNNER_TEMP"];
118
119#[must_use]
126pub fn shared_dirs() -> Vec<PathBuf> {
127 shared_dirs_for(std::env::temp_dir())
128}
129
130fn shared_dirs_for(temp_dir: PathBuf) -> Vec<PathBuf> {
131 SHARED_DIR_VARIABLES
132 .iter()
133 .filter_map(std::env::var_os)
134 .filter(|value| !value.is_empty())
135 .map(PathBuf::from)
136 .chain(temp_dirs_with(temp_dir))
137 .filter_map(|dir| dir.canonicalize().ok())
138 .collect()
139}
140
141const UNIX_SYSTEM_TEMP_DIR: &str = "/tmp";
145
146#[must_use]
150pub fn system_temp_dirs() -> Vec<PathBuf> {
151 temp_dirs_with(std::env::temp_dir())
152}
153
154fn temp_dirs_with(temp_dir: PathBuf) -> Vec<PathBuf> {
155 let mut dirs = vec![temp_dir];
156 if cfg!(unix) {
157 dirs.push(PathBuf::from(UNIX_SYSTEM_TEMP_DIR));
158 }
159 dirs
160}
161
162#[cfg(unix)]
165fn is_stream_target(path: &Path) -> bool {
166 use std::os::unix::fs::FileTypeExt;
167 std::fs::metadata(path).is_ok_and(|meta| {
168 let file_type = meta.file_type();
169 file_type.is_char_device() || file_type.is_fifo()
170 })
171}
172
173#[cfg(not(unix))]
174const fn is_stream_target(_path: &Path) -> bool {
175 false
176}
177
178#[cfg(windows)]
180const WINDOWS_NULL_DEVICE: &str = r"\\.\NUL";
181
182fn is_null_device(path: &Path) -> bool {
187 cfg!(windows) && names_windows_null_device(path)
188}
189
190fn names_windows_null_device(path: &Path) -> bool {
197 let Some(text) = path.to_str() else {
198 return false;
199 };
200 let name = text
201 .strip_prefix(r"\\.\")
202 .or_else(|| text.strip_prefix("//./"))
203 .unwrap_or_else(|| text.strip_suffix(':').unwrap_or(text));
204 name.eq_ignore_ascii_case("NUL")
205}
206
207#[derive(Debug, Clone, Copy, PartialEq, Eq)]
210pub enum WriteTarget {
211 Path,
213 DiscoveredConfig,
216}
217
218#[derive(Debug)]
220struct Confinement {
221 cwd: PathBuf,
222 paths: WriteScope,
223 config: WriteScope,
224}
225
226static CONFINEMENT: OnceLock<Confinement> = OnceLock::new();
227
228pub fn confine(cwd: PathBuf, paths: WriteScope, config: WriteScope) {
233 let _ = CONFINEMENT.set(Confinement { cwd, paths, config });
234}
235
236#[derive(Debug)]
238pub enum WriteFailure {
239 Directory(io::Error),
241 File(io::Error),
245}
246
247impl WriteFailure {
248 #[must_use]
251 pub const fn is_directory(&self) -> bool {
252 matches!(self, Self::Directory(_))
253 }
254}
255
256impl std::fmt::Display for WriteFailure {
257 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
258 match self {
259 Self::Directory(error) | Self::File(error) => error.fmt(f),
260 }
261 }
262}
263
264impl std::error::Error for WriteFailure {}
265
266impl From<WriteFailure> for io::Error {
267 fn from(failure: WriteFailure) -> Self {
268 match failure {
269 WriteFailure::Directory(error) | WriteFailure::File(error) => error,
270 }
271 }
272}
273
274pub fn create_file(path: &Path, target: WriteTarget) -> Result<File, WriteFailure> {
286 let confinement = CONFINEMENT.get();
287 let absolute = match confinement {
288 Some(confinement) => confinement.cwd.join(path),
289 None => std::env::current_dir().map_or_else(|_| path.to_path_buf(), |cwd| cwd.join(path)),
290 };
291 let scope = confinement.map(|confinement| match target {
292 WriteTarget::Path => &confinement.paths,
293 WriteTarget::DiscoveredConfig => &confinement.config,
294 });
295 create_checked(path, &absolute, scope)
296}
297
298pub fn write_file(path: &Path, contents: &[u8], target: WriteTarget) -> Result<(), WriteFailure> {
305 let mut file = create_file(path, target)?;
306 file.write_all(contents).map_err(WriteFailure::File)?;
307 file.flush().map_err(WriteFailure::File)
308}
309
310fn create_checked(
311 requested: &Path,
312 absolute: &Path,
313 scope: Option<&WriteScope>,
314) -> Result<File, WriteFailure> {
315 if is_null_device(requested) {
316 return open_null_device().map_err(WriteFailure::File);
317 }
318 let resolved = resolve(absolute);
319 if is_stream_target(&resolved) {
320 return open_stream(&resolved).map_err(WriteFailure::File);
321 }
322 if scope.is_some_and(|scope| !scope.contains(&resolved)) {
323 return Err(WriteFailure::File(io::Error::new(
324 io::ErrorKind::PermissionDenied,
325 format!(
326 "{} resolves to {}, which is outside the directories this run may write to",
327 requested.display(),
328 resolved.display()
329 ),
330 )));
331 }
332 if let Some(parent) = resolved.parent()
333 && !parent.as_os_str().is_empty()
334 {
335 std::fs::create_dir_all(parent).map_err(WriteFailure::Directory)?;
336 let real_parent = parent.canonicalize().map_err(WriteFailure::File)?;
339 if real_parent != parent {
340 return Err(WriteFailure::File(io::Error::new(
341 io::ErrorKind::PermissionDenied,
342 format!(
343 "{} changed while fallow prepared the write, so fallow did not write it",
344 requested.display()
345 ),
346 )));
347 }
348 }
349 open_no_follow(&resolved).map_err(WriteFailure::File)
350}
351
352fn open_stream(path: &Path) -> io::Result<File> {
357 let mut options = std::fs::OpenOptions::new();
358 options.write(true);
359 #[cfg(unix)]
360 {
361 use std::os::unix::fs::OpenOptionsExt;
362 options.custom_flags(libc::O_NOFOLLOW);
363 }
364 let file = options.open(path)?;
365 #[cfg(unix)]
366 ensure_stream_handle(&file, path)?;
367 Ok(file)
368}
369
370#[cfg(windows)]
372fn open_null_device() -> io::Result<File> {
373 std::fs::OpenOptions::new()
374 .write(true)
375 .open(WINDOWS_NULL_DEVICE)
376}
377
378#[cfg(not(windows))]
380fn open_null_device() -> io::Result<File> {
381 Err(io::Error::new(
382 io::ErrorKind::Unsupported,
383 "only Windows has a null device name",
384 ))
385}
386
387#[cfg(unix)]
389fn ensure_stream_handle(file: &File, path: &Path) -> io::Result<()> {
390 use std::os::unix::fs::FileTypeExt;
391 let file_type = file.metadata()?.file_type();
392 if file_type.is_char_device() || file_type.is_fifo() {
393 return Ok(());
394 }
395 Err(io::Error::new(
396 io::ErrorKind::PermissionDenied,
397 format!(
398 "{} is no longer a device or a named pipe, so fallow did not write it",
399 path.display()
400 ),
401 ))
402}
403
404fn open_no_follow(path: &Path) -> io::Result<File> {
408 let mut options = std::fs::OpenOptions::new();
409 options.write(true).create(true).truncate(true);
410 #[cfg(unix)]
411 {
412 use std::os::unix::fs::OpenOptionsExt;
413 options.custom_flags(libc::O_NOFOLLOW);
414 }
415 #[cfg(not(unix))]
418 if path
419 .symlink_metadata()
420 .is_ok_and(|meta| meta.file_type().is_symlink())
421 {
422 return Err(io::Error::new(
423 io::ErrorKind::PermissionDenied,
424 format!(
425 "{} became a symlink after fallow checked it, so fallow did not write it",
426 path.display()
427 ),
428 ));
429 }
430 options.open(path)
431}
432
433const MAX_LINK_HOPS: usize = 40;
435
436#[must_use]
441pub fn resolve(path: &Path) -> PathBuf {
442 resolve_with_hops(path, 0)
443}
444
445fn resolve_with_hops(path: &Path, hops: usize) -> PathBuf {
446 let mut existing = path;
447 let mut missing = Vec::new();
448 loop {
449 if let Ok(real) = existing.canonicalize() {
450 return append_missing(real, &missing);
451 }
452 if hops < MAX_LINK_HOPS
453 && let Ok(target) = std::fs::read_link(existing)
454 {
455 let base = existing.parent().unwrap_or_else(|| Path::new(""));
456 let followed = resolve_with_hops(&base.join(target), hops + 1);
457 return append_missing(followed, &missing);
458 }
459 let (Some(parent), Some(last)) = (existing.parent(), existing.components().next_back())
460 else {
461 return append_missing(PathBuf::new(), &missing);
462 };
463 missing.push(last);
464 existing = parent;
465 }
466}
467
468fn append_missing(mut resolved: PathBuf, missing: &[Component<'_>]) -> PathBuf {
470 for component in missing.iter().rev() {
471 match component {
472 Component::ParentDir => {
473 resolved.pop();
474 }
475 Component::CurDir => {}
476 other => resolved.push(other.as_os_str()),
477 }
478 }
479 resolved
480}
481
482#[cfg(test)]
483mod tests {
484 use std::path::Path;
485
486 use super::{WriteScope, create_checked, names_windows_null_device, resolve};
487
488 #[cfg(unix)]
492 #[test]
493 fn scope_accepts_the_unix_system_temp_dir_when_tmpdir_names_another_folder() {
494 use super::shared_dirs_for;
495
496 let project = tempfile::tempdir().expect("project dir");
497 let other_temp = tempfile::tempdir().expect("temp dir");
498 let scope = WriteScope::new(
499 project.path(),
500 project.path(),
501 shared_dirs_for(other_temp.path().to_path_buf()),
502 )
503 .expect("scope");
504 assert_eq!(
505 scope.check("--save-baseline", Path::new("/tmp/x.json"), project.path()),
506 None
507 );
508 }
509
510 #[test]
514 fn the_windows_null_device_is_named_by_nul_alone() {
515 for name in [
516 "NUL", "nul", "Nul", "NUL:", r"\\.\NUL", r"\\.\nul", "//./NUL",
517 ] {
518 assert!(names_windows_null_device(Path::new(name)), "{name}");
519 }
520 for name in [
521 "NUL.txt",
522 "nul.sarif",
523 "null",
524 "NULL",
525 "report",
526 r"dir\NUL",
527 "dir/nul",
528 r".\NUL",
529 r"C:\NUL",
530 "",
531 ] {
532 assert!(!names_windows_null_device(Path::new(name)), "{name}");
533 }
534 }
535
536 #[test]
537 fn resolve_normalises_the_missing_part() {
538 let dir = tempfile::tempdir().expect("temp dir");
539 let base = dir.path().canonicalize().unwrap();
540 assert_eq!(
541 resolve(&base.join("a/b/../c.json")),
542 base.join("a").join("c.json")
543 );
544 assert_eq!(
545 resolve(&base.join("a/../../x.json")),
546 base.parent().unwrap().join("x.json")
547 );
548 }
549
550 #[cfg(unix)]
551 #[test]
552 fn a_dangling_link_resolves_to_its_target() {
553 let dir = tempfile::tempdir().expect("temp dir");
554 let base = dir.path().canonicalize().unwrap();
555 let root = base.join("project");
556 std::fs::create_dir_all(&root).unwrap();
557 std::os::unix::fs::symlink(base.join("elsewhere.json"), root.join("b.json")).unwrap();
558 assert_eq!(resolve(&root.join("b.json")), base.join("elsewhere.json"));
559 }
560
561 #[test]
562 fn scope_accepts_a_temp_dir_through_a_symlinked_spelling() {
563 let dir = tempfile::tempdir().expect("temp dir");
564 let root = dir.path().join("project");
565 let temp = dir.path().join("temp");
566 std::fs::create_dir_all(&root).unwrap();
567 std::fs::create_dir_all(&temp).unwrap();
568 let scope =
569 WriteScope::new(&root, &root, vec![temp.canonicalize().unwrap()]).expect("scope");
570 assert!(
573 scope
574 .check("--save-baseline", &temp.join("b.json"), &root)
575 .is_none()
576 );
577 assert!(
578 scope
579 .check("--save-baseline", &dir.path().join("b.json"), &root)
580 .is_some()
581 );
582 }
583
584 #[test]
585 fn a_root_that_cannot_be_resolved_fails_closed() {
586 let dir = tempfile::tempdir().expect("temp dir");
587 let missing = dir.path().join("missing");
588 assert!(WriteScope::new(&missing, dir.path(), Vec::new()).is_err());
589 }
590
591 #[test]
592 fn the_work_tree_needs_the_working_directory_inside_it() {
593 let dir = tempfile::tempdir().expect("temp dir");
594 let home = dir.path().join("home");
595 let root = home.join("project");
596 let elsewhere = dir.path().join("elsewhere");
597 std::fs::create_dir_all(&root).unwrap();
598 std::fs::create_dir_all(&elsewhere).unwrap();
599 std::fs::create_dir_all(home.join(".git")).unwrap();
600 let target = home.join(".config").join("x.json");
601 let from_outside = WriteScope::new(&root, &elsewhere, Vec::new()).expect("scope");
602 assert!(
603 from_outside
604 .check("--save-baseline", &target, &elsewhere)
605 .is_some()
606 );
607 let from_inside = WriteScope::new(&root, &home, Vec::new()).expect("scope");
608 assert!(
609 from_inside
610 .check("--save-baseline", &target, &home)
611 .is_none()
612 );
613 }
614
615 #[test]
616 fn scope_accepts_the_root_and_rejects_a_sibling() {
617 let dir = tempfile::tempdir().expect("temp dir");
618 let root = dir.path().join("project");
619 std::fs::create_dir_all(&root).unwrap();
620 let scope = WriteScope::new(&root, &root, Vec::new()).expect("scope");
621 assert!(
622 scope
623 .check("--save-baseline", "nested/b.json".as_ref(), &root)
624 .is_none()
625 );
626 let message = scope
627 .check("--save-baseline", "../b.json".as_ref(), &root)
628 .expect("outside");
629 assert!(message.contains("outside the project root"), "{message}");
630 }
631
632 #[test]
633 fn scope_accepts_the_git_work_tree_of_the_root() {
634 let dir = tempfile::tempdir().expect("temp dir");
635 let repo = dir.path().join("repo");
636 let root = repo.join("packages/app");
637 std::fs::create_dir_all(&root).unwrap();
638 std::fs::create_dir_all(repo.join(".git")).unwrap();
639 let scope = WriteScope::new(&root, &repo, Vec::new()).expect("scope");
640 assert!(
641 scope
642 .check("--save-baseline", "baselines/b.json".as_ref(), &repo)
643 .is_none()
644 );
645 let message = scope
646 .check("--save-baseline", "../b.json".as_ref(), &repo)
647 .expect("outside");
648 assert!(message.contains("Git work tree"), "{message}");
649 }
650
651 #[test]
652 fn a_checked_write_lands_inside_the_scope() {
653 let dir = tempfile::tempdir().expect("temp dir");
654 let root = dir.path().join("project");
655 std::fs::create_dir_all(&root).unwrap();
656 let scope = WriteScope::new(&root, &root, Vec::new()).expect("scope");
657 let target = root.join("out/nested/report.json");
658 assert!(scope.check("--output-file", &target, &root).is_none());
659 let file = create_checked(&target, &target, Some(&scope)).expect("write inside");
660 drop(file);
661 assert!(target.is_file());
662 }
663
664 #[cfg(unix)]
666 #[test]
667 fn a_character_device_is_allowed_outside_the_scope() {
668 let dir = tempfile::tempdir().expect("temp dir");
669 let root = dir.path().join("project");
670 std::fs::create_dir_all(&root).unwrap();
671 let scope = WriteScope::new(&root, &root, Vec::new()).expect("scope");
672 let null = std::path::Path::new("/dev/null");
673 assert!(scope.check("--output-file", null, &root).is_none());
674 let file = create_checked(null, null, Some(&scope)).expect("write to /dev/null");
675 drop(file);
676 }
677
678 #[cfg(unix)]
681 #[test]
682 fn a_named_pipe_is_allowed_outside_the_scope() {
683 use std::io::Write as _;
684 let dir = tempfile::tempdir().expect("temp dir");
685 let root = dir.path().join("project");
686 std::fs::create_dir_all(&root).unwrap();
687 let fifo = dir.path().join("report.fifo");
688 let made = std::process::Command::new("mkfifo")
689 .arg(&fifo)
690 .status()
691 .expect("run mkfifo");
692 assert!(made.success());
693 let scope = WriteScope::new(&root, &root, Vec::new()).expect("scope");
694 assert!(scope.check("--sarif-file", &fifo, &root).is_none());
695 let reader_path = fifo.clone();
696 let reader = std::thread::spawn(move || std::fs::read_to_string(reader_path));
697 let mut file = create_checked(&fifo, &fifo, Some(&scope)).expect("write to fifo");
698 file.write_all(b"sarif").unwrap();
699 drop(file);
700 assert_eq!(reader.join().unwrap().unwrap(), "sarif");
701 }
702
703 #[cfg(unix)]
706 #[test]
707 fn a_stream_target_swapped_after_the_check_is_refused() {
708 use super::{ensure_stream_handle, open_stream};
709 let dir = tempfile::tempdir().expect("temp dir");
710 let link = dir.path().join("null-link");
711 std::os::unix::fs::symlink("/dev/null", &link).unwrap();
712 assert!(open_stream(&link).is_err(), "a symlink is not followed");
713
714 let regular = dir.path().join("regular.json");
715 std::fs::write(®ular, "keep").unwrap();
716 assert!(open_stream(®ular).is_err(), "a regular file is refused");
717 let handle = std::fs::File::open(®ular).unwrap();
718 assert!(ensure_stream_handle(&handle, ®ular).is_err());
719 assert_eq!(std::fs::read_to_string(®ular).unwrap(), "keep");
720
721 let null = std::fs::File::open("/dev/null").unwrap();
722 assert!(ensure_stream_handle(&null, std::path::Path::new("/dev/null")).is_ok());
723 }
724
725 #[cfg(unix)]
728 #[test]
729 fn a_directory_swapped_for_a_symlink_after_the_check_is_refused() {
730 let dir = tempfile::tempdir().expect("temp dir");
731 let root = dir.path().join("project");
732 let elsewhere = dir.path().join("elsewhere");
733 std::fs::create_dir_all(root.join("out")).unwrap();
734 std::fs::create_dir_all(&elsewhere).unwrap();
735 let scope = WriteScope::new(&root, &root, Vec::new()).expect("scope");
736 let target = root.join("out/report.json");
737 assert!(scope.check("--output-file", &target, &root).is_none());
738
739 std::fs::remove_dir(root.join("out")).unwrap();
740 std::os::unix::fs::symlink(&elsewhere, root.join("out")).unwrap();
741
742 let error = std::io::Error::from(
743 create_checked(&target, &target, Some(&scope)).expect_err("refused"),
744 );
745 assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
746 assert!(!elsewhere.join("report.json").exists());
747 }
748
749 #[cfg(unix)]
752 #[test]
753 fn a_file_swapped_for_a_symlink_after_the_check_is_refused() {
754 let dir = tempfile::tempdir().expect("temp dir");
755 let root = dir.path().join("project");
756 std::fs::create_dir_all(&root).unwrap();
757 let outside = dir.path().join("outside.json");
758 let scope = WriteScope::new(&root, &root, Vec::new()).expect("scope");
759 let target = root.join("report.json");
760 assert!(scope.check("--output-file", &target, &root).is_none());
761
762 std::os::unix::fs::symlink(&outside, &target).unwrap();
763
764 assert!(create_checked(&target, &target, Some(&scope)).is_err());
765 assert!(!outside.exists());
766 }
767
768 #[cfg(unix)]
771 #[test]
772 fn the_open_does_not_follow_a_final_symlink() {
773 let dir = tempfile::tempdir().expect("temp dir");
774 let real = dir.path().join("real.json");
775 std::fs::write(&real, "keep").unwrap();
776 let link = dir.path().join("link.json");
777 std::os::unix::fs::symlink(&real, &link).unwrap();
778
779 assert!(super::open_no_follow(&link).is_err());
780 assert_eq!(std::fs::read_to_string(&real).unwrap(), "keep");
781 }
782}