diff --git a/crates/sync-engine/src/db.rs b/crates/sync-engine/src/db.rs index c3f28da..cfe5fc4 100644 --- a/crates/sync-engine/src/db.rs +++ b/crates/sync-engine/src/db.rs @@ -146,6 +146,16 @@ impl Database { [], ); + // The executable bit, which OneDrive does not carry. + // + // Kept out of `items` deliberately: it is local-only, it survives the + // row being replaced when an upload adopts the real OneDrive ID, and it + // must not be touched by delta sync. Presence means executable. + let _ = conn.execute( + "CREATE TABLE IF NOT EXISTS exec_bits (item_id TEXT PRIMARY KEY)", + [], + ); + // Partial index on pinned — created after ALTER TABLE so the column is guaranteed to exist. let _ = conn.execute( "CREATE INDEX IF NOT EXISTS idx_items_pinned ON items(pinned) WHERE pinned = 1", @@ -281,6 +291,54 @@ impl Database { .await } + /// Remember whether a file is executable. + /// + /// OneDrive has no concept of a POSIX mode, so this is ours to keep. Losing + /// it is not cosmetic: a build system that writes a script, marks it + /// executable and runs it fails outright, and `chmod` reporting success + /// while changing nothing gives no clue why. + pub async fn set_executable(&self, item_id: &str, executable: bool) -> Result<()> { + let item_id = item_id.to_string(); + self.with_conn(move |conn| { + if executable { + conn.execute( + "INSERT OR IGNORE INTO exec_bits (item_id) VALUES (?1)", + params![item_id], + )?; + } else { + conn.execute("DELETE FROM exec_bits WHERE item_id = ?1", params![item_id])?; + } + Ok(()) + }) + .await + } + + /// Whether a file was marked executable. + pub async fn is_executable(&self, item_id: &str) -> Result { + let item_id = item_id.to_string(); + self.with_conn(move |conn| { + let mut stmt = conn.prepare_cached("SELECT 1 FROM exec_bits WHERE item_id = ?1")?; + let mut rows = stmt.query(params![item_id])?; + let found = rows.next()?.is_some(); + Ok(found) + }) + .await + } + + /// Carry the bit across an ID change — an upload adopting the real OneDrive + /// ID replaces the row, and the mode must not be lost with it. + pub async fn move_executable(&self, old_id: &str, new_id: &str) -> Result<()> { + let (old_id, new_id) = (old_id.to_string(), new_id.to_string()); + self.with_conn(move |conn| { + conn.execute( + "UPDATE OR REPLACE exec_bits SET item_id = ?2 WHERE item_id = ?1", + params![old_id, new_id], + )?; + Ok(()) + }) + .await + } + /// Items directly under `sync_dir` (depth 1) — used to bootstrap the FUSE root drive ID. pub async fn get_root_drive_id(&self, sync_dir: &Path) -> Result> { let sync_dir = sync_dir.to_path_buf(); diff --git a/crates/vfs/src/filesystem.rs b/crates/vfs/src/filesystem.rs index ed0c8a7..ac45bad 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, PermissionsExt}, sync::{ atomic::{AtomicU64, Ordering}, Arc, @@ -246,7 +246,7 @@ impl OneDriveFS { } else { FileType::RegularFile }; - let perm: u16 = if item.is_folder { 0o755 } else { 0o644 }; + // `perm` is computed below, once the cached copy has been consulted. let mtime = item .modified_at @@ -275,12 +275,22 @@ 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)) { + let (size, mtime, executable) = 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), + // The cached copy carries the mode, so this costs nothing on + // top of the stat already being done. OneDrive has no POSIX + // mode of its own; this is the only place it lives. + std::os::unix::fs::PermissionsExt::mode(&meta.permissions()) & 0o111 != 0, ), - _ => (item.size, mtime), + _ => (item.size, mtime, false), + }; + + let perm: u16 = if item.is_folder || executable { + 0o755 + } else { + 0o644 }; FileAttr { @@ -576,7 +586,37 @@ impl Filesystem for OneDriveFS { } } - // For everything else (times, mode, uid, gid) just return current attrs. + // chmod. Only the executable bit is honoured — OneDrive stores no mode, + // and read/write are governed by the mount, not by us. But the exec bit + // has to stick: a build system writes a script, marks it executable and + // runs it. Accepting the chmod and changing nothing made that fail with + // "permission denied" and no way to see why, since `chmod` reported + // success and `ls -l` kept saying 644. + 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 { + let executable = mode & 0o111 != 0; + let cache_path = self.cache_dir.join(&item_id); + if cache_path.exists() { + let perms = + std::fs::Permissions::from_mode(if executable { 0o755 } else { 0o644 }); + if let Err(e) = std::fs::set_permissions(&cache_path, perms) { + error!("chmod {cache_path:?}: {e}"); + return Err(libc::EIO.into()); + } + } + // Also recorded in the database: a later download replaces the + // cached copy, and the mode would go with it. + if let Err(e) = self.db.set_executable(&item_id, executable).await { + error!("could not record the executable bit for {item_id}: {e}"); + } + } + } + + // 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), @@ -808,6 +848,14 @@ impl Filesystem for OneDriveFS { if let Err(e) = db.set_placeholder(&id, false).await { warn!("Failed to clear placeholder for {id}: {e}"); } + // The download wrote a fresh file, so any mode the user set + // went with the old one. Put it back. + if db.is_executable(&id).await.unwrap_or(false) { + let perms = std::fs::Permissions::from_mode(0o755); + if let Err(e) = std::fs::set_permissions(&path, perms) { + warn!("could not restore the executable bit on {id}: {e}"); + } + } } Ok(Err(e)) => { error!("on-demand download failed for {id}: {e}"); @@ -1169,6 +1217,12 @@ impl Filesystem for OneDriveFS { if let Err(e) = db.upsert_item(&updated_item).await { error!("Failed to adopt the real ID: {e}"); } + // The mode is keyed by ID too. + if let Err(e) = + db.move_executable(&old_id, &updated_item.id).await + { + warn!("could not carry the executable bit: {e}"); + } let mut ids = id_to_inode.write().await; if let Some(ino) = ids.remove(&old_id) { ids.insert(updated_item.id.clone(), ino); diff --git a/crates/vfs/tests/mount_roundtrip.rs b/crates/vfs/tests/mount_roundtrip.rs index 70f49b6..44f0c8d 100644 --- a/crates/vfs/tests/mount_roundtrip.rs +++ b/crates/vfs/tests/mount_roundtrip.rs @@ -955,3 +955,123 @@ 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" ); } + +/// `chmod +x` has to stick, and the file has to run. +/// +/// The mount reported a hardcoded 644 for every file and accepted `chmod` +/// without doing anything, so marking a script executable silently did nothing: +/// `chmod` reported success, `ls -l` kept saying 644, and running it failed with +/// exit 126. Cargo writes a build script, marks it executable and runs it — so +/// no Rust build could work inside the mount, and nothing in the error said why. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_script_made_executable_stays_executable_and_runs() { + 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; + Mock::given(method("PUT")) + .and(path_regex(r"^/me/drive/items/root:/build\.sh:/content$")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "id": "script-item", + "name": "build.sh", + "eTag": "etag-script", + "size": 24, + "lastModifiedDateTime": "2026-01-06T00:00:00Z", + "file": { "mimeType": "text/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::from_secs(30), + ) + .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::io::Write; + use std::os::unix::fs::PermissionsExt; + let script = mp.join("build.sh"); + + let mut fh = std::fs::File::create(&script).expect("create the script"); + fh.write_all(b"#!/bin/sh\necho built\n").expect("write"); + drop(fh); + + std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)) + .expect("chmod +x"); + + let mode = std::fs::metadata(&script) + .expect("stat the script") + .permissions() + .mode(); + assert_eq!( + mode & 0o111, + 0o111, + "chmod +x reported success but the mode is still {:o} — this is the \ + silent no-op that made cargo builds fail inside the mount", + mode & 0o777 + ); + + let out = std::process::Command::new(&script) + .output() + .expect("run the script"); + assert!( + out.status.success(), + "the script would not run: exit {:?} — 126 is the shell's \ + \"found it, cannot execute it\"", + out.status.code() + ); + assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), "built"); + }) + .await; + + let _ = mount_handle.unmount().await; + result.expect("filesystem operations through the mount"); +}