diff --git a/.claude/skills/sc-cli-reference/SKILL.md b/.claude/skills/sc-cli-reference/SKILL.md index 250caf76..3e93947c 100644 --- a/.claude/skills/sc-cli-reference/SKILL.md +++ b/.claude/skills/sc-cli-reference/SKILL.md @@ -66,6 +66,9 @@ cargo run --bin sc -- merge --identity # ON a private br # public branch IN (keeps an embargo current); the # reverse (merge/cherry-pick/rebase FROM a private # branch) is refused — publish first +cargo run --bin sc -- merge --abort --identity # ON a private branch: abort a stopped merge + # (restores the private tip's checkout; the key is + # required, a keyless abort refuses and leaves the stop) cargo run --bin sc -- merge [--identity ] # three-way merge (ff when possible; exits # 1 on conflicts; --identity only needed when a # protected path diverged in content on both sides) diff --git a/CLAUDE.md b/CLAUDE.md index 50a2f211..7c832e4d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -239,6 +239,11 @@ transport-adjacent. The rest, imperatively: disk (out of view, or protected and skipped) instead of carrying the prior tip, and under a sparse spec set on the public branch its conflict stop lays out in-view files only and refuses an out-of-view conflict before any write (#240; no decided root, it would be unsealed). + A stopped private merge records `.sc/CONFLICT_PLAINTEXT` and + `.sc/CONFLICT_SIDECARS` like the public stop (completion leaves sidecars out of + the sealed tree and removes them), and `merge --abort` needs `--identity` (a + keyless or non-recipient abort refuses, leaving the stop intact) and restores + the private tip's checkout (#246). `sc branch revoke` rotates the KEK but a recipient who already fetched keeps the old manifest (rotation ≠ erasure). **Keep identity files outside the working tree** — a key committed under a private branch is sealed in and @@ -284,7 +289,7 @@ transport-adjacent. The rest, imperatively: the view. - **A merge, switch, cherry-pick, rebase, undo or sparse-spec change refuses, before any write, to lay a file or directory onto an untracked or ignored one** (`refuse_untracked_overwrite`); move it - away and retry. Merging into an unborn branch and the conflict stop of a merge into a private branch are not guarded. + away and retry. Merging into an unborn branch and the conflict stop of a merge into a private branch are not guarded (except that a private stop refuses a `.theirs` sidecar that would land on an existing file). - **Every ref-moving or commit-creating op (including all secret/protect policy ops) is guarded against an in-progress merge/pick/rebase** — finish or abort the in-progress op first. A push into a repo with a stopped op is diff --git a/ROADMAP.md b/ROADMAP.md index 9cb1d7c8..c21a54c4 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -543,7 +543,9 @@ across every phase. branch remain individually sealed under a branch KEK. Grant is O(1), revoke rotates the KEK, and publish atomically replays scanner-gated public history. A conflicted merge of a public branch into a private one under a sparse spec honors the view and decides - out-of-view paths by the merge, not the prior tip (#240). (ADR-0044.) + out-of-view paths by the merge, not the prior tip (#240). A stopped merge into + a private branch aborts with `--identity` and records its `.theirs` sidecars + and plaintext like the public stop (#246). (ADR-0044.) - **Phase 35 — Native desktop browser.** A bundled Tauri v2 application opens `.sc` repositories through the Rust crates and renders local/remote refs, the all-parent snapshot DAG, provenance, public files, and first-parent diffs. diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs index a397e715..26269204 100644 --- a/crates/cli/src/main.rs +++ b/crates/cli/src/main.rs @@ -153,7 +153,8 @@ enum Cmd { /// Branch to merge in. branch: Option, /// Abandon an in-progress merge and restore the working tree. When given, - /// the BRANCH argument is ignored. + /// the BRANCH argument is ignored. On a private branch it needs + /// `--identity` (the tip is sealed). #[arg(long)] abort: bool, /// Author recorded on the merge snapshot (default: $SC_AUTHOR, then the @@ -161,7 +162,8 @@ enum Cmd { #[arg(long)] author: Option, /// Identity key to decrypt protected paths that diverged in content on - /// both sides (ciphertext-id fast paths need no identity at all). + /// both sides (ciphertext-id fast paths need no identity at all), and + /// to open a private branch. #[arg(long)] identity: Option, }, @@ -2179,7 +2181,13 @@ fn run_merge( ) -> Result<()> { let repo = open_repo()?; if abort { - let skipped = repo.merge_abort()?; + // Only a private branch needs the key to restore its checkout. + let sk = if repo.head_private()?.is_some() { + resolve_identity_opt(identity)? + } else { + None + }; + let skipped = repo.merge_abort_with_identity(sk.as_ref())?; println!("merge aborted; working tree restored"); for path in &skipped { eprintln!("skipped (no key): {path}"); diff --git a/crates/cli/tests/merge_exit.rs b/crates/cli/tests/merge_exit.rs index 9c56b81f..04bf89a9 100644 --- a/crates/cli/tests/merge_exit.rs +++ b/crates/cli/tests/merge_exit.rs @@ -54,3 +54,62 @@ fn merge_with_conflicts_exits_nonzero_and_abort_exits_zero() { std::fs::remove_dir_all(&root).unwrap(); } + +#[test] +fn abort_on_a_private_branch_needs_the_identity() { + let root = tmp("private"); + let keys = tmp("private-keys"); + let id = keys.join("alice.id"); + let id_arg = id.to_str().unwrap(); + assert!(sc(&keys, &["keygen", "--out", id_arg]).status.success()); + + assert!(sc(&root, &["init"]).status.success()); + std::fs::write(root.join("file.txt"), "base\n").unwrap(); + assert!(sc(&root, &["commit", "-m", "base"]).status.success()); + let ok = |args: &[&str]| { + let out = sc(&root, args); + assert!( + out.status.success(), + "{args:?}: {}", + String::from_utf8_lossy(&out.stderr) + ); + }; + ok(&["branch", "fix", "--private", "--identity", id_arg]); + ok(&["switch", "fix", "--identity", id_arg]); + std::fs::write(root.join("file.txt"), "private\n").unwrap(); + ok(&["commit", "-m", "private", "--identity", id_arg]); + ok(&["switch", "main", "--identity", id_arg]); + std::fs::write(root.join("file.txt"), "public\n").unwrap(); + ok(&["commit", "-m", "public"]); + ok(&["switch", "fix", "--identity", id_arg]); + + let out = sc(&root, &["merge", "main", "--identity", id_arg]); + assert_eq!(out.status.code(), Some(1), "conflicted merge must exit 1"); + + // No key: refused, and the stop is still there to abort. + let mut keyless = Command::new(env!("CARGO_BIN_EXE_sc")); + keyless + .args(["merge", "--abort"]) + .current_dir(&root) + .env("SC_IDENTITY", keys.join("absent")); + assert!(!keyless.output().unwrap().status.success()); + assert!(std::fs::read_to_string(root.join("file.txt")) + .unwrap() + .contains("<<<<<<<")); + + let abort = sc(&root, &["merge", "--abort", "--identity", id_arg]); + assert!( + abort.status.success(), + "abort: {}", + String::from_utf8_lossy(&abort.stderr) + ); + assert_eq!( + std::fs::read_to_string(root.join("file.txt")).unwrap(), + "private\n" + ); + assert!(!root.join(".sc/MERGE_HEAD").exists()); + + std::fs::remove_dir_all(&root).unwrap(); + std::fs::remove_dir_all(&keys).unwrap(); + assert!(!root.exists() && !keys.exists(), "test dir left behind"); +} diff --git a/crates/repo/src/lib.rs b/crates/repo/src/lib.rs index 35b8b7b3..c09d4936 100644 --- a/crates/repo/src/lib.rs +++ b/crates/repo/src/lib.rs @@ -29,6 +29,8 @@ mod partial_walks; pub mod pick_state; pub mod private; #[cfg(test)] +mod private_abort; +#[cfg(test)] mod private_sparse; pub mod promisor; pub mod protect; diff --git a/crates/repo/src/private.rs b/crates/repo/src/private.rs index 974f3c25..16f07509 100644 --- a/crates/repo/src/private.rs +++ b/crates/repo/src/private.rs @@ -43,7 +43,7 @@ impl PrivateCtx { /// The inner (plaintext-id) tip snapshot id. At branch creation this is /// the public base itself; after the first private commit it is a private /// inner id resolvable only through the index. - fn inner_tip(&self) -> Result { + pub(crate) fn inner_tip(&self) -> Result { self.index .inner_tip .ok_or_else(|| Error::BadRef("private branch manifest has no inner tip".into())) @@ -183,7 +183,7 @@ impl Repo { } } - fn get_inner_snapshot( + pub(crate) fn get_inner_snapshot( &self, store: &mut Store, ctx: &PrivateCtx, @@ -706,6 +706,30 @@ impl Repo { tracked.extend(d.keys().cloned()); } let files = worktree::read_worktree(&self.layout, &tracked)?; + // A sidecar the stop wrote is working-tree scratch: it reaches neither + // the scanner nor the sealed tree, unless the merge's outcome tracks + // that name (then it is the user's own file). + let (files, sidecars) = if merge_head.is_some() { + let scratch = crate::conflict_plaintext::read_sidecars(&self.layout)?; + let source = decided.as_ref().unwrap_or(&prior); + let is_scratch = |p: &str| scratch.contains(p) && !source.contains_key(p); + ( + files + .into_iter() + .filter(|(p, _, _)| !is_scratch(p)) + .collect(), + scratch, + ) + } else { + (files, Default::default()) + }; + // Paths the stop wrote in plaintext. One now absent from disk was + // deleted by the user: it must not be carried back from the merge. + let conflict_plaintext = if merge_head.is_some() { + crate::conflict_plaintext::read(&self.layout)? + } else { + Default::default() + }; // Scanner gate on the plaintext partition (protected-prefix files are // sealed at publish, exempt here exactly as in a public commit). @@ -759,7 +783,10 @@ impl Repo { // recorded: a decided tree cannot sit in unsealed `.sc/` state. let source = decided.as_ref().unwrap_or(&prior); for (path, e) in source { - if entries.contains_key(path) || disk_paths.contains(path) { + if entries.contains_key(path) + || disk_paths.contains(path) + || conflict_plaintext.contains(path) + { continue; } if !sparse.matches(path) || e.2 & PROTECTED != 0 { @@ -789,6 +816,7 @@ impl Repo { Some(mh) => vec![inner_tip, mh], }; let mut index = ctx.index.clone(); + let committed_paths: BTreeSet = entries.keys().cloned().collect(); let new_tip = self.seal_commit( &mut store, &ctx, &mut index, &carried, entries, new_blobs, parents, secrets, protection, author, message, @@ -807,6 +835,12 @@ impl Repo { }; let new_mid = store.put(Object::Manifest(new_manifest))?; drop(store); + // The sidecars were left out of the sealed tree; remove them before + // the ref moves, or the next commit would take them. A failure here + // fails this commit with nothing moved and the record intact. + if !sidecars.is_empty() { + self.remove_conflict_sidecars_unless(&mut |p| committed_paths.contains(p))?; + } refs::write_branch_tip(&self.layout, &branch, &new_mid)?; crate::merge_state::clear(&self.layout)?; let label = if merge_head.is_some() { @@ -825,6 +859,51 @@ impl Repo { Ok(new_tip) } + /// Abandon a stopped merge into the private branch at HEAD: put the + /// private tip back on disk and clear the merge state. The ref never moved + /// during the stop and nothing was stored outside the sealed manifest, so + /// only the checkout needs restoring. It needs the identity (the tip is a + /// manifest); a caller who cannot open the branch is refused before any + /// write, leaving the stop intact for someone who can. + pub(crate) fn merge_abort_private(&self, identity: Option<&SecretKey>) -> Result> { + let (branch, mid, manifest) = self + .head_private()? + .ok_or_else(|| Error::NotPrivateBranch("HEAD".into()))?; + let ctx = self.open_private(&branch, mid, manifest, identity)?; + let sk = identity.expect("open_private succeeded"); + let theirs_id = crate::merge_state::read_merge_head(&self.layout)? + .expect("in_progress is true but MERGE_HEAD is absent"); + let sparse = self.sparse_spec()?; + + let store_arc = self.vfs.store(); + let mut store = store_arc.lock().unwrap(); + let inner_tip = ctx.inner_tip()?; + let ours = self.get_inner_snapshot(&mut store, &ctx, &inner_tip)?; + let theirs = store.get_snapshot(&theirs_id)?; + let prior = self.inner_tree_files(&mut store, &ctx, ours.root)?; + // The stop wrote files from ours and from theirs, in view only; theirs' + // adds are not in the restored tree, so the removal pass must know + // them (as the public abort does by passing theirs' root). + let mut written: BTreeSet = prior.keys().cloned().collect(); + written + .extend(worktree::tree_file_entries_with_perms(&mut store, theirs.root)?.into_keys()); + written.retain(|p| sparse.matches(p)); + let skipped = self.materialize_private( + "merge --abort", + &mut store, + &ctx, + ours.root, + &written, + &ours.protection, + sk, + )?; + drop(store); + // After the restore, so a failed restore leaves the sidecars to retry. + self.remove_conflict_sidecars_unless(&mut |p| prior.contains_key(p))?; + crate::merge_state::clear(&self.layout)?; + Ok(skipped) + } + /// Build inner trees + snapshot from a decided file map, seal everything /// genuinely new (not in the index, not in `carried`), record the new /// DEKs in `index`, and return the new inner tip id. The shared tail of @@ -1390,6 +1469,26 @@ impl Repo { plaintext.insert(&f.path, None); } drop(store); + // A sidecar lands beside its conflicted file and is removed again + // at completion or abort, so it must not stand on a file either + // side tracks or on one the user owns (the public stop's rule). + let merged_paths: BTreeSet = fm.files.iter().map(|f| f.path.clone()).collect(); + for (name, _) in &fm.sidecars { + if prior_paths.contains(name) || merged_paths.contains(name) { + return Err(Error::InvalidArgument(format!( + "merge has conflicts, and its sidecar {name} would overwrite a tracked \ + file; rename or remove that file, then retry" + ))); + } + let full = worktree::safe_join(&self.layout.root, name)?; + if full.symlink_metadata().is_ok() { + return Err(Error::InvalidArgument(format!( + "merge has conflicts, and writing {name} would overwrite an untracked \ + or ignored file or directory (possibly a sidecar left by an earlier \ + stop); move it away, then retry" + ))); + } + } // Removals first: a failed one must fail the stop before any // other write, or completion would commit the stale plaintext. for (path, pt) in &plaintext { @@ -1402,6 +1501,29 @@ impl Repo { } } } + // Record what is about to land on disk in plaintext, and the + // sidecars, before writing it: completion and abort need both + // (see `conflict_plaintext`). Nothing here is sealed, and it names + // only paths the checkout already holds. + crate::conflict_plaintext::write( + &self.layout, + &fm.files + .iter() + .filter(|f| { + sparse.matches(&f.path) + && (f.needs_encrypt + || matches!(plaintext.get(f.path.as_str()), Some(Some(_)))) + }) + .map(|f| f.path.clone()) + .collect::>(), + )?; + crate::conflict_plaintext::write_sidecars( + &self.layout, + &fm.sidecars + .iter() + .map(|(n, _)| n.clone()) + .collect::>(), + )?; for f in fm.files.iter().filter(|f| sparse.matches(&f.path)) { let full = worktree::safe_join(&self.layout.root, &f.path)?; if matches!(plaintext.get(f.path.as_str()), Some(None)) { @@ -1420,7 +1542,6 @@ impl Repo { let full = worktree::safe_join(&self.layout.root, name)?; std::fs::write(&full, bytes)?; } - let merged_paths: BTreeSet = fm.files.iter().map(|f| f.path.clone()).collect(); for p in prior_paths.difference(&merged_paths) { if !sparse.matches(p) { continue; diff --git a/crates/repo/src/private_abort.rs b/crates/repo/src/private_abort.rs new file mode 100644 index 00000000..247c4ad6 --- /dev/null +++ b/crates/repo/src/private_abort.rs @@ -0,0 +1,425 @@ +//! Aborting or completing a stopped merge into a private branch (#246). The +//! branch tip is a manifest, so abort restores through the private checkout +//! path and needs an identity; the stop's `.theirs` sidecars are +//! recorded like the public stop's, so completion leaves them out of the +//! sealed tree and both endings remove them. + +use std::path::{Path, PathBuf}; + +use scl_core::Object; +use scl_crypto::SecretKey; + +use crate::error::Error; +use crate::repo::Repo; + +const BIN_PRIVATE: &[u8] = &[0, 1, 2, 0xff]; +const BIN_PUBLIC: &[u8] = &[0, 9, 8, 0xfe]; + +fn put(root: &Path, rel: &str, content: &[u8]) { + let p = root.join(rel); + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); + std::fs::write(p, content).unwrap(); +} + +fn read(root: &Path, rel: &str) -> String { + std::fs::read_to_string(root.join(rel)).unwrap() +} + +struct Fixture { + root: PathBuf, + repo: Repo, + sk: SecretKey, +} + +impl Fixture { + fn id(&self) -> Option<&SecretKey> { + Some(&self.sk) + } + fn tip(&self) -> scl_core::ObjectId { + self.repo.head_private().unwrap().unwrap().1 + } + fn paths(&self) -> Vec { + let (b, mid, m) = self.repo.head_private().unwrap().unwrap(); + let ctx = self.repo.open_private(&b, mid, m, self.id()).unwrap(); + let store_arc = self.repo.vfs().store(); + let mut store = store_arc.lock().unwrap(); + let tip = ctx.inner_tip().unwrap(); + let root = self + .repo + .get_inner_snapshot(&mut store, &ctx, &tip) + .unwrap() + .root; + self.repo + .inner_tree_files(&mut store, &ctx, root) + .unwrap() + .into_keys() + .collect() + } + fn assert_no_state(&self) { + assert!(!crate::merge_state::in_progress(self.repo.layout())); + for f in [ + "MERGE_HEAD", + "MERGE_CONFLICTS", + "CONFLICT_PLAINTEXT", + "CONFLICT_SIDECARS", + ] { + assert!(!self.root.join(".sc").join(f).exists(), "{f} left behind"); + } + } + fn finish(self) { + drop(self.repo); + std::fs::remove_dir_all(&self.root).unwrap(); + assert!(!self.root.exists(), "test dir left behind"); + } +} + +/// `main` holds a.txt, bin.dat and src/lib.rs; private `fix` edits a.txt (text), +/// bin.dat (binary), src/lib.rs (only with `view`) and adds p.txt; `main` then edits a.txt, bin.dat +/// and src/lib.rs and adds m.txt. `text` and `bin` pick which of the two files +/// both sides edit (a conflict); the other is left alone on the private side. +/// With `view`, the sparse spec `src/` is in force. +fn fixture(tag: &str, text: bool, bin: bool, view: bool) -> Fixture { + let root = std::env::temp_dir().join(format!("scl-priv-abort-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(&root).unwrap(); + let repo = Repo::init(&root).unwrap(); + put(&root, "a.txt", b"base\n"); + put(&root, "bin.dat", &[0, 0, 0]); + put(&root, "src/lib.rs", b"base\n"); + repo.commit("t", "base").unwrap(); + let (sk, _) = scl_crypto::generate_keypair(); + repo.branch_private("fix", &sk, &[], &[]).unwrap(); + repo.switch_with_identity("fix", Some(&sk)).unwrap(); + if text { + put(&root, "a.txt", b"private edit\n"); + } + if bin { + put(&root, "bin.dat", BIN_PRIVATE); + } + put(&root, "p.txt", b"private only\n"); + if view { + put(&root, "src/lib.rs", b"private\n"); + } + repo.commit_private("alice", "private work", Some(&sk)) + .unwrap(); + repo.switch_with_identity("main", Some(&sk)).unwrap(); + put(&root, "a.txt", b"public edit\n"); + put(&root, "bin.dat", BIN_PUBLIC); + put(&root, "src/lib.rs", b"public\n"); + put(&root, "m.txt", b"public only\n"); + repo.commit("t", "main moves").unwrap(); + if view { + repo.set_sparse(&["src/".to_string()], Some(&sk)).unwrap(); + } + repo.switch_with_identity("fix", Some(&sk)).unwrap(); + Fixture { root, repo, sk } +} + +/// No non-sealed object may hold `needle`: abort leaves nothing at rest +/// outside the sealed manifest. +fn assert_opaque(repo: &Repo, needle: &[u8]) { + let store_arc = repo.vfs().store(); + let mut store = store_arc.lock().unwrap(); + for id in store.all_ids().unwrap() { + let obj = store.get(&id).unwrap(); + if matches!(obj, Object::Sealed(_) | Object::Manifest(_)) { + continue; + } + assert!( + !obj.encode().windows(needle.len()).any(|w| w == needle), + "plaintext leaked into a public {} object", + obj.kind_name() + ); + } +} + +#[test] +fn abort_after_a_text_conflict_restores_the_private_tip() { + let f = fixture("text", true, false, false); + let before = f.tip(); + assert!(matches!( + f.repo.merge_into_private("main", "alice", f.id()), + Err(Error::MergeConflicts(1)) + )); + assert!(read(&f.root, "a.txt").contains("<<<<<<<")); + assert!(f.root.join("m.txt").exists(), "the stop lays theirs' adds"); + f.repo.merge_abort_with_identity(f.id()).unwrap(); + f.assert_no_state(); + assert_eq!(f.tip(), before, "abort must not move the ref"); + assert_eq!(read(&f.root, "a.txt"), "private edit\n"); + assert_eq!(read(&f.root, "src/lib.rs"), "base\n"); + assert_eq!(read(&f.root, "p.txt"), "private only\n"); + assert!(!f.root.join("m.txt").exists(), "theirs' add survived abort"); + let s = f.repo.status_private(f.id()).unwrap(); + assert!(s.added.is_empty() && s.modified.is_empty() && s.deleted.is_empty()); + assert_opaque(&f.repo, b"private edit"); + f.finish(); +} + +#[test] +fn abort_after_a_binary_conflict_removes_the_sidecar() { + let f = fixture("bin", false, true, false); + let before = f.tip(); + assert!(matches!( + f.repo.merge_into_private("main", "alice", f.id()), + Err(Error::MergeConflicts(1)) + )); + assert_eq!( + std::fs::read(f.root.join("bin.dat.theirs")).unwrap(), + BIN_PUBLIC + ); + assert_eq!( + crate::conflict_plaintext::read_sidecars(f.repo.layout()) + .unwrap() + .into_iter() + .collect::>(), + vec!["bin.dat.theirs"], + "the stop must record its sidecar" + ); + f.repo.merge_abort_with_identity(f.id()).unwrap(); + f.assert_no_state(); + assert!(!f.root.join("bin.dat.theirs").exists()); + assert_eq!(std::fs::read(f.root.join("bin.dat")).unwrap(), BIN_PRIVATE); + assert_eq!(f.tip(), before); + f.finish(); +} + +#[test] +fn completion_leaves_the_sidecar_out_of_the_sealed_tree_and_removes_it() { + let f = fixture("done", false, true, false); + assert!(matches!( + f.repo.merge_into_private("main", "alice", f.id()), + Err(Error::MergeConflicts(1)) + )); + assert!(f.root.join("bin.dat.theirs").exists()); + f.repo.commit_private("alice", "merge", f.id()).unwrap(); + f.assert_no_state(); + assert!( + !f.root.join("bin.dat.theirs").exists(), + "sidecar left on disk" + ); + let paths = f.paths(); + assert!( + !paths.iter().any(|p| p.ends_with(".theirs")), + "sidecar sealed into the tree: {paths:?}" + ); + assert!(paths.contains(&"bin.dat".to_string())); + assert!(f.repo.status_private(f.id()).unwrap().added.is_empty()); + f.finish(); +} + +#[test] +fn a_tracked_theirs_file_refuses_the_stop() { + // `bin.dat.theirs` is the user's own tracked file on both sides' history: + // the stop must refuse to overwrite it rather than record it as scratch. + let root = std::env::temp_dir().join(format!("scl-priv-abort-own-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(&root).unwrap(); + let repo = Repo::init(&root).unwrap(); + put(&root, "bin.dat", &[0, 0, 0]); + repo.commit("t", "base").unwrap(); + let (sk, _) = scl_crypto::generate_keypair(); + repo.branch_private("fix", &sk, &[], &[]).unwrap(); + repo.switch_with_identity("fix", Some(&sk)).unwrap(); + put(&root, "bin.dat", BIN_PRIVATE); + put(&root, "bin.dat.theirs", b"mine\n"); + repo.commit_private("alice", "private", Some(&sk)).unwrap(); + repo.switch_with_identity("main", Some(&sk)).unwrap(); + put(&root, "bin.dat", BIN_PUBLIC); + repo.commit("t", "public").unwrap(); + repo.switch_with_identity("fix", Some(&sk)).unwrap(); + let err = repo + .merge_into_private("main", "alice", Some(&sk)) + .unwrap_err(); + assert!(err.to_string().contains("bin.dat.theirs"), "{err}"); + assert!(!crate::merge_state::in_progress(repo.layout())); + assert_eq!(read(&root, "bin.dat.theirs"), "mine\n"); + drop(repo); + std::fs::remove_dir_all(&root).unwrap(); + assert!(!root.exists(), "test dir left behind"); +} + +#[test] +fn an_untracked_file_at_the_sidecar_path_refuses_the_stop() { + let f = fixture("occupied", false, true, false); + put(&f.root, "bin.dat.theirs", b"user's own\n"); + let err = f + .repo + .merge_into_private("main", "alice", f.id()) + .unwrap_err(); + assert!(err.to_string().contains("bin.dat.theirs"), "{err}"); + assert!(!crate::merge_state::in_progress(f.repo.layout())); + assert_eq!(read(&f.root, "bin.dat.theirs"), "user's own\n"); + f.finish(); +} + +#[test] +fn abort_under_a_sparse_spec_writes_nothing_outside_the_view() { + let f = fixture("sparse", false, false, true); + let before = f.tip(); + // Only src/lib.rs is in view, and both sides edited it. + assert!(matches!( + f.repo.merge_into_private("main", "alice", f.id()), + Err(Error::MergeConflicts(1)) + )); + assert!(read(&f.root, "src/lib.rs").contains("<<<<<<<")); + f.repo.merge_abort_with_identity(f.id()).unwrap(); + f.assert_no_state(); + assert_eq!(f.tip(), before); + assert_eq!(read(&f.root, "src/lib.rs"), "private\n"); + for outside in ["a.txt", "bin.dat", "p.txt", "m.txt"] { + assert!( + !f.root.join(outside).exists(), + "{outside} written outside the view" + ); + } + assert!(f.repo.sparse_spec().unwrap().matches("src/lib.rs")); + f.finish(); +} + +#[test] +fn abort_refuses_without_the_identity_and_keeps_the_stop_intact() { + let f = fixture("noaccess", true, false, false); + assert!(matches!( + f.repo.merge_into_private("main", "alice", f.id()), + Err(Error::MergeConflicts(1)) + )); + let marked = read(&f.root, "a.txt"); + let (outsider, _) = scl_crypto::generate_keypair(); + for who in [None, Some(&outsider)] { + let err = f.repo.merge_abort_with_identity(who).unwrap_err(); + assert!(matches!(err, Error::PrivateNoAccess(_)), "{err}"); + assert!(crate::merge_state::in_progress(f.repo.layout())); + assert_eq!(read(&f.root, "a.txt"), marked, "a refused abort wrote"); + } + // The keyless entry point is the one the public tests use. + assert!(matches!( + f.repo.merge_abort(), + Err(Error::PrivateNoAccess(_)) + )); + f.repo.merge_abort_with_identity(f.id()).unwrap(); + f.assert_no_state(); + f.finish(); +} + +#[test] +fn a_protected_conflict_is_recorded_aborted_and_honors_a_deletion() { + for finish_by_delete in [false, true] { + let root = std::env::temp_dir().join(format!( + "scl-priv-abort-prot-{finish_by_delete}-{}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(&root).unwrap(); + let repo = Repo::init(&root).unwrap(); + let (sk, pk) = scl_crypto::generate_keypair(); + put(&root, "readme.txt", b"hi\n"); + repo.commit("t", "base").unwrap(); + repo.protect("vault/", std::slice::from_ref(&pk), None) + .unwrap(); + put(&root, "vault/key.pem", b"PEM-V1\n"); + repo.commit("t", "add protected").unwrap(); + repo.branch_private("fix", &sk, &[], &[]).unwrap(); + repo.switch_with_identity("fix", Some(&sk)).unwrap(); + put(&root, "vault/key.pem", b"PEM-PRIVATE\n"); + repo.commit_private("alice", "private", Some(&sk)).unwrap(); + repo.switch_with_identity("main", Some(&sk)).unwrap(); + put(&root, "vault/key.pem", b"PEM-PUBLIC\n"); + repo.commit("t", "public").unwrap(); + repo.switch_with_identity("fix", Some(&sk)).unwrap(); + let before = repo.head_private().unwrap().unwrap().1; + assert!(matches!( + repo.merge_into_private("main", "alice", Some(&sk)), + Err(Error::MergeConflicts(1)) + )); + assert_eq!( + crate::conflict_plaintext::read(repo.layout()) + .unwrap() + .into_iter() + .collect::>(), + vec!["vault/key.pem"], + "the stop must record the plaintext it wrote" + ); + if finish_by_delete { + std::fs::remove_file(root.join("vault/key.pem")).unwrap(); + repo.commit_private("alice", "drop it", Some(&sk)).unwrap(); + let (b, mid, m) = repo.head_private().unwrap().unwrap(); + let ctx = repo.open_private(&b, mid, m, Some(&sk)).unwrap(); + let store_arc = repo.vfs().store(); + let mut store = store_arc.lock().unwrap(); + let tip = ctx.inner_tip().unwrap(); + let r = repo + .get_inner_snapshot(&mut store, &ctx, &tip) + .unwrap() + .root; + let files = repo.inner_tree_files(&mut store, &ctx, r).unwrap(); + assert!( + !files.contains_key("vault/key.pem"), + "a deleted conflict file was carried back" + ); + } else { + repo.merge_abort_with_identity(Some(&sk)).unwrap(); + assert_eq!(read(&root, "vault/key.pem"), "PEM-PRIVATE\n"); + assert_eq!(repo.head_private().unwrap().unwrap().1, before); + assert_opaque(&repo, b"PEM-PRIVATE"); + } + assert!(!root.join(".sc/CONFLICT_PLAINTEXT").exists()); + assert!(!crate::merge_state::in_progress(repo.layout())); + drop(repo); + std::fs::remove_dir_all(&root).unwrap(); + assert!(!root.exists(), "test dir left behind"); + } +} + +#[test] +fn a_decrypted_carried_protected_file_the_user_deletes_stays_deleted() { + let root = std::env::temp_dir().join(format!("scl-priv-abort-carry-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(&root).unwrap(); + let repo = Repo::init(&root).unwrap(); + let (sk, pk) = scl_crypto::generate_keypair(); + put(&root, "a.txt", b"base\n"); + repo.commit("t", "base").unwrap(); + repo.protect("vault/", std::slice::from_ref(&pk), None) + .unwrap(); + put(&root, "vault/key.pem", b"PEM-V1\n"); + repo.commit("t", "add protected").unwrap(); + repo.branch_private("fix", &sk, &[], &[]).unwrap(); + repo.switch_with_identity("fix", Some(&sk)).unwrap(); + put(&root, "a.txt", b"private\n"); + repo.commit_private("alice", "private", Some(&sk)).unwrap(); + repo.switch_with_identity("main", Some(&sk)).unwrap(); + put(&root, "a.txt", b"public\n"); + put(&root, "vault/key.pem", b"PEM-V2\n"); + repo.commit("t", "public").unwrap(); + repo.switch_with_identity("fix", Some(&sk)).unwrap(); + assert!(matches!( + repo.merge_into_private("main", "alice", Some(&sk)), + Err(Error::MergeConflicts(1)) + )); + // The public rotation was clean and carried: laid out decrypted. + assert_eq!(read(&root, "vault/key.pem"), "PEM-V2\n"); + assert!(crate::conflict_plaintext::read(repo.layout()) + .unwrap() + .contains("vault/key.pem")); + std::fs::remove_file(root.join("vault/key.pem")).unwrap(); + put(&root, "a.txt", b"resolved\n"); + repo.commit_private("alice", "resolve", Some(&sk)).unwrap(); + let (b, mid, m) = repo.head_private().unwrap().unwrap(); + let ctx = repo.open_private(&b, mid, m, Some(&sk)).unwrap(); + let store_arc = repo.vfs().store(); + let mut store = store_arc.lock().unwrap(); + let tip = ctx.inner_tip().unwrap(); + let r = repo + .get_inner_snapshot(&mut store, &ctx, &tip) + .unwrap() + .root; + assert!(!repo + .inner_tree_files(&mut store, &ctx, r) + .unwrap() + .contains_key("vault/key.pem")); + drop(store); + drop(repo); + std::fs::remove_dir_all(&root).unwrap(); + assert!(!root.exists(), "test dir left behind"); +} diff --git a/crates/repo/src/repo.rs b/crates/repo/src/repo.rs index 63a8965f..bea184a6 100644 --- a/crates/repo/src/repo.rs +++ b/crates/repo/src/repo.rs @@ -2250,6 +2250,27 @@ impl Repo { /// a restore that fails leaves the sidecars to retry. The record is retired /// once swept. pub(crate) fn remove_conflict_sidecars(&self, roots: &[ObjectId]) -> Result<()> { + if self.recorded_sidecars()?.is_empty() { + return Ok(()); + } + let partial = self.promisor()?.is_some(); + let store_arc = self.vfs.store(); + let mut store = store_arc.lock().unwrap(); + self.remove_conflict_sidecars_unless(&mut |sidecar| { + roots.iter().any(|root| { + worktree::tree_entry_at(&mut store, *root, sidecar, partial) + .map_or(true, |e| e.is_some()) + }) + }) + } + + /// [`Repo::remove_conflict_sidecars`] with the "does the restored tree + /// track this path" question answered by `tracked`: a private branch asks + /// its sealed tree, which `tree_entry_at` cannot read. + pub(crate) fn remove_conflict_sidecars_unless( + &self, + tracked: &mut dyn FnMut(&str) -> bool, + ) -> Result<()> { let sidecars = self.recorded_sidecars()?; if sidecars.is_empty() { return Ok(()); @@ -2259,16 +2280,9 @@ impl Repo { // user may recreate before the retry. A removal that fails puts the // failed and unprocessed paths back so the retry can finish the job. crate::conflict_plaintext::write_sidecars(&self.layout, &[])?; - let partial = self.promisor()?.is_some(); - let store_arc = self.vfs.store(); - let mut store = store_arc.lock().unwrap(); let sidecars: Vec = sidecars.into_iter().collect(); for (i, sidecar) in sidecars.iter().enumerate() { - let tracked = roots.iter().any(|root| { - worktree::tree_entry_at(&mut store, *root, sidecar, partial) - .map_or(true, |e| e.is_some()) - }); - if tracked { + if tracked(sidecar) { continue; } let removed = worktree::safe_join(&self.layout.root, sidecar).and_then(|full| { @@ -2293,11 +2307,27 @@ impl Repo { /// Returns the protected paths that could not be restored. No identity is /// available at abort time, so protected files are skipped (left absent) /// rather than decrypted — that's expected; re-supply an identity via a - /// `switch_with_identity` back to the branch to materialize them. + /// `switch_with_identity` back to the branch to materialize them. A merge + /// into a private branch cannot be aborted this way: it needs + /// [`Repo::merge_abort_with_identity`]. pub fn merge_abort(&self) -> Result> { + self.merge_abort_with_identity(None) + } + + /// [`Repo::merge_abort`] with the caller's identity. A public branch + /// ignores it. On a private branch it is required (the tip is a sealed + /// manifest, and the checkout is restored from it): a caller who cannot + /// open the branch gets [`Error::PrivateNoAccess`] before anything changes. + pub fn merge_abort_with_identity( + &self, + identity: Option<&scl_crypto::SecretKey>, + ) -> Result> { if !crate::merge_state::in_progress(&self.layout) { return Err(Error::InvalidArgument("no merge in progress".into())); } + if self.head_private()?.is_some() { + return self.merge_abort_private(identity); + } let theirs_id = crate::merge_state::read_merge_head(&self.layout)? .expect("in_progress is true but MERGE_HEAD is absent"); // Fill the view's closure first (lazy partial clones only), outside diff --git a/docs/adr/0044-per-branch-access-control.md b/docs/adr/0044-per-branch-access-control.md index d6452de1..bf55e776 100644 --- a/docs/adr/0044-per-branch-access-control.md +++ b/docs/adr/0044-per-branch-access-control.md @@ -404,6 +404,42 @@ Pinned by `private_sparse.rs`: the final tree equals the run without sparse writes nothing outside the view, and an out-of-view conflict refuses cleanly; and by `private.rs` tests for the full-checkout protected-path case. +## Aborting and completing a stopped private merge (#246) + +`merge --abort` used to call `get_snapshot` on the branch tip, which for a +private branch is a manifest, so it failed with `WrongKind` and left the merge +state in place. The private stop also recorded neither `CONFLICT_PLAINTEXT` nor +`CONFLICT_SIDECARS`, so completion sealed a binary conflict's `.theirs` +sidecar into the tree and left it on disk. Now: + +- **Abort** (`Repo::merge_abort_with_identity`; `merge_abort()` is the keyless + form) opens the branch first, so a caller with no key or a non-recipient key + gets `PrivateNoAccess` before any write and the stop stays for someone who + can finish it. It then restores the private tip through the same checkout + path as `switch` (decrypting protected files the identity can read, skipping + the rest), removes every in-view path theirs' tree holds that the tip does not (as + the public abort does with theirs' root, so an untracked user file at such a + path goes too), removes the recorded sidecars unless the tip tracks that name, and clears the merge + state. The ref never moved and nothing was stored outside the sealed + manifest, so there is nothing to undo at rest. It does not re-derive the + three-way (that can fail for a recipient who cannot read a protected path + both sides changed); it uses theirs' public tree to know which files the + stop wrote. +- **The stop records** the in-view paths it wrote as plaintext + (`needs_encrypt` files and decrypted carried protected files) and its + sidecars, in the unsealed `.sc/` files the public stop already uses. They + name paths the checkout holds anyway, not content or ids, so the opacity + argument is unchanged. +- **Completion** drops recorded sidecars from the scanner input and the sealed + tree (unless the merge's outcome tracks that name), removes them before the + ref moves, and treats a recorded plaintext path absent from disk as deleted + rather than carrying it back from the re-derived outcome. +- **The stop refuses** a sidecar whose path either side tracks or that already + exists on disk, before any write, since abort and completion would otherwise + delete a file the user owns. + +Pinned by `private_abort.rs` and `crates/cli/tests/merge_exit.rs`. + ## Deferred (to ROADMAP.md) - `sc branch publish --squash` (hide intermediate history at publish).