Skip to content
7 changes: 6 additions & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -366,7 +366,7 @@ transport-adjacent. The rest, imperatively:
directory onto an untracked or ignored one** (`refuse_untracked_overwrite`); move it
away and retry. A directory holding only tracked files is not such a case: a file/directory change at one path crosses switch, undo, abort and `--continue`, and the emptied directories are cleared (#247). `materialize` checks every such directory before its first removal, so a refusal changes nothing and an abort stays retryable; a forward op also refuses a user's empty directory there (it cannot tell it from a husk), while `materialize` itself prunes empty ones. (On a case-insensitive checkout, replacing `foo/a` with a file `Foo` is refused: the check does not follow the case alias. Fail-closed.) On a sparse checkout the same holds for a path the result adds
outside the view (a later commit would take the user's file instead, #248); there any directory at the path refuses, tracked contents or not.
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).
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, and every `materialize`, unborn merge included, refuses a path with a symlink among its parent directories).
- **A snapshot never holds a path as both a file and a directory (#278).** The
tree builders (`scl_vfs::Repo::build_root`, and `private::build_tree_objects` for private branches) refuse it with
`FileDirCollision { file, child }` before writing any tree. It matters because
Expand All @@ -375,6 +375,11 @@ transport-adjacent. The rest, imperatively:
makes the commit, merge completion, `sc ws harvest` or `sc ws refresh` fail
until the directory is removed (ADR-0034 refinement 9). Across commits a path
may still change kind (#247).
- **Tree paths go through `scl_core::check_tree_path` before any write.** Tree
decode accepts any entry name, so the flatteners in `worktree.rs`, `safe_join`
and `Worktree::checkout` refuse `.sc` (any depth, any alias), traversal, NUL
and, on Windows, `\` and `:`; both tree builders refuse to commit them. A new
write-out path must flatten through those walkers or call it itself.
- **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
Expand Down
125 changes: 110 additions & 15 deletions crates/cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3996,21 +3996,42 @@ fn run_clone_git(url: &str, dst: &std::path::Path) -> Result<()> {
);
}

std::fs::create_dir_all(dst)?;
let repo = scl_repo::Repo::init(dst)?;
repo.remote_add_git("origin", url)?;

// Sync the mirror, then point the unborn HEAD at the remote's default
// branch name BEFORE fetching, so the tracking ref and local branch agree.
let mirror = git_remote_effective_path(&repo, "origin", url, true)?;
let default = scl_gitio::bridge::remote_default_branch(&mirror)?;
scl_repo::refs::write_head(repo.layout(), &default)?;

run_fetch_git(&repo, "origin")?;
// Adopt: merge the tracking ref into the unborn branch (ADR-0018's
// unborn fast-forward). Author resolution mirrors run_merge's.
let author = resolve_author(None);
repo.merge(&format!("origin/{default}"), &author)?;
// An existing destination must be an empty directory (git parity).
let mut claim = scl_repo::sync::claim_clone_dir(dst)?;
let repo = match claim.init_repo() {
Ok(r) => r,
Err(e) => {
// Removes `.sc/` only if `init_repo` created it exclusively.
scl_repo::sync::discard_failed_clone(&claim);
return Err(e.into());
}
};
// A failed clone takes itself back out, as `git clone` does, while `repo`
// still holds the repo lock.
let adopted = (|| -> Result<String> {
repo.remote_add_git("origin", url)?;

// Sync the mirror, then point the unborn HEAD at the remote's default
// branch name BEFORE fetching, so the tracking ref and local branch agree.
let mirror = git_remote_effective_path(&repo, "origin", url, true)?;
let default = scl_gitio::bridge::remote_default_branch(&mirror)?;
scl_repo::refs::write_head(repo.layout(), &default)?;

run_fetch_git(&repo, "origin")?;
// Adopt: merge the tracking ref into the unborn branch (ADR-0018's
// unborn fast-forward). Author resolution mirrors run_merge's.
let author = resolve_author(None);
repo.merge(&format!("origin/{default}"), &author)?;
Ok(default)
})();
let default = match adopted {
Ok(default) => default,
Err(e) => {
scl_repo::sync::discard_failed_clone(&claim);
drop(repo);
return Err(e);
}
};
println!("cloned {url} into {} (branch {default})", dst.display());
Ok(())
}
Expand Down Expand Up @@ -5381,6 +5402,80 @@ mod tests {
std::fs::remove_dir_all(&root).unwrap();
}

/// A Git repo that tracks `.sc/recipients.toml` must not get that file into
/// the cloner's `.sc/`: the clone fails and takes its directory back out.
#[test]
fn clone_of_a_git_repo_tracking_a_control_file_is_refused() {
let _g = GIT_ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());
let root = std::env::temp_dir().join(format!("scl-cli-gitplant-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(&root).unwrap();
let hub = root.join("hub.git");
std::process::Command::new("git")
.args(["init", "--bare", "-b", "main", hub.to_str().unwrap()])
.status()
.unwrap();
let seed = root.join("seed");
std::process::Command::new("git")
.args(["init", "-b", "main", seed.to_str().unwrap()])
.status()
.unwrap();
std::fs::create_dir_all(seed.join(".sc")).unwrap();
std::fs::write(seed.join(".sc/recipients.toml"), "planted").unwrap();
std::fs::write(seed.join("a.txt"), "x").unwrap();
for args in [
vec!["add", "."],
vec![
"-c",
"user.name=t",
"-c",
"user.email=t@t",
"commit",
"-m",
"seed",
],
] {
std::process::Command::new("git")
.current_dir(&seed)
.args(&args)
.status()
.unwrap();
}
std::process::Command::new("git")
.current_dir(&seed)
.args(["push", &format!("file://{}", hub.display()), "main"])
.status()
.unwrap();

let dst = root.join("victim");
let err = run_clone_git(&format!("file://{}", hub.display()), &dst).unwrap_err();
assert!(
err.to_string().contains("unsafe path"),
"unexpected error: {err:#}"
);
assert!(!dst.exists(), "the failed clone removes its directory");

std::fs::remove_dir_all(&root).unwrap();
}

/// Git parity: `sc clone` into a non-empty directory is refused before any
/// network or write, so a symlink already in it cannot redirect the checkout.
#[test]
fn clone_git_into_a_non_empty_directory_is_refused() {
let root = std::env::temp_dir().join(format!("scl-cli-nonempty-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(&root).unwrap();
std::fs::write(root.join("mine.txt"), "keep me").unwrap();
let err = run_clone_git("file:///nonexistent/hub.git", &root).unwrap_err();
assert!(
err.to_string().contains("not an empty directory"),
"unexpected error: {err:#}"
);
assert_eq!(std::fs::read(root.join("mine.txt")).unwrap(), b"keep me");
assert!(!root.join(".sc").exists());
std::fs::remove_dir_all(&root).unwrap();
}

#[test]
fn clone_git_flag_with_local_path_errors_clearly() {
// Env mutation (git init) — serialize with the shared git-env lock.
Expand Down
9 changes: 9 additions & 0 deletions crates/core/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,15 @@ pub enum Error {
#[error("bad pack index: {0}")]
BadPackIndex(String),

/// A tree path that must never be written under a checkout (traversal,
/// NUL, the `.sc` control directory or an alias of it, and on Windows a
/// separator or drive marker); see [`crate::check_tree_path`].
#[error("unsafe path in tree: {path:?}: {reason}")]
UnsafePath {
path: String,
reason: crate::pathname::PathRefusal,
},

#[error("backend io error: {0}")]
Io(#[from] std::io::Error),
}
Expand Down
2 changes: 2 additions & 0 deletions crates/core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ pub mod id;
pub mod object;
pub mod owner_only;
pub mod pack;
pub mod pathname;
pub mod store;
#[cfg(windows)]
mod winacl;
Expand Down Expand Up @@ -180,6 +181,7 @@ pub use object::{
RecipientState, SealedObj, Secret, SignatureObj, Snapshot, Transcript, Tree, TreeEntry,
WrappedKey, PROTECTED, RANDOMIZED,
};
pub use pathname::{check_tree_path, PathRefusal};
pub use store::{Backend, SpillPolicy, Store, StoreConfig, StoreStats};

#[cfg(test)]
Expand Down
Loading
Loading