From f400a0e1bf1b4293d3898c2835b51573b8ce8673 Mon Sep 17 00:00:00 2001 From: Frank Date: Sat, 8 Aug 2026 21:27:05 +0200 Subject: [PATCH] Keep the mode, refuse a short download, and stop claiming disk we do not use MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three findings from an external conformance suite that states what a cloud file must answer and checks it through a real mount. Five of its eight invariants already passed, including the two hardest — the atomic save and the delete-during-upload races fixed in #52 and #51 both held up under a test that was not written by whoever fixed them. **`chmod +x` returned success and changed nothing.** setattr accepted a mode change and dropped it on the floor, and every attribute answer used a hardcoded 0o644. OneDrive has nowhere to store a mode, so it has to live here or not at all — and the exec bit is the one that matters, because losing it turns a working script into one that will not run with nothing to point at. Modes now live in their own table, the same way local-only symlinks already do, and are held in memory because every stat reads them and a stat must not become a query. The second half of that was worse and only showed up under the suite. The mode is keyed by item ID, and a created file's ID changes when the upload adopts the real OneDrive one. A `chmod +x` made before the upload landed was orphaned under a `_local_*` key nothing would ever ask about again, so it applied right up until the file finished uploading and then quietly stopped. The cache file already moves across adoption; the mode moves with it now. **A download that ended early was served as a short file.** The size of a placeholder comes from the delta pass. If the object changes on OneDrive before anyone reads it, the stream ends at a different length — and we took a completed download to mean a correct one. The reader had asked about a 4096-byte file and got 2048, with no error, and because getattr answers from the cache file the wrong size then became what stat reported from then on. A hydration now either brings what the row promised or it brings nothing: the partial copy is discarded, the row stays a placeholder so the next open tries again, and the reader gets EIO instead of a file that is quietly not what it asked for. **A placeholder claimed disk it was not using.** blocks was computed from size, so a cloud-only file reported a full allocation. That makes `du -sh ~/OneDrive` report the whole drive, which means on-demand cannot be seen to be working even when it is — and the cache-size policy reads those numbers. blocks now comes from the cached copy, and is zero when there is not one. Tests: two mount round trips, one for the mode across an adoption and one for the short download, which also asserts the placeholder's blocks. Both confirmed to fail before the corresponding fix. The five existing round trips and the rest of the suite are unchanged. --- crates/sync-engine/src/db.rs | 45 +++++ crates/vfs/src/filesystem.rs | 122 ++++++++++++- crates/vfs/tests/mount_roundtrip.rs | 262 ++++++++++++++++++++++++++++ 3 files changed, 423 insertions(+), 6 deletions(-) diff --git a/crates/sync-engine/src/db.rs b/crates/sync-engine/src/db.rs index c3f28da..c33fa61 100644 --- a/crates/sync-engine/src/db.rs +++ b/crates/sync-engine/src/db.rs @@ -130,6 +130,16 @@ impl Database { created_at TEXT NOT NULL ); + -- POSIX mode for items whose mode differs from the default. + -- Local-only: OneDrive does not store a mode, so without this a + -- `chmod +x` is lost the moment the attribute is next answered + -- from the database -- and an executable script silently stops + -- being executable. + CREATE TABLE IF NOT EXISTS local_modes ( + item_id TEXT PRIMARY KEY, + mode INTEGER NOT NULL + ); + CREATE TABLE IF NOT EXISTS local_symlinks ( parent_path TEXT NOT NULL, name TEXT NOT NULL, @@ -640,6 +650,9 @@ impl Database { let id = id.to_string(); self.with_conn(move |conn| { conn.execute("DELETE FROM items WHERE id = ?1", params![id])?; + // The mode goes with the item. An id that came back with a stale + // mode attached would be worse than having no mode at all. + conn.execute("DELETE FROM local_modes WHERE item_id = ?1", params![id])?; Ok(()) }) .await @@ -680,6 +693,38 @@ impl Database { /// Uploads are queued in the database rather than held in memory so a /// failure survives a daemon restart: a file the user saved must not be /// silently left un-uploaded because the network blipped. + /// Remember a POSIX mode that differs from the default. + /// + /// The cloud has nowhere to put this, so it lives here or it is lost. The + /// exec bit is the one that matters: losing it turns a working script into + /// one that will not run, with nothing to point at. + pub async fn set_mode(&self, id: &str, mode: u32) -> Result<()> { + let id = id.to_string(); + self.with_conn(move |conn| { + conn.execute( + "INSERT INTO local_modes (item_id, mode) VALUES (?1, ?2) + ON CONFLICT(item_id) DO UPDATE SET mode = excluded.mode", + params![id, mode as i64], + )?; + Ok(()) + }) + .await + } + + /// Every remembered mode, for loading into memory when the mount starts. + pub async fn all_modes(&self) -> Result> { + self.with_conn(move |conn| { + let mut stmt = conn.prepare("SELECT item_id, mode FROM local_modes")?; + let rows = stmt + .query_map([], |row| { + Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)? as u32)) + })? + .collect::>>()?; + Ok(rows) + }) + .await + } + pub async fn enqueue_upload(&self, entry: &PendingUpload) -> Result<()> { let entry = entry.clone(); self.with_conn(move |conn| { diff --git a/crates/vfs/src/filesystem.rs b/crates/vfs/src/filesystem.rs index ed0c8a7..a9ad639 100644 --- a/crates/vfs/src/filesystem.rs +++ b/crates/vfs/src/filesystem.rs @@ -14,7 +14,7 @@ use graph_client::GraphClient; use std::{ collections::{BTreeMap, HashMap, HashSet}, ffi::OsStr, - os::unix::fs::FileExt, + os::unix::fs::{FileExt, MetadataExt}, sync::{ atomic::{AtomicU64, Ordering}, Arc, @@ -92,6 +92,12 @@ pub struct OneDriveFS { /// walk all of them before it can say so. Caching briefly turns a screenful /// of folders re-asking into one query each. folder_state_cache: RwLock>, + /// item_id -> POSIX mode, for items whose mode is not the default. + /// + /// A std lock rather than a tokio one on purpose: `db_item_to_attr` is + /// synchronous and is on every stat, so the mode has to be readable without + /// awaiting. Nothing awaits while this is held. + modes: Arc>>, fh_counter: AtomicU64, sync_dir: std::path::PathBuf, /// Local directory for caching downloaded on-demand files. @@ -127,6 +133,18 @@ impl OneDriveFS { .unwrap_or(None) .unwrap_or_default(); + // Remembered modes, loaded once. Every stat reads this map, so it must + // not be a query. + let modes: HashMap = db + .all_modes() + .await + .unwrap_or_else(|e| { + warn!("could not load saved modes ({e}) — defaults will be used"); + Vec::new() + }) + .into_iter() + .collect(); + Ok(Self { db, graph, @@ -136,6 +154,7 @@ impl OneDriveFS { dirty_fhs: RwLock::new(HashSet::new()), excluded_patterns, folder_state_cache: RwLock::new(HashMap::new()), + modes: Arc::new(std::sync::RwLock::new(modes)), fh_counter: AtomicU64::new(1), sync_dir, cache_dir, @@ -246,7 +265,18 @@ impl OneDriveFS { } else { FileType::RegularFile }; - let perm: u16 = if item.is_folder { 0o755 } else { 0o644 }; + // A mode the user set beats the default. OneDrive cannot store one, so + // it is remembered locally -- without that, `chmod +x` returned success + // and changed nothing, and an executable script silently stopped being + // executable. + let default_perm: u16 = if item.is_folder { 0o755 } else { 0o644 }; + let perm: u16 = self + .modes + .read() + .ok() + .and_then(|m| m.get(&item.id).copied()) + .map(|m| (m & 0o7777) as u16) + .unwrap_or(default_perm); let mtime = item .modified_at @@ -275,18 +305,26 @@ impl OneDriveFS { // A cache file is only ever whole: downloads land via rename from a // `.tmp`, so its length is either the remote content or a local edit // that is ahead of it. Either way it beats the row. - let (size, mtime) = match std::fs::metadata(self.cache_dir.join(&item.id)) { + // `blocks` is reported from the cached copy, not computed from `size`. + // A placeholder holds no content, and saying otherwise makes `du -sh` + // report the full cloud size -- so on-demand cannot be seen to be + // working even when it is, and any disk-pressure policy built on those + // numbers is reading fiction. + let (size, mtime, blocks) = match std::fs::metadata(self.cache_dir.join(&item.id)) { Ok(meta) if !item.is_folder => ( meta.len(), meta.modified().map(sys_time_to_ts).unwrap_or(mtime), + meta.blocks(), ), - _ => (item.size, mtime), + // No cached copy: metadata only, and it occupies nothing. + _ if !item.is_folder => (item.size, mtime, 0), + _ => (item.size, mtime, item.size.div_ceil(512)), }; FileAttr { ino, size, - blocks: size.div_ceil(512), + blocks, atime: mtime, mtime, ctime, @@ -576,7 +614,26 @@ impl Filesystem for OneDriveFS { } } - // For everything else (times, mode, uid, gid) just return current attrs. + // A mode change is real work, not something to nod at. Accepting it and + // discarding it made `chmod +x` return success and change nothing, so + // an executable file stopped being executable with nothing to point at. + if let Some(mode) = set_attr.mode { + let item_id = { + let map = self.inodes.read().await; + map.get(&inode).map(|e| e.item_id.clone()) + }; + if let Some(item_id) = item_id { + if let Err(e) = self.db.set_mode(&item_id, mode).await { + error!("could not persist mode for {item_id}: {e}"); + return Err(libc::EIO.into()); + } + if let Ok(mut m) = self.modes.write() { + m.insert(item_id, mode); + } + } + } + + // For everything else (times, uid, gid) just return current attrs. match self.attr_for_inode(inode).await { Some(attr) => Ok(ReplyAttr { ttl: std::time::Duration::from_secs(TTL_SEC), @@ -805,6 +862,32 @@ impl Filesystem for OneDriveFS { .await { Ok(Ok(_)) => { + // A download that finished is not the same as a download + // that brought what was promised. If the object changed on + // OneDrive after this placeholder was recorded, the stream + // ends early and the reader is handed a silently truncated + // file — the size it asked about and the bytes it got do + // not agree, and nothing says so. + // + // The placeholder is either filled with what it promised or + // left alone. There is no third outcome: a partly filled + // cache file looks hydrated and is not, and `getattr` + // answers from it, so leaving one behind would make the + // wrong size durable. + let landed = std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0); + if landed != item.size { + warn!( + "{id}: hydration brought {landed} bytes for an object \ + recorded as {} — discarding it and asking for a \ + fresh delta rather than serving a truncated file", + item.size + ); + let _ = std::fs::remove_file(&path); + // The row is what disagreed, so it must not be trusted + // as hydrated. Leaving is_placeholder set means the next + // open tries again, against whatever the next delta says. + return Err(libc::EIO.into()); + } if let Err(e) = db.set_placeholder(&id, false).await { warn!("Failed to clear placeholder for {id}: {e}"); } @@ -946,6 +1029,7 @@ impl Filesystem for OneDriveFS { // locally created file returns one — see below. let cache_dir = self.cache_dir.clone(); let inodes = Arc::clone(&self.inodes); + let modes = Arc::clone(&self.modes); let id_to_inode = Arc::clone(&self.id_to_inode); let pending = Arc::clone(&self.pending); @@ -1190,6 +1274,32 @@ impl Filesystem for OneDriveFS { } } + // The mode moves with the identity, like the + // cache file just did. It is keyed by item ID, + // and adoption changes that ID -- so without + // this the mode is orphaned under a `_local_*` + // key nothing will ever ask about again, and a + // `chmod +x` made before the upload finished + // quietly stops applying. + if adopted { + let carried = modes.write().ok().and_then(|mut m| { + m.remove(&old_id).inspect(|mode| { + m.insert(updated_item.id.clone(), *mode); + }) + }); + if let Some(mode) = carried { + if let Err(e) = + db.set_mode(&updated_item.id, mode).await + { + warn!( + "could not carry mode {mode:o} from \ + {old_id} to {}: {e}", + updated_item.id + ); + } + } + } + // Already written above when adopting a new ID. if !adopted { if let Err(e) = db.upsert_item(&updated_item).await { diff --git a/crates/vfs/tests/mount_roundtrip.rs b/crates/vfs/tests/mount_roundtrip.rs index 70f49b6..d6e6e91 100644 --- a/crates/vfs/tests/mount_roundtrip.rs +++ b/crates/vfs/tests/mount_roundtrip.rs @@ -955,3 +955,265 @@ async fn a_file_deleted_inside_the_quiet_period_never_uploads() { "the deleted file is still queued, so it will upload later and come back" ); } + +/// A `chmod +x` made before the upload finishes must still apply afterwards. +/// +/// OneDrive has nowhere to store a mode, so the client keeps it. Two things had +/// to be true and neither was: the mode had to be persisted at all — `setattr` +/// accepted it and dropped it, so `chmod +x` returned success and changed +/// nothing — and it had to survive the upload adopting the real OneDrive ID. +/// The mode is keyed by item ID, and adoption changes that ID, so a mode set +/// while the upload was in flight was orphaned under a `_local_*` key nothing +/// would ever ask about again. The cache file already moves across adoption; +/// the mode has to move with it. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn chmod_survives_the_upload_that_adopts_a_real_id() { + if !fuse_available() { + skip("no /dev/fuse or fusermount3 available"); + return; + } + + let tmp = tempfile::tempdir().unwrap(); + let mountpoint = tmp.path().join("mount"); + let cache_dir = tmp.path().join("cache"); + std::fs::create_dir_all(&mountpoint).unwrap(); + std::fs::create_dir_all(&cache_dir).unwrap(); + + let server = mock_graph().await; + // A created file uploads to its own name, and comes back with a real ID. + Mock::given(method("PUT")) + .and(path_regex(r"^/me/drive/items/root:/run\.sh:/content$")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "id": "real-id-for-run-sh", + "name": "run.sh", + "eTag": "etag-run", + "size": 20, + "lastModifiedDateTime": "2026-01-05T00:00:00Z", + "file": { "mimeType": "application/x-shellscript" }, + "parentReference": { "id": "root" } + }))) + .mount(&server) + .await; + + let graph = test_graph(&server.uri(), tmp.path()); + let db = Arc::new(Database::open(&tmp.path().join("items.db")).unwrap()); + let config = Arc::new(test_config(&mountpoint)); + + let token = TokenSet { + access_token: "test-token".into(), + refresh_token: Some("refresh".into()), + expires_at: chrono::Utc::now() + chrono::Duration::hours(1), + token_type: "Bearer".into(), + scope: "Files.ReadWrite.All".into(), + }; + let auth = Arc::new(AuthManager::for_tests(token, tmp.path().join("t2.json"))); + let (engine, _events) = SyncEngine::new( + Arc::clone(&config), + Arc::clone(&db), + Arc::clone(&graph), + auth, + Some(cache_dir.clone()), + ); + engine.sync_once().await.expect("delta pass"); + + let fs = vfs::OneDriveFS::new( + Arc::clone(&db), + Arc::clone(&graph), + mountpoint.clone(), + cache_dir.clone(), + config.excluded_patterns.clone(), + Duration::ZERO, + ) + .await + .expect("build filesystem"); + + let mount_handle = match fuse3::raw::Session::new(fuse3::MountOptions::default()) + .mount_with_unprivileged(fs, &mountpoint) + .await + { + Ok(handle) => handle, + Err(e) => { + skip(&format!("could not mount FUSE: {e}")); + return; + } + }; + + let mp = mountpoint.clone(); + let result = tokio::task::spawn_blocking(move || { + use std::os::unix::fs::PermissionsExt; + let script = mp.join("run.sh"); + std::fs::write(&script, b"#!/bin/sh\necho hi\n").expect("write script"); + + let mut perms = std::fs::metadata(&script).expect("stat").permissions(); + perms.set_mode(0o755); + std::fs::set_permissions(&script, perms).expect("chmod +x"); + + let after_chmod = std::fs::metadata(&script) + .expect("stat after chmod") + .permissions() + .mode() + & 0o777; + assert_eq!( + after_chmod, 0o755, + "chmod +x returned success and changed nothing — the exec bit was \ + never applied, so a script the user made executable will not run" + ); + }) + .await; + + // Let the upload land and adopt the real OneDrive ID. + let _ = await_upload(&server, Duration::from_secs(10)).await; + tokio::time::sleep(Duration::from_millis(500)).await; + + let mp = mountpoint.clone(); + let after = tokio::task::spawn_blocking(move || { + use std::os::unix::fs::PermissionsExt; + std::fs::metadata(mp.join("run.sh")) + .expect("stat after the upload adopted the real ID") + .permissions() + .mode() + & 0o777 + }) + .await; + + let _ = mount_handle.unmount().await; + result.expect("the pre-upload half panicked"); + assert_eq!( + after.expect("stat panicked"), + 0o755, + "the mode was lost when the upload adopted the real OneDrive ID — it is \ + keyed by item ID, and nothing carried it across the swap" + ); +} + +/// A download that ends early must be refused, not served as a short file. +/// +/// The placeholder's size comes from the delta pass. If the object changes on +/// OneDrive before anyone reads it, the download brings a different number of +/// bytes — and serving those means the reader asked about a file of one size +/// and received another, with no error. Worse, `getattr` answers from the cache +/// file, so the wrong size becomes what `stat` reports from then on. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_short_download_is_refused_rather_than_served_truncated() { + if !fuse_available() { + skip("no /dev/fuse or fusermount3 available"); + return; + } + + let tmp = tempfile::tempdir().unwrap(); + let mountpoint = tmp.path().join("mount"); + let cache_dir = tmp.path().join("cache"); + std::fs::create_dir_all(&mountpoint).unwrap(); + std::fs::create_dir_all(&cache_dir).unwrap(); + + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/me/drive/root")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "id": "root", "name": "root", "folder": { "childCount": 1 } + }))) + .mount(&server) + .await; + // The delta says 4096 bytes... + Mock::given(method("GET")) + .and(path("/me/drive/items/root/delta")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "value": [{ + "id": "short1", + "name": "report.pdf", + "eTag": "etag-1", + "size": 4096, + "lastModifiedDateTime": "2026-01-01T00:00:00Z", + "file": { "mimeType": "application/pdf" }, + "parentReference": { "id": "root", "path": "/drive/root:" } + }], + "@odata.deltaLink": "https://example.invalid/delta?token=next" + }))) + .mount(&server) + .await; + // ...but the content is half that, as it would be if the object changed. + Mock::given(method("GET")) + .and(path("/me/drive/items/short1/content")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(vec![b'x'; 2048])) + .mount(&server) + .await; + + let graph = test_graph(&server.uri(), tmp.path()); + let db = Arc::new(Database::open(&tmp.path().join("items.db")).unwrap()); + let config = Arc::new(test_config(&mountpoint)); + + let token = TokenSet { + access_token: "test-token".into(), + refresh_token: Some("refresh".into()), + expires_at: chrono::Utc::now() + chrono::Duration::hours(1), + token_type: "Bearer".into(), + scope: "Files.ReadWrite.All".into(), + }; + let auth = Arc::new(AuthManager::for_tests(token, tmp.path().join("t2.json"))); + let (engine, _events) = SyncEngine::new( + Arc::clone(&config), + Arc::clone(&db), + Arc::clone(&graph), + auth, + Some(cache_dir.clone()), + ); + engine.sync_once().await.expect("delta pass"); + + let fs = vfs::OneDriveFS::new( + Arc::clone(&db), + Arc::clone(&graph), + mountpoint.clone(), + cache_dir.clone(), + config.excluded_patterns.clone(), + Duration::ZERO, + ) + .await + .expect("build filesystem"); + + let mount_handle = match fuse3::raw::Session::new(fuse3::MountOptions::default()) + .mount_with_unprivileged(fs, &mountpoint) + .await + { + Ok(handle) => handle, + Err(e) => { + skip(&format!("could not mount FUSE: {e}")); + return; + } + }; + + let mp = mountpoint.clone(); + let cache = cache_dir.clone(); + let result = tokio::task::spawn_blocking(move || { + use std::os::unix::fs::MetadataExt; + let file = mp.join("report.pdf"); + + // A placeholder holds nothing, and must say so — otherwise `du` claims + // disk that is not in use and on-demand cannot be seen to be working. + let md = std::fs::metadata(&file).expect("stat placeholder"); + assert_eq!(md.len(), 4096, "a placeholder must report the real size"); + assert_eq!( + md.blocks(), + 0, + "a placeholder reported {} allocated blocks for content it does not hold", + md.blocks() + ); + + let err = std::fs::read(&file) + .expect_err("a download that brought 2048 of 4096 bytes must not be served"); + assert_eq!( + err.raw_os_error(), + Some(libc::EIO), + "expected EIO for a download that disagreed with the placeholder, got {err:?}" + ); + + assert!( + !cache.join("short1").exists(), + "the truncated download was left in the cache — it looks hydrated, it \ + is not, and getattr answers from it" + ); + }) + .await; + + let _ = mount_handle.unmount().await; + result.expect("assertions ran on the mount"); +}