From 09339f657975029ca8e7eb1ef47e849787a326ce Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Tue, 20 Oct 2026 07:37:32 +0300 Subject: [PATCH 1/5] fix(repo,cli): accept bracketed IPv6 hosts in sc+http(s):// urls (#219) ScHttpUrl::parse split on the first ':' and rejected [::1]:7777. It now unbrackets the host (kept bare for TLS name checks and the pin key) and re-brackets it for the connect address, Host header, pin file and display. Co-Authored-By: Claude Sonnet 5.5 --- crates/cli/src/main.rs | 19 +++-- crates/cli/tests/remote_add_validation.rs | 8 ++ crates/repo/src/http_transport.rs | 96 +++++++++++++++++++++-- crates/repo/src/tls_pins.rs | 63 +++++++++++++-- 4 files changed, 166 insertions(+), 20 deletions(-) diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs index 7efe3e88..de99d1c1 100644 --- a/crates/cli/src/main.rs +++ b/crates/cli/src/main.rs @@ -1133,9 +1133,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) )); } @@ -1149,11 +1148,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(()) } @@ -1165,8 +1169,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(()) diff --git a/crates/cli/tests/remote_add_validation.rs b/crates/cli/tests/remote_add_validation.rs index 86d8b310..359c23e3 100644 --- a/crates/cli/tests/remote_add_validation.rs +++ b/crates/cli/tests/remote_add_validation.rs @@ -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"); @@ -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!( @@ -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"); diff --git a/crates/repo/src/http_transport.rs b/crates/repo/src/http_transport.rs index a57cf7d4..c1214bce 100644 --- a/crates/repo/src/http_transport.rs +++ b/crates/repo/src/http_transport.rs @@ -229,14 +229,19 @@ impl ScHttpUrl { }; let slash = rest.find('/').unwrap_or(rest.len()); let (authority, path) = rest.split_at(slash); - let (host, port) = match authority.split_once(':') { - Some((h, p)) => { + let (host, port) = match split_authority(authority) { + Some((h, Some(p))) => { let port = p.parse::().map_err(|_| { Error::InvalidArgument(format!("bad port in sc+http url: {url}")) })?; (h, port) } - None => (authority, DEFAULT_PORT), + Some((h, None)) => (h, DEFAULT_PORT), + None => { + return Err(Error::InvalidArgument(format!( + "malformed bracketed host in sc+http url: {url}" + ))) + } }; if host.is_empty() { return Err(Error::InvalidArgument(format!( @@ -268,9 +273,31 @@ impl ScHttpUrl { }) } - /// `host:port`, for `TcpStream::connect`. + /// `host:port`, for `TcpStream::connect`; an IPv6 literal is re-bracketed + /// (`[::1]:7777`). `host` itself stays bare, which is what TLS name + /// checks and the pin file key on. pub fn authority(&self) -> String { - format!("{}:{}", self.host, self.port) + crate::tls_pins::host_port(&self.host, self.port) + } +} + +/// Split a URL authority into host and optional port text. A bracketed IPv6 +/// literal (`[::1]:7777`) yields the bare address; `None` means the brackets +/// are malformed or do not hold an IPv6 address. An unbracketed authority +/// splits on its first `:`, so a bare IPv6 literal falls out as an empty host +/// or a bad port for the caller to reject. +pub(crate) fn split_authority(authority: &str) -> Option<(&str, Option<&str>)> { + let Some(rest) = authority.strip_prefix('[') else { + return Some(match authority.split_once(':') { + Some((h, p)) => (h, Some(p)), + None => (authority, None), + }); + }; + let (host, tail) = rest.split_once(']')?; + host.parse::().ok()?; + match tail { + "" => Some((host, None)), + t => Some((host, Some(t.strip_prefix(':')?))), } } @@ -546,7 +573,12 @@ impl HttpTransport { } }; - write_client_opening(&mut w, &url.host, &url.path, token)?; + write_client_opening( + &mut w, + &crate::tls_pins::bracket_host(&url.host), + &url.path, + token, + )?; w.flush() .map_err(|e| Error::ConnectionLost(format!("sc+http opening flush: {e}")))?; @@ -1354,6 +1386,36 @@ mod tests { assert_eq!(u.path, "/"); } + #[test] + fn parse_bracketed_ipv6_literal() { + let u = ScHttpUrl::parse("sc+http://[::1]:7777/repo").unwrap(); + assert_eq!( + (u.host.as_str(), u.port, u.path.as_str()), + ("::1", 7777, "/repo") + ); + assert!(!u.tls); + assert_eq!(u.authority(), "[::1]:7777"); + + let u = ScHttpUrl::parse("sc+https://[2001:db8::1]/r").unwrap(); + assert_eq!((u.host.as_str(), u.port), ("2001:db8::1", DEFAULT_PORT)); + assert!(u.tls); + assert_eq!(u.authority(), format!("[2001:db8::1]:{DEFAULT_PORT}")); + } + + #[test] + fn parse_rejects_malformed_bracketed_hosts() { + for bad in [ + "sc+http://[::1/repo", + "sc+http://[::1]x/repo", + "sc+http://[::1]:notaport/repo", + "sc+http://[]/repo", + "sc+http://[host]/repo", + "sc+http://::1:7777/repo", + ] { + assert!(ScHttpUrl::parse(bad).is_err(), "{bad}"); + } + } + #[test] fn parse_rejects_other_schemes() { assert!(ScHttpUrl::parse("http://h/r").is_err()); @@ -1596,6 +1658,28 @@ mod tests { std::fs::remove_dir_all(&root).unwrap(); } + /// A bracketed IPv6 literal URL dials the bare address: the 404 mapping is + /// only reachable once TCP connect and the opening both worked. + #[test] + fn connect_dials_a_bracketed_ipv6_literal() { + // Hosts without IPv6 loopback cannot run this. + let Ok(listener) = std::net::TcpListener::bind("[::1]:0") else { + return; + }; + let port = listener.local_addr().unwrap().port(); + let server = std::thread::spawn(move || { + let (sock, _) = listener.accept().unwrap(); + let mut reader = BufReader::new(sock.try_clone().unwrap()); + let mut sock = sock; + read_client_opening(&mut reader).unwrap(); + write_status(&mut sock, 404).unwrap(); + }); + let url = ScHttpUrl::parse(&format!("sc+http://[::1]:{port}/nope")).unwrap(); + let err = HttpTransport::connect(&url).unwrap_err(); + assert!(matches!(err, Error::NotARepo), "got {err:?}"); + server.join().unwrap(); + } + // SC_PACK_CHUNK env mutation races other tests that also transfer packs // — mirrors `stdio_transport::tests::PACK_CHUNK_ENV_LOCK`. static PACK_CHUNK_ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); diff --git a/crates/repo/src/tls_pins.rs b/crates/repo/src/tls_pins.rs index 1c110544..ab62a199 100644 --- a/crates/repo/src/tls_pins.rs +++ b/crates/repo/src/tls_pins.rs @@ -209,8 +209,13 @@ pub fn record(file: &Path, host: &str, port: u16, pin: &[u8; 32]) -> Result<()> .append(true) .open(file) .map_err(|e| Error::InvalidArgument(format!("open pin file {}: {e}", file.display())))?; - writeln!(f, "{host}:{port} {}", scl_tlsio::fingerprint_hex(pin)) - .map_err(|e| Error::InvalidArgument(format!("write pin file {}: {e}", file.display())))?; + writeln!( + f, + "{} {}", + host_port(host, port), + scl_tlsio::fingerprint_hex(pin) + ) + .map_err(|e| Error::InvalidArgument(format!("write pin file {}: {e}", file.display())))?; Ok(()) } @@ -265,6 +270,22 @@ fn resolve_pin_path(file: &Path) -> PathBuf { } } +/// `host` as it appears in a URL authority or `Host:` header: an IPv6 literal +/// gets its brackets back. +pub(crate) fn bracket_host(host: &str) -> String { + if host.contains(':') { + format!("[{host}]") + } else { + host.to_string() + } +} + +/// `host:port` with an IPv6 literal bracketed (`[::1]:7777`); the pin file's +/// key format and the display form. +pub fn host_port(host: &str, port: u16) -> String { + format!("{}:{port}", bracket_host(host)) +} + /// One pin as stored: the `host:port` it was recorded for and its SPKI hash. #[derive(Debug, Clone, PartialEq, Eq)] pub struct PinEntry { @@ -282,13 +303,18 @@ pub fn fingerprint(pin: &[u8; 32]) -> String { /// [`crate::http_transport::DEFAULT_PORT`]), the same split an `sc+https://` /// URL's authority gets, so a pin names exactly what a connection looks up. pub fn parse_host_port(s: &str) -> Result<(String, u16)> { - let (host, port) = match s.split_once(':') { - Some((h, p)) => ( + let (host, port) = match crate::http_transport::split_authority(s) { + Some((h, Some(p))) => ( h, p.parse::() .map_err(|_| Error::InvalidArgument(format!("bad port in {s:?}")))?, ), - None => (s, crate::http_transport::DEFAULT_PORT), + Some((h, None)) => (h, crate::http_transport::DEFAULT_PORT), + None => { + return Err(Error::InvalidArgument(format!( + "bad bracketed host in {s:?}" + ))) + } }; if host.is_empty() { return Err(Error::InvalidArgument(format!("empty host in {s:?}"))); @@ -313,8 +339,12 @@ fn parse_line(line: &str) -> Option { return None; } let (key, value) = line.split_once(' ')?; - let (host, port) = key.split_once(':')?; + let (host, port) = key.rsplit_once(':')?; let port = port.parse::().ok()?; + let host = host + .strip_prefix('[') + .and_then(|h| h.strip_suffix(']')) + .unwrap_or(host); Some(PinEntry { host: host.to_string(), port, @@ -371,7 +401,8 @@ pub fn set_pin(file: &Path, host: &str, port: u16, pin: &[u8; 32]) -> Result Date: Tue, 20 Oct 2026 07:40:37 +0300 Subject: [PATCH 2/5] docs(repo,cli): reword the .sc gate claim and fix rustdoc warnings (#219) Since #207 the 404 for a missing repo follows the auth gate. Plain code spans replace links from public docs to private items; two clap doc comments no longer parse as HTML or an intra-doc link. Co-Authored-By: Claude Sonnet 5.5 --- crates/cli/src/main.rs | 9 +++++---- crates/repo/src/http_transport.rs | 8 ++++---- crates/repo/src/merge.rs | 6 +++--- crates/repo/src/repo.rs | 4 ++-- crates/repo/src/tls_pins.rs | 2 +- crates/repo/src/transport.rs | 4 ++-- crates/repo/src/wire.rs | 9 +++++---- 7 files changed, 22 insertions(+), 20 deletions(-) diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs index de99d1c1..6d9d9e58 100644 --- a/crates/cli/src/main.rs +++ b/crates/cli/src/main.rs @@ -452,7 +452,7 @@ enum Cmd { /// Target Git repo path (created bare if absent). #[arg(long)] to: PathBuf, - /// Ref to update (default: refs/heads/). + /// Ref to update (default: `refs/heads/`). #[arg(long)] r#ref: Option, /// Allow exporting protected ciphertext and dropping secrets. @@ -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, @@ -760,7 +760,7 @@ enum ServeSub { #[command(subcommand)] op: ServeTokenOp, }, - /// Print this repo's serve-TLS fingerprint (sha256: of the SPKI), + /// Print this repo's serve-TLS fingerprint (`sha256:` 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 }, @@ -3747,7 +3747,8 @@ 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 (a client without a + // valid token gets the 401 first, anyone else a 404). // `--stdio` has no such gate upstream — enforce it here, before // touching stdin, so a `--store` session never auto-vivifies // `/.sc/tmp/` under an uninitialized directory (which diff --git a/crates/repo/src/http_transport.rs b/crates/repo/src/http_transport.rs index c1214bce..b137c451 100644 --- a/crates/repo/src/http_transport.rs +++ b/crates/repo/src/http_transport.rs @@ -667,7 +667,7 @@ impl Transport for HttpTransport { /// Applied only around the opening read — the opening timeout is REPLACED /// (not cleared) by `limits.timeout_secs`'s session read+write timeouts /// after the 200 status is written, before handing off to `wire::serve` — -/// see [`handle_http_connection`] for the timeout sequencing. +/// see `handle_http_connection` for the timeout sequencing. const OPENING_READ_TIMEOUT: Duration = Duration::from_secs(30); /// How long the client allows the connect, TLS handshake, opening and wire @@ -830,7 +830,7 @@ pub struct ServeLimits { pub max_connections: u32, /// Per-connection idle/session timeout in seconds, applied to both the /// read and write halves once the session begins (see - /// [`handle_http_connection`]). `0` = disabled. + /// `handle_http_connection`). `0` = disabled. pub timeout_secs: u64, /// Forwarded to [`crate::wire::WirePolicy::max_pack_size`]. `0` = /// unlimited. @@ -1006,7 +1006,7 @@ pub fn serve_tls_fingerprint(root: &std::path::Path) -> Result { /// /// Fail-closed bind gate (P29): a non-loopback `addr` is refused up front /// unless justified by `read_only`, `allow_public`, or ≥1 configured serve -/// token (see [`bind_is_allowed`]) — an unauthenticated server must not +/// token (see `bind_is_allowed`) — an unauthenticated server must not /// silently listen on a public interface. pub fn serve_http( addr: &str, @@ -1083,7 +1083,7 @@ pub fn serve_http( /// P31 additions: a live-connection counter enforces `limits.max_connections` /// (shedding with `503` BEFORE spawning a thread or reading an opening, so a /// shed connection costs no fd beyond the accept itself); a per-`accept()` -/// error is paced by [`AcceptBackoff`] instead of busy-looping. +/// error is paced by `AcceptBackoff` instead of busy-looping. pub fn serve_http_listener( listener: TcpListener, root: &std::path::Path, diff --git a/crates/repo/src/merge.rs b/crates/repo/src/merge.rs index 2c2ae402..ba182550 100644 --- a/crates/repo/src/merge.rs +++ b/crates/repo/src/merge.rs @@ -84,11 +84,11 @@ fn ancestors(store: &mut Store, id: ObjectId) -> Result> { Ok(set) } -/// One merged file in a [`FileMerge`] working set. +/// One merged file in a `FileMerge` working set. /// /// `bytes` carries ciphertext when a protected entry was resolved by /// ciphertext-id fast path (`needs_encrypt: false` — the blob survives as-is, -/// its wraps travel in [`FileMerge::wrapped_carry`]); it carries plaintext when +/// its wraps travel in `FileMerge::wrapped_carry`); it carries plaintext when /// a protected entry was content-merged (`needs_encrypt: true` — a later stage /// must re-encrypt before committing). Plain files are always plaintext with /// `perms: 0, needs_encrypt: false`. @@ -136,7 +136,7 @@ pub struct Merge { /// Merged secret registry. pub secrets: BTreeMap, /// Wrapped DEKs for every surviving carried ciphertext blob (see - /// [`FileMerge::wrapped_carry`]) — threaded up from `three_way_files` so + /// `FileMerge::wrapped_carry`) — threaded up from `three_way_files` so /// `Repo::merge_with_identity` (P15) can union it with freshly-encrypted /// wraps without a second file-tree walk. Extending `Merge` rather than /// having callers reach into `FileMerge` directly keeps `three_way`'s diff --git a/crates/repo/src/repo.rs b/crates/repo/src/repo.rs index 5e960e96..00a88027 100644 --- a/crates/repo/src/repo.rs +++ b/crates/repo/src/repo.rs @@ -1352,7 +1352,7 @@ impl Repo { /// Like [`merge`][Repo::merge] but threads `identity` through the /// real-three-way path so protected paths that diverged in *content* on /// both sides can be decrypted, diff3'd, and re-encrypted (P15). Clean - /// ciphertext-id fast paths (ADR: [`crate::merge::three_way_files`]) still + /// ciphertext-id fast paths (ADR: `crate::merge::three_way_files`) still /// need no identity at all. A conflicted merge carrying protection writes /// plaintext markers to the working tree only (never through the CAS) and /// is completed by `sc commit`, which re-encrypts under the union of both @@ -1360,7 +1360,7 @@ impl Repo { /// /// Returns the merged tip plus the protected paths that could not be /// materialized to disk for lack of a matching key (skipped, exactly like - /// [`switch_with_identity`][Repo::switch_with_identity]); [`merge`] + /// [`switch_with_identity`][Repo::switch_with_identity]); `merge` /// drops the list. pub fn merge_with_identity( &self, diff --git a/crates/repo/src/tls_pins.rs b/crates/repo/src/tls_pins.rs index ab62a199..c9acd90b 100644 --- a/crates/repo/src/tls_pins.rs +++ b/crates/repo/src/tls_pins.rs @@ -21,7 +21,7 @@ pub struct TlsClientPolicy { /// `SC_HTTPS_STRICT`: refuse unknown hosts instead of accept-new. /// `=1` enables it; any non-empty value other than `0` is also treated /// as enabled (fails closed on typos like `=true`/`=yes` rather than - /// silently falling back to accept-new — see [`strict_from`]). + /// silently falling back to accept-new — see `strict_from`). pub strict: bool, /// `SC_HTTPS_CA_FILE` / `SC_HTTPS_CA=system` (ADR-0054): validate the /// server's certificate chain, validity and name against a CA instead of diff --git a/crates/repo/src/transport.rs b/crates/repo/src/transport.rs index c2616bc9..1763296b 100644 --- a/crates/repo/src/transport.rs +++ b/crates/repo/src/transport.rs @@ -595,7 +595,7 @@ impl Transport for LocalTransport { } /// Bounded sender (P25): builds the transfer set into a temp pack file - /// via [`LocalTransport::build_pack_tempfile`] (peak RAM one object), + /// via `LocalTransport::build_pack_tempfile` (peak RAM one object), /// then copies that file's raw bytes into `out` with a small fixed /// buffer (`std::io::copy`) — `out` still receives exactly the raw /// `.pack` bytes `build_pack` used to hand back directly, so every @@ -621,7 +621,7 @@ impl Transport for LocalTransport { /// Bounded receiver (P25): spills `src` to a temp pack file with a small /// fixed buffer (`std::io::copy` — bounded RAM, and writes exactly what /// `src` produced, satisfying Task 1 carry-in #2's exact-EOF framing - /// requirement), then ingests it via [`ingest_pack_file`]'s two-pass + /// requirement), then ingests it via `ingest_pack_file`'s two-pass /// atomic-after-verify contract (see that function's doc comment for the /// full correctness argument, including Task 1 carry-in #1). The temp /// file is removed on drop regardless of outcome. diff --git a/crates/repo/src/wire.rs b/crates/repo/src/wire.rs index bae08a5c..bac2691a 100644 --- a/crates/repo/src/wire.rs +++ b/crates/repo/src/wire.rs @@ -932,15 +932,16 @@ fn open_bucket_serve_transport(store_url: &str, home: &std::path::Path) -> Resul /// `PROTOCOL_VERSION`, same read-only gate and pack-spool caps — every verb /// except the pack pair goes through [`Transport`] identically either way. /// All durable state lives in the bucket; this process holds only an RAII -/// scratch dir ([`TempServeDir`]) for pack spills, created under `home`'s own +/// scratch dir (`TempServeDir`) for pack spills, created under `home`'s own /// `.sc/tmp/` (CLAUDE.md / THREAT-MODEL.md's "pack-spool scratch lives in the /// serve home" contract) and removed when the session ends. `home` is the /// same serve-HOME directory `serve_with_policy` materializes a local repo /// into — callers MUST have already confirmed it has a `.sc/` before calling -/// this, or [`TempServeDir::create_in`] will silently `create_dir_all` one +/// this, or `TempServeDir::create_in` will silently `create_dir_all` one /// into existence under an uninitialized directory. Both current callers do: -/// `handle_http_connection` gates unconditionally on `.sc/` presence (a 404 -/// before any dispatch, store mode included) and the CLI's `run_serve` +/// `handle_http_connection` gates on `.sc/` presence before any dispatch +/// (store mode included; a client without a valid token gets the 401 first, +/// anyone else a 404) and the CLI's `run_serve` /// checks `path.join(".sc").is_dir()` itself before reaching this function /// (P36c review — `--stdio` has no upstream gate the way `--http` does, so /// it cannot lean on `LocalTransport::open`'s own check the way a From a1e3c5170c2950de0f5bf35191a4d723d86f9177 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Tue, 20 Oct 2026 07:45:15 +0300 Subject: [PATCH 3/5] test(repo): cover the --theirs carry edges and ws cache pruning (#219) Theirs-side resolve carry (#205): rebase --continue, a convergent blob on their side, the seal fallback when their wrap list is missing, and the documented under-grant after a grant on our side. Protected-cache pruning (#204): a live workspace's .sc/ws/cache- drops a deleted protected file. Co-Authored-By: Claude Sonnet 5.5 --- crates/repo/src/conflicts.rs | 239 +++++++++++++++++++++++++++++++++++ crates/repo/src/ws.rs | 43 +++++++ 2 files changed, 282 insertions(+) diff --git a/crates/repo/src/conflicts.rs b/crates/repo/src/conflicts.rs index a5b6068f..a36f45bb 100644 --- a/crates/repo/src/conflicts.rs +++ b/crates/repo/src/conflicts.rs @@ -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"); diff --git a/crates/repo/src/ws.rs b/crates/repo/src/ws.rs index a6f471c8..f01c1b58 100644 --- a/crates/repo/src/ws.rs +++ b/crates/repo/src/ws.rs @@ -1371,6 +1371,49 @@ mod tests { std::fs::remove_dir_all(&root).unwrap(); } + #[test] + fn a_live_workspace_cache_is_pruned_when_a_protected_file_is_deleted() { + // #204 through the ws path: the cache file at `.sc/ws/cache-` only + // outlives a harvest while the workspace stays live, so a scanner + // rejection keeps it open. The deleted protected file's entry must be + // gone from the saved cache; the surviving one stays. + let root = tmp_root("ws-cache-prune"); + let repo = init(&root); + 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/keep"), "kept\n").unwrap(); + std::fs::write(root.join("secret/gone"), "doomed\n").unwrap(); + repo.commit("t", "add protected").unwrap(); + + let session = repo.ws_fork(1, "t", Some(&sk)).unwrap(); + let dir = session.workspaces[0].dir.clone(); + let cache_file = repo.layout().ws_cache_path(1); + let cached = |name: &str| { + std::fs::read_to_string(&cache_file) + .unwrap() + .lines() + .any(|l| l.ends_with(&format!(" {name}"))) + }; + assert!(cached("secret/keep") && cached("secret/gone"), "setup"); + + std::fs::remove_file(dir.join("secret/gone")).unwrap(); + // An AWS-style key id trips the P5 scanner, so the workspace stays live. + std::fs::write(dir.join("leak.txt"), "AKIAIOSFODNN7EXAMPLE\n").unwrap(); + let outcomes = repo.ws_harvest(None, "t", Some(&sk)).unwrap(); + assert!( + matches!(outcomes[0], WsHarvestOutcome::Rejected { index: 1, .. }), + "got {outcomes:?}" + ); + + assert!(cached("secret/keep"), "a surviving file keeps its entry"); + assert!(!cached("secret/gone"), "the deleted file's entry is pruned"); + + drop(repo); + std::fs::remove_dir_all(&root).unwrap(); + assert!(!root.exists(), "test must leave no residue"); + } + #[test] fn ws_changed_for_ignores_untouched_randomized_protected_file() { // P33 Task 7 (ws_changed_for arm): before this fix, `ws_changed_for` From 7f8f4c81b2384df9fc6d3af9f9d78b03782cd365 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Tue, 20 Oct 2026 08:10:51 +0300 Subject: [PATCH 4/5] fix(repo,cli): canonical IPv6 pin keys, accurate gate wording, IPv6 pin CLI test (#219) Co-Authored-By: Claude Sonnet 5.5 --- crates/cli/src/main.rs | 5 ++-- crates/cli/tests/tls_pins_cli.rs | 32 +++++++++++++++++++++++++ crates/repo/src/http_transport.rs | 17 ++++++++----- crates/repo/src/wire.rs | 4 ++-- docs/adr/0042-in-binary-tls-sc-https.md | 2 +- docs/adr/0053-tls-pin-management.md | 4 ++-- 6 files changed, 51 insertions(+), 13 deletions(-) diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs index 6d9d9e58..818f3981 100644 --- a/crates/cli/src/main.rs +++ b/crates/cli/src/main.rs @@ -3747,8 +3747,9 @@ fn run_serve( ); } // `--http`'s `handle_http_connection` gates on `.sc/` presence - // before any dispatch, store mode included (a client without a - // valid token gets the 401 first, anyone else a 404). + // 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 // `/.sc/tmp/` under an uninitialized directory (which diff --git a/crates/cli/tests/tls_pins_cli.rs b/crates/cli/tests/tls_pins_cli.rs index ab5598b1..7e2634a7 100644 --- a/crates/cli/tests/tls_pins_cli.rs +++ b/crates/cli/tests/tls_pins_cli.rs @@ -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"); +} diff --git a/crates/repo/src/http_transport.rs b/crates/repo/src/http_transport.rs index b137c451..43c98e8b 100644 --- a/crates/repo/src/http_transport.rs +++ b/crates/repo/src/http_transport.rs @@ -266,7 +266,7 @@ impl ScHttpUrl { ))); } Ok(ScHttpUrl { - host: host.to_string(), + host, port, path, tls, @@ -282,19 +282,20 @@ impl ScHttpUrl { } /// Split a URL authority into host and optional port text. A bracketed IPv6 -/// literal (`[::1]:7777`) yields the bare address; `None` means the brackets +/// literal (`[::1]:7777`) yields the address in its canonical text form, so +/// `[::1]` and `[0:0:0:0:0:0:0:1]` share one pin key; `None` means the brackets /// are malformed or do not hold an IPv6 address. An unbracketed authority /// splits on its first `:`, so a bare IPv6 literal falls out as an empty host /// or a bad port for the caller to reject. -pub(crate) fn split_authority(authority: &str) -> Option<(&str, Option<&str>)> { +pub(crate) fn split_authority(authority: &str) -> Option<(String, Option<&str>)> { let Some(rest) = authority.strip_prefix('[') else { return Some(match authority.split_once(':') { - Some((h, p)) => (h, Some(p)), - None => (authority, None), + Some((h, p)) => (h.to_string(), Some(p)), + None => (authority.to_string(), None), }); }; let (host, tail) = rest.split_once(']')?; - host.parse::().ok()?; + let host = host.parse::().ok()?.to_string(); match tail { "" => Some((host, None)), t => Some((host, Some(t.strip_prefix(':')?))), @@ -1395,6 +1396,9 @@ mod tests { ); assert!(!u.tls); assert_eq!(u.authority(), "[::1]:7777"); + // Spellings of one address share a host, hence one pin key. + let long = ScHttpUrl::parse("sc+http://[0:0:0:0:0:0:0:1]:7777/repo").unwrap(); + assert_eq!(long.host, "::1"); let u = ScHttpUrl::parse("sc+https://[2001:db8::1]/r").unwrap(); assert_eq!((u.host.as_str(), u.port), ("2001:db8::1", DEFAULT_PORT)); @@ -1664,6 +1668,7 @@ mod tests { fn connect_dials_a_bracketed_ipv6_literal() { // Hosts without IPv6 loopback cannot run this. let Ok(listener) = std::net::TcpListener::bind("[::1]:0") else { + eprintln!("skipping: no IPv6 loopback on this host"); return; }; let port = listener.local_addr().unwrap().port(); diff --git a/crates/repo/src/wire.rs b/crates/repo/src/wire.rs index bac2691a..53a744fb 100644 --- a/crates/repo/src/wire.rs +++ b/crates/repo/src/wire.rs @@ -940,8 +940,8 @@ fn open_bucket_serve_transport(store_url: &str, home: &std::path::Path) -> Resul /// this, or `TempServeDir::create_in` will silently `create_dir_all` one /// into existence under an uninitialized directory. Both current callers do: /// `handle_http_connection` gates on `.sc/` presence before any dispatch -/// (store mode included; a client without a valid token gets the 401 first, -/// anyone else a 404) and the CLI's `run_serve` +/// (store mode included; the 404 follows the auth gate (#207), so a listener +/// that requires a token answers 401 first) and the CLI's `run_serve` /// checks `path.join(".sc").is_dir()` itself before reaching this function /// (P36c review — `--stdio` has no upstream gate the way `--http` does, so /// it cannot lean on `LocalTransport::open`'s own check the way a diff --git a/docs/adr/0042-in-binary-tls-sc-https.md b/docs/adr/0042-in-binary-tls-sc-https.md index ad53e47a..318c3589 100644 --- a/docs/adr/0042-in-binary-tls-sc-https.md +++ b/docs/adr/0042-in-binary-tls-sc-https.md @@ -89,7 +89,7 @@ Storage and knobs: - `~/.config/sc/known_hosts` (`$XDG_CONFIG_HOME/sc/known_hosts` if set, falling back to `$HOME/.config/sc/known_hosts`; `SC_HTTPS_KNOWN_HOSTS` - overrides the path outright), one `host:port sha256:` line per pin. + overrides the path outright), one `host:port sha256:` line per pin (an IPv6 literal host is bracketed, `[::1]:7777`, and stored in its canonical text form). - `SC_HTTPS_FINGERPRINT=sha256:` pre-pins a connection (e.g. for CI) without ever writing to the known_hosts file — an explicit, non-persisted override. diff --git a/docs/adr/0053-tls-pin-management.md b/docs/adr/0053-tls-pin-management.md index 16d1e0b4..c40a3833 100644 --- a/docs/adr/0053-tls-pin-management.md +++ b/docs/adr/0053-tls-pin-management.md @@ -12,12 +12,12 @@ ADR-0042 pins a server's SPKI hash per `host:port` in a user-level `known_hosts` `sc tls` is a thin command over the file, with no new trust semantics: -- `sc tls list [--json]`: the well-formed pins in file order, as `host:port sha256:` lines (JSON for scripts). A host pinned twice is listed twice, because a connection uses the first; a missing file or no pins prints a hint on stderr. +- `sc tls list [--json]`: the well-formed pins in file order, as `host:port sha256:` lines, with an IPv6 literal bracketed (`[::1]:7777`; JSON for scripts). A host pinned twice is listed twice, because a connection uses the first; a missing file or no pins prints a hint on stderr. - `sc tls forget `: removes every pin for that host and port, hostname case-insensitively, the port exact (default 8730, as in the URL). It leaves every other line (comments, malformed lines) as it was and rewrites the file atomically and durably, and only when something was removed. Forgetting an unpinned host is an error, not a silent success. A later accept-new connection (no `SC_HTTPS_STRICT`, no `SC_HTTPS_FINGERPRINT`) re-pins what it sees, as accept-new always did; under strict mode, or with a pre-pin, the host stays unpinned (strict refuses it) and `sc tls pin` is the way to set it. - `sc tls pin `: pins without connecting first (the fingerprint `sc serve fingerprint` prints), replacing any pin the host had. This is the explicit, auditable path for a deployment that distributes the pin out of band, and it works under `SC_HTTPS_STRICT=1`. - `sc tls path`: the file in effect (`SC_HTTPS_KNOWN_HOSTS`, else `$XDG_CONFIG_HOME/sc/known_hosts`, else `~/.config/sc/known_hosts`). -Host and port parse as an `sc+https://` URL's authority does, so a pin names what a connection looks up: a host with whitespace, `/` or `#` is refused, the host is stored lowercase, and connection lookup compares the host case-insensitively (the port exactly). Every write to the pin file, including the first-connect append, takes an advisory lock on `.lock` (`File::lock`: `flock` on unix, `LockFileEx` on Windows), so concurrent `sc` processes cannot lose or resurrect a pin; a pin file that is a symlink (a shared or dotfile-managed store) is followed, so an update replaces the target and the link survives; a bare relative file name is anchored at the working directory for the durable write. Bad input (not 32 bytes of hex, an empty host, a bad port) is refused before the file is touched or created. +Host and port parse as an `sc+https://` URL's authority does (an IPv6 literal is written in brackets and stored in canonical form, so `[::1]` and `[0:0:0:0:0:0:0:1]` are one pin), so a pin names what a connection looks up: a host with whitespace, `/` or `#` is refused, the host is stored lowercase, and connection lookup compares the host case-insensitively (the port exactly). Every write to the pin file, including the first-connect append, takes an advisory lock on `.lock` (`File::lock`: `flock` on unix, `LockFileEx` on Windows), so concurrent `sc` processes cannot lose or resurrect a pin; a pin file that is a symlink (a shared or dotfile-managed store) is followed, so an update replaces the target and the link survives; a bare relative file name is anchored at the working directory for the durable write. Bad input (not 32 bytes of hex, an empty host, a bad port) is refused before the file is touched or created. The pin-mismatch error names `sc tls pin` (which works under strict mode) first and `sc tls forget` with a non-strict reconnect second; the strict-unknown-host error names `sc tls pin`. From f9f3520125be611bc58f698d6699492a9abef096 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Tue, 20 Oct 2026 08:24:17 +0300 Subject: [PATCH 5/5] fix(repo): read pin-file keys with the URL authority grammar (#219) A bracketed DNS name such as [example.com]:8730 had its brackets stripped and became a live pin. parse_line now uses split_authority, so brackets must hold an IPv6 literal and anything else is skipped. Co-Authored-By: Claude Sonnet 5.5 --- crates/repo/src/tls_pins.rs | 28 +++++++++++++++++++++------- 1 file changed, 21 insertions(+), 7 deletions(-) diff --git a/crates/repo/src/tls_pins.rs b/crates/repo/src/tls_pins.rs index c9acd90b..f3aea7b5 100644 --- a/crates/repo/src/tls_pins.rs +++ b/crates/repo/src/tls_pins.rs @@ -339,14 +339,12 @@ fn parse_line(line: &str) -> Option { return None; } let (key, value) = line.split_once(' ')?; - let (host, port) = key.rsplit_once(':')?; - let port = port.parse::().ok()?; - let host = host - .strip_prefix('[') - .and_then(|h| h.strip_suffix(']')) - .unwrap_or(host); + // Same authority grammar as a URL: brackets must hold an IPv6 literal, so + // a malformed key is skipped rather than read as a pin for another host. + let (host, port) = crate::http_transport::split_authority(key)?; + let port = port?.parse::().ok()?; Some(PinEntry { - host: host.to_string(), + host, port, pin: parse_fingerprint(value.trim()).ok()?, }) @@ -479,6 +477,22 @@ mod tests { assert!(!dir.exists()); } + #[test] + fn pin_lines_follow_the_url_authority_grammar() { + let hex = "ab".repeat(32); + let line = |key: &str| parse_line(&format!("{key} sha256:{hex}")); + // Brackets hold only an IPv6 literal, read in canonical form. + assert_eq!(line("[::1]:7777").unwrap().host, "::1"); + assert_eq!(line("[0:0:0:0:0:0:0:1]:7777").unwrap().host, "::1"); + assert_eq!(line("example.com:8730").unwrap().host, "example.com"); + // Malformed keys are skipped, never read as a pin for another host. + assert!(line("[example.com]:8730").is_none()); + assert!(line("[::1:7777").is_none()); + assert!(line("[::1]7777").is_none()); + assert!(line("[::1]").is_none(), "a port is required"); + assert!(line("::1:7777").is_none(), "unbracketed IPv6"); + } + #[test] fn pin_file_line_format_is_host_port_sha256_hex() { let dir = tmp("fmt");