Skip to content
Merged
29 changes: 18 additions & 11 deletions crates/cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -452,7 +452,7 @@ enum Cmd {
/// Target Git repo path (created bare if absent).
#[arg(long)]
to: PathBuf,
/// Ref to update (default: refs/heads/<current-branch>).
/// Ref to update (default: `refs/heads/<current-branch>`).
#[arg(long)]
r#ref: Option<String>,
/// Allow exporting protected ciphertext and dropping secrets.
Expand Down Expand Up @@ -661,7 +661,7 @@ enum EscrowOp {
Set { key_or_name: String },
/// Append a key to the escrow list (deduped).
Add { key_or_name: String },
/// Remove one escrow key by recipient id or [recipients] name.
/// Remove one escrow key by recipient id or `[recipients]` name.
Remove { id_or_name: String },
/// List the configured escrow keys.
Show,
Expand Down Expand Up @@ -760,7 +760,7 @@ enum ServeSub {
#[command(subcommand)]
op: ServeTokenOp,
},
/// Print this repo's serve-TLS fingerprint (sha256:<hex> of the SPKI),
/// Print this repo's serve-TLS fingerprint (`sha256:<hex>` of the SPKI),
/// minting `.sc/serve-tls/` if absent — distribute this to clients as
/// SC_HTTPS_FINGERPRINT or to verify a first-connect pin. (P32)
Fingerprint { path: Option<PathBuf> },
Expand Down Expand Up @@ -1141,9 +1141,8 @@ fn run_tls(op: TlsOp) -> Result<()> {
} else {
for e in &entries {
print_line(&format!(
"{}:{} {}",
e.host,
e.port,
"{} {}",
tls_pins::host_port(&e.host, e.port),
tls_pins::fingerprint(&e.pin)
));
}
Expand All @@ -1157,11 +1156,16 @@ fn run_tls(op: TlsOp) -> Result<()> {
let (host, port) = tls_pins::parse_host_port(&target)?;
let n = tls_pins::forget(&file, &host, port)?;
if n == 0 {
anyhow::bail!("no pin for {host}:{port} in {}", file.display());
anyhow::bail!(
"no pin for {} in {}",
tls_pins::host_port(&host, port),
file.display()
);
}
println!(
"forgot {n} pin(s) for {host}:{port}; a later connection pins what it sees \
unless SC_HTTPS_STRICT=1 or SC_HTTPS_FINGERPRINT is set (then use `sc tls pin`)"
"forgot {n} pin(s) for {}; a later connection pins what it sees \
unless SC_HTTPS_STRICT=1 or SC_HTTPS_FINGERPRINT is set (then use `sc tls pin`)",
tls_pins::host_port(&host, port)
);
Ok(())
}
Expand All @@ -1173,8 +1177,9 @@ fn run_tls(op: TlsOp) -> Result<()> {
let pin = tls_pins::parse_fingerprint(&fingerprint)?;
let replaced = tls_pins::set_pin(&file, &host, port, &pin)?;
println!(
"{} {host}:{port} -> {}",
"{} {} -> {}",
if replaced { "re-pinned" } else { "pinned" },
tls_pins::host_port(&host, port),
tls_pins::fingerprint(&pin)
);
Ok(())
Expand Down Expand Up @@ -3750,7 +3755,9 @@ fn run_serve(
);
}
// `--http`'s `handle_http_connection` gates on `.sc/` presence
// unconditionally (404 before any dispatch, store mode included).
// before any dispatch, store mode included (the 404 follows the
// auth gate (#207); a listener that requires a token answers 401
// first).
// `--stdio` has no such gate upstream — enforce it here, before
// touching stdin, so a `--store` session never auto-vivifies
// `<path>/.sc/tmp/` under an uninitialized directory (which
Expand Down
8 changes: 8 additions & 0 deletions crates/cli/tests/remote_add_validation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ fn malformed_http_urls_are_refused_at_add_time_and_good_ones_recorded() {
"sc+http://host:99999/repo",
"sc+https:/host/repo", // near-miss scheme: one slash
"sc+http:host/repo",
"sc+http://[::1/repo", // unclosed bracket
"sc+http://[::1]x/repo", // junk after the bracket
"sc+http://[host]:7777/r", // brackets hold only an IPv6 literal
"sc+http://::1:7777/repo", // unbracketed IPv6
] {
let out = sc(&root, &["remote", "add", "origin", bad]);
assert!(!out.status.success(), "{bad} should be refused");
Expand All @@ -43,6 +47,8 @@ fn malformed_http_urls_are_refused_at_add_time_and_good_ones_recorded() {
for (name, good) in [
("plain", "sc+http://127.0.0.1:7777/repo"),
("secure", "sc+https://example.com/repo"),
("v6", "sc+http://[::1]:7777/repo"),
("v6s", "sc+https://[2001:db8::1]/repo"),
] {
let out = sc(&root, &["remote", "add", name, good]);
assert!(
Expand All @@ -54,6 +60,8 @@ fn malformed_http_urls_are_refused_at_add_time_and_good_ones_recorded() {
let list = String::from_utf8_lossy(&sc(&root, &["remote", "list"]).stdout).into_owned();
assert!(list.contains("sc+http://127.0.0.1:7777/repo"), "{list}");
assert!(list.contains("sc+https://example.com/repo"), "{list}");
assert!(list.contains("sc+http://[::1]:7777/repo"), "{list}");
assert!(list.contains("sc+https://[2001:db8::1]/repo"), "{list}");

std::fs::remove_dir_all(&root).unwrap();
assert!(!root.exists(), "test must leave no residue");
Expand Down
32 changes: 32 additions & 0 deletions crates/cli/tests/tls_pins_cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,3 +159,35 @@ fn list_json_survives_a_non_utf8_pin_file_path() {
std::fs::remove_dir_all(&dir).unwrap();
assert!(!dir.exists());
}

#[test]
fn ipv6_literal_pins_use_the_bracketed_form() {
let dir = tmp("v6");
let kh = dir.join("known_hosts");
let fp = format!("sha256:{}", "ab".repeat(32));

let o = sc(&kh, &["tls", "pin", "[0:0:0:0:0:0:0:1]:7777", &fp]);
assert!(o.status.success(), "{}", err(&o));
assert!(out(&o).contains("pinned [::1]:7777"), "{}", out(&o));
assert_eq!(
out(&sc(&kh, &["tls", "list"])),
format!("[::1]:7777 {fp}\n")
);
assert_eq!(
std::fs::read_to_string(&kh).unwrap(),
format!("[::1]:7777 {fp}\n")
);

let o = sc(&kh, &["tls", "forget", "[::1]:7777"]);
assert!(o.status.success(), "{}", err(&o));
assert!(
out(&o).contains("forgot 1 pin(s) for [::1]:7777"),
"{}",
out(&o)
);
assert_eq!(out(&sc(&kh, &["tls", "list"])), "");
assert!(!sc(&kh, &["tls", "pin", "::1", &fp]).status.success());

std::fs::remove_dir_all(&dir).unwrap();
assert!(!dir.exists(), "test must leave no residue");
}
239 changes: 239 additions & 0 deletions crates/repo/src/conflicts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1241,6 +1241,245 @@ mod tests {
assert!(!root.exists(), "test must leave no residue");
}

/// The (blob id, perms) at `path` in `snapshot`'s tree.
fn protected_entry_at(repo: &Repo, snapshot: ObjectId, path: &str) -> (ObjectId, u8) {
let store_arc = repo.vfs().store();
let mut store = store_arc.lock().unwrap();
let root = store.get_snapshot(&snapshot).unwrap().root;
let (id, _mode, perms) = *tree_file_entries_with_perms(&mut store, root)
.unwrap()
.get(path)
.unwrap();
(id, perms)
}

/// A protected repo with `secret/a.txt` committed as `base\n` on `main`
/// and a `feature` branch forked from it.
fn protected_fork(tag: &str) -> (std::path::PathBuf, Repo, scl_crypto::SecretKey) {
let root = tmp_root(tag);
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();
(root, repo, alice_sk)
}

/// Commit `secret/a.txt` on the current branch as a pre-P33 CONVERGENT
/// blob (the CLI can no longer mint one), wrapped for `pk`. The file on
/// disk is set to `plaintext` first so the checkout stays clean.
fn commit_convergent_secret(
repo: &Repo,
plaintext: &[u8],
pk: &scl_crypto::PublicKey,
) -> ObjectId {
std::fs::write(repo.layout().root.join("secret/a.txt"), plaintext).unwrap();
let tip = repo.head_tip().unwrap().unwrap();
let mut protection = repo.snapshot(&tip).unwrap().protection;
let (cipher, dek) = scl_crypto::encrypt_path(plaintext);
protection.wrapped.insert(
Object::blob(cipher.clone()).id(),
vec![scl_crypto::wrap_dek_for(&dek, pk)],
);
let root = repo
.vfs
.write_tree_with_perms(&[(
"secret/a.txt".to_string(),
cipher,
scl_core::FileMode::FILE,
PROTECTED,
)])
.unwrap();
repo.commit_snapshot(
root,
vec![tip],
Default::default(),
protection,
"me",
"convergent secret",
)
.unwrap()
}

#[test]
fn resolve_theirs_on_a_protected_path_carries_their_ciphertext_on_rebase_continue() {
let (root, repo, alice_sk) = protected_fork("resolve-theirs-carry-rebase");
std::fs::write(root.join("secret/a.txt"), b"main-edit\n").unwrap();
repo.commit("me", "main edits secret").unwrap();
repo.switch_with_identity("feature", Some(&alice_sk))
.unwrap();
std::fs::write(root.join("secret/a.txt"), b"feature-edit\n").unwrap();
let replayed = repo.commit("me", "feature edits secret").unwrap();

let stopped = repo.rebase("main", "me", Some(&alice_sk)).unwrap();
assert!(
matches!(stopped, crate::replay::RebaseResult::Stopped { .. }),
"got {stopped:?}"
);
repo.resolve_path("secret/a.txt", ResolveSide::Theirs, Some(&alice_sk))
.unwrap();
let crate::replay::RebaseResult::Rebased { new_tip, .. } =
repo.rebase_continue("me", Some(&alice_sk)).unwrap()
else {
panic!("expected Rebased");
};

assert_eq!(
protected_blob_at(&repo, new_tip, "secret/a.txt"),
protected_blob_at(&repo, replayed, "secret/a.txt"),
"a --theirs resolution keeps the replayed commit's ciphertext"
);

drop(repo);
std::fs::remove_dir_all(&root).unwrap();
assert!(!root.exists(), "test must leave no residue");
}

#[test]
fn resolve_theirs_carries_a_convergent_blob_from_their_side() {
let (root, repo, alice_sk) = protected_fork("resolve-theirs-convergent");
let alice_pk = alice_sk.public();
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();
let theirs_tip = commit_convergent_secret(&repo, b"theirs\n", &alice_pk);
let (theirs_blob, theirs_perms) = protected_entry_at(&repo, theirs_tip, "secret/a.txt");
assert_eq!(theirs_perms & scl_core::RANDOMIZED, 0, "setup: convergent");
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();

let (blob, perms) = protected_entry_at(&repo, merged, "secret/a.txt");
assert_eq!((blob, perms), (theirs_blob, theirs_perms));
// Still decryptable: a fresh checkout of the merge gets their plaintext.
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");
}

/// The carry needs their wrap list in the merged protection. Repoint the
/// merge head at a copy of their snapshot without it (a state a real merge
/// never produces, since completion unions both parents' wraps) and the
/// path must seal fresh instead of carrying a blob nobody can open.
#[test]
fn resolve_theirs_seals_when_their_wrap_list_is_missing() {
let (root, repo, alice_sk) = protected_fork("resolve-theirs-no-wraps");
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();
let theirs_blob = protected_blob_at(&repo, theirs_tip, "secret/a.txt");
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();
let theirs = repo.snapshot(&theirs_tip).unwrap();
let stripped = repo
.build_snapshot(
theirs.root,
theirs.parents.clone(),
theirs.secrets.clone(),
scl_core::Protection {
prefixes: theirs.protection.prefixes.clone(),
wrapped: Default::default(),
},
"me",
"theirs without wraps",
)
.unwrap();
crate::merge_state::write(repo.layout(), &stripped, &[], None).unwrap();
let merged = repo.commit("me", "take theirs").unwrap();

assert_ne!(
protected_blob_at(&repo, merged, "secret/a.txt"),
theirs_blob,
"without their wraps the path is re-sealed, not carried"
);
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",
"the re-sealed blob decrypts"
);

drop(repo);
std::fs::remove_dir_all(&root).unwrap();
assert!(!root.exists(), "test must leave no residue");
}

/// Documented under-grant (ADR-0043): their blob keeps their wrap list, so
/// a recipient granted on our side after the fork is not applied to it.
#[test]
fn resolve_theirs_after_a_grant_on_our_side_under_grants_until_rewrap() {
let (root, repo, alice_sk) = protected_fork("resolve-theirs-under-grant");
let (_bob_sk, bob_pk) = scl_crypto::generate_keypair();
std::fs::write(root.join("secret/a.txt"), b"ours\n").unwrap();
repo.commit("me", "ours edits secret").unwrap();
repo.grant("secret/", &alice_sk, &bob_pk).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();
let merged = repo.commit("me", "take theirs").unwrap();

let blob = protected_blob_at(&repo, merged, "secret/a.txt");
assert_eq!(blob, protected_blob_at(&repo, theirs_tip, "secret/a.txt"));
let snap = repo.snapshot(&merged).unwrap();
let wrapped_for = |pk: &scl_crypto::PublicKey| {
snap.protection.wrapped[&blob]
.iter()
.any(|w| w.recipient_id == pk.recipient_id().to_string())
};
assert!(
wrapped_for(&alice_sk.public()),
"their recipient keeps access"
);
assert!(
!wrapped_for(&bob_pk),
"the grant made on our side is not applied to their blob"
);
assert!(
snap.protection.prefixes[0]
.recipients
.iter()
.any(|r| r.key == bob_pk.to_bytes()),
"the merged rule still lists the new recipient"
);

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");
Expand Down
Loading
Loading