Skip to main content

fallow_types/
path_guard.rs

1//! Refuse writes through a symlink that leaves a trusted directory.
2//!
3//! A cloned repository can commit a symlink where fallow writes a file, for
4//! example `.fallow/.gitignore` or the `.fallow` directory itself. A write
5//! through that link reaches a file outside the project. A link that resolves
6//! inside the base directory is safe and stays allowed.
7
8use std::path::{Component, Path, PathBuf};
9
10/// The first entry below `base`, up to and including `path`, that is a
11/// symlink whose resolved target is outside the canonical `base`. A dangling
12/// link also counts, because its target can appear outside `base` later.
13/// A path outside `base`, one with a `..` or `.` component, or a `base` that
14/// does not resolve returns `path` itself. A missing entry ends the walk,
15/// because nothing below it exists yet.
16#[must_use]
17pub fn outside_link(base: &Path, path: &Path) -> Option<PathBuf> {
18    let Ok(relative) = path.strip_prefix(base) else {
19        return Some(path.to_path_buf());
20    };
21    let Ok(canonical_base) = std::fs::canonicalize(base) else {
22        return Some(path.to_path_buf());
23    };
24    let mut current = base.to_path_buf();
25    for component in relative.components() {
26        let Component::Normal(name) = component else {
27            return Some(path.to_path_buf());
28        };
29        current.push(name);
30        match current.symlink_metadata() {
31            Ok(meta) if meta.file_type().is_symlink() => {
32                let inside = std::fs::canonicalize(&current)
33                    .is_ok_and(|resolved| resolved.starts_with(&canonical_base));
34                if !inside {
35                    return Some(current);
36                }
37            }
38            Ok(_) => {}
39            Err(_) => return None,
40        }
41    }
42    None
43}
44
45/// The directory that cache writes must stay in. A cache directory inside the
46/// project root is checked from the root, so a committed `.fallow` link is
47/// refused. A cache directory outside the root comes from the user, such as
48/// `FALLOW_CACHE_DIR` on a CI runner, so only the entries below it are checked.
49/// A `..` in the cache directory is resolved by text first, so
50/// `cache.dir: "../shared"` counts as a directory outside the root.
51#[must_use]
52pub fn cache_write_base<'a>(root: &'a Path, cache_dir: &'a Path) -> &'a Path {
53    if lexically_normalized(cache_dir).starts_with(root) {
54        root
55    } else {
56        cache_dir
57    }
58}
59
60/// `path` with each `..` applied to the component before it, and each `.`
61/// dropped, without a file system read.
62#[must_use]
63pub fn lexically_normalized(path: &Path) -> PathBuf {
64    let mut normalized = PathBuf::new();
65    for component in path.components() {
66        match component {
67            Component::CurDir => {}
68            Component::ParentDir => {
69                normalized.pop();
70            }
71            other => normalized.push(other),
72        }
73    }
74    normalized
75}
76
77/// Fail when a write to `path` would follow a symlink that leaves `base`.
78///
79/// Call this before each create, write, rename or delete under a cache
80/// directory, with the base from [`cache_write_base`]. A base that does not
81/// exist yet has no link below it, so the first save into a new cache
82/// directory passes. A dangling link at the base itself exists, so it is
83/// still checked.
84///
85/// # Errors
86///
87/// Returns a `PermissionDenied` error that names the link.
88pub fn ensure_no_outside_link(base: &Path, path: &Path) -> std::io::Result<()> {
89    if base.symlink_metadata().is_err() {
90        return Ok(());
91    }
92    match outside_link(base, path) {
93        None => Ok(()),
94        Some(link) => Err(std::io::Error::new(
95            std::io::ErrorKind::PermissionDenied,
96            format!(
97                "refusing to write {}: {} is a symlink that resolves outside {}",
98                path.display(),
99                link.display(),
100                base.display()
101            ),
102        )),
103    }
104}
105
106/// A cache directory and the directory that its writes must stay in.
107///
108/// Every cache writer takes this type instead of a bare directory, so a
109/// writer cannot skip the symlink check.
110#[derive(Clone, Copy, Debug)]
111pub struct CacheTarget<'a> {
112    dir: &'a Path,
113    write_base: &'a Path,
114}
115
116impl<'a> CacheTarget<'a> {
117    /// The cache directory `dir` of the project at `root`.
118    #[must_use]
119    pub fn new(root: &'a Path, dir: &'a Path) -> Self {
120        Self {
121            dir,
122            write_base: cache_write_base(root, dir),
123        }
124    }
125
126    /// A cache directory that is its own base, such as a directory that the
127    /// user chose.
128    #[must_use]
129    pub const fn inside(dir: &'a Path) -> Self {
130        Self {
131            dir,
132            write_base: dir,
133        }
134    }
135
136    /// The cache directory.
137    #[must_use]
138    pub const fn dir(&self) -> &'a Path {
139        self.dir
140    }
141
142    /// The same base with `dir` as the cache directory, for a subdirectory.
143    #[must_use]
144    pub const fn with_dir(&self, dir: &'a Path) -> Self {
145        Self {
146            dir,
147            write_base: self.write_base,
148        }
149    }
150
151    /// Fail when a write to `path` would follow a symlink that leaves the
152    /// base.
153    ///
154    /// # Errors
155    ///
156    /// Returns the error of [`ensure_no_outside_link`].
157    pub fn check(&self, path: &Path) -> std::io::Result<()> {
158        ensure_no_outside_link(self.write_base, path)
159    }
160
161    /// Create the cache directory and replace the file `name` in it with
162    /// `data` through [`crate::atomic_file::write_atomic`], after the
163    /// symlink check.
164    ///
165    /// # Errors
166    ///
167    /// Returns the error of the check, of the directory creation, or of the
168    /// write.
169    pub fn write_file(&self, name: &str, data: &[u8]) -> std::io::Result<()> {
170        let path = self.dir.join(name);
171        self.check(&path)?;
172        std::fs::create_dir_all(self.dir)?;
173        crate::atomic_file::write_atomic(&path, data)
174    }
175
176    /// Write `.gitignore` with `*`, so the cache directory is never
177    /// committed. An equal file stays as it is.
178    ///
179    /// # Errors
180    ///
181    /// Returns the error of [`Self::write_file`].
182    pub fn write_gitignore(&self) -> std::io::Result<()> {
183        let path = self.dir.join(".gitignore");
184        self.check(&path)?;
185        if std::fs::read(&path).is_ok_and(|content| content == b"*\n") {
186            return Ok(());
187        }
188        self.write_file(".gitignore", b"*\n")
189    }
190}
191
192#[cfg(all(test, unix, not(miri)))]
193mod tests {
194    use super::*;
195    use std::os::unix::fs::symlink;
196
197    struct Fixture {
198        _dir: tempfile::TempDir,
199        root: PathBuf,
200        outside: PathBuf,
201    }
202
203    fn fixture() -> Fixture {
204        let dir = tempfile::tempdir().expect("tempdir");
205        let root = dir.path().join("project");
206        let outside = dir.path().join("outside");
207        std::fs::create_dir_all(&root).expect("root");
208        std::fs::create_dir_all(&outside).expect("outside");
209        Fixture {
210            _dir: dir,
211            root,
212            outside,
213        }
214    }
215
216    #[test]
217    fn a_plain_path_passes() {
218        let f = fixture();
219        let path = f.root.join(".fallow/cache/x/cache.bin");
220        assert_eq!(outside_link(&f.root, &path), None);
221        assert!(ensure_no_outside_link(&f.root, &path).is_ok());
222    }
223
224    #[test]
225    fn a_linked_cache_dir_is_refused() {
226        let f = fixture();
227        symlink(&f.outside, f.root.join(".fallow")).expect("link");
228        let path = f.root.join(".fallow/.gitignore");
229        assert_eq!(outside_link(&f.root, &path), Some(f.root.join(".fallow")));
230        let error = ensure_no_outside_link(&f.root, &path).expect_err("refused");
231        assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
232    }
233
234    #[test]
235    fn a_dangling_file_link_is_refused() {
236        let f = fixture();
237        std::fs::create_dir_all(f.root.join(".fallow")).expect("cache");
238        let link = f.root.join(".fallow/.gitignore");
239        symlink(f.outside.join("missing"), &link).expect("link");
240        assert_eq!(outside_link(&f.root, &link), Some(link));
241    }
242
243    #[test]
244    fn a_link_inside_the_base_passes() {
245        let f = fixture();
246        std::fs::create_dir_all(f.root.join("build/cache")).expect("target");
247        symlink(f.root.join("build/cache"), f.root.join(".fallow")).expect("link");
248        assert_eq!(
249            outside_link(&f.root, &f.root.join(".fallow/cache.bin")),
250            None
251        );
252    }
253
254    #[test]
255    fn a_path_outside_the_base_is_refused() {
256        let f = fixture();
257        let path = f.outside.join("cache.bin");
258        assert_eq!(outside_link(&f.root, &path), Some(path));
259    }
260
261    #[test]
262    fn the_base_follows_where_the_cache_dir_is() {
263        let root = Path::new("/p");
264        assert_eq!(cache_write_base(root, Path::new("/p/.fallow")), root);
265        assert_eq!(
266            cache_write_base(root, Path::new("/ci/cache")),
267            Path::new("/ci/cache")
268        );
269    }
270
271    #[test]
272    fn a_target_writes_the_file_and_the_gitignore() {
273        let f = fixture();
274        let dir = f.root.join(".fallow/cache");
275        let target = CacheTarget::new(&f.root, &dir);
276        target.write_gitignore().expect("gitignore");
277        target.write_file("cache.bin", b"data").expect("file");
278        assert_eq!(std::fs::read(dir.join(".gitignore")).expect("read"), b"*\n");
279        assert_eq!(std::fs::read(dir.join("cache.bin")).expect("read"), b"data");
280    }
281
282    #[test]
283    fn a_target_refuses_a_linked_cache_dir_and_writes_nothing() {
284        let f = fixture();
285        symlink(&f.outside, f.root.join(".fallow")).expect("link");
286        let dir = f.root.join(".fallow");
287        let target = CacheTarget::new(&f.root, &dir);
288        assert!(target.write_gitignore().is_err());
289        assert!(target.write_file("cache.bin", b"data").is_err());
290        assert_eq!(std::fs::read_dir(&f.outside).expect("outside").count(), 0);
291    }
292
293    #[test]
294    fn a_target_refuses_a_dangling_gitignore_link() {
295        let f = fixture();
296        let dir = f.root.join(".fallow");
297        std::fs::create_dir_all(&dir).expect("cache");
298        symlink(f.outside.join("victim"), dir.join(".gitignore")).expect("link");
299        assert!(CacheTarget::new(&f.root, &dir).write_gitignore().is_err());
300        assert!(!f.outside.join("victim").exists());
301    }
302
303    #[test]
304    fn a_relative_cache_dir_above_the_root_is_its_own_base() {
305        let root = Path::new("/p/project");
306        let shared = Path::new("/p/project/../shared");
307        assert_eq!(cache_write_base(root, shared), shared);
308        let inside = Path::new("/p/project/sub/../.fallow");
309        assert_eq!(cache_write_base(root, inside), root);
310    }
311
312    #[test]
313    fn a_relative_cache_dir_above_the_root_gets_its_cache() {
314        let f = fixture();
315        let dir = f.root.join("../shared");
316        let target = CacheTarget::new(&f.root, &dir);
317        target.write_file("cache.bin", b"data").expect("file");
318        assert!(f.outside.join("../shared/cache.bin").exists());
319    }
320
321    #[test]
322    fn a_missing_base_passes_the_check() {
323        let f = fixture();
324        let base = f.outside.join("new");
325        assert!(ensure_no_outside_link(&base, &base.join("cache.bin")).is_ok());
326    }
327
328    #[test]
329    fn a_target_writes_into_a_new_cache_dir() {
330        let f = fixture();
331        let dir = f.outside.join("new/cache");
332        CacheTarget::inside(&dir)
333            .write_gitignore()
334            .expect("gitignore");
335        assert!(dir.join(".gitignore").exists());
336    }
337
338    #[test]
339    fn a_user_cache_dir_outside_the_root_is_checked_from_itself() {
340        let f = fixture();
341        let target = CacheTarget::new(&f.root, &f.outside);
342        target.write_file("cache.bin", b"data").expect("file");
343        assert!(f.outside.join("cache.bin").exists());
344    }
345}