diff --git a/crates/format/src/atomic.rs b/crates/format/src/atomic.rs index d759ff6d9f..dd0cd4cc6c 100644 --- a/crates/format/src/atomic.rs +++ b/crates/format/src/atomic.rs @@ -89,13 +89,15 @@ fn create_new(path: &Path) -> io::Result { /// and none of them looks its path up again. A folder replaced (or swapped for a link) before it is /// opened fails `allowed`. A folder replaced after it is opened does not receive the file. A link at /// the final name is followed once before the folder is opened, as [`write_atomic_with`] follows it; -/// a link put there later is replaced, never followed. Elsewhere this is `allowed(path)` followed by +/// a link put there later is replaced, never followed. A folder that moved after it was opened is +/// checked with `allowed` again at its new path right before the file is put in place, and a folder +/// whose new path the system does not report fails. Elsewhere this is `allowed(path)` followed by /// [`write_atomic_with`]. #[cfg(unix)] pub fn write_atomic_checked( path: &Path, fill: impl FnOnce(&mut File) -> io::Result<()>, - allowed: impl FnOnce(&Path) -> io::Result<()>, + allowed: impl Fn(&Path) -> io::Result<()>, ) -> io::Result<()> { use rustix::fs::{AtFlags, Mode, OFlags}; // A path written as a folder (`draft.svg/`, `draft.svg/.`) is not a file path: `file_name` @@ -126,6 +128,24 @@ pub fn write_atomic_checked( }; // The folder may have moved since it was opened: messages name it where it is now. let now = |file: &std::ffi::OsStr| folder_now(&dir, &real).join(file); + // Right before the file is put in place: a folder that moved since it was opened is checked + // again where it is now, so a move out of the allowed folders does not receive the file. + let still_allowed = || -> io::Result<()> { + let here = folder_now(&dir, &real); + let open = rustix::fs::fstat(&dir)?; + // The path itself, not a link that leads to the folder from elsewhere. + let same = |p: &Path| { + std::fs::canonicalize(p).is_ok_and(|c| c == p) && rustix::fs::stat(p).is_ok_and(|s| (s.st_dev, s.st_ino) == (open.st_dev, open.st_ino)) + }; + if here == real && same(&real) { + return Ok(()); + } + if here == real || !same(&here) { + return Err(io::Error::other(format!("{}: the folder moved while the file was written", target.display()))); + } + allowed(&here.join(stored_name(&dir, &here, &name))) + .map_err(|_| io::Error::other(format!("{}: the folder moved while the file was written", target.display()))) + }; let synced = || { // Opened for reading here: the folder handle above may allow name lookups only. let flushed = @@ -133,13 +153,21 @@ pub fn write_atomic_checked( flushed.map_err(|e| io::Error::new(io::Error::from(e).kind(), WrittenError { path: now(&name), error: e.into() })) }; let open_target = |write: bool| -> io::Result { + // A missing target is created by `create_target`, after the last check. An existing one is + // opened with `O_CREAT` as before, so Linux's `fs.protected_regular` still applies to it. + if write && matches!(rustix::fs::statat(&dir, &name, AtFlags::SYMLINK_NOFOLLOW), Err(e) if e == rustix::io::Errno::NOENT) { + return Err(io::ErrorKind::NotFound.into()); + } let flags = if write { OFlags::WRONLY | OFlags::CREATE } else { OFlags::RDONLY }; Ok(File::from(rustix::fs::openat(&dir, &name, flags | OFlags::NOFOLLOW | OFlags::CLOEXEC, mode)?)) }; + let create_target = || -> io::Result { Ok(File::from(rustix::fs::openat(&dir, &name, new_file, mode)?)) }; match rustix::fs::openat(&dir, &tmp_name, new_file, mode).map(File::from) { Ok(mut f) => { let filled = fill(&mut f).and_then(|()| sync_file(&f)).and_then(|()| not_cancelled()); - if let Err(e) = filled { + // Checked before the temporary file takes the old file's wider permissions, and again + // right before the rename. + if let Err(e) = filled.and_then(|()| still_allowed()) { drop(f); remove_tmp(); return Err(e); @@ -151,6 +179,10 @@ pub fn write_atomic_checked( let _ = keep_permissions_at(&dir, &name, &old, &f); } drop(f); + if let Err(e) = still_allowed() { + remove_tmp(); + return Err(e); + } #[cfg(test)] let refuse = RENAME_REFUSED.with(std::cell::Cell::get); #[cfg(not(test))] @@ -189,7 +221,9 @@ pub fn write_atomic_checked( }, remove_tmp: &remove_tmp, open_target: &open_target, + create_target: &create_target, synced: &synced, + still_allowed: &still_allowed, }; write_over_in(&over, refused.into()) } @@ -207,7 +241,7 @@ pub fn write_atomic_checked( // Best effort: the temporary file is all there is to clean up. let _ = std::fs::remove_file(&elsewhere); }; - if let Err(e) = filled { + if let Err(e) = filled.and_then(|()| still_allowed()) { remove(); return Err(e); } @@ -222,7 +256,9 @@ pub fn write_atomic_checked( open_tmp: &|| File::open(&elsewhere), remove_tmp: &remove, open_target: &open_target, + create_target: &create_target, synced: &synced, + still_allowed: &still_allowed, }; write_over_in(&over, refused.into()) } @@ -422,7 +458,10 @@ fn write_over(tmp: &Path, target: &Path, refused: io::Error) -> io::Result<()> { let _ = std::fs::remove_file(tmp); }, open_target: &|write| if write { OpenOptions::new().write(true).create(true).truncate(false).open(target) } else { File::open(target) }, + #[cfg(unix)] + create_target: &|| create_new(target), synced: &|| sync_written_parent(target), + still_allowed: &|| Ok(()), }; write_over_in(&over, refused) } @@ -441,38 +480,92 @@ struct Over<'a> { open_tmp: &'a dyn Fn() -> io::Result, /// Best effort. remove_tmp: &'a dyn Fn(), - /// The target for writing (created when missing, not truncated) when `true`, for reading when - /// `false`. + /// Opens the target without truncating it for writing when `true`, or for reading when `false`. + /// Checked Unix writes defer creation of a missing target to `create_target`. open_target: &'a dyn Fn(bool) -> io::Result, + /// Creates a missing target after the final check and fails if its name is taken. + #[cfg(unix)] + create_target: &'a dyn Fn() -> io::Result, /// The target's folder flushed, after the target is written. synced: &'a dyn Fn() -> io::Result<()>, + /// Asked right before the target is overwritten: an error leaves it as it was. + still_allowed: &'a dyn Fn() -> io::Result<()>, } /// [`write_over`] through `over`. fn write_over_in(over: &Over<'_>, refused: io::Error) -> io::Result<()> { - let opened = (over.open_tmp)().and_then(|from| Ok((from, (over.open_target)(true)?))); - let Ok((mut from, mut to)) = opened else { + // Checked Unix writes create a missing target only after the final check. + if let Err(e) = (over.still_allowed)() { + (over.remove_tmp)(); + return Err(e); + } + let opened = (over.open_tmp)().and_then(|from| { + let to = match (over.open_target)(true) { + Ok(to) => Some(to), + #[cfg(unix)] + Err(e) if e.kind() == io::ErrorKind::NotFound => None, + Err(e) => return Err(e), + }; + Ok((from, to)) + }); + let Ok((mut from, to)) = opened else { // Best effort: the temporary file is all there is to clean up. (over.remove_tmp)(); return Err(refused); }; // Nothing to keep of a file that is new or empty. The copy is read from the file `to` writes // into: one put at its name meanwhile is not copied in its place. - let kept = to.metadata().map_or(true, |m| m.len() > 0); + let kept = to.as_ref().is_some_and(|to| to.metadata().map_or(true, |m| m.len() > 0)); if kept && let Err(e) = (over.open_target)(false).and_then(|mut target| { - if !same_file(&target, &to) { + if !to.as_ref().is_some_and(|to| same_file(&target, to)) { return Err(io::Error::other("the file was replaced while it was opened")); } keep_old(&mut target, over) }) { + #[cfg(unix)] + if let Err(e) = (over.still_allowed)() { + drop((from, to)); + (over.remove_tmp)(); + return Err(e); + } let why = format!( "{refused}, and the file can't be copied aside before it is overwritten ({e}); the new content is kept in {}", (over.tmp)().display() ); return Err(io::Error::new(refused.kind(), RecoveryError(why))); } + if let Err(e) = (over.still_allowed)() { + // Nothing was overwritten: neither copy is needed. + drop((from, to)); + (over.remove_tmp)(); + if kept { + (over.remove_old)(); + } + return Err(e); + } + let mut to = match to { + Some(to) => to, + #[cfg(unix)] + None => match (over.create_target)() { + Ok(to) => to, + // A file put at the name meanwhile is left alone, and reported as there. + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => { + (over.remove_tmp)(); + return Err(e); + } + Err(_) => { + (over.remove_tmp)(); + return Err(refused); + } + }, + #[cfg(not(unix))] + None => { + (over.remove_tmp)(); + return Err(refused); + } + }; let copied = to.set_len(0).and_then(|()| io::copy(&mut from, &mut to)).and_then(|_| sync_file(&to)); drop((from, to)); match (copied, kept) { @@ -826,8 +919,18 @@ mod tests { (d, root, outside) } + /// Whether this system says where an open folder is now: macOS always, Linux and Android through + /// `/proc/self/fd`, which a chroot may lack. Decided without `folder_now`. #[cfg(unix)] - fn under(root: &Path) -> impl FnOnce(&Path) -> io::Result<()> + '_ { + fn reports_open_folder_paths() -> bool { + if cfg!(target_vendor = "apple") { + return true; + } + cfg!(any(target_os = "linux", target_os = "android")) && Path::new("/proc/self/fd").is_dir() + } + + #[cfg(unix)] + fn under(root: &Path) -> impl Fn(&Path) -> io::Result<()> + '_ { move |p: &Path| if p.starts_with(root) { Ok(()) } else { Err(io::Error::other(format!("{} is outside", p.display()))) } } @@ -851,22 +954,51 @@ mod tests { #[test] fn a_checked_write_stays_in_the_folder_it_opened() { let (d, root, outside) = checked_folders("checked-after"); - let check = under(&root); let r = write_atomic_checked( &root.join("inside/doc.txt"), - |f| f.write_all(b"new"), - |p| { - check(p)?; + |f| { std::fs::rename(root.join("inside"), root.join("moved"))?; - std::os::unix::fs::symlink(&outside, root.join("inside")) + std::os::unix::fs::symlink(&outside, root.join("inside"))?; + f.write_all(b"new") }, + under(&root), ); + if !reports_open_folder_paths() { + assert!(r.as_ref().is_err_and(|e| e.to_string().contains("the folder moved")), "{r:?}"); + assert!(!outside.join("doc.txt").exists() && !root.join("moved/doc.txt").exists()); + assert!(std::fs::read_dir(root.join("moved")).unwrap().next().is_none()); + let _ = std::fs::remove_dir_all(d); + return; + } r.unwrap(); assert!(!outside.join("doc.txt").exists(), "the write followed the replaced folder"); assert_eq!(std::fs::read(root.join("moved/doc.txt")).unwrap(), b"new"); let _ = std::fs::remove_dir_all(d); } + /// A folder moved out of the allowed root while the file is written receives nothing: the move is + /// caught before the file is put in place, and the temporary file is removed. + #[cfg(unix)] + #[test] + fn a_checked_write_refuses_a_folder_moved_outside_while_it_fills() { + let (d, root, outside) = checked_folders("checked-moved-out"); + let r = write_atomic_checked( + &root.join("inside/doc.txt"), + |f| { + f.write_all(b"new")?; + std::fs::rename(root.join("inside"), outside.join("inside")) + }, + under(&root), + ); + assert!(r.as_ref().is_err_and(|e| !read_only_location(e)), "{r:?}"); + let message = r.unwrap_err().to_string(); + assert!(message.contains(&root.join("inside/doc.txt").display().to_string()), "{message}"); + assert!(message.contains("the folder moved"), "{message}"); + assert!(!message.contains(&outside.display().to_string()), "{message}"); + assert!(std::fs::read_dir(outside.join("inside")).unwrap().next().is_none(), "nothing is left outside"); + let _ = std::fs::remove_dir_all(d); + } + /// A link put at the file's name after the check is replaced by the file, not followed. #[cfg(unix)] #[test] @@ -922,31 +1054,34 @@ mod tests { let _ = std::fs::remove_dir_all(d); } - /// A checked write whose folder moved after it was opened, refused the rename, and failed to - /// copy into the file: the temporary file and the copy of the old content stay in that folder, - /// and the error names them where they are now. (FreeBSD does not say where an open folder is - /// now: there the error names them where the folder was opened.) + /// A failed fallback names the recovery files in the folder's current location when available. + /// A move is refused when the system cannot resolve the open folder's current path. #[cfg(unix)] #[test] fn a_checked_write_names_the_kept_file_where_its_folder_moved() { let (d, root, _) = checked_folders("checked-moved"); std::fs::write(root.join("inside/doc.txt"), b"original").unwrap(); - let check = under(&root); let r = write_atomic_checked( &root.join("inside/doc.txt"), - |f| f.write_all(b"new"), - |p| { - check(p)?; + |f| { std::fs::rename(root.join("inside"), root.join("moved"))?; RENAME_REFUSED.with(|c| c.set(true)); // The temporary file's flush and the copy of the old content work, the next doesn't. FLUSHES_LEFT.with(|c| c.set(Some(2))); - Ok(()) + f.write_all(b"new") }, + under(&root), ); RENAME_REFUSED.with(|c| c.set(false)); FLUSHES_LEFT.with(|c| c.set(None)); let message = r.unwrap_err().to_string(); + if !reports_open_folder_paths() { + assert!(message.contains("the folder moved"), "{message}"); + assert_eq!(std::fs::read(root.join("moved/doc.txt")).unwrap(), b"original"); + assert_eq!(std::fs::read_dir(root.join("moved")).unwrap().count(), 1); + let _ = std::fs::remove_dir_all(d); + return; + } let kept = |ext: &str| -> PathBuf { let found: Vec<_> = std::fs::read_dir(root.join("moved")) .unwrap() @@ -958,15 +1093,200 @@ mod tests { }; let (tmp, old) = (kept("tmp"), kept("old")); assert_eq!((std::fs::read(&tmp).unwrap(), std::fs::read(&old).unwrap()), (b"new".to_vec(), b"original".to_vec())); - let named_in = - if cfg!(any(target_os = "linux", target_os = "android", target_vendor = "apple")) { root.join("moved") } else { root.join("inside") }; for file in [&tmp, &old] { - let named = named_in.join(file.file_name().unwrap()); + let named = root.join("moved").join(file.file_name().unwrap()); assert!(message.contains(&named.display().to_string()), "{} in {message}", named.display()); } let _ = std::fs::remove_dir_all(d); } + /// A refused rename whose folder is no longer allowed by the time the file would be overwritten + /// leaves the file as it was, and neither copy stays behind. + #[test] + fn a_refused_rename_does_not_overwrite_once_no_longer_allowed() { + let d = dir("no-rename-disallowed"); + let (path, tmp, old) = (d.join("doc.txt"), d.join("doc.tmp"), d.join("doc.old")); + std::fs::write(&path, b"original").unwrap(); + std::fs::write(&tmp, b"new").unwrap(); + let checks = std::cell::Cell::new(0); + let over = Over { + tmp: &|| tmp.clone(), + create_old: &|| create_private(&old), + old: &|| old.clone(), + remove_old: &|| { + let _ = std::fs::remove_file(&old); + }, + open_tmp: &|| File::open(&tmp), + remove_tmp: &|| { + let _ = std::fs::remove_file(&tmp); + }, + open_target: &|write| if write { OpenOptions::new().write(true).open(&path) } else { File::open(&path) }, + #[cfg(unix)] + create_target: &|| create_new(&path), + synced: &|| Ok(()), + still_allowed: &|| { + checks.set(checks.get() + 1); + if checks.get() == 1 { + Ok(()) + } else { + assert_eq!(std::fs::read(&old).unwrap(), b"original"); + Err(io::Error::other("moved outside")) + } + }, + }; + let e = write_over_in(&over, denied::<()>().unwrap_err()).unwrap_err(); + assert_eq!(checks.get(), 2); + assert!(e.to_string().contains("moved outside"), "{e}"); + assert_eq!(std::fs::read(&path).unwrap(), b"original"); + assert!(!tmp.exists() && !old.exists()); + let _ = std::fs::remove_dir_all(d); + } + + /// A backup failure after a folder moves outside removes the new content and reports the refusal. + #[cfg(unix)] + #[test] + fn a_refused_rename_rechecks_authorization_after_a_backup_error() { + let (d, root, outside) = checked_folders("no-rename-backup-moved"); + let inside = root.join("inside"); + let moved = outside.join("inside"); + let path = inside.join("doc.txt"); + std::fs::write(&path, b"original").unwrap(); + std::fs::write(inside.join("doc.tmp"), b"new").unwrap(); + let checks = std::cell::Cell::new(0); + let over = Over { + tmp: &|| moved.join("doc.tmp"), + create_old: &|| { + std::fs::rename(&inside, &moved)?; + Err(io::Error::other("backup failed")) + }, + old: &|| moved.join("doc.old"), + remove_old: &|| {}, + open_tmp: &|| File::open(inside.join("doc.tmp")), + remove_tmp: &|| { + let _ = std::fs::remove_file(moved.join("doc.tmp")); + }, + open_target: &|write| if write { OpenOptions::new().write(true).open(&path) } else { File::open(&path) }, + create_target: &|| create_new(&path), + synced: &|| Ok(()), + still_allowed: &|| { + checks.set(checks.get() + 1); + if inside.exists() { Ok(()) } else { Err(io::Error::other("moved outside")) } + }, + }; + let e = write_over_in(&over, denied::<()>().unwrap_err()).unwrap_err(); + assert_eq!(checks.get(), 2); + assert!(e.to_string().contains("moved outside"), "{e}"); + assert!(!e.to_string().contains(&outside.display().to_string()), "{e}"); + assert!(!e.get_ref().is_some_and(|e| e.is::())); + assert_eq!(std::fs::read(moved.join("doc.txt")).unwrap(), b"original"); + assert_eq!(std::fs::read_dir(&moved).unwrap().count(), 1); + let _ = std::fs::remove_dir_all(d); + } + + /// A refused fallback leaves a missing target absent when the final check fails. + #[cfg(unix)] + #[test] + fn a_refused_rename_leaves_a_missing_target_absent_once_no_longer_allowed() { + let d = dir("no-rename-disallowed-new"); + let (path, tmp, old) = (d.join("doc.txt"), d.join("doc.tmp"), d.join("doc.old")); + std::fs::write(&tmp, b"new").unwrap(); + let checks = std::cell::Cell::new(0); + let created = std::cell::Cell::new(false); + let over = Over { + tmp: &|| tmp.clone(), + create_old: &|| create_private(&old), + old: &|| old.clone(), + remove_old: &|| { + let _ = std::fs::remove_file(&old); + }, + open_tmp: &|| File::open(&tmp), + remove_tmp: &|| { + let _ = std::fs::remove_file(&tmp); + }, + open_target: &|write| { + if write { OpenOptions::new().write(true).open(&path) } else { File::open(&path) } + }, + create_target: &|| { + created.set(true); + create_new(&path) + }, + synced: &|| Ok(()), + still_allowed: &|| { + checks.set(checks.get() + 1); + if checks.get() == 1 { + assert!(!path.exists()); + Ok(()) + } else { + assert!(!created.get() && !path.exists()); + Err(io::Error::other("moved outside")) + } + }, + }; + let e = write_over_in(&over, denied::<()>().unwrap_err()).unwrap_err(); + assert_eq!(checks.get(), 2); + assert!(e.to_string().contains("moved outside"), "{e}"); + assert!(!created.get()); + assert!(!path.exists()); + assert!(!tmp.exists() && !old.exists()); + let _ = std::fs::remove_dir_all(d); + } + + /// A checked fallback creates a missing target after authorization succeeds. + #[cfg(unix)] + #[test] + fn a_checked_write_creates_a_missing_target_when_the_rename_is_refused() { + let (d, root, _) = checked_folders("checked-new-no-rename"); + let path = root.join("inside/doc.txt"); + RENAME_REFUSED.with(|c| c.set(true)); + let r = write_atomic_checked(&path, |f| f.write_all(b"new"), under(&root)); + RENAME_REFUSED.with(|c| c.set(false)); + r.unwrap(); + assert_eq!(std::fs::read(&path).unwrap(), b"new"); + assert_eq!(std::fs::read_dir(root.join("inside")).unwrap().count(), 1); + let _ = std::fs::remove_dir_all(d); + } + + /// A file created by another writer at the final check is preserved whether that check succeeds or fails. + #[cfg(unix)] + #[test] + fn a_refused_rename_preserves_a_target_created_at_the_final_check() { + for allowed in [false, true] { + let d = dir("no-rename-new-target-taken"); + let (path, tmp) = (d.join("doc.txt"), d.join("doc.tmp")); + std::fs::write(&tmp, b"new").unwrap(); + let checks = std::cell::Cell::new(0); + let over = Over { + tmp: &|| tmp.clone(), + create_old: &|| Err(io::Error::other("no backup expected")), + old: &|| d.join("doc.old"), + remove_old: &|| {}, + open_tmp: &|| File::open(&tmp), + remove_tmp: &|| { + let _ = std::fs::remove_file(&tmp); + }, + open_target: &|write| if write { OpenOptions::new().write(true).open(&path) } else { File::open(&path) }, + create_target: &|| create_new(&path), + synced: &|| Ok(()), + still_allowed: &|| { + checks.set(checks.get() + 1); + if checks.get() == 1 { + return Ok(()); + } + std::fs::write(&path, b"someone else's")?; + if allowed { Ok(()) } else { Err(io::Error::other("moved outside")) } + }, + }; + let e = write_over_in(&over, denied::<()>().unwrap_err()).unwrap_err(); + assert_eq!(checks.get(), 2); + if !allowed { + assert!(e.to_string().contains("moved outside"), "{e}"); + } + assert_eq!(std::fs::read(&path).unwrap(), b"someone else's"); + assert!(!tmp.exists() && !d.join("doc.old").exists()); + let _ = std::fs::remove_dir_all(d); + } + } + /// A refused rename copies the old content through the file handle it then overwrites: when a /// different file is at the name by the time it is opened for reading, nothing is overwritten and /// the new content stays in the temporary file. @@ -991,7 +1311,9 @@ mod tests { let _ = std::fs::remove_file(&tmp); }, open_target: &|write| if write { OpenOptions::new().write(true).open(&path) } else { File::open(&other) }, + create_target: &|| create_new(&path), synced: &|| Ok(()), + still_allowed: &|| Ok(()), }; let e = write_over_in(&over, denied::<()>().unwrap_err()).unwrap_err(); assert!(e.to_string().contains("the file was replaced while it was opened"), "{e}");