diff --git a/ROADMAP.md b/ROADMAP.md index 027214b8..b26ac1f3 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -790,13 +790,11 @@ scale-&-reach horizon): files actually present; a ws cache file is already removed with its session. A dropped entry can only cost one re-seal if the path returns (randomized sealing, so unchanged content gets a new blob id). -- **Theirs-side resolve carry (P33 final-review follow-on).** `sc resolve - --theirs` on a PROTECTED path records into the main-tree cache today, but - completion's format-dispatched carry only consults the cache against the - prior TIP (ours') entry, so a theirs-side recording never matches and - completion re-seals randomized anyway (spurious-but-safe). Extending the - carry-candidate map to also check `merge_head`/decided-root entries would - let a theirs-side resolution skip the re-seal too. +- **Theirs-side resolve carry — shipped.** Completion's carry now also checks + the cache against the other parent's blob (merge head or picked commit), so a + `sc resolve --theirs` protected path keeps their ciphertext instead of + re-sealing; their wrap list must be in the unioned protection, and a lookup + gap on a partial clone just seals. - **Non-unix local-key fallback (P33 final-review follow-on).** `.sc/local-key` is minted 0600-from-first-byte via a unix-only `OpenOptions::mode` call; there is no non-unix fallback today, so the key file is left world-readable diff --git a/crates/repo/src/conflicts.rs b/crates/repo/src/conflicts.rs index 7f0cf705..a5b6068f 100644 --- a/crates/repo/src/conflicts.rs +++ b/crates/repo/src/conflicts.rs @@ -252,19 +252,14 @@ impl Repo { // P33 Task 8: a resolved PROTECTED path's plaintext is now // sitting on disk exactly as the chosen side's ciphertext // decrypted it — record it in the main-tree cache regardless - // of which side was chosen. This only pays off for an - // `--ours` resolution: completion's format-dispatched carry - // (`snapshot_files`) consults the cache against the prior - // TIP entry's blob id, so an `--ours` recording matches and - // the completing `sc commit`/`sc rebase --continue` carries - // the existing ciphertext instead of re-sealing under a - // fresh random nonce. A `--theirs` recording keys the cache - // to a blob id completion never looks up against (the tip is - // still ours), so it goes unmatched and completion re-seals - // randomized anyway — spurious cache-population, but benign - // (never incorrect, just a wasted write). Plain paths never - // touch the cache — it exists only to skip re-sealing - // convergent-free randomized ciphertext. + // of which side was chosen. Completion's format-dispatched + // carry (`snapshot_files`) consults the cache against the + // tip entry (ours) and the other parent's entry (theirs), so + // either recording matches and the completing `sc commit` / + // `sc rebase --continue` carries the chosen ciphertext + // instead of re-sealing under a fresh random nonce. Plain + // 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 { @@ -1113,6 +1108,139 @@ mod tests { std::fs::remove_dir_all(&root).ok(); } + /// The protected blob id at `path` in `snapshot`'s tree. + fn protected_blob_at(repo: &Repo, snapshot: ObjectId, path: &str) -> ObjectId { + let store_arc = repo.vfs().store(); + let mut store = store_arc.lock().unwrap(); + let root = store.get_snapshot(&snapshot).unwrap().root; + tree_file_entries_with_perms(&mut store, root) + .unwrap() + .get(path) + .unwrap() + .0 + } + + #[test] + fn resolve_theirs_on_a_protected_path_carries_their_ciphertext_on_merge() { + let root = tmp_root("resolve-theirs-carry-merge"); + let repo = Repo::init(&root).unwrap(); + let (alice_sk, alice_pk) = scl_crypto::generate_keypair(); + repo.protect("secret/", &[alice_pk], None).unwrap(); + std::fs::create_dir_all(root.join("secret")).unwrap(); + std::fs::write(root.join("secret/a.txt"), b"base\n").unwrap(); + repo.commit("me", "base").unwrap(); + repo.branch("feature").unwrap(); + + std::fs::write(root.join("secret/a.txt"), b"ours\n").unwrap(); + repo.commit("me", "ours edits secret").unwrap(); + repo.switch_with_identity("feature", Some(&alice_sk)) + .unwrap(); + std::fs::write(root.join("secret/a.txt"), b"theirs\n").unwrap(); + let theirs_tip = repo.commit("me", "theirs edits secret").unwrap(); + repo.switch_with_identity("main", Some(&alice_sk)).unwrap(); + + let err = repo + .merge_with_identity("feature", "me", Some(&alice_sk)) + .unwrap_err(); + assert!(matches!(err, Error::MergeConflicts(1)), "got {err:?}"); + repo.resolve_path("secret/a.txt", ResolveSide::Theirs, Some(&alice_sk)) + .unwrap(); + let merged = repo.commit("me", "take theirs").unwrap(); + + assert_eq!( + protected_blob_at(&repo, merged, "secret/a.txt"), + protected_blob_at(&repo, theirs_tip, "secret/a.txt"), + "a --theirs resolution keeps their ciphertext instead of re-sealing" + ); + // The carried ciphertext is decryptable: a fresh checkout of the merge + // gets their plaintext back. + repo.switch_with_identity("feature", Some(&alice_sk)) + .unwrap(); + repo.switch_with_identity("main", Some(&alice_sk)).unwrap(); + assert_eq!( + std::fs::read(root.join("secret/a.txt")).unwrap(), + b"theirs\n" + ); + + drop(repo); + std::fs::remove_dir_all(&root).unwrap(); + assert!(!root.exists(), "test must leave no residue"); + } + + #[test] + fn resolve_theirs_on_a_protected_path_carries_their_ciphertext_on_pick() { + let root = tmp_root("resolve-theirs-carry-pick"); + let repo = Repo::init(&root).unwrap(); + let (alice_sk, alice_pk) = scl_crypto::generate_keypair(); + repo.protect("secret/", &[alice_pk], None).unwrap(); + std::fs::create_dir_all(root.join("secret")).unwrap(); + std::fs::write(root.join("secret/a.txt"), b"base\n").unwrap(); + repo.commit("me", "base").unwrap(); + repo.branch("work").unwrap(); + + std::fs::write(root.join("secret/a.txt"), b"main-edit\n").unwrap(); + repo.commit("me", "main edits secret").unwrap(); + repo.switch_with_identity("work", Some(&alice_sk)).unwrap(); + std::fs::write(root.join("secret/a.txt"), b"work-edit\n").unwrap(); + let picked = repo.commit("me", "work edits secret").unwrap(); + repo.switch_with_identity("main", Some(&alice_sk)).unwrap(); + + let err = repo + .cherry_pick("work", "me", Some(&alice_sk), None) + .unwrap_err(); + assert!(matches!(err, Error::PickConflicts(1)), "got {err:?}"); + repo.resolve_path("secret/a.txt", ResolveSide::Theirs, Some(&alice_sk)) + .unwrap(); + let done = repo.commit("me", "pick, theirs").unwrap(); + + assert_eq!( + protected_blob_at(&repo, done, "secret/a.txt"), + protected_blob_at(&repo, picked, "secret/a.txt"), + "a --theirs pick resolution keeps the picked ciphertext" + ); + + drop(repo); + std::fs::remove_dir_all(&root).unwrap(); + assert!(!root.exists(), "test must leave no residue"); + } + + #[test] + fn a_hand_edit_after_resolve_theirs_still_seals_fresh() { + let root = tmp_root("resolve-theirs-edit"); + let repo = Repo::init(&root).unwrap(); + let (alice_sk, alice_pk) = scl_crypto::generate_keypair(); + repo.protect("secret/", &[alice_pk], None).unwrap(); + std::fs::create_dir_all(root.join("secret")).unwrap(); + std::fs::write(root.join("secret/a.txt"), b"base\n").unwrap(); + repo.commit("me", "base").unwrap(); + repo.branch("feature").unwrap(); + + std::fs::write(root.join("secret/a.txt"), b"ours\n").unwrap(); + repo.commit("me", "ours edits secret").unwrap(); + repo.switch_with_identity("feature", Some(&alice_sk)) + .unwrap(); + std::fs::write(root.join("secret/a.txt"), b"theirs\n").unwrap(); + let theirs_tip = repo.commit("me", "theirs edits secret").unwrap(); + repo.switch_with_identity("main", Some(&alice_sk)).unwrap(); + + repo.merge_with_identity("feature", "me", Some(&alice_sk)) + .unwrap_err(); + repo.resolve_path("secret/a.txt", ResolveSide::Theirs, Some(&alice_sk)) + .unwrap(); + // The cache holds "theirs"; different bytes must not ride along. + std::fs::write(root.join("secret/a.txt"), b"edited\n").unwrap(); + let merged = repo.commit("me", "edited").unwrap(); + + assert_ne!( + protected_blob_at(&repo, merged, "secret/a.txt"), + protected_blob_at(&repo, theirs_tip, "secret/a.txt") + ); + + drop(repo); + std::fs::remove_dir_all(&root).unwrap(); + assert!(!root.exists(), "test must leave no residue"); + } + #[test] fn resolved_merge_completes_via_commit() { let root = tmp_root("resolve-completes"); diff --git a/crates/repo/src/repo.rs b/crates/repo/src/repo.rs index 9c78cafb..8e316868 100644 --- a/crates/repo/src/repo.rs +++ b/crates/repo/src/repo.rs @@ -476,7 +476,10 @@ impl Repo { // convergent forever). A RANDOMIZED prior can't be compared by // re-encrypting (a fresh seal differs every time), so it consults the // `.sc`-local stat/tag cache; a lost/stale cache degrades to a spurious - // reseal, never to incorrectness. Everything else seals. + // reseal, never to incorrectness. Everything else seals. On a merge or + // pick completion the same proof also runs against the other parent's + // entry, so a protected path resolved to THEIR side keeps their + // ciphertext (below). let tip_entries: BTreeMap = match tip { Some(t) => { let store_arc = self.vfs.store(); @@ -495,31 +498,69 @@ impl Repo { // (path, plaintext) for each sealed path, so its fresh blob id can be // recorded into the cache after `encrypt_protected` returns. let mut sealed_plaintexts: Vec<(String, Vec)> = Vec::new(); + // Merge/pick completion only: the other parent's root, so a path + // resolved to THEIR side can carry their ciphertext too (ADR-0043). + let other_root: Option = match merge_head.or(pick_head) { + Some(h) if cache.is_some() => Some(self.snapshot(&h)?.root), + _ => None, + }; for (path, bytes, mode, granted) in protected { - // Decide carry (Some(prior blob id + perms)) vs. seal (None). - let carry: Option<(ObjectId, u8)> = match tip_entries.get(&path) { - Some((blob_id, _m, perms)) if perms & scl_core::PROTECTED != 0 => { - let unchanged = if perms & scl_core::RANDOMIZED == 0 { - // Convergent prior: exact re-encrypt-and-compare. + // Does `blob_id` (a protected blob with `perms`) provably hold + // exactly `bytes`? A convergent prior is proven by re-encrypting + // and comparing; a randomized one can't be, so it consults the + // `.sc`-local stat/tag cache, which resolves its stat path against + // its own checkout root (P33 Task 7), so a workspace commit stats + // the workspace file, not the host's. Carry iff the cached id is + // the prior id (same content AND same recorded seal); a lost or + // stale cache degrades to a spurious reseal, never incorrectness. + let proves = + |blob_id: &ObjectId, perms: u8, cache: Option<&crate::cache::ProtectedCache>| { + if perms & scl_core::RANDOMIZED == 0 { Object::blob(scl_crypto::encrypt_path(&bytes).0).id() == *blob_id } else { - // Randomized prior: the local stat/tag cache is the only - // way to prove "same plaintext". Carry iff the cached id - // matches the prior tip id (double-checked: same content - // AND same recorded seal). The cache resolves the abs - // stat path against its own checkout root (P33 Task 7), - // so a workspace commit stats the workspace file, not - // the host's. - cache.as_deref().and_then(|c| c.unchanged(&path, &bytes)) == Some(*blob_id) - }; - if unchanged { - Some((*blob_id, *perms)) - } else { - None + cache.and_then(|c| c.unchanged(&path, &bytes)) == Some(*blob_id) } + }; + // Decide carry (Some(prior blob id + perms)) vs. seal (None). + let mut carry: Option<(ObjectId, u8)> = match tip_entries.get(&path) { + Some((blob_id, _m, perms)) + if perms & scl_core::PROTECTED != 0 + && proves(blob_id, *perms, cache.as_deref()) => + { + Some((*blob_id, *perms)) } _ => None, }; + // Not ours: a path resolved with `--theirs` was recorded against + // the other parent's blob id. Carry it only when its blob is held + // and its wrap list is non-empty in the unioned protection, so the + // carried ciphertext stays decryptable; any lookup trouble (a gap + // on a partial clone) just seals. Like every carry, it keeps that + // wrap list verbatim rather than re-deriving it from the merged + // rule's `granted_keys()` (see the wrap-lifecycle note below). + if carry.is_none() { + if let Some(root) = other_root { + let found = { + let store_arc = self.vfs.store(); + let mut store = store_arc.lock().unwrap(); + crate::worktree::tree_entry_at(&mut store, root, &path, partial) + .ok() + .flatten() + .filter(|(id, _, _)| store.contains(id)) + }; + if let Some((blob_id, _m, perms)) = found { + if perms & scl_core::PROTECTED != 0 + && protection + .wrapped + .get(&blob_id) + .is_some_and(|wks| !wks.is_empty()) + && proves(&blob_id, perms, cache.as_deref()) + { + carry = Some((blob_id, perms)); + } + } + } + } match carry { Some((blob_id, perms)) => { @@ -528,9 +569,12 @@ impl Repo { let cipher = { let store_arc = self.vfs.store(); let mut store = store_arc.lock().unwrap(); - match store.get(&blob_id)? { - Object::Blob(b) => Some(b.to_vec()), - _ => None, + match store.get(&blob_id) { + Ok(Object::Blob(b)) => Some(b.to_vec()), + Ok(_) => None, + // Absent prior blob: seal below rather than abort. + Err(scl_core::Error::NotFound(_)) => None, + Err(e) => return Err(e.into()), } }; match cipher { @@ -806,7 +850,11 @@ impl Repo { // them back to `granted_keys()` on the next commit, whereas carry // preserves them on unchanged content. This is not a new disclosure // (the recipient already holds the key; the ciphertext is unchanged) - // and `sc rewrap` remains the deliberate cutover, per ADR-0027. + // and `sc rewrap` remains the deliberate cutover, per ADR-0027. A path + // resolved to THEIR side carries their wrap list the same way: a + // recipient revoked, or a key granted, on our side after the fork is + // not applied to that blob until `sc rewrap`/`sc grant` (under-grant, + // never over-grant), exactly as a clean merge that takes their blob. let prior = std::mem::take(&mut protection.wrapped); crate::protect::reuse_prior_wraps(&mut fresh_wrapped, &prior); protection.wrapped = fresh_wrapped; diff --git a/docs/adr/0043-randomized-protected-encryption.md b/docs/adr/0043-randomized-protected-encryption.md index 513ed912..b3bedabc 100644 --- a/docs/adr/0043-randomized-protected-encryption.md +++ b/docs/adr/0043-randomized-protected-encryption.md @@ -77,6 +77,15 @@ after upgrade. Dispatched on the *prior tip entry's* format: | **Randomized** | Consult the unchanged-detection cache (below); a hit carries the cached id, a miss seals randomized. | | **New protected path** | Seal randomized. | +On a merge or pick completion the same proof also runs against the *other +parent's* entry for the path (the merge head, or the picked commit): a path +resolved with `sc resolve --theirs` has the chosen plaintext recorded against +their blob id, so it carries their ciphertext instead of re-sealing. The blob +must be held and its wrap list non-empty in the unioned protection. Their wrap +list is carried verbatim, like any carry, so a recipient revoked or a key +granted on our side after the fork is not applied to that blob until +`sc rewrap`/`sc grant` — the same result as a clean merge that takes their side. + Had dispatch been cache-only — "no cache entry ⇒ re-seal" — the first commit after upgrading to a P33 binary would have found an empty cache and re-sealed **every** unchanged protected file randomized, a mass-migration commit nobody @@ -118,7 +127,7 @@ cannot be safely keyed without it). conflicts **by construction — even when the plaintexts are trivially identical** and needs `--identity` (or P23 `sc conflicts`/`sc resolve`) to resolve, at which point diff3 merges the identical plaintexts cleanly and - re-seals the result randomized. + re-seals the result randomized (a `--ours`/`--theirs` resolution carries the chosen side's ciphertext instead). - **(4b) `sc rewrap` is no longer policy-only / tree-identical when it upgrades.** A rewrap that re-seals any convergent blob randomized changes that blob's id and therefore the root tree — the commit is content-changing,