From 69629152eda193a024fb784f2b528ab072064c86 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 09:00:44 +0200 Subject: [PATCH 1/4] fix(repo): refuse a commit that would store plaintext of a path whose rule was dropped upstream Protection rules are repository data. A tip that keeps a path's PROTECTED entry but omits its rule made a recipient's checkout hold the plaintext, and the next ordinary commit stored it unsealed. snapshot_files (commit, amend, completion, ws harvest, sc work) now refuses before writing any object when a working-tree path is PROTECTED on the tip or the merge/pick head and no rule covers it. --- crates/repo/src/repo.rs | 88 +++++++++++++++++++++++++++++++++++++++++ docs/THREAT-MODEL.md | 9 +++++ 2 files changed, 97 insertions(+) diff --git a/crates/repo/src/repo.rs b/crates/repo/src/repo.rs index 09881820..cec677de 100644 --- a/crates/repo/src/repo.rs +++ b/crates/repo/src/repo.rs @@ -537,6 +537,46 @@ impl Repo { None => BTreeMap::new(), }; + // Protection rules are repository data: a tip (or the other parent of a + // completion) can keep a path's PROTECTED entry while its rule is gone. + // A checkout holds that path's plaintext, and it would land here as an + // unprotected file, so refuse before any object is written. No stock + // command removes a rule (merges union them). + { + let mut dropped: Vec<&str> = Vec::new(); + let mut note = |entries: &BTreeMap| { + for (path, ..) in &all { + if entries + .get(path) + .is_some_and(|(.., perms)| perms & scl_core::PROTECTED != 0) + { + dropped.push(path); + } + } + }; + note(&tip_entries); + if let Some(h) = merge_head.or(pick_head) { + let other_root = self.snapshot(&h)?.root; + let store_arc = self.vfs.store(); + let mut store = store_arc.lock().unwrap(); + note(&if partial { + worktree::tree_file_entries_with_perms_sparse(&mut store, other_root, sparse)? + } else { + worktree::tree_file_entries_with_perms(&mut store, other_root)? + }); + } + if !dropped.is_empty() { + dropped.sort_unstable(); + dropped.dedup(); + return Err(Error::InvalidArgument(format!( + "protected on a parent but covered by no protection rule: {}; committing \ + would store plaintext. The rule was removed upstream; restore it with \ + `sc protect`.", + dropped.join(", ") + ))); + } + } + let mut to_seal: Vec = Vec::new(); // (path, plaintext) for each sealed path, so its fresh blob id can be // recorded into the cache after `encrypt_protected` returns. @@ -7373,6 +7413,54 @@ mod tests { std::fs::remove_dir_all(&src_root).unwrap(); std::fs::remove_dir_all(&dst_root).unwrap(); } + + /// A tip that keeps a protected entry (PROTECTED bit, wrap list) but lacks + /// the rule is repository data a writer can build by hand. A recipient who + /// switches to it holds the plaintext, so their next ordinary commit must + /// not publish it. + #[test] + fn a_commit_never_stores_plaintext_of_a_path_whose_rule_was_dropped_upstream() { + let root = tmp_root("commit-rule-dropped"); + let repo = Repo::init(&root).unwrap(); + let (sk, pk) = scl_crypto::generate_keypair(); + repo.protect("secret/", &[pk], None).unwrap(); + std::fs::create_dir_all(root.join("secret")).unwrap(); + std::fs::write(root.join("secret/x"), "secret x\n").unwrap(); + std::fs::write(root.join("other.txt"), "other\n").unwrap(); + let base = repo.commit("t", "protected").unwrap(); + repo.branch("feat").unwrap(); + repo.switch("feat").unwrap(); + let snap = repo.snapshot(&base).unwrap(); + let mut dropped = snap.protection.clone(); + dropped.prefixes.clear(); + repo.commit_snapshot( + snap.root, + vec![base], + snap.secrets.clone(), + dropped, + "t", + "drop the rule", + ) + .unwrap(); + // Plaintext on disk through the normal API. + let _ = std::fs::remove_file(root.join("secret/x")); + repo.switch_with_identity("main", Some(&sk)).unwrap(); + repo.switch_with_identity("feat", Some(&sk)).unwrap(); + assert_eq!( + std::fs::read_to_string(root.join("secret/x")).unwrap(), + "secret x\n" + ); + std::fs::write(root.join("other.txt"), "edited\n").unwrap(); + let before = repo.head_tip().unwrap(); + let err = repo.commit("t", "unrelated edit").unwrap_err().to_string(); + assert!( + err.contains("secret/x") && err.contains("sc protect"), + "{err}" + ); + assert_eq!(repo.head_tip().unwrap(), before); + drop(repo); + std::fs::remove_dir_all(&root).unwrap(); + } } #[cfg(test)] diff --git a/docs/THREAT-MODEL.md b/docs/THREAT-MODEL.md index d3d0ab68..2cf0a38d 100644 --- a/docs/THREAT-MODEL.md +++ b/docs/THREAT-MODEL.md @@ -103,6 +103,15 @@ too, not just the src-control-side metadata. protected blob under a fresh key (ADR-0051), whereas a plain `sc rewrap` only replaces wrap lists and leaves the key a revoked holder already has. History keeps the old wraps and ciphertext regardless. +- **A dropped rule cannot turn a recipient's commit into a plaintext leak:** + protection rules are repository data, so a writer can hand-build a tip that + keeps a path's `PROTECTED` entry but omits its rule. A recipient who checks + that tip out holds the plaintext, and an unguarded `sc commit` would store it + unsealed. Every commit-building path (commit, amend, merge/pick/rebase + completion, `sc ws harvest`, `sc work`) therefore refuses, before writing any + object, when a working-tree path is `PROTECTED` on a parent (the tip, and the + merge or pick head on a completion) and no rule in the resulting policy covers + it; restore the rule with `sc protect`. - **Local cache key, `sc keygen` identity and TLS serve key are owner-only on unix and Windows (P33, #214, #281):** the unchanged-detection cache is keyed by `.sc/local-key`, created owner-only from From bc5f4f261577a6151212ddbaecd771b38c6e8a24 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 10:21:19 +0200 Subject: [PATCH 2/4] fix(repo): broaden the dropped-rule guard to every uncovered protected entry Refuse when any tip entry is PROTECTED and no rule in the new protection covers it (new plain files under the dropped rule, keyless commits dropping absent entries), check the merge/pick head by point lookups for plain paths only so a partial clone never walks an unheld subtree, and refuse plain paths that differ only in ASCII case from a rule prefix or protected tip path. The hint says to abort while a merge, pick or rebase is stopped. --- crates/repo/src/repo.rs | 269 ++++++++++++++++++++++++++++++++-------- docs/THREAT-MODEL.md | 16 ++- 2 files changed, 230 insertions(+), 55 deletions(-) diff --git a/crates/repo/src/repo.rs b/crates/repo/src/repo.rs index cec677de..942d3c24 100644 --- a/crates/repo/src/repo.rs +++ b/crates/repo/src/repo.rs @@ -537,45 +537,18 @@ impl Repo { None => BTreeMap::new(), }; - // Protection rules are repository data: a tip (or the other parent of a - // completion) can keep a path's PROTECTED entry while its rule is gone. - // A checkout holds that path's plaintext, and it would land here as an - // unprotected file, so refuse before any object is written. No stock - // command removes a rule (merges union them). - { - let mut dropped: Vec<&str> = Vec::new(); - let mut note = |entries: &BTreeMap| { - for (path, ..) in &all { - if entries - .get(path) - .is_some_and(|(.., perms)| perms & scl_core::PROTECTED != 0) - { - dropped.push(path); - } - } - }; - note(&tip_entries); - if let Some(h) = merge_head.or(pick_head) { - let other_root = self.snapshot(&h)?.root; - let store_arc = self.vfs.store(); - let mut store = store_arc.lock().unwrap(); - note(&if partial { - worktree::tree_file_entries_with_perms_sparse(&mut store, other_root, sparse)? - } else { - worktree::tree_file_entries_with_perms(&mut store, other_root)? - }); - } - if !dropped.is_empty() { - dropped.sort_unstable(); - dropped.dedup(); - return Err(Error::InvalidArgument(format!( - "protected on a parent but covered by no protection rule: {}; committing \ - would store plaintext. The rule was removed upstream; restore it with \ - `sc protect`.", - dropped.join(", ") - ))); - } - } + // Protection rules are repository data: a parent can keep an entry's + // PROTECTED bit while its rule is gone. A checkout then holds that + // path's plaintext and a commit would store it unsealed (or drop the + // absent entry's protection), so refuse before any object is written. + // No stock command removes a rule (merges union them). + self.refuse_uncovered_protected( + &protection, + &tip_entries, + &all, + merge_head.or(pick_head), + partial, + )?; let mut to_seal: Vec = Vec::new(); // (path, plaintext) for each sealed path, so its fresh blob id can be @@ -1200,6 +1173,101 @@ impl Repo { Ok(id) } + /// The commit-time guard for rules dropped upstream. `tip_entries` are the + /// tip's flattened entries (sparse-aware on a partial clone), `plain` the + /// working-tree files that would land unsealed, `other` the merge or pick + /// head of a completion. Refuses (writing nothing) when + /// 1. a tip entry is PROTECTED and `protection` covers its path with no + /// rule, which also catches an unrelated keyless commit dropping it; + /// 2. a plain path is PROTECTED on `other` (point lookups only, so a + /// subtree a partial clone does not hold is never walked); + /// 3. a plain path differs only in ASCII case from a rule prefix or a + /// PROTECTED tip path: a case-insensitive checkout writes the decrypted + /// file under that spelling, where it would then commit unsealed. + fn refuse_uncovered_protected( + &self, + protection: &Protection, + tip_entries: &BTreeMap, + plain: &[(String, Vec, scl_core::FileMode, u8)], + other: Option, + partial: bool, + ) -> Result<()> { + let protected = |perms: &u8| perms & scl_core::PROTECTED != 0; + let mut bad: Vec = tip_entries + .iter() + .filter(|(p, (.., perms))| { + protected(perms) && crate::protect::matching_prefix(protection, p).is_none() + }) + .map(|(p, _)| p.clone()) + .collect(); + if let Some(h) = other { + let root = self.snapshot(&h)?.root; + let store_arc = self.vfs.store(); + let mut store = store_arc.lock().unwrap(); + for (path, ..) in plain { + if worktree::tree_entry_at(&mut store, root, path, partial)? + .is_some_and(|(.., perms)| protected(&perms)) + { + bad.push(path.clone()); + } + } + } + let folded_rules: Vec = protection + .prefixes + .iter() + .map(|r| r.prefix.to_ascii_lowercase()) + .collect(); + let folded_tip: std::collections::BTreeSet = tip_entries + .iter() + .filter(|(_, (.., perms))| protected(perms)) + .map(|(p, _)| p.to_ascii_lowercase()) + .collect(); + let mut aliased: Vec = Vec::new(); + if !folded_rules.is_empty() || !folded_tip.is_empty() { + for (path, ..) in plain { + let f = path.to_ascii_lowercase(); + if folded_tip.contains(&f) + || folded_rules + .iter() + .any(|r| crate::protect::path_under_prefix(&f, r)) + { + aliased.push(path.clone()); + } + } + } + if bad.is_empty() && aliased.is_empty() { + return Ok(()); + } + let stopped = crate::merge_state::in_progress(&self.layout) + || crate::pick_state::in_progress(&self.layout) + || crate::rebase_state::in_progress(&self.layout); + let hint = if stopped { + "abort the operation, restore the rule, and retry" + } else { + "restore the rule with `sc protect`" + }; + bad.sort_unstable(); + bad.dedup(); + aliased.sort_unstable(); + aliased.dedup(); + let mut msg = String::new(); + if !bad.is_empty() { + msg += &format!( + "protected on a parent but covered by no protection rule: {}; committing would \ + store plaintext or drop the protection. The rule was removed upstream; {hint}. ", + bad.join(", ") + ); + } + if !aliased.is_empty() { + msg += &format!( + "differs only in case from a protected path or rule, so a case-insensitive \ + checkout would commit its plaintext unsealed: {}; rename it", + aliased.join(", ") + ); + } + Err(Error::InvalidArgument(msg.trim_end().to_string())) + } + /// Build + persist a snapshot and advance the current branch ref. pub(crate) fn commit_snapshot( &self, @@ -7414,13 +7482,11 @@ mod tests { std::fs::remove_dir_all(&dst_root).unwrap(); } - /// A tip that keeps a protected entry (PROTECTED bit, wrap list) but lacks - /// the rule is repository data a writer can build by hand. A recipient who - /// switches to it holds the plaintext, so their next ordinary commit must - /// not publish it. - #[test] - fn a_commit_never_stores_plaintext_of_a_path_whose_rule_was_dropped_upstream() { - let root = tmp_root("commit-rule-dropped"); + /// `main` holds a protected `secret/x` (sealed to the returned identity); + /// `feat` is a hand-built child with the same tree but no rule. HEAD is on + /// `feat` with no identity used yet. + fn repo_with_dropped_rule(tag: &str) -> (Repo, std::path::PathBuf, scl_crypto::SecretKey) { + let root = tmp_root(tag); let repo = Repo::init(&root).unwrap(); let (sk, pk) = scl_crypto::generate_keypair(); repo.protect("secret/", &[pk], None).unwrap(); @@ -7442,6 +7508,26 @@ mod tests { "drop the rule", ) .unwrap(); + (repo, root, sk) + } + + fn assert_refused(repo: &Repo, what: &str) { + let before = repo.head_tip().unwrap(); + let err = repo.commit("t", what).unwrap_err().to_string(); + assert!( + err.contains("secret/x") && err.contains("sc protect"), + "{err}" + ); + assert_eq!(repo.head_tip().unwrap(), before); + } + + /// A tip that keeps a protected entry (PROTECTED bit, wrap list) but lacks + /// the rule is repository data a writer can build by hand. A recipient who + /// switches to it holds the plaintext, so their next ordinary commit must + /// not publish it. + #[test] + fn a_commit_never_stores_plaintext_of_a_path_whose_rule_was_dropped_upstream() { + let (repo, root, sk) = repo_with_dropped_rule("commit-rule-dropped"); // Plaintext on disk through the normal API. let _ = std::fs::remove_file(root.join("secret/x")); repo.switch_with_identity("main", Some(&sk)).unwrap(); @@ -7451,13 +7537,96 @@ mod tests { "secret x\n" ); std::fs::write(root.join("other.txt"), "edited\n").unwrap(); - let before = repo.head_tip().unwrap(); - let err = repo.commit("t", "unrelated edit").unwrap_err().to_string(); + assert_refused(&repo, "unrelated edit"); + drop(repo); + std::fs::remove_dir_all(&root).unwrap(); + } + + #[test] + fn a_keyless_commit_does_not_silently_drop_uncovered_protected_entries() { + let (repo, root, _sk) = repo_with_dropped_rule("commit-rule-dropped-keyless"); + std::fs::write(root.join("other.txt"), "edited\n").unwrap(); + assert_refused(&repo, "keyless edit"); + drop(repo); + std::fs::remove_dir_all(&root).unwrap(); + } + + #[test] + fn a_new_plain_file_under_a_dropped_rule_is_refused() { + let (repo, root, _sk) = repo_with_dropped_rule("commit-rule-dropped-new"); + std::fs::write(root.join("secret/new.txt"), "fresh\n").unwrap(); + assert_refused(&repo, "new file"); + drop(repo); + std::fs::remove_dir_all(&root).unwrap(); + } + + #[test] + fn a_plain_path_differing_only_in_case_from_a_rule_or_protected_path_is_refused() { + let root = tmp_root("commit-case-alias"); + let repo = Repo::init(&root).unwrap(); + let (_sk, pk) = scl_crypto::generate_keypair(); + repo.protect("secret/", &[pk], None).unwrap(); + std::fs::create_dir_all(root.join("secret")).unwrap(); + std::fs::write(root.join("secret/x"), "secret x\n").unwrap(); + let tip = repo.commit("t", "protected").unwrap(); + let sparse = repo.sparse_spec().unwrap(); + let snap = |path: &str| { + repo.snapshot_files( + vec![( + path.to_string(), + b"plain\n".to_vec(), + scl_core::FileMode::FILE, + )], + Some(tip), + None, + None, + None, + None, + None, + &sparse, + None, + "t", + "m", + ) + }; + // Under the folded rule prefix (the exact spelling would be sealed). + for path in ["Secret/.keep", "SECRET/x"] { + let err = snap(path).unwrap_err().to_string(); + assert!( + err.contains("differs only in case") && err.contains(path), + "{err}" + ); + } + // Unrelated spellings still commit. + snap("secretary.txt").unwrap(); + drop(repo); + std::fs::remove_dir_all(&root).unwrap(); + } + + #[test] + fn a_stopped_operation_hint_says_to_abort_not_to_protect() { + let (repo, root, _sk) = repo_with_dropped_rule("commit-rule-dropped-stopped"); + std::fs::write(repo.layout().dot_sc.join("MERGE_HEAD"), "x").unwrap(); + let err = repo + .snapshot_files( + Vec::new(), + repo.head_tip().unwrap(), + None, + None, + None, + None, + None, + &repo.sparse_spec().unwrap(), + None, + "t", + "m", + ) + .unwrap_err() + .to_string(); assert!( - err.contains("secret/x") && err.contains("sc protect"), + err.contains("abort the operation") && !err.contains("sc protect"), "{err}" ); - assert_eq!(repo.head_tip().unwrap(), before); drop(repo); std::fs::remove_dir_all(&root).unwrap(); } diff --git a/docs/THREAT-MODEL.md b/docs/THREAT-MODEL.md index 2cf0a38d..cd4de228 100644 --- a/docs/THREAT-MODEL.md +++ b/docs/THREAT-MODEL.md @@ -107,11 +107,17 @@ too, not just the src-control-side metadata. protection rules are repository data, so a writer can hand-build a tip that keeps a path's `PROTECTED` entry but omits its rule. A recipient who checks that tip out holds the plaintext, and an unguarded `sc commit` would store it - unsealed. Every commit-building path (commit, amend, merge/pick/rebase - completion, `sc ws harvest`, `sc work`) therefore refuses, before writing any - object, when a working-tree path is `PROTECTED` on a parent (the tip, and the - merge or pick head on a completion) and no rule in the resulting policy covers - it; restore the rule with `sc protect`. + unsealed. Snapshot assembly (commit, amend, merge/pick/rebase completion, + `sc ws harvest`, `sc work`) therefore refuses, before it writes any snapshot + object, when a tip entry is `PROTECTED` and no rule in the resulting policy + covers it, when a plain working-tree path is `PROTECTED` on the merge or pick + head, or when a plain path differs only in ASCII case from a rule prefix or a + protected tip path (a case-insensitive checkout would write the decrypted + file under that spelling). Callers may first clean sparse-widen residue, fill + objects or mint the cache key. The hint is to restore the rule with + `sc protect`, or, while a merge, pick or rebase is stopped, to abort it, + restore the rule and retry. Case aliases of the other parent's protected + paths are not checked. - **Local cache key, `sc keygen` identity and TLS serve key are owner-only on unix and Windows (P33, #214, #281):** the unchanged-detection cache is keyed by `.sc/local-key`, created owner-only from From 1188bd4b77c98059b08d52eef63dc959e5a9739b Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 10:49:25 +0200 Subject: [PATCH 3/4] fix(repo): fill the other parent's trees, alias-check on disk, cache loaded trees The dropped-rule guard walked the merge/pick head's path with a plain store lookup, so a widened partial-clone merge failed on a tree it never held. It now fetches the missing trees by id on a lazy, online clone (any other clone keeps the gap error with its `sc backfill` hint) and keeps the trees it loaded in a per-guard map, so a flat directory is read once. The case-alias refusal now also requires the protected spelling to be the same file or directory as the plain path in the checkout the commit reads from (device and inode on unix, always assumed elsewhere), so a distinct `docs/private/` beside a rule `Docs/private/` commits on a case-sensitive filesystem. snapshot_files takes that checkout root. --- crates/repo/src/fill.rs | 7 ++ crates/repo/src/partial_merge.rs | 53 +++++++++ crates/repo/src/repo.rs | 193 ++++++++++++++++++++++++++----- crates/repo/src/workspace.rs | 1 + docs/THREAT-MODEL.md | 6 +- 5 files changed, 226 insertions(+), 34 deletions(-) diff --git a/crates/repo/src/fill.rs b/crates/repo/src/fill.rs index 91599f0d..4aa4160f 100644 --- a/crates/repo/src/fill.rs +++ b/crates/repo/src/fill.rs @@ -291,6 +291,13 @@ pub(crate) struct NeedsFiller<'a> { } impl NeedsFiller<'_> { + /// Make the tree `id` present (a lazy, online clone fetches it by id; any + /// other clone fails with the gap error naming `path` and its `sc + /// backfill` hint). Call it with the store lock released. + pub(crate) fn ensure_tree(&mut self, id: &ObjectId, path: &str) -> Result<()> { + self.filler.ensure_present(id, path, true) + } + /// Make the objects a tree merge asked for present. Each `(id, path)` is /// what `merge_trees` could not read and where it found it. A lazy, online /// partial clone fetches them by id in batches; any other partial clone diff --git a/crates/repo/src/partial_merge.rs b/crates/repo/src/partial_merge.rs index 6037bdbe..bddd3361 100644 --- a/crates/repo/src/partial_merge.rs +++ b/crates/repo/src/partial_merge.rs @@ -1179,3 +1179,56 @@ fn a_sidecar_that_would_overwrite_a_tracked_file_is_refused() { drop(clone); fx.cleanup(); } + +/// Widening a stopped merge lays out a file only ours changed, so completing it +/// asks the other parent about that path: its unchanged `docs/` tree was never +/// held. A lazy, online clone fetches that tree by id; a clone that cannot +/// fetch keeps the gap error with its `sc backfill` hint and the stop intact. +#[test] +fn completing_a_widened_merge_fills_the_other_parents_tree_for_a_plain_path() { + let fx = Fx::origin("widen-other-parent", |_| {}); + fx.origin_branch( + "ours_b", + &[ + ("src/a.txt", b"uno\ntwo\nthree\n"), + ("docs/a.md", b"a ours\n"), + ], + ); + let b1 = fx.origin_branch("b1", &[("src/a.txt", b"ONE\ntwo\nthree\n")]); + let theirs_docs = dir_id(&fx.origin, &b1, "docs"); + let clone = fx.clone(false); + clone.merge("origin/ours_b", "t").unwrap(); // fast-forward + assert!(matches!( + clone.merge("origin/b1", "t").unwrap_err(), + Error::MergeConflicts(1) + )); + crate::promisor::set_lazy(clone.layout(), true).unwrap(); + clone + .set_sparse(&["src/".to_string(), "docs/".to_string()], None) + .unwrap(); + assert_eq!( + std::fs::read(fx.clone_root.join("docs/a.md")).unwrap(), + b"a ours\n" + ); + assert!( + !has(&clone, &theirs_docs), + "premise: the other parent's docs tree is still a gap" + ); + clone + .resolve_path("src/a.txt", crate::conflicts::ResolveSide::Ours, None) + .unwrap(); + + crate::promisor::set_lazy(clone.layout(), false).unwrap(); + let err = clone.commit("t", "merge").unwrap_err(); + assert!(matches!(err, Error::GapOutsideFilter(_)), "got {err:?}"); + assert!(err.to_string().contains("sc backfill"), "{err}"); + assert!(clone.merge_in_progress(), "the stop is intact"); + + crate::promisor::set_lazy(clone.layout(), true).unwrap(); + let merged = clone.commit("t", "merge").unwrap(); + assert!(!clone.merge_in_progress()); + assert!(has(&clone, &theirs_docs), "fetched by id for the lookup"); + assert_eq!(clone.snapshot(&merged).unwrap().parents.len(), 2); + drop(clone); + fx.cleanup(); +} diff --git a/crates/repo/src/repo.rs b/crates/repo/src/repo.rs index 942d3c24..ccaaeb63 100644 --- a/crates/repo/src/repo.rs +++ b/crates/repo/src/repo.rs @@ -300,6 +300,7 @@ impl Repo { pick_registry_base, None, &self.sparse_spec()?, + &self.layout.root, Some(&mut cache), author, message, @@ -360,6 +361,9 @@ impl Repo { /// with "the view the host repo happens to have right now" — the two /// diverge exactly when a `sc ws` session outlives a `sparse set/disable` /// on the host, or when the caller is `sc work` at all. + /// `checkout` is the directory `files` was read from (the host root, or a + /// workspace's own dir): the case-alias guard asks it whether two + /// spellings of a protected path are one file. pub(crate) fn snapshot_files( &self, files: Vec<(String, Vec, scl_core::FileMode)>, @@ -370,6 +374,7 @@ impl Repo { pick_registry_base: Option, parents_override: Option>, sparse: &crate::sparse::Sparse, + checkout: &Path, mut cache: Option<&mut crate::cache::ProtectedCache>, author: &str, message: &str, @@ -547,7 +552,7 @@ impl Repo { &tip_entries, &all, merge_head.or(pick_head), - partial, + checkout, )?; let mut to_seal: Vec = Vec::new(); @@ -1009,6 +1014,7 @@ impl Repo { pick_registry_base, None, &self.sparse_spec()?, + &self.layout.root, Some(&mut c), author, message, @@ -1099,6 +1105,7 @@ impl Repo { None, Some(tip_snap.parents.clone()), &self.sparse_spec()?, + &self.layout.root, Some(&mut cache), author, &msg, @@ -1176,21 +1183,24 @@ impl Repo { /// The commit-time guard for rules dropped upstream. `tip_entries` are the /// tip's flattened entries (sparse-aware on a partial clone), `plain` the /// working-tree files that would land unsealed, `other` the merge or pick - /// head of a completion. Refuses (writing nothing) when + /// head of a completion, `checkout` the directory `plain` was read from. + /// Refuses (writing nothing) when /// 1. a tip entry is PROTECTED and `protection` covers its path with no /// rule, which also catches an unrelated keyless commit dropping it; - /// 2. a plain path is PROTECTED on `other` (point lookups only, so a - /// subtree a partial clone does not hold is never walked); + /// 2. a plain path is PROTECTED on `other` (point lookups along the path + /// only; a tree a lazy, online partial clone lacks is fetched by id, any + /// other clone gets the gap error with its `sc backfill` hint); /// 3. a plain path differs only in ASCII case from a rule prefix or a - /// PROTECTED tip path: a case-insensitive checkout writes the decrypted - /// file under that spelling, where it would then commit unsealed. + /// PROTECTED tip path AND that spelling is the same file or directory in + /// `checkout`: a case-insensitive checkout writes the decrypted file + /// under the plain spelling, where it would then commit unsealed. fn refuse_uncovered_protected( &self, protection: &Protection, tip_entries: &BTreeMap, plain: &[(String, Vec, scl_core::FileMode, u8)], other: Option, - partial: bool, + checkout: &Path, ) -> Result<()> { let protected = |perms: &u8| perms & scl_core::PROTECTED != 0; let mut bad: Vec = tip_entries @@ -1202,35 +1212,57 @@ impl Repo { .collect(); if let Some(h) = other { let root = self.snapshot(&h)?.root; - let store_arc = self.vfs.store(); - let mut store = store_arc.lock().unwrap(); + // Loaded trees by id, so a flat directory is read once however + // many plain paths sit in it. + let mut trees: std::collections::HashMap = + std::collections::HashMap::new(); + let mut filler = self.needs_filler()?; for (path, ..) in plain { - if worktree::tree_entry_at(&mut store, root, path, partial)? - .is_some_and(|(.., perms)| protected(&perms)) - { - bad.push(path.clone()); + let comps: Vec<&str> = path.split('/').collect(); + let mut cur = root; + for (i, comp) in comps.iter().enumerate() { + if let std::collections::hash_map::Entry::Vacant(slot) = trees.entry(cur) { + filler.ensure_tree(&cur, path)?; + slot.insert(self.vfs.store().lock().unwrap().get_tree(&cur)?); + } + let Some(e) = trees[&cur].get(comp) else { + break; + }; + match (e.kind, i + 1 == comps.len()) { + (scl_core::EntryKind::Tree, false) => cur = e.id, + (scl_core::EntryKind::Blob, true) => { + if protected(&e.perms) { + bad.push(path.clone()); + } + break; + } + _ => break, + } } } } - let folded_rules: Vec = protection - .prefixes - .iter() - .map(|r| r.prefix.to_ascii_lowercase()) - .collect(); - let folded_tip: std::collections::BTreeSet = tip_entries + // A rule prefix or protected tip path that `path` could alias, by + // ASCII case, with the spelling to compare on disk. + let mut aliased: Vec = Vec::new(); + let protected_tip: Vec<&String> = tip_entries .iter() .filter(|(_, (.., perms))| protected(perms)) - .map(|(p, _)| p.to_ascii_lowercase()) + .map(|(p, _)| p) .collect(); - let mut aliased: Vec = Vec::new(); - if !folded_rules.is_empty() || !folded_tip.is_empty() { + if !protection.prefixes.is_empty() || !protected_tip.is_empty() { for (path, ..) in plain { let f = path.to_ascii_lowercase(); - if folded_tip.contains(&f) - || folded_rules - .iter() - .any(|r| crate::protect::path_under_prefix(&f, r)) - { + // ASCII folding keeps byte lengths, so a rule's bare length + // cuts the same directory out of `path`. + let by_rule = protection.prefixes.iter().any(|r| { + let bare = r.prefix.trim_end_matches('/'); + crate::protect::path_under_prefix(&f, &bare.to_ascii_lowercase()) + && same_file(checkout, &path[..bare.len()], bare) + }); + let by_path = protected_tip + .iter() + .any(|q| q.to_ascii_lowercase() == f && same_file(checkout, path, q)); + if by_rule || by_path { aliased.push(path.clone()); } } @@ -3160,6 +3192,28 @@ fn stop_write_blocker( } } +/// Do `a` and `b` (checkout-relative) name the same file or directory, as a +/// case-insensitive filesystem makes two spellings do? Compared by device and +/// inode without following a final symlink (the commit reads symlinks as +/// themselves); a path that does not exist is not the same as anything. Off +/// unix there is no cheap identity, so the answer is a conservative yes. +#[cfg(unix)] +fn same_file(root: &Path, a: &str, b: &str) -> bool { + use std::os::unix::fs::MetadataExt; + match ( + std::fs::symlink_metadata(root.join(a)), + std::fs::symlink_metadata(root.join(b)), + ) { + (Ok(x), Ok(y)) => x.dev() == y.dev() && x.ino() == y.ino(), + _ => false, + } +} + +#[cfg(not(unix))] +fn same_file(_root: &Path, _a: &str, _b: &str) -> bool { + true +} + #[cfg(test)] mod tests { #[test] @@ -7436,6 +7490,7 @@ mod tests { None, None, &dst.sparse_spec().unwrap(), + &dst_root, None, "t", "msg", @@ -7584,18 +7639,25 @@ mod tests { None, None, &sparse, + &root, None, "t", "m", ) }; // Under the folded rule prefix (the exact spelling would be sealed). + // Refused only where the checkout really makes them one path. + let insensitive = fs_ignores_case(&root); for path in ["Secret/.keep", "SECRET/x"] { - let err = snap(path).unwrap_err().to_string(); - assert!( - err.contains("differs only in case") && err.contains(path), - "{err}" - ); + if insensitive { + let err = snap(path).unwrap_err().to_string(); + assert!( + err.contains("differs only in case") && err.contains(path), + "{err}" + ); + } else { + snap(path).unwrap(); + } } // Unrelated spellings still commit. snap("secretary.txt").unwrap(); @@ -7603,6 +7665,72 @@ mod tests { std::fs::remove_dir_all(&root).unwrap(); } + /// Does the filesystem under `dir` treat `Probe` and `probe` as one file? + fn fs_ignores_case(dir: &Path) -> bool { + let probe = dir.join("case-probe"); + std::fs::write(&probe, b"p").unwrap(); + let same = dir.join("CASE-PROBE").exists(); + std::fs::remove_file(&probe).unwrap(); + same + } + + /// A plain `docs/private/README` beside a rule `Docs/private/` is a + /// distinct path on a case-sensitive filesystem and must commit there; on + /// a case-insensitive one the checkout makes them one directory. + #[test] + fn a_case_variant_of_a_rule_prefix_is_refused_only_where_it_aliases() { + let root = tmp_root("commit-case-variant-rule"); + let repo = Repo::init(&root).unwrap(); + let (_sk, pk) = scl_crypto::generate_keypair(); + repo.protect("Docs/private/", &[pk], None).unwrap(); + std::fs::create_dir_all(root.join("Docs/private")).unwrap(); + std::fs::write(root.join("Docs/private/x"), "x\n").unwrap(); + let tip = repo.commit("t", "protected").unwrap(); + let res = repo.snapshot_files( + vec![( + "docs/private/README".to_string(), + b"plain\n".to_vec(), + scl_core::FileMode::FILE, + )], + Some(tip), + None, + None, + None, + None, + None, + &repo.sparse_spec().unwrap(), + &root, + None, + "t", + "m", + ); + if fs_ignores_case(&root) { + assert!(res + .unwrap_err() + .to_string() + .contains("differs only in case")); + } else { + res.unwrap(); + } + drop(repo); + std::fs::remove_dir_all(&root).unwrap(); + } + + #[cfg(unix)] + #[test] + fn same_file_compares_identity_and_never_follows_a_final_symlink() { + let root = tmp_root("same-file"); + std::fs::create_dir_all(root.join("d")).unwrap(); + std::fs::write(root.join("d/a"), b"a").unwrap(); + std::fs::write(root.join("d/b"), b"b").unwrap(); + std::os::unix::fs::symlink("a", root.join("d/link")).unwrap(); + assert!(same_file(&root, "d/a", "d/a")); + assert!(!same_file(&root, "d/a", "d/b")); + assert!(!same_file(&root, "d/a", "d/link")); + assert!(!same_file(&root, "d/a", "d/missing")); + std::fs::remove_dir_all(&root).unwrap(); + } + #[test] fn a_stopped_operation_hint_says_to_abort_not_to_protect() { let (repo, root, _sk) = repo_with_dropped_rule("commit-rule-dropped-stopped"); @@ -7617,6 +7745,7 @@ mod tests { None, None, &repo.sparse_spec().unwrap(), + &root, None, "t", "m", diff --git a/crates/repo/src/workspace.rs b/crates/repo/src/workspace.rs index f4691cdb..f375e48f 100644 --- a/crates/repo/src/workspace.rs +++ b/crates/repo/src/workspace.rs @@ -160,6 +160,7 @@ pub(crate) fn workspace_candidate( None, None, sparse, + dir, cache, author, message, diff --git a/docs/THREAT-MODEL.md b/docs/THREAT-MODEL.md index cd4de228..f529cae1 100644 --- a/docs/THREAT-MODEL.md +++ b/docs/THREAT-MODEL.md @@ -112,8 +112,10 @@ too, not just the src-control-side metadata. object, when a tip entry is `PROTECTED` and no rule in the resulting policy covers it, when a plain working-tree path is `PROTECTED` on the merge or pick head, or when a plain path differs only in ASCII case from a rule prefix or a - protected tip path (a case-insensitive checkout would write the decrypted - file under that spelling). Callers may first clean sparse-widen residue, fill + protected tip path and the checkout makes the two spellings one file (same + device and inode; always assumed off unix), so a case-insensitive checkout + would write the decrypted file under that spelling. A lazy, online partial + clone fetches the other parent's missing trees by id for that lookup. Callers may first clean sparse-widen residue, fill objects or mint the cache key. The hint is to restore the rule with `sc protect`, or, while a merge, pick or rebase is stopped, to abort it, restore the rule and retry. Case aliases of the other parent's protected From bcf31d8a9f296bfc26b55db6785a3a22a4e126f1 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 11:06:42 +0200 Subject: [PATCH 4/4] fix(repo): index the case-alias guard by folded spelling The guard folded and scanned every protected tip path for every plain file. It now builds a folded-spelling map of protected tip paths and rule prefixes once and looks up each plain path and its parent directories, running the device/inode comparison only on a match. The alias tests expect a refusal off unix too, where the identity check always assumes aliasing, and the distinct-path test creates both directories on disk. --- crates/repo/src/repo.rs | 61 +++++++++++++++++++++++++++-------------- 1 file changed, 40 insertions(+), 21 deletions(-) diff --git a/crates/repo/src/repo.rs b/crates/repo/src/repo.rs index ccaaeb63..748fbe33 100644 --- a/crates/repo/src/repo.rs +++ b/crates/repo/src/repo.rs @@ -1242,27 +1242,42 @@ impl Repo { } } // A rule prefix or protected tip path that `path` could alias, by - // ASCII case, with the spelling to compare on disk. + // ASCII case. Both are indexed once by folded spelling, so each plain + // path costs a few lookups and only a match touches the disk. let mut aliased: Vec = Vec::new(); - let protected_tip: Vec<&String> = tip_entries - .iter() - .filter(|(_, (.., perms))| protected(perms)) - .map(|(p, _)| p) - .collect(); - if !protection.prefixes.is_empty() || !protected_tip.is_empty() { + let mut tips: std::collections::HashMap> = Default::default(); + for (p, (.., perms)) in tip_entries { + if protected(perms) { + tips.entry(p.to_ascii_lowercase()).or_default().push(p); + } + } + let mut rules: std::collections::HashMap> = Default::default(); + for r in &protection.prefixes { + let bare = r.prefix.trim_end_matches('/'); + rules + .entry(bare.to_ascii_lowercase()) + .or_default() + .push(bare); + } + if !rules.is_empty() || !tips.is_empty() { for (path, ..) in plain { let f = path.to_ascii_lowercase(); - // ASCII folding keeps byte lengths, so a rule's bare length - // cuts the same directory out of `path`. - let by_rule = protection.prefixes.iter().any(|r| { - let bare = r.prefix.trim_end_matches('/'); - crate::protect::path_under_prefix(&f, &bare.to_ascii_lowercase()) - && same_file(checkout, &path[..bare.len()], bare) - }); - let by_path = protected_tip - .iter() - .any(|q| q.to_ascii_lowercase() == f && same_file(checkout, path, q)); - if by_rule || by_path { + let by_path = tips + .get(&f) + .is_some_and(|qs| qs.iter().any(|q| same_file(checkout, path, q))); + // The path itself and each parent directory, as a rule's bare + // form; ASCII folding keeps byte lengths, so the same prefix + // cuts the original spelling. + let by_rule = !by_path + && f.match_indices('/') + .map(|(i, _)| i) + .chain(std::iter::once(f.len())) + .any(|i| { + rules.get(&f[..i]).is_some_and(|bares| { + bares.iter().any(|b| same_file(checkout, &path[..i], b)) + }) + }); + if by_path || by_rule { aliased.push(path.clone()); } } @@ -7646,8 +7661,9 @@ mod tests { ) }; // Under the folded rule prefix (the exact spelling would be sealed). - // Refused only where the checkout really makes them one path. - let insensitive = fs_ignores_case(&root); + // Refused only where the checkout really makes them one path (off + // unix the identity check always assumes they are). + let insensitive = fs_ignores_case(&root) || !cfg!(unix); for path in ["Secret/.keep", "SECRET/x"] { if insensitive { let err = snap(path).unwrap_err().to_string(); @@ -7686,6 +7702,9 @@ mod tests { std::fs::create_dir_all(root.join("Docs/private")).unwrap(); std::fs::write(root.join("Docs/private/x"), "x\n").unwrap(); let tip = repo.commit("t", "protected").unwrap(); + // Two existing directories on a case-sensitive filesystem. + std::fs::create_dir_all(root.join("docs/private")).unwrap(); + std::fs::write(root.join("docs/private/README"), "plain\n").unwrap(); let res = repo.snapshot_files( vec![( "docs/private/README".to_string(), @@ -7704,7 +7723,7 @@ mod tests { "t", "m", ); - if fs_ignores_case(&root) { + if fs_ignores_case(&root) || !cfg!(unix) { assert!(res .unwrap_err() .to_string()