fallow_types/
path_guard.rs1use std::path::{Component, Path, PathBuf};
9
10#[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(¤t)
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#[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#[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
77pub 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#[derive(Clone, Copy, Debug)]
111pub struct CacheTarget<'a> {
112 dir: &'a Path,
113 write_base: &'a Path,
114}
115
116impl<'a> CacheTarget<'a> {
117 #[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 #[must_use]
129 pub const fn inside(dir: &'a Path) -> Self {
130 Self {
131 dir,
132 write_base: dir,
133 }
134 }
135
136 #[must_use]
138 pub const fn dir(&self) -> &'a Path {
139 self.dir
140 }
141
142 #[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 pub fn check(&self, path: &Path) -> std::io::Result<()> {
158 ensure_no_outside_link(self.write_base, path)
159 }
160
161 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 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}