use std::path::{Component, Path, PathBuf};
#[must_use]
pub fn outside_link(base: &Path, path: &Path) -> Option<PathBuf> {
let Ok(relative) = path.strip_prefix(base) else {
return Some(path.to_path_buf());
};
let Ok(canonical_base) = std::fs::canonicalize(base) else {
return Some(path.to_path_buf());
};
let mut current = base.to_path_buf();
for component in relative.components() {
let Component::Normal(name) = component else {
return Some(path.to_path_buf());
};
current.push(name);
match current.symlink_metadata() {
Ok(meta) if meta.file_type().is_symlink() => {
let inside = std::fs::canonicalize(¤t)
.is_ok_and(|resolved| resolved.starts_with(&canonical_base));
if !inside {
return Some(current);
}
}
Ok(_) => {}
Err(_) => return None,
}
}
None
}
#[must_use]
pub fn cache_write_base<'a>(root: &'a Path, cache_dir: &'a Path) -> &'a Path {
if lexically_normalized(cache_dir).starts_with(root) {
root
} else {
cache_dir
}
}
#[must_use]
pub fn lexically_normalized(path: &Path) -> PathBuf {
let mut normalized = PathBuf::new();
for component in path.components() {
match component {
Component::CurDir => {}
Component::ParentDir => {
normalized.pop();
}
other => normalized.push(other),
}
}
normalized
}
pub fn ensure_no_outside_link(base: &Path, path: &Path) -> std::io::Result<()> {
if base.symlink_metadata().is_err() {
return Ok(());
}
match outside_link(base, path) {
None => Ok(()),
Some(link) => Err(std::io::Error::new(
std::io::ErrorKind::PermissionDenied,
format!(
"refusing to write {}: {} is a symlink that resolves outside {}",
path.display(),
link.display(),
base.display()
),
)),
}
}
#[derive(Clone, Copy, Debug)]
pub struct CacheTarget<'a> {
dir: &'a Path,
write_base: &'a Path,
}
impl<'a> CacheTarget<'a> {
#[must_use]
pub fn new(root: &'a Path, dir: &'a Path) -> Self {
Self {
dir,
write_base: cache_write_base(root, dir),
}
}
#[must_use]
pub const fn inside(dir: &'a Path) -> Self {
Self {
dir,
write_base: dir,
}
}
#[must_use]
pub const fn dir(&self) -> &'a Path {
self.dir
}
#[must_use]
pub const fn with_dir(&self, dir: &'a Path) -> Self {
Self {
dir,
write_base: self.write_base,
}
}
pub fn check(&self, path: &Path) -> std::io::Result<()> {
ensure_no_outside_link(self.write_base, path)
}
pub fn write_file(&self, name: &str, data: &[u8]) -> std::io::Result<()> {
let path = self.dir.join(name);
self.check(&path)?;
std::fs::create_dir_all(self.dir)?;
crate::atomic_file::write_atomic(&path, data)
}
pub fn write_gitignore(&self) -> std::io::Result<()> {
let path = self.dir.join(".gitignore");
self.check(&path)?;
if std::fs::read(&path).is_ok_and(|content| content == b"*\n") {
return Ok(());
}
self.write_file(".gitignore", b"*\n")
}
}
#[cfg(all(test, unix, not(miri)))]
mod tests {
use super::*;
use std::os::unix::fs::symlink;
struct Fixture {
_dir: tempfile::TempDir,
root: PathBuf,
outside: PathBuf,
}
fn fixture() -> Fixture {
let dir = tempfile::tempdir().expect("tempdir");
let root = dir.path().join("project");
let outside = dir.path().join("outside");
std::fs::create_dir_all(&root).expect("root");
std::fs::create_dir_all(&outside).expect("outside");
Fixture {
_dir: dir,
root,
outside,
}
}
#[test]
fn a_plain_path_passes() {
let f = fixture();
let path = f.root.join(".fallow/cache/x/cache.bin");
assert_eq!(outside_link(&f.root, &path), None);
assert!(ensure_no_outside_link(&f.root, &path).is_ok());
}
#[test]
fn a_linked_cache_dir_is_refused() {
let f = fixture();
symlink(&f.outside, f.root.join(".fallow")).expect("link");
let path = f.root.join(".fallow/.gitignore");
assert_eq!(outside_link(&f.root, &path), Some(f.root.join(".fallow")));
let error = ensure_no_outside_link(&f.root, &path).expect_err("refused");
assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
}
#[test]
fn a_dangling_file_link_is_refused() {
let f = fixture();
std::fs::create_dir_all(f.root.join(".fallow")).expect("cache");
let link = f.root.join(".fallow/.gitignore");
symlink(f.outside.join("missing"), &link).expect("link");
assert_eq!(outside_link(&f.root, &link), Some(link));
}
#[test]
fn a_link_inside_the_base_passes() {
let f = fixture();
std::fs::create_dir_all(f.root.join("build/cache")).expect("target");
symlink(f.root.join("build/cache"), f.root.join(".fallow")).expect("link");
assert_eq!(
outside_link(&f.root, &f.root.join(".fallow/cache.bin")),
None
);
}
#[test]
fn a_path_outside_the_base_is_refused() {
let f = fixture();
let path = f.outside.join("cache.bin");
assert_eq!(outside_link(&f.root, &path), Some(path));
}
#[test]
fn the_base_follows_where_the_cache_dir_is() {
let root = Path::new("/p");
assert_eq!(cache_write_base(root, Path::new("/p/.fallow")), root);
assert_eq!(
cache_write_base(root, Path::new("/ci/cache")),
Path::new("/ci/cache")
);
}
#[test]
fn a_target_writes_the_file_and_the_gitignore() {
let f = fixture();
let dir = f.root.join(".fallow/cache");
let target = CacheTarget::new(&f.root, &dir);
target.write_gitignore().expect("gitignore");
target.write_file("cache.bin", b"data").expect("file");
assert_eq!(std::fs::read(dir.join(".gitignore")).expect("read"), b"*\n");
assert_eq!(std::fs::read(dir.join("cache.bin")).expect("read"), b"data");
}
#[test]
fn a_target_refuses_a_linked_cache_dir_and_writes_nothing() {
let f = fixture();
symlink(&f.outside, f.root.join(".fallow")).expect("link");
let dir = f.root.join(".fallow");
let target = CacheTarget::new(&f.root, &dir);
assert!(target.write_gitignore().is_err());
assert!(target.write_file("cache.bin", b"data").is_err());
assert_eq!(std::fs::read_dir(&f.outside).expect("outside").count(), 0);
}
#[test]
fn a_target_refuses_a_dangling_gitignore_link() {
let f = fixture();
let dir = f.root.join(".fallow");
std::fs::create_dir_all(&dir).expect("cache");
symlink(f.outside.join("victim"), dir.join(".gitignore")).expect("link");
assert!(CacheTarget::new(&f.root, &dir).write_gitignore().is_err());
assert!(!f.outside.join("victim").exists());
}
#[test]
fn a_relative_cache_dir_above_the_root_is_its_own_base() {
let root = Path::new("/p/project");
let shared = Path::new("/p/project/../shared");
assert_eq!(cache_write_base(root, shared), shared);
let inside = Path::new("/p/project/sub/../.fallow");
assert_eq!(cache_write_base(root, inside), root);
}
#[test]
fn a_relative_cache_dir_above_the_root_gets_its_cache() {
let f = fixture();
let dir = f.root.join("../shared");
let target = CacheTarget::new(&f.root, &dir);
target.write_file("cache.bin", b"data").expect("file");
assert!(f.outside.join("../shared/cache.bin").exists());
}
#[test]
fn a_missing_base_passes_the_check() {
let f = fixture();
let base = f.outside.join("new");
assert!(ensure_no_outside_link(&base, &base.join("cache.bin")).is_ok());
}
#[test]
fn a_target_writes_into_a_new_cache_dir() {
let f = fixture();
let dir = f.outside.join("new/cache");
CacheTarget::inside(&dir)
.write_gitignore()
.expect("gitignore");
assert!(dir.join(".gitignore").exists());
}
#[test]
fn a_user_cache_dir_outside_the_root_is_checked_from_itself() {
let f = fixture();
let target = CacheTarget::new(&f.root, &f.outside);
target.write_file("cache.bin", b"data").expect("file");
assert!(f.outside.join("cache.bin").exists());
}
}