diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index df4e403d..8ea729d1 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -372,9 +372,11 @@ operation if tracked files are modified or deleted (to prevent data loss). New, untracked files are left in place. `status` diffs the working tree against HEAD. The write-out paths (switch, merge, rebase, `sparse set`, clone, `ws fork`, private and conflict write-outs) apply the recorded file mode through one -helper, so an executable file stays executable on unix and a stale execute bit -is cleared on a plain file (#242). `sc resolve` after the user deleted a -conflicted file does not use it yet (#243). +helper (`scl_vfs::apply_file_mode`, also used by `Worktree::checkout`), so an +executable file stays executable on unix, a stale execute bit is cleared on a +plain file, and setuid/setgid/sticky are always cleared (#242, #243). `sc +resolve` applies the chosen side's mode after rewriting a deleted conflicted +file. A chmod the filesystem refuses is tolerated with a one-time warning. ### Mode-scoped disk invariant diff --git a/CLAUDE.md b/CLAUDE.md index 0515a765..50a2f211 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -118,7 +118,7 @@ the code, those win. |---|---|---| | P1 | In-RAM copy-on-write virtual worktrees; bounded blob budget + LRU eviction, optional spill; zero disk residue | [0005](docs/adr/0005-in-ram-vfs-over-fuse.md), [0006](docs/adr/0006-memory-budget-and-eviction.md) | | P2 | Committed secrets: per-secret DEK (XChaCha20-Poly1305) wrapped per X25519 recipient; secrets are env vars, never files — `checkout` never materializes them; `sc run` injects into a child env, or onto a descriptor with `--secrets-fd N` (unix) | [0008](docs/adr/0008-committed-secrets-envelope-encryption.md), [0009](docs/adr/0009-key-management-and-authorization.md), [0010](docs/adr/0010-secret-registry-and-opaque-wrapped-dek.md), [0052](docs/adr/0052-secret-injection-by-fd.md) | -| P3 | Persistent `.sc/` repo: loose objects, branches, symbolic HEAD, single-writer lock, working tree; write-out paths restore the recorded executable bit (unix; #242; `sc resolve` after a deleted conflicted file still drops it, #243) | [0011](docs/adr/0011-persistent-store-and-working-tree.md) | +| P3 | Persistent `.sc/` repo: loose objects, branches, symbolic HEAD, single-writer lock, working tree; write-out paths restore the recorded executable bit (unix; #242; special bits are always cleared, `sc resolve` restores the chosen side's mode, and a swallowed chmod warns once; #243) | [0011](docs/adr/0011-persistent-store-and-working-tree.md) | | P4 | Snapshot-DAG three-way merge; ff when possible; conflict markers + `.theirs` sidecars | [0012](docs/adr/0012-three-way-merge.md) | | P5 | Commit-time secret scanner (pattern + entropy) hard-rejects plaintext secrets; `sc scan` preview; hash-scoped allowlist | [0017](docs/adr/0017-secret-scanner.md) | | P6 | Local-path remotes: `clone`/`fetch`/`push`, remote-tracking refs, `Transport` trait | [0013](docs/adr/0013-remote-sync-model.md) | @@ -300,7 +300,7 @@ truth — do not re-list items here); entries that name an issue mirror the open GitHub issues. Standing entries: named/concurrent `sc ws` sessions (#215), blob-size clone filters (#217), bucket compaction and gc (#216), the non-unix `.sc/local-key` ACL (#214), transcript-drop delivery gaps (#230), and the open -sparse, private-branch and abort edge cases (#241, #246, #247, #248, #243). +sparse, private-branch and abort edge cases (#241, #246, #247, #248). ## Agent skills diff --git a/ROADMAP.md b/ROADMAP.md index 3e1700d6..9cb1d7c8 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -601,8 +601,8 @@ across every phase. path, and `sc sparse set` may widen while a merge, pick or rebase is stopped (#224, #236); a stopped completion no longer resurrects out-of-view deletions (#239). - - Checkout restores the executable bit on the write-out paths (#242); `sc resolve` - after the user deleted a conflicted file still drops it (#243). + - Checkout restores the executable bit on the write-out paths (#242, #243); + `sc resolve` after a deleted conflicted file restores it too. - A warning when the protected-cache key cannot be permission-restricted on a non-unix target (#225; the owner-only ACL is #214). @@ -764,10 +764,6 @@ P28 review follow-ons, the port de-flake, the clippy allow-list) are recorded in sidecar is committed into the sealed tree. #247: `--abort` of a stopped merge, pick or rebase fails with `IsADirectory` when the decided root replaced a file with a directory. -- **Exec-bit review follow-ups (#243, from #242).** Mask setuid/setgid/sticky in - `worktree::write_file`, tests for the protected and private write-out paths, - `sc resolve` after a deleted conflicted file loses the execute bit, and - `vfs::Worktree::checkout` should tolerate `Unsupported` like `write_file`. - **Network-Git same-remote edge cases** (ADR-0018's re-synthesis limitation across different Git repos). - **Richer signer trust models** beyond trusted-key lists (delegation, expiry) diff --git a/crates/repo/src/conflicts.rs b/crates/repo/src/conflicts.rs index a36f45bb..6b0af04b 100644 --- a/crates/repo/src/conflicts.rs +++ b/crates/repo/src/conflicts.rs @@ -248,6 +248,23 @@ impl Repo { std::fs::create_dir_all(parent)?; } std::fs::write(&full, &bytes)?; + // A file the user deleted is recreated at 0644: lay the chosen + // side's recorded mode back so an executable stays one. + let triple = self.op_triple()?; + let chosen_snapshot = match side { + ResolveSide::Ours => triple.ours, + ResolveSide::Theirs => triple.theirs, + }; + let partial = self.promisor()?.is_some(); + let mode = { + let store_arc = self.vfs.store(); + let mut store = store_arc.lock().unwrap(); + let snap = store.get_snapshot(&chosen_snapshot)?; + tree_entry_at(&mut store, snap.root, path, partial)?.map(|(_, m, _)| m) + }; + if let Some(mode) = mode { + crate::worktree::apply_file_mode(&full, mode)?; + } // P33 Task 8: a resolved PROTECTED path's plaintext is now // sitting on disk exactly as the chosen side's ciphertext @@ -261,12 +278,6 @@ impl Repo { // paths never touch the cache — it exists only to skip // re-sealing convergent-free randomized ciphertext. if kind == ConflictKind::Protected { - let triple = self.op_triple()?; - let chosen_snapshot = match side { - ResolveSide::Ours => triple.ours, - ResolveSide::Theirs => triple.theirs, - }; - let partial = self.promisor()?.is_some(); let store_arc = self.vfs.store(); let blob_id = { let mut store = store_arc.lock().unwrap(); diff --git a/crates/repo/src/worktree.rs b/crates/repo/src/worktree.rs index be17f841..551c293d 100644 --- a/crates/repo/src/worktree.rs +++ b/crates/repo/src/worktree.rs @@ -140,8 +140,9 @@ fn tracked_under(tracked: &BTreeSet, dir: &str) -> bool { /// the one place checkout-style writes go through so `read_worktree` (which /// reads the mode back from the filesystem) round-trips. EXEC adds an execute /// bit wherever the file already has a read bit (the umask-respecting default -/// stays); FILE clears any execute bits an existing file had. A no-op off unix; -/// a filesystem that refuses the chmod (no mode bits) is not an error. +/// stays); FILE clears any execute bits an existing file had; setuid/setgid/ +/// sticky are always cleared. A no-op off unix; a filesystem that refuses the +/// chmod (no mode bits) is not an error (see [`scl_vfs::apply_file_mode`]). pub(crate) fn write_file(path: &Path, bytes: &[u8], mode: FileMode) -> std::io::Result<()> { std::fs::write(path, bytes)?; apply_file_mode(path, mode) @@ -149,32 +150,7 @@ pub(crate) fn write_file(path: &Path, bytes: &[u8], mode: FileMode) -> std::io:: /// The mode half of [`write_file`], for a caller that wrote the bytes itself /// (the stopped-op widen writes atomically). -pub(crate) fn apply_file_mode(path: &Path, mode: FileMode) -> std::io::Result<()> { - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - let cur = std::fs::metadata(path)?.permissions().mode(); - let want = if mode.0 & 0o111 != 0 { - cur | ((cur & 0o444) >> 2) - } else { - cur & !0o111 - }; - if want != cur { - match std::fs::set_permissions(path, std::fs::Permissions::from_mode(want)) { - Err(e) - if e.kind() != std::io::ErrorKind::Unsupported - && e.kind() != std::io::ErrorKind::PermissionDenied => - { - return Err(e) - } - _ => {} - } - } - } - #[cfg(not(unix))] - let _ = mode; - Ok(()) -} +pub(crate) use scl_vfs::apply_file_mode; #[cfg(unix)] fn file_mode(path: &Path) -> FileMode { @@ -1527,4 +1503,28 @@ mod tests { std::fs::remove_dir_all(&root).unwrap(); assert!(!root.exists()); } + + /// setuid/setgid/sticky never survive a write (git recreates files and + /// carries none over): a pre-existing 02644 file must not become 02755. + #[cfg(unix)] + #[test] + fn write_file_clears_special_bits() { + use std::os::unix::fs::PermissionsExt; + let dir = std::env::temp_dir().join(format!("scl-repo-wt-special-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let f = dir.join("f"); + let mode = |p: &Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o7777; + for (want, expect) in [(FileMode::EXEC, 0o755), (FileMode::FILE, 0o644)] { + std::fs::write(&f, b"x").unwrap(); + std::fs::set_permissions(&f, std::fs::Permissions::from_mode(0o2644)).unwrap(); + if mode(&f) & 0o2000 == 0 { + continue; // filesystem drops the bit: nothing to test + } + write_file(&f, b"y", want).unwrap(); + assert_eq!(mode(&f), expect); + } + std::fs::remove_dir_all(&dir).unwrap(); + assert!(!dir.exists()); + } } diff --git a/crates/repo/tests/exec_bit.rs b/crates/repo/tests/exec_bit.rs index ff679a32..9578d586 100644 --- a/crates/repo/tests/exec_bit.rs +++ b/crates/repo/tests/exec_bit.rs @@ -221,3 +221,132 @@ fn ws_checkout_keeps_exec_bit() { assert_eq!(committed(&repo, "run.sh"), FileMode::EXEC); assert_eq!(committed(&repo, "plain.txt"), FileMode::FILE); } + +/// Set the on-disk permission bits exactly (a stale or restrictive mode). +fn chmod(root: &Path, rel: &str, mode: u32) { + std::fs::set_permissions(root.join(rel), std::fs::Permissions::from_mode(mode)).unwrap(); +} + +fn disk_mode(root: &Path, rel: &str) -> u32 { + std::fs::metadata(root.join(rel)) + .unwrap() + .permissions() + .mode() + & 0o777 +} + +/// The decrypted-protected-plaintext path of `materialize` keeps the recorded +/// bit, clears a stale one, and never widens read bits. +#[test] +fn protected_switch_keeps_and_clears_exec_without_widening_reads() { + let (repo, root) = base("prot-switch"); + let (sk, pk) = scl_crypto::generate_keypair(); + repo.protect("secret/", &[pk], None).unwrap(); + put(&root, "secret/run.sh", "#!/bin/sh\n", true); + repo.commit("t", "add").unwrap(); + repo.branch("plain").unwrap(); + repo.switch_with_identity("plain", Some(&sk)).unwrap(); + put(&root, "secret/run.sh", "not a script\n", false); + repo.commit("t", "demote").unwrap(); + + // Owner-only file on disk: EXEC adds only the owner execute bit. + chmod(&root, "secret/run.sh", 0o600); + repo.switch_with_identity("main", Some(&sk)).unwrap(); + assert_eq!(disk_mode(&root, "secret/run.sh"), 0o700); + // EXEC -> FILE clears the stale bits. + repo.switch_with_identity("plain", Some(&sk)).unwrap(); + assert_eq!(disk_mode(&root, "secret/run.sh") & 0o111, 0); +} + +/// The protected conflict write-out lays the recorded bit onto the markers. +#[test] +fn protected_conflict_writeout_keeps_exec_bit() { + let (repo, root) = base("prot-conflict"); + let (sk, pk) = scl_crypto::generate_keypair(); + repo.protect("secret/", &[pk], None).unwrap(); + put(&root, "secret/run.sh", "l1\nl2\nl3\n", true); + repo.commit("t", "base").unwrap(); + repo.branch("feat").unwrap(); + put(&root, "secret/run.sh", "MAIN\nl2\nl3\n", true); + repo.commit("t", "main").unwrap(); + repo.switch_with_identity("feat", Some(&sk)).unwrap(); + put(&root, "secret/run.sh", "FEAT\nl2\nl3\n", true); + repo.commit("t", "feat").unwrap(); + repo.switch_with_identity("main", Some(&sk)).unwrap(); + + chmod(&root, "secret/run.sh", 0o600); + assert!(repo.merge_with_identity("feat", "t", Some(&sk)).is_err()); + let text = std::fs::read_to_string(root.join("secret/run.sh")).unwrap(); + assert!(text.contains("<<<<<<<"), "markers: {text}"); + // The write-out may recreate the file (umask-dependent read bits). + assert!(on_disk_exec(&root, "secret/run.sh")); +} + +/// `sc resolve` recreates a conflicted file the user deleted with its mode. +#[test] +fn resolve_after_delete_restores_exec_bit() { + let (repo, root) = base("resolve-del"); + put(&root, "run.sh", "l1\nl2\nl3\n", true); + repo.commit("t", "base").unwrap(); + repo.branch("feat").unwrap(); + put(&root, "run.sh", "MAIN\nl2\nl3\n", true); + repo.commit("t", "main").unwrap(); + repo.switch("feat").unwrap(); + put(&root, "run.sh", "FEAT\nl2\nl3\n", true); + repo.commit("t", "feat").unwrap(); + repo.switch("main").unwrap(); + assert!(repo.merge("feat", "t").is_err()); + + std::fs::remove_file(root.join("run.sh")).unwrap(); + repo.resolve_path("run.sh", scl_repo::ResolveSide::Theirs, None) + .unwrap(); + assert_eq!( + std::fs::read_to_string(root.join("run.sh")).unwrap(), + "FEAT\nl2\nl3\n" + ); + assert!(on_disk_exec(&root, "run.sh")); +} + +/// Private branches: `materialize_private` (plain and protected-carried +/// paths) and the private-merge conflict write-out keep/clear the bit. +#[test] +fn private_branch_materialize_and_conflict_writeout_keep_exec_bit() { + let (repo, root) = base("private"); + let (sk, pk) = scl_crypto::generate_keypair(); + repo.protect("secret/", &[pk], None).unwrap(); + for rel in ["run.sh", "secret/tool.sh"] { + put(&root, rel, "l1\nl2\nl3\n", true); + } + repo.commit("t", "base").unwrap(); + repo.branch_private("fix", &sk, &[], &[]).unwrap(); + + // Switching in lays both files out executable, from owner-only files. + for rel in ["run.sh", "secret/tool.sh"] { + chmod(&root, rel, 0o600); + } + repo.switch_with_identity("fix", Some(&sk)).unwrap(); + for rel in ["run.sh", "secret/tool.sh"] { + assert_eq!(disk_mode(&root, rel), 0o700, "{rel} after switch"); + } + + // Conflicting edits on both sides stop the merge with markers. + for rel in ["run.sh", "secret/tool.sh"] { + put(&root, rel, "FIX\nl2\nl3\n", true); + } + repo.commit_private("t", "private edit", Some(&sk)).unwrap(); + repo.switch_with_identity("main", Some(&sk)).unwrap(); + for rel in ["run.sh", "secret/tool.sh"] { + put(&root, rel, "MAIN\nl2\nl3\n", true); + } + repo.commit("t", "main edit").unwrap(); + repo.switch_with_identity("fix", Some(&sk)).unwrap(); + for rel in ["run.sh", "secret/tool.sh"] { + chmod(&root, rel, 0o600); + } + assert!(repo.merge_into_private("main", "t", Some(&sk)).is_err()); + for rel in ["run.sh", "secret/tool.sh"] { + let text = std::fs::read_to_string(root.join(rel)).unwrap(); + assert!(text.contains("<<<<<<<"), "{rel} markers: {text}"); + assert_eq!(disk_mode(&root, rel), 0o700, "{rel} after conflict"); + } +} diff --git a/crates/vfs/src/lib.rs b/crates/vfs/src/lib.rs index 32c36c07..e0cabd8e 100644 --- a/crates/vfs/src/lib.rs +++ b/crates/vfs/src/lib.rs @@ -26,6 +26,56 @@ pub enum Error { } pub type Result = std::result::Result; +/// Lay `mode`'s executable bit onto the file at `path`, the one place every +/// checkout-style write sets modes so the filesystem round-trips EXEC/FILE. +/// EXEC adds an execute bit wherever the file already has a read bit (the +/// umask-respecting default stays, read bits never widen); FILE clears execute +/// bits. setuid/setgid/sticky are always cleared, as git does by recreating the +/// file. A no-op off unix. A filesystem that refuses the chmod (no mode bits, +/// or not our file) is not an error, but warns once per process because status +/// ignores modes and the next commit would record EXEC as FILE. +pub fn apply_file_mode(path: &Path, mode: FileMode) -> std::io::Result<()> { + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let cur = std::fs::metadata(path)?.permissions().mode(); + let mut want = if mode.0 & 0o111 != 0 { + cur | ((cur & 0o444) >> 2) + } else { + cur & !0o111 + }; + want &= !0o7000; + if want != cur { + match std::fs::set_permissions(path, std::fs::Permissions::from_mode(want)) { + Err(e) + if e.kind() == std::io::ErrorKind::Unsupported + || e.kind() == std::io::ErrorKind::PermissionDenied => + { + warn_chmod_swallowed(path, &e); + } + Err(e) => return Err(e), + Ok(()) => {} + } + } + } + #[cfg(not(unix))] + let _ = (path, mode); + Ok(()) +} + +#[cfg(unix)] +fn warn_chmod_swallowed(path: &Path, err: &std::io::Error) { + static WARNED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + if !WARNED.swap(true, std::sync::atomic::Ordering::Relaxed) { + eprintln!( + "warning: could not set the file mode on {} ({err}); the on-disk executable bit \ + may differ from the recorded mode, and the next commit may record the file's \ + on-disk mode instead (this warning is shown once)", + path.display() + ); + } +} + /// A shared object store plus the operations that fork worktrees from it. #[derive(Clone)] pub struct Repo { @@ -400,12 +450,7 @@ impl Worktree { std::fs::create_dir_all(parent)?; } std::fs::write(&full, &bytes[..])?; - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - let mode = self.mode_of(&path); - std::fs::set_permissions(&full, std::fs::Permissions::from_mode(mode.0))?; - } + apply_file_mode(&full, self.mode_of(&path))?; count += 1; } Ok(count)