Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
4 changes: 2 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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) |
Expand Down Expand Up @@ -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

Expand Down
8 changes: 2 additions & 6 deletions ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).

Expand Down Expand Up @@ -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)
Expand Down
23 changes: 17 additions & 6 deletions crates/repo/src/conflicts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)?;
Comment on lines +265 to +266

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Update the docs after fixing deleted-file resolution

This now restores the chosen side's recorded mode, but the repository's authoritative documentation still says the opposite: CLAUDE.md:121, ARCHITECTURE.md:376-377, and ROADMAP.md:604-605,767-770 all describe #243 as unresolved/deferred. After this commit closes #243, those statements misreport both current behavior and the active roadmap, so update or remove them alongside this fix.

AGENTS.md reference: AGENTS.md:L3-L9

Useful? React with 👍 / 👎.

}

// P33 Task 8: a resolved PROTECTED path's plaintext is now
// sitting on disk exactly as the chosen side's ciphertext
Expand All @@ -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();
Expand Down
56 changes: 28 additions & 28 deletions crates/repo/src/worktree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,41 +140,17 @@ fn tracked_under(tracked: &BTreeSet<String>, 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)
}

/// 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 {
Expand Down Expand Up @@ -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());
}
}
129 changes: 129 additions & 0 deletions crates/repo/tests/exec_bit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
}
}
57 changes: 51 additions & 6 deletions crates/vfs/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,56 @@ pub enum Error {
}
pub type Result<T> = std::result::Result<T, Error>;

/// 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()
);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
}

/// A shared object store plus the operations that fork worktrees from it.
#[derive(Clone)]
pub struct Repo {
Expand Down Expand Up @@ -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)
Expand Down
Loading