From 6f9d7489f27a3fcdf720e3f5c8868949dbdf856c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 11:30:05 -0800 Subject: [PATCH 1/3] craft-cloud-local: two saves from one etag no longer both succeed write checked the etag and then renamed its temporary file over the target with nothing between them. Two Job::Write calls carrying the same etag, each on its own thread, could both pass the check before either renamed, so both reported success and the later rename replaced the first save without a Conflict. The temporary file is still written and synced first. The etag is then checked again under a process-wide lock held through the rename and the metadata read, so the second save gets Fault::Conflict and its temporary file is removed. --- crates/cloud-local/src/lib.rs | 121 +++++++++++++++++++++++++++++----- 1 file changed, 105 insertions(+), 16 deletions(-) diff --git a/crates/cloud-local/src/lib.rs b/crates/cloud-local/src/lib.rs index b3cf5cbe9d..f79271499e 100644 --- a/crates/cloud-local/src/lib.rs +++ b/crates/cloud-local/src/lib.rs @@ -62,6 +62,7 @@ use std::ffi::OsStr; use std::fs; use std::io::{Read as _, Write as _}; use std::path::{Component, Path, PathBuf}; +use std::sync::Mutex; use std::sync::atomic::{AtomicU64, Ordering}; use cap_std::fs::{Dir, OpenOptions}; @@ -322,27 +323,41 @@ fn read(root: &Path, entry: &Entry) -> Result<(Entry, Vec), Fault> { /// so a hard link sharing the target's inode keeps its own, unmodified copy: /// the rename replaces `entry.id`'s directory entry, and never reaches /// through to any other name pointing at the same inode. +/// +/// The etag is checked once before any bytes are written, and again under +/// [`WRITE_LOCK`] just before the rename. Two saves made from the same etag +/// at once otherwise both pass the check before either renames, both report +/// success, and the later rename replaces the first save without a +/// [`Fault::Conflict`]. fn write(root: &Path, entry: &Entry, bytes: &[u8]) -> Result { let rel = relative(&entry.id)?; let dir = open_root(root)?; - match dir.symlink_metadata(&rel) { - Ok(meta) if meta.is_symlink() => return Err(Fault::Refused("that path is a link, not a plain file".to_owned())), - Ok(meta) => { - if Some(etag_of(&meta)) != entry.etag { - return Err(Fault::Conflict); - } - } - Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} - Err(error) => return Err(io_fault(&error)), - } + check_unchanged(&dir, &rel, entry)?; if let Some(parent) = rel.parent() { dir.create_dir_all(parent).map_err(|error| io_fault(&error))?; } - write_replacing(&dir, &rel, bytes)?; - let meta = dir.metadata(&rel).map_err(|error| io_fault(&error))?; + let meta = write_replacing(&dir, &rel, bytes, || check_unchanged(&dir, &rel, entry))?; Ok(Entry { size: Some(meta.len()), etag: Some(etag_of(&meta)), ..entry.clone() }) } +/// Refuses a link at `rel`, and a file whose etag is no longer `entry.etag`. +/// A file that does not exist passes. +fn check_unchanged(dir: &Dir, rel: &Path, entry: &Entry) -> Result<(), Fault> { + match dir.symlink_metadata(rel) { + Ok(meta) if meta.is_symlink() => Err(Fault::Refused("that path is a link, not a plain file".to_owned())), + Ok(meta) if Some(etag_of(&meta)) != entry.etag => Err(Fault::Conflict), + Ok(_) => Ok(()), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(error) => Err(io_fault(&error)), + } +} + +/// Held by [`write_replacing`] from its last check until the rename is done +/// and the new file's metadata is read, so no other save in this process can +/// change the file in between. The temporary file is written and synced +/// before the lock is taken, so a slow save does not hold up the others. +static WRITE_LOCK: Mutex<()> = Mutex::new(()); + /// The next in a run of sibling temporary names, unique within this process. /// Not meant to resist a second process picking the same name; the create /// this writes with is exclusive (`create_new`), so a collision there is @@ -355,7 +370,11 @@ static TEMP_SEQUENCE: AtomicU64 = AtomicU64::new(0); /// be a hard link to a file outside `root`, the outside copy would be /// corrupted along with it. A rename only ever replaces `rel`'s own /// directory entry. -fn write_replacing(dir: &Dir, rel: &Path, bytes: &[u8]) -> Result<(), Fault> { +/// +/// `check` runs under [`WRITE_LOCK`] right before the rename; when it fails, +/// the temporary file is removed and `rel` is left as it was. Returns the +/// metadata of the file just published. +fn write_replacing(dir: &Dir, rel: &Path, bytes: &[u8], check: impl FnOnce() -> Result<(), Fault>) -> Result { let name = rel.file_name().ok_or_else(|| Fault::Refused("that path names no file".to_owned()))?; let mut temp_name = OsStr::new(".").to_os_string(); temp_name.push(name); @@ -375,11 +394,19 @@ fn write_replacing(dir: &Dir, rel: &Path, bytes: &[u8]) -> Result<(), Fault> { let _ = dir.remove_file(&temp_rel); return Err(fault); } - if let Err(error) = dir.rename(&temp_rel, dir, rel) { + let published = { + let _serialized = WRITE_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + check().and_then(|()| { + #[cfg(test)] + tests::after_check(); + dir.rename(&temp_rel, dir, rel).map_err(|error| io_fault(&error))?; + dir.metadata(rel).map_err(|error| io_fault(&error)) + }) + }; + if published.is_err() { let _ = dir.remove_file(&temp_rel); - return Err(io_fault(&error)); } - Ok(()) + published } fn create(root: &Path, folder: &str, name: &str, bytes: &[u8]) -> Result { @@ -435,6 +462,68 @@ fn create(root: &Path, folder: &str, name: &str, bytes: &[u8]) -> Result; + static AFTER_CHECK: Mutex> = Mutex::new(None); + + pub(super) fn after_check() { + let hook = AFTER_CHECK.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take(); + if let Some(hook) = hook { + hook(); + } + } + + fn entry_for(id: &str) -> Entry { + Entry { + room: format!("local:{id}"), + name: id.trim_start_matches('/').to_owned(), + kind: EntryKind::File, + size: None, + modified: None, + mime: None, + etag: None, + writable: true, + shared_by: None, + path: id.to_owned(), + id: id.to_owned(), + } + } + + #[test] + fn two_saves_from_one_etag_cannot_both_pass_the_check() { + let root = tempfile::tempdir().unwrap(); + std::fs::write(root.path().join("Note.txt"), b"original").unwrap(); + let (read_entry, _) = read(root.path(), &entry_for("/Note.txt")).unwrap(); + + let (checked_tx, checked_rx) = mpsc::channel::<()>(); + let (go_tx, go_rx) = mpsc::channel::<()>(); + *AFTER_CHECK.lock().unwrap() = Some(Box::new(move || { + checked_tx.send(()).unwrap(); + go_rx.recv().unwrap(); + })); + + let first = { + let (root, entry) = (root.path().to_owned(), read_entry.clone()); + std::thread::spawn(move || write(&root, &entry, b"first save")) + }; + checked_rx.recv().unwrap(); + // The first save has passed its check and not yet renamed. A second + // save must not be able to reach its own check in between. + assert!(WRITE_LOCK.try_lock().is_err(), "the check and the rename must run under one lock"); + let second = { + let (root, entry) = (root.path().to_owned(), read_entry.clone()); + std::thread::spawn(move || write(&root, &entry, b"second save")) + }; + go_tx.send(()).unwrap(); + + assert!(first.join().unwrap().is_ok()); + assert!(matches!(second.join().unwrap(), Err(Fault::Conflict)), "the second save started from a stale etag"); + assert_eq!(std::fs::read(root.path().join("Note.txt")).unwrap(), b"first save"); + let left: Vec<_> = std::fs::read_dir(root.path()).unwrap().map(|item| item.unwrap().file_name()).collect(); + assert_eq!(left, ["Note.txt"], "the refused save's temporary file is removed"); + } #[test] fn a_parent_segment_cannot_walk_out_of_root() { From fe2937eab5f6ebfaef13701af110c36e19e50547 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 17:44:46 -0800 Subject: [PATCH 2/3] craft-cloud-local: the README says where a save's etag check holds A Job::Write rechecks the etag under a lock held through the rename, so two saves from one etag cannot both succeed within one process. The README now says so, says that a second process writing the same folder is not covered, and says that two same-length saves on a filesystem with coarse timestamps can leave the same etag. --- crates/cloud-local/README.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/crates/cloud-local/README.md b/crates/cloud-local/README.md index a5006c2ca3..a2e7cf0ca8 100644 --- a/crates/cloud-local/README.md +++ b/crates/cloud-local/README.md @@ -37,3 +37,16 @@ write never truncates its target in place. It writes a new sibling file and rena over the target, so the target's directory entry is replaced rather than its bytes being overwritten. A rename only ever changes one name; it does not reach through to any other name, inside the root or out, that happens to point at the same inode. + +## Concurrent saves + +A `Job::Write` checks the file's etag again just before the rename, and holds one lock for this +process from that check until the rename is done. Within one process, two saves made from the +same etag cannot both succeed: the second gets `Fault::Conflict`. A second process writing the +same folder does not take that lock, so its save can still land between the check and the rename. +A deployment that needs the guarantee across processes needs a backend whose provider offers a +conditional write. + +The etag is the file's length and modification time. On a filesystem whose timestamps are coarser +than the time between two saves, two saves of the same length can leave the same etag, and the +second save is then not refused. From 228f5a4596fe6cf05c4bf0225631ca370909a487 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 18:12:43 -0800 Subject: [PATCH 3/3] craft-cloud-local: the concurrent-save test always reaches the locked recheck The second save now signals once its temporary file is written, before it takes WRITE_LOCK, and the test releases the first save only then. The second save therefore always passes its early check and is refused by the recheck under the lock, and the test fails when that recheck is removed. --- crates/cloud-local/src/lib.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/crates/cloud-local/src/lib.rs b/crates/cloud-local/src/lib.rs index f79271499e..08144a6ca5 100644 --- a/crates/cloud-local/src/lib.rs +++ b/crates/cloud-local/src/lib.rs @@ -394,6 +394,8 @@ fn write_replacing(dir: &Dir, rel: &Path, bytes: &[u8], check: impl FnOnce() -> let _ = dir.remove_file(&temp_rel); return Err(fault); } + #[cfg(test)] + tests::before_lock(); let published = { let _serialized = WRITE_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner); check().and_then(|()| { @@ -475,6 +477,17 @@ mod tests { } } + /// Run once by the next [`write_replacing`] to finish its temporary file, + /// before it takes [`WRITE_LOCK`], then cleared. + static BEFORE_LOCK: Mutex> = Mutex::new(None); + + pub(super) fn before_lock() { + let hook = BEFORE_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take(); + if let Some(hook) = hook { + hook(); + } + } + fn entry_for(id: &str) -> Entry { Entry { room: format!("local:{id}"), @@ -512,10 +525,16 @@ mod tests { // The first save has passed its check and not yet renamed. A second // save must not be able to reach its own check in between. assert!(WRITE_LOCK.try_lock().is_err(), "the check and the rename must run under one lock"); + // The second save passes its early check and writes its temporary + // file before the first one renames, so only the recheck under the + // lock can refuse it. + let (ready_tx, ready_rx) = mpsc::channel::<()>(); + *BEFORE_LOCK.lock().unwrap() = Some(Box::new(move || ready_tx.send(()).unwrap())); let second = { let (root, entry) = (root.path().to_owned(), read_entry.clone()); std::thread::spawn(move || write(&root, &entry, b"second save")) }; + ready_rx.recv().unwrap(); go_tx.send(()).unwrap(); assert!(first.join().unwrap().is_ok());