Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .claude/skills/sc-cli-reference/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,13 @@ cargo run --bin sc -- clone sc+https://host[:port]/repo <dst> # TLS clone (P32
# SC_HTTPS_FINGERPRINT=<sha256:hex> pre-pins (CI),
# SC_HTTPS_STRICT=1 refuses unknown hosts;
# remote add/fetch/push accept the same URL form
cargo run --bin sc -- tls list [--json] # pins in the known_hosts file (ADR-0053)
cargo run --bin sc -- tls forget <host[:port]> # drop a host's pin (changed server key); a later
# accept-new connect (no SC_HTTPS_STRICT, no
# SC_HTTPS_FINGERPRINT) re-pins; errors if nothing
# was pinned
cargo run --bin sc -- tls pin <host[:port]> <sha256:hex> # pin without connecting (replaces)
cargo run --bin sc -- tls path # the pin file in effect
bash demo/run_tls_demo.sh # sc+https proof (P32): TLS round trip w/ signed
# chunked blob, TOFU pin/mismatch/strict/pre-pin,
# tightened plaintext gate — run twice
Expand Down
4 changes: 2 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -268,8 +268,8 @@ transport-adjacent. The rest, imperatively:
Deferred work is tracked in **`ROADMAP.md` → Deferred** (single source of
truth — do not re-list items here). Notable standing entries: transparent
lazy-fetch for partial clones, per-case gap-tolerant merge/replay on partial
clones, CA-path validation alongside TOFU pinning, and pin-management
UX (`sc tls`).
clones, and CA-path validation alongside TOFU pinning. `sc tls list/forget/pin/path`
manages the `sc+https://` pin file (ADR-0053).

## Agent skills

Expand Down
6 changes: 3 additions & 3 deletions ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -836,9 +836,9 @@ scale-&-reach horizon):
the Phase 32 entry above. Follow-ons this phase named rather than closed:
CA-path validation as an additive trust option for PEM-provisioned
deployments (v1 is pin-only, names/validity ignored); opt-in SNI/
certificate-name validation; pin-management UX (`sc tls` list/remove
entries in `~/.config/sc/known_hosts` — today only `sc serve fingerprint`
and first-connect/`SC_HTTPS_FINGERPRINT` write pins, nothing removes one);
certificate-name validation; pin-management UX (shipped in ADR-0053 as `sc tls list/forget/pin/path`;
before it, only first-connect and `SC_HTTPS_FINGERPRINT` wrote pins and
nothing listed or removed one);
TLS session-resumption knobs (not evaluated this phase — a later
throughput pass if repeated short-lived connections to the same host prove
handshake cost material).
Expand Down
103 changes: 103 additions & 0 deletions crates/cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -506,6 +506,12 @@ enum Cmd {
#[command(subcommand)]
op: SparseOp,
},
/// Manage the `sc+https://` pins in the user-level known_hosts file
/// (`$XDG_CONFIG_HOME/sc/known_hosts`, or `$SC_HTTPS_KNOWN_HOSTS`).
Tls {
#[command(subcommand)]
op: TlsOp,
},
/// Widen a partial clone: fetch objects under these prefixes from the
/// promisor origin and widen `.sc/promisor` to include them. Errors if
/// this repo is not a partial clone.
Expand Down Expand Up @@ -597,6 +603,32 @@ enum TranscriptOp {
},
}

#[derive(Subcommand)]
enum TlsOp {
/// List the pinned `host:port` fingerprints, in file order.
List {
/// Emit JSON instead of `host:port sha256:<hex>` lines.
#[arg(long)]
json: bool,
},
/// Remove every pin for a host (the recovery for a changed server key).
/// The port defaults to 8730.
Forget {
/// `host` or `host:port`.
target: String,
},
/// Pin a host to a fingerprint (replacing any pin it had), e.g. one
/// printed by `sc serve fingerprint`, without connecting first.
Pin {
/// `host` or `host:port`.
target: String,
/// `sha256:<hex>` (or bare hex), as `sc serve fingerprint` prints it.
fingerprint: String,
},
/// Print the pin file in effect.
Path,
}

#[derive(Subcommand)]
enum SparseOp {
/// Print the repo's current sparse-checkout prefixes.
Expand Down Expand Up @@ -1065,6 +1097,7 @@ fn main() -> Result<()> {
Cmd::Sign { r#ref, identity } => run_sign(&r#ref, identity),
Cmd::Verify { r#ref, require } => run_verify(r#ref, require),
Cmd::Sparse { op } => run_sparse(op),
Cmd::Tls { op } => run_tls(op),
Cmd::Backfill {
prefixes,
all,
Expand All @@ -1074,6 +1107,76 @@ fn main() -> Result<()> {
}
}

fn run_tls(op: TlsOp) -> Result<()> {
use scl_repo::tls_pins;
let file = tls_pins::known_hosts_path()?;
match op {
TlsOp::List { json } => {
let entries = tls_pins::list(&file)?;
if json {
let rows: Vec<_> = entries
.iter()
.map(|e| {
serde_json::json!({
"host": e.host,
"port": e.port,
"pin": tls_pins::fingerprint(&e.pin),
})
})
.collect();
// `display()` is lossy for a non-UTF-8 path; a `PathBuf` would fail to serialize.
print_line(
&serde_json::json!({"file": file.display().to_string(), "pins": rows})
.to_string(),
);
} else {
for e in &entries {
print_line(&format!(
"{}:{} {}",
e.host,
e.port,
tls_pins::fingerprint(&e.pin)
));
}
if entries.is_empty() {
eprintln!("no pins in {}", file.display());
}
}
Ok(())
}
TlsOp::Forget { target } => {
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());
}
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`)"
);
Ok(())
}
TlsOp::Pin {
target,
fingerprint,
} => {
let (host, port) = tls_pins::parse_host_port(&target)?;
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::fingerprint(&pin)
);
Ok(())
}
TlsOp::Path => {
print_line(&file.display().to_string());
Ok(())
}
}
}

fn run_sparse(op: SparseOp) -> Result<()> {
match op {
SparseOp::Show { json } => {
Expand Down
161 changes: 161 additions & 0 deletions crates/cli/tests/tls_pins_cli.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
//! `sc tls` (ADR-0042 follow-on): list, forget and pin entries in the
//! `sc+https://` known_hosts file without editing it by hand.

use std::path::Path;
use std::process::Command;

fn sc(known_hosts: &Path, args: &[&str]) -> std::process::Output {
// Run in the test-owned directory that holds the pin file.
Command::new(env!("CARGO_BIN_EXE_sc"))
.args(args)
.current_dir(known_hosts.parent().expect("pin file has a parent dir"))
.env("SC_HTTPS_KNOWN_HOSTS", known_hosts)
.output()
.expect("sc runs")
}
Comment thread
tonibergholm marked this conversation as resolved.
Resolved

fn out(o: &std::process::Output) -> String {
String::from_utf8_lossy(&o.stdout).into_owned()
}

fn err(o: &std::process::Output) -> String {
String::from_utf8_lossy(&o.stderr).into_owned()
}

fn tmp(tag: &str) -> std::path::PathBuf {
let d = std::env::temp_dir().join(format!("scl-cli-tls-pins-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
d
}

#[test]
fn pin_list_forget_round_trip_through_the_cli() {
let dir = tmp("flow");
let kh = dir.join("known_hosts");
let fp_a = format!("sha256:{}", "ab".repeat(32));
let fp_b = format!("sha256:{}", "cd".repeat(32));

// Nothing pinned yet: a hint on stderr, no lines on stdout.
let empty = sc(&kh, &["tls", "list"]);
assert!(empty.status.success());
assert_eq!(out(&empty), "");
assert!(err(&empty).contains("no pins"), "{}", err(&empty));

// Pin by host (default port) and by host:port.
let o = sc(&kh, &["tls", "pin", "a.example", &fp_a]);
assert!(o.status.success(), "{}", err(&o));
assert!(out(&o).contains("pinned a.example:8730"), "{}", out(&o));
assert!(sc(&kh, &["tls", "pin", "b.example:9000", &fp_b])
.status
.success());
let list = out(&sc(&kh, &["tls", "list"]));
assert_eq!(
list,
format!("a.example:8730 {fp_a}\nb.example:9000 {fp_b}\n")
);

// JSON for scripts.
let json = out(&sc(&kh, &["tls", "list", "--json"]));
let v: serde_json::Value = serde_json::from_str(&json).unwrap();
assert_eq!(v["pins"][1]["host"], "b.example");
assert_eq!(v["pins"][1]["port"], 9000);
assert_eq!(v["pins"][1]["pin"], fp_b);

// Re-pinning replaces, and says so.
let re = sc(&kh, &["tls", "pin", "a.example", &fp_b]);
assert!(out(&re).contains("re-pinned"), "{}", out(&re));
assert_eq!(out(&sc(&kh, &["tls", "list"])).lines().count(), 2);

// A host typed in another case is the same host.
assert!(sc(&kh, &["tls", "pin", "C.Example:9001", &fp_a])
.status
.success());
assert!(out(&sc(&kh, &["tls", "list"])).contains("c.example:9001"));
assert!(sc(&kh, &["tls", "forget", "c.EXAMPLE:9001"])
.status
.success());

// Forget removes that host's pin only; the other survives untouched.
let f = sc(&kh, &["tls", "forget", "A.EXAMPLE"]);
assert!(f.status.success(), "{}", err(&f));
assert_eq!(
out(&sc(&kh, &["tls", "list"])),
format!("b.example:9000 {fp_b}\n")
);

// Forgetting what is not pinned is an error, not a silent success.
let miss = sc(&kh, &["tls", "forget", "nope.example"]);
assert!(!miss.status.success());
assert!(
err(&miss).contains("no pin for nope.example:8730"),
"{}",
err(&miss)
);

// `path` names the file in effect.
assert_eq!(out(&sc(&kh, &["tls", "path"])).trim(), kh.to_str().unwrap());
std::fs::remove_dir_all(&dir).unwrap();
assert!(!dir.exists());
}

#[test]
fn bad_input_is_refused_before_the_file_is_touched() {
let dir = tmp("bad");
let kh = dir.join("known_hosts");
for args in [
vec!["tls", "pin", "h", "not-a-fingerprint"],
vec!["tls", "pin", "h", &format!("sha256:{}", "ab".repeat(31))],
vec![
"tls",
"pin",
":9000",
&format!("sha256:{}", "ab".repeat(32)),
],
vec![
"tls",
"pin",
"h:notaport",
&format!("sha256:{}", "ab".repeat(32)),
],
vec!["tls", "forget", "h:99999"],
vec![
"tls",
"pin",
"h/repo",
&format!("sha256:{}", "ab".repeat(32)),
],
vec!["tls", "pin", "a b", &format!("sha256:{}", "ab".repeat(32))],
] {
let o = sc(&kh, &args);
assert!(!o.status.success(), "{args:?} must be refused");
}
assert!(
!kh.exists(),
"a refused command must not create the pin file"
);
std::fs::remove_dir_all(&dir).unwrap();
assert!(!dir.exists());
}

/// A pin file path that is not valid UTF-8 is rendered lossily instead of
/// panicking while building the JSON.
#[cfg(unix)]
#[test]
fn list_json_survives_a_non_utf8_pin_file_path() {
use std::os::unix::ffi::OsStrExt;
let dir = tmp("nonutf8");
let kh = dir.join(std::ffi::OsStr::from_bytes(b"known_\xff_hosts"));
let o = Command::new(env!("CARGO_BIN_EXE_sc"))
.args(["tls", "list", "--json"])
.current_dir(&dir)
.env("SC_HTTPS_KNOWN_HOSTS", &kh)
.output()
.unwrap();
assert!(o.status.success(), "{}", err(&o));
let v: serde_json::Value = serde_json::from_str(&out(&o)).unwrap();
assert!(v["file"].as_str().unwrap().contains("known_"));
assert_eq!(v["pins"].as_array().unwrap().len(), 0);
std::fs::remove_dir_all(&dir).unwrap();
assert!(!dir.exists());
}
9 changes: 6 additions & 3 deletions crates/repo/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,8 +122,10 @@ pub enum Error {
#[error(
"sc+https server key for {host} does not match the pinned fingerprint ({file})\n \
pinned: {pinned}\n server: {seen}\n\
If the server key legitimately changed, remove that host's line from the pin file \
and reconnect (the next connect re-pins); verify with `sc serve fingerprint` on the server."
If the server key legitimately changed, verify the new fingerprint with `sc serve \
fingerprint` on the server, then run `sc tls pin {host} sha256:<hex>` (works under \
SC_HTTPS_STRICT=1), or `sc tls forget {host}` and reconnect without SC_HTTPS_STRICT \
so the next connect re-pins."
)]
TlsPinMismatch {
host: String,
Expand All @@ -133,7 +135,8 @@ pub enum Error {
},
#[error(
"sc+https host {0} is not pinned and SC_HTTPS_STRICT=1 refuses unknown hosts; \
pre-pin with SC_HTTPS_FINGERPRINT=sha256:<hex> or connect once without SC_HTTPS_STRICT"
pre-pin with `sc tls pin {0} sha256:<hex>` or SC_HTTPS_FINGERPRINT=sha256:<hex>, or \
connect once without SC_HTTPS_STRICT"
)]
TlsStrictUnknownHost(String),
#[error(
Expand Down
Loading
Loading