From 149dcb202a26db8d003f3b6ca192971ff825f4c4 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Mon, 19 Oct 2026 15:57:54 +0300 Subject: [PATCH 1/3] feat(tlsio,repo): CA-path validation for sc+https:// (ADR-0054) SC_HTTPS_CA_FILE= or SC_HTTPS_CA=system switches a client from SPKI pinning to validating the chain, validity window and name against a CA, so a CA-issued (ACME/private CA) server needs no first-connect trust and survives certificate rotation. It replaces pinning for the connection (the pin file is neither read nor written), completes the handshake before any application byte, and fails closed on an unusable bundle, an unrecognized value, both knobs, or a pre-pin combined with CA trust. Revocation is not checked. Pin mode is the unchanged default. Co-Authored-By: Claude Sonnet 5.5 --- .claude/skills/sc-cli-reference/SKILL.md | 3 + CLAUDE.md | 5 +- Cargo.lock | 5 +- ROADMAP.md | 6 +- crates/repo/src/http_transport.rs | 82 +++++++ crates/repo/src/tls_pins.rs | 80 +++++++ crates/tlsio/Cargo.toml | 1 + crates/tlsio/src/lib.rs | 6 +- crates/tlsio/src/stream.rs | 9 + crates/tlsio/src/trust.rs | 264 +++++++++++++++++++++++ docs/THREAT-MODEL.md | 25 ++- docs/adr/0054-tls-ca-validation.md | 38 ++++ docs/adr/README.md | 1 + 13 files changed, 511 insertions(+), 14 deletions(-) create mode 100644 crates/tlsio/src/trust.rs create mode 100644 docs/adr/0054-tls-ca-validation.md diff --git a/.claude/skills/sc-cli-reference/SKILL.md b/.claude/skills/sc-cli-reference/SKILL.md index 5c4691af..5da2abfa 100644 --- a/.claude/skills/sc-cli-reference/SKILL.md +++ b/.claude/skills/sc-cli-reference/SKILL.md @@ -352,6 +352,9 @@ cargo run --bin sc -- clone sc+https://host[:port]/repo # TLS clone (P32 # overrides), mismatch always hard-fails; # SC_HTTPS_FINGERPRINT= pre-pins (CI), # SC_HTTPS_STRICT=1 refuses unknown hosts; + # SC_HTTPS_CA_FILE= | SC_HTTPS_CA=system validate the + # chain, dates and name against a CA instead of + # pinning (no pin file read/written; ADR-0054); # 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 # drop a host's pin (changed server key); a later diff --git a/CLAUDE.md b/CLAUDE.md index a5fdb4ea..7c22a353 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -268,8 +268,9 @@ 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, and CA-path validation alongside TOFU pinning. `sc tls list/forget/pin/path` -manages the `sc+https://` pin file (ADR-0053). +clones. `sc tls list/forget/pin/path` manages the `sc+https://` pin file +(ADR-0053); `SC_HTTPS_CA_FILE=` / `SC_HTTPS_CA=system` switch a client to CA +validation instead of pinning (ADR-0054). ## Agent skills diff --git a/Cargo.lock b/Cargo.lock index b583ce8c..39bd3818 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5220,9 +5220,9 @@ dependencies = [ [[package]] name = "rustls-native-certs" -version = "0.8.4" +version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" dependencies = [ "openssl-probe", "rustls-pki-types", @@ -5453,6 +5453,7 @@ dependencies = [ "rcgen", "ring", "rustls", + "rustls-native-certs", "rustls-pki-types", "thiserror 2.0.21", ] diff --git a/ROADMAP.md b/ROADMAP.md index 38d9c78a..5ad5b5ac 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -835,8 +835,10 @@ scale-&-reach horizon): a narrowed non-loopback bind gate (`--tls` + token, not token alone). See 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 (shipped in ADR-0053 as `sc tls list/forget/pin/path`; + deployments (shipped in ADR-0054: `SC_HTTPS_CA_FILE` / `SC_HTTPS_CA=system`, + with chain, validity and name checks; v1 was pin-only, names/validity + ignored); opt-in SNI/ + certificate-name validation (covered by the CA mode); 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 diff --git a/crates/repo/src/http_transport.rs b/crates/repo/src/http_transport.rs index b0854912..8d0ed9ac 100644 --- a/crates/repo/src/http_transport.rs +++ b/crates/repo/src/http_transport.rs @@ -400,6 +400,21 @@ impl HttpTransport { HttpWriteHalf::Plain(stream), ) } + // CA validation (ADR-0054): chain, validity and name against a CA, + // not a pin; the pin file is neither read nor written, and the + // handshake still completes before any application byte. + (true, Some(p)) if p.ca.is_some() => { + let trust = match p.ca.as_ref().expect("guarded by is_some") { + crate::tls_pins::CaSource::File(f) => scl_tlsio::CaTrust::from_pem_file(f), + crate::tls_pins::CaSource::System => scl_tlsio::CaTrust::system(), + }?; + let tls = scl_tlsio::client_connect_ca(stream, &url.host, &trust)?; + let (rh, wh) = tls.split(); + ( + BufReader::new(HttpReadHalf::Tls(rh)), + HttpWriteHalf::Tls(wh), + ) + } (true, Some(p)) => { let expected = match p.pre_pin { Some(pin) => Some(pin), @@ -2179,6 +2194,7 @@ mod tests { known_hosts: kh.clone(), pre_pin: None, strict: false, + ca: None, }; // 1. Unknown host, accept-new: connects AND records the pin. @@ -2197,6 +2213,7 @@ mod tests { known_hosts: kh.clone(), pre_pin: None, strict: true, + ca: None, }; HttpTransport::connect_with_pins(&url, None, Some(&strict_known)).unwrap(); let fresh = pins_dir.join("fresh_kh"); @@ -2204,6 +2221,7 @@ mod tests { known_hosts: fresh.clone(), pre_pin: None, strict: true, + ca: None, }; match HttpTransport::connect_with_pins(&url, None, Some(&strict_unknown)) { Err(Error::TlsStrictUnknownHost(_)) => {} @@ -2217,6 +2235,7 @@ mod tests { known_hosts: prepin_file.clone(), pre_pin: Some(spki), strict: true, + ca: None, }; HttpTransport::connect_with_pins(&url, None, Some(&prepin)).unwrap(); assert!(!prepin_file.exists(), "pre-pin must not persist"); @@ -2228,6 +2247,7 @@ mod tests { known_hosts: bad.clone(), pre_pin: None, strict: false, + ca: None, }; match HttpTransport::connect_with_pins(&url, None, Some(&badpol)) { Err(Error::TlsPinMismatch { @@ -2248,6 +2268,67 @@ mod tests { std::fs::remove_dir_all(&root).unwrap(); } + /// CA validation replaces pinning (ADR-0054): a server the CA does not + /// vouch for is refused, the pin file is neither created nor read, and an + /// unusable CA bundle fails the connection instead of falling back to + /// accept-new. + #[test] + fn a_ca_policy_never_touches_the_pin_file_and_fails_closed() { + let root = tmp_repo("tls-ca-policy"); + let (addr, _spki) = spawn_tls_server(&root); + let (host, port) = addr + .rsplit_once(':') + .map(|(h, p)| (h.to_string(), p.parse::().unwrap())) + .unwrap(); + let url = ScHttpUrl { + host, + port, + path: "/".into(), + tls: true, + }; + let dir = std::env::temp_dir().join(format!("scl-ca-policy-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let kh = dir.join("known_hosts"); + let policy = |ca| crate::tls_pins::TlsClientPolicy { + known_hosts: kh.clone(), + pre_pin: None, + strict: false, + ca: Some(ca), + }; + + // The server's own self-signed certificate is not a CA for the name + // dialled (it covers `sc-serve`, not 127.0.0.1): refused. + let own_cert = root.join(".sc/serve-tls/cert.pem"); + let as_ca = policy(crate::tls_pins::CaSource::File(own_cert)); + match HttpTransport::connect_with_pins(&url, None, Some(&as_ca)) { + Err(Error::Tls(e)) => { + assert!(e.to_string().contains("certificate validation"), "got {e}") + } + other => panic!( + "expected a CA validation failure, got {:?}", + other.map(|_| ()) + ), + } + assert!(!kh.exists(), "CA mode must not write a pin"); + + // A missing or empty bundle fails closed, never falls back to TOFU. + let missing = policy(crate::tls_pins::CaSource::File(dir.join("absent.pem"))); + assert!(matches!( + HttpTransport::connect_with_pins(&url, None, Some(&missing)), + Err(Error::Tls(_)) + )); + std::fs::write(dir.join("empty.pem"), "").unwrap(); + let empty = policy(crate::tls_pins::CaSource::File(dir.join("empty.pem"))); + assert!(matches!( + HttpTransport::connect_with_pins(&url, None, Some(&empty)), + Err(Error::Tls(_)) + )); + assert!(!kh.exists(), "still no pin written"); + std::fs::remove_dir_all(&dir).unwrap(); + std::fs::remove_dir_all(&root).unwrap(); + } + /// Transport verbs work over TLS end to end (list_refs against the real /// server — the full clone/push/fetch acceptance rides the CLI test in /// Task 7). @@ -2269,6 +2350,7 @@ mod tests { known_hosts: std::env::temp_dir().join(format!("scl-verbs-kh-{}", std::process::id())), pre_pin: Some(spki), strict: false, + ca: None, }; let t = HttpTransport::connect_with_pins(&url, None, Some(&policy)).unwrap(); // A fresh `tmp_repo` has no commits, so `list_refs()` is legitimately diff --git a/crates/repo/src/tls_pins.rs b/crates/repo/src/tls_pins.rs index 9a349ad2..cdc91e33 100644 --- a/crates/repo/src/tls_pins.rs +++ b/crates/repo/src/tls_pins.rs @@ -23,6 +23,53 @@ pub struct TlsClientPolicy { /// as enabled (fails closed on typos like `=true`/`=yes` rather than /// 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 + /// pinning. When set, the pin file is neither read nor written. + pub ca: Option, +} + +/// Where a CA-validated connection gets its trust anchors. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum CaSource { + /// A PEM bundle of CA certificates (`SC_HTTPS_CA_FILE`). + File(PathBuf), + /// The platform trust store (`SC_HTTPS_CA=system`). + System, +} + +/// Pure decision for the CA env knobs, factored out for the same reason as +/// [`strict_from`]. Fails closed: an unrecognized `SC_HTTPS_CA` value, both +/// knobs at once, or CA trust together with a pre-pin is an error, never a +/// silent fall back to pinning or accept-new. +fn ca_from( + file: Option<&std::ffi::OsStr>, + mode: Option<&str>, + has_pre_pin: bool, +) -> Result> { + let file = file.filter(|f| !f.is_empty()); + let mode = mode.filter(|m| !m.is_empty()); + let source = match (file, mode) { + (None, None) => return Ok(None), + (Some(_), Some(_)) => { + return Err(Error::InvalidArgument( + "set one of SC_HTTPS_CA_FILE and SC_HTTPS_CA, not both".to_string(), + )) + } + (Some(f), None) => CaSource::File(PathBuf::from(f)), + (None, Some("system")) => CaSource::System, + (None, Some(other)) => { + return Err(Error::InvalidArgument(format!( + "SC_HTTPS_CA must be `system` (or use SC_HTTPS_CA_FILE=), got {other:?}" + ))) + } + }; + if has_pre_pin { + return Err(Error::InvalidArgument( + "SC_HTTPS_FINGERPRINT (a pin) cannot be combined with CA validation".to_string(), + )); + } + Ok(Some(source)) } impl TlsClientPolicy { @@ -33,10 +80,16 @@ impl TlsClientPolicy { _ => None, }; let strict = strict_from(std::env::var("SC_HTTPS_STRICT").ok().as_deref()); + let ca = ca_from( + std::env::var_os("SC_HTTPS_CA_FILE").as_deref(), + std::env::var("SC_HTTPS_CA").ok().as_deref(), + pre_pin.is_some(), + )?; Ok(TlsClientPolicy { known_hosts, pre_pin, strict, + ca, }) } } @@ -577,4 +630,31 @@ mod tests { std::fs::remove_dir_all(&dir).unwrap(); assert!(!dir.exists()); } + + #[test] + fn ca_from_resolves_the_knobs_and_fails_closed() { + use std::ffi::OsStr; + assert_eq!(ca_from(None, None, false).unwrap(), None); + assert_eq!( + ca_from(Some(OsStr::new("")), Some(""), false).unwrap(), + None + ); + assert_eq!( + ca_from(Some(OsStr::new("/etc/ca.pem")), None, false).unwrap(), + Some(CaSource::File("/etc/ca.pem".into())) + ); + assert_eq!( + ca_from(None, Some("system"), false).unwrap(), + Some(CaSource::System) + ); + for bad in [ + ca_from(None, Some("yes"), false), + ca_from(None, Some("System"), false), + ca_from(Some(OsStr::new("/x")), Some("system"), false), + ca_from(None, Some("system"), true), + ca_from(Some(OsStr::new("/x")), None, true), + ] { + assert!(bad.is_err(), "must fail closed, got {bad:?}"); + } + } } diff --git a/crates/tlsio/Cargo.toml b/crates/tlsio/Cargo.toml index 20fc6289..61b1e18e 100644 --- a/crates/tlsio/Cargo.toml +++ b/crates/tlsio/Cargo.toml @@ -10,6 +10,7 @@ hex = "0.4.3" rcgen = "0.14.8" ring = "0.17.14" rustls = { version = "0.23.41", default-features = false, features = ["ring", "std", "tls12", "logging"] } +rustls-native-certs = "0.8.5" rustls-pki-types = { version = "1.15.0", features = ["std"] } thiserror = "2.0.18" diff --git a/crates/tlsio/src/lib.rs b/crates/tlsio/src/lib.rs index 83c55872..8d44428a 100644 --- a/crates/tlsio/src/lib.rs +++ b/crates/tlsio/src/lib.rs @@ -1,12 +1,13 @@ //! TLS quarantine crate (P32, ADR-0042): the ONLY crate linking rustls and //! rcgen (the gix→gitio / RustCrypto→crypto precedent). Exposes blocking //! `Read + Write` TLS streams for the sc+https:// transport, a pin-only -//! TOFU certificate verifier, self-signed cert mint/load, and SPKI-SHA-256 -//! fingerprints. Depends on no other workspace crate. +//! TOFU certificate verifier, an additive CA-path validator (ADR-0054), +//! self-signed cert mint/load, and SPKI-SHA-256 fingerprints. Depends on no other workspace crate. mod identity; mod spki; mod stream; +mod trust; pub use identity::{load_or_mint, load_pem, ServerIdentity}; pub use rustls::pki_types::{CertificateDer, PrivateKeyDer}; @@ -15,6 +16,7 @@ pub use stream::{ client_connect, server_config, server_stream, TlsClientReadHalf, TlsClientStream, TlsClientWriteHalf, TlsServerConfig, TlsServerReadHalf, TlsServerStream, TlsServerWriteHalf, }; +pub use trust::{client_connect_ca, CaTrust}; /// Errors from the TLS layer. `PinMismatch` carries both fingerprints so the /// caller (crates/repo) can render a recovery hint naming its pin source — diff --git a/crates/tlsio/src/stream.rs b/crates/tlsio/src/stream.rs index 37f91d39..af1e6e09 100644 --- a/crates/tlsio/src/stream.rs +++ b/crates/tlsio/src/stream.rs @@ -121,6 +121,15 @@ pub struct TlsClientStream { inner: rustls::StreamOwned, } +impl TlsClientStream { + /// Wrap a completed client handshake (used by the CA-validating connect). + pub(crate) fn from_parts(conn: rustls::ClientConnection, tcp: TcpStream) -> TlsClientStream { + TlsClientStream { + inner: rustls::StreamOwned::new(conn, tcp), + } + } +} + impl std::fmt::Debug for TlsClientStream { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("TlsClientStream").finish_non_exhaustive() diff --git a/crates/tlsio/src/trust.rs b/crates/tlsio/src/trust.rs new file mode 100644 index 00000000..28c32d9e --- /dev/null +++ b/crates/tlsio/src/trust.rs @@ -0,0 +1,264 @@ +//! CA-path validation (ADR-0054): the additive alternative to SPKI pinning for +//! deployments whose server presents a certificate issued by a real CA (a +//! certbot/ACME certificate that rotates, an organisation's private CA). +//! +//! Unlike the pin verifier, this checks everything a browser would: the chain +//! to a trusted root, the validity window, and that the certificate covers the +//! name the client dialled (DNS or IP SAN). Handshake signatures are verified +//! as always. It never falls back to accept-new: a client that asked for CA +//! trust and cannot establish it fails. + +use std::net::TcpStream; +use std::path::Path; +use std::sync::Arc; + +use rustls::pki_types::{pem::PemObject, CertificateDer, ServerName}; +use rustls::RootCertStore; + +use crate::stream::TlsClientStream; +use crate::{Error, Result}; + +/// The trust anchors a CA-validated connection accepts. +#[derive(Clone)] +pub struct CaTrust { + roots: Arc, + /// How many anchors were loaded (for the caller's diagnostics). + count: usize, +} + +impl CaTrust { + /// Anchors from a PEM bundle (one or more `CERTIFICATE` blocks). A file + /// with no usable certificate is an error, never an empty store that would + /// make every connection fail later with a confusing message. + pub fn from_pem_file(path: &Path) -> Result { + let certs: Vec> = CertificateDer::pem_file_iter(path) + .map_err(|e| Error::Mint(format!("read CA bundle {}: {e}", path.display())))? + .collect::>() + .map_err(|e| Error::Mint(format!("parse CA bundle {}: {e}", path.display())))?; + Self::from_der(certs, &path.display().to_string()) + } + + /// Anchors from the platform's trust store (system roots). + pub fn system() -> Result { + let loaded = rustls_native_certs::load_native_certs(); + if loaded.certs.is_empty() { + let why = loaded + .errors + .first() + .map(|e| format!(": {e}")) + .unwrap_or_default(); + return Err(Error::Mint(format!( + "no system root certificates could be loaded{why}" + ))); + } + Self::from_der(loaded.certs, "the system trust store") + } + + fn from_der(certs: Vec>, from: &str) -> Result { + let mut roots = RootCertStore::empty(); + let (added, _ignored) = roots.add_parsable_certificates(certs); + if added == 0 { + return Err(Error::Mint(format!( + "{from} holds no usable CA certificate" + ))); + } + Ok(CaTrust { + roots: Arc::new(roots), + count: added, + }) + } + + /// The number of trust anchors loaded. + pub fn anchors(&self) -> usize { + self.count + } +} + +/// Connect-side wrap with CA validation: chain, validity and name must all +/// check out before any application byte is written. `host` is the name the +/// caller dialled (a DNS name or an IP address). +pub fn client_connect_ca( + mut tcp: TcpStream, + host: &str, + trust: &CaTrust, +) -> Result { + let provider = Arc::new(rustls::crypto::ring::default_provider()); + let config = rustls::ClientConfig::builder_with_provider(provider) + .with_safe_default_protocol_versions() + .map_err(|e| Error::Handshake(e.to_string()))? + .with_root_certificates(Arc::clone(&trust.roots)) + .with_no_client_auth(); + let name = ServerName::try_from(host.to_string()) + .map_err(|e| Error::Handshake(format!("bad server name {host}: {e}")))?; + let mut conn = rustls::ClientConnection::new(Arc::new(config), name) + .map_err(|e| Error::Handshake(e.to_string()))?; + while conn.is_handshaking() { + if let Err(e) = conn.complete_io(&mut tcp) { + return Err(Error::Handshake(format!( + "certificate validation for {host} failed: {e}" + ))); + } + } + Ok(TlsClientStream::from_parts(conn, tcp)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{server_config, server_stream, ServerIdentity}; + use std::io::{Read, Write}; + use std::net::TcpListener; + + struct Pki { + ca_pem: String, + identity: ServerIdentity, + } + + /// A throwaway CA and a leaf it issued for `names` (DNS names and, when + /// they parse as such, IP addresses). + fn pki(names: &[&str]) -> Pki { + let ca_key = rcgen::KeyPair::generate().unwrap(); + let mut ca_params = rcgen::CertificateParams::new(Vec::::new()).unwrap(); + ca_params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained); + ca_params.key_usages = vec![ + rcgen::KeyUsagePurpose::KeyCertSign, + rcgen::KeyUsagePurpose::CrlSign, + ]; + let ca = ca_params.self_signed(&ca_key).unwrap(); + let issuer = rcgen::Issuer::new(ca_params, ca_key); + + let leaf_key = rcgen::KeyPair::generate().unwrap(); + let leaf_params = + rcgen::CertificateParams::new(names.iter().map(|n| n.to_string()).collect::>()) + .unwrap(); + let leaf = leaf_params.signed_by(&leaf_key, &issuer).unwrap(); + let der = leaf.der().clone(); + let spki = crate::spki_sha256(&der).unwrap(); + Pki { + ca_pem: ca.pem(), + identity: ServerIdentity { + certs: vec![der], + key: rustls::pki_types::PrivateKeyDer::Pkcs8( + rustls::pki_types::PrivatePkcs8KeyDer::from(leaf_key.serialize_der()), + ), + spki_sha256: spki, + }, + } + } + + fn tmp(tag: &str) -> std::path::PathBuf { + let d = std::env::temp_dir().join(format!("scl-tlsio-ca-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d + } + + fn trust_from(dir: &std::path::Path, pem: &str) -> CaTrust { + let f = dir.join("ca.pem"); + std::fs::write(&f, pem).unwrap(); + CaTrust::from_pem_file(&f).unwrap() + } + + /// One-connection echo server for the identity; returns its address. + fn serve(identity: ServerIdentity) -> (String, std::thread::JoinHandle<()>) { + let cfg = server_config(identity).unwrap(); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap().to_string(); + let h = std::thread::spawn(move || { + let (tcp, _) = listener.accept().unwrap(); + let Ok(stream) = server_stream(&cfg, tcp) else { + return; // a client that rejects the cert aborts the handshake + }; + let (mut r, mut w) = stream.split(); + let mut buf = [0u8; 5]; + if r.read_exact(&mut buf).is_ok() { + let _ = w.write_all(&buf); + let _ = w.flush(); + } + }); + (addr, h) + } + + #[test] + fn a_certificate_issued_by_the_trusted_ca_for_the_dialled_name_connects() { + let dir = tmp("ok"); + let p = pki(&["localhost", "127.0.0.1"]); + let trust = trust_from(&dir, &p.ca_pem); + assert_eq!(trust.anchors(), 1); + for host in ["localhost", "127.0.0.1"] { + let (addr, h) = serve(pki_clone(&p)); + let tcp = std::net::TcpStream::connect(&addr).unwrap(); + let stream = client_connect_ca(tcp, host, &trust).unwrap(); + let (mut r, mut w) = stream.split(); + w.write_all(b"hello").unwrap(); + w.flush().unwrap(); + let mut back = [0u8; 5]; + r.read_exact(&mut back).unwrap(); + assert_eq!(&back, b"hello", "dialled as {host}"); + h.join().unwrap(); + } + std::fs::remove_dir_all(&dir).unwrap(); + assert!(!dir.exists()); + } + + fn pki_clone(p: &Pki) -> ServerIdentity { + ServerIdentity { + certs: p.identity.certs.clone(), + key: p.identity.key.clone_key(), + spki_sha256: p.identity.spki_sha256, + } + } + + #[test] + fn a_certificate_from_an_untrusted_ca_is_rejected() { + let dir = tmp("untrusted"); + let server = pki(&["localhost"]); + let other_ca = pki(&["unrelated"]); // a different CA entirely + let trust = trust_from(&dir, &other_ca.ca_pem); + let (addr, h) = serve(server.identity); + let tcp = std::net::TcpStream::connect(&addr).unwrap(); + let err = client_connect_ca(tcp, "localhost", &trust).unwrap_err(); + assert!( + err.to_string() + .contains("certificate validation for localhost failed"), + "{err}" + ); + h.join().ok(); + std::fs::remove_dir_all(&dir).unwrap(); + assert!(!dir.exists()); + } + + /// Chain-valid but issued for another name: pinning ignores names, CA + /// validation must not. + #[test] + fn a_certificate_for_another_name_is_rejected_even_from_a_trusted_ca() { + let dir = tmp("name"); + let p = pki(&["only.example"]); + let trust = trust_from(&dir, &p.ca_pem); + let (addr, h) = serve(p.identity); + let tcp = std::net::TcpStream::connect(&addr).unwrap(); + let err = client_connect_ca(tcp, "localhost", &trust).unwrap_err(); + assert!(err.to_string().contains("failed"), "{err}"); + h.join().ok(); + std::fs::remove_dir_all(&dir).unwrap(); + assert!(!dir.exists()); + } + + #[test] + fn a_bundle_with_no_certificate_is_an_error_not_an_empty_store() { + let dir = tmp("empty"); + let f = dir.join("empty.pem"); + std::fs::write(&f, "# nothing here\n").unwrap(); + let err = CaTrust::from_pem_file(&f).err().expect("must fail"); + assert!( + err.to_string().contains("no usable CA certificate"), + "{err}" + ); + let missing = CaTrust::from_pem_file(&dir.join("absent.pem")) + .err() + .expect("must fail"); + assert!(missing.to_string().contains("read CA bundle"), "{missing}"); + std::fs::remove_dir_all(&dir).unwrap(); + assert!(!dir.exists()); + } +} diff --git a/docs/THREAT-MODEL.md b/docs/THREAT-MODEL.md index 46a877cd..4c063ebc 100644 --- a/docs/THREAT-MODEL.md +++ b/docs/THREAT-MODEL.md @@ -210,12 +210,25 @@ too, not just the src-control-side metadata. `SC_HTTPS_FINGERPRINT` lets an operator (e.g. CI) pre-pin out-of-band instead of trusting the first connection; `SC_HTTPS_STRICT=1` refuses to connect to any host with no existing pin, closing the accept-new window - entirely for operators who need it. Trust is **pin-only in v1** — - certificate names and validity periods are deliberately ignored, and - CA-path validation as an additional trust option is deferred (see - `ROADMAP.md`). The TLS handshake signature is still verified even though - names/validity are not, so a captured certificate replayed without its - matching private key is rejected regardless of pin state. + entirely for operators who need it. Pin trust ignores certificate names + and validity periods deliberately. The TLS handshake signature is still + verified even though names/validity are not, so a captured certificate + replayed without its matching private key is rejected regardless of pin + state. +- **CA validation is the additive alternative (ADR-0054).** A client that sets + `SC_HTTPS_CA_FILE=` (a CA bundle) or `SC_HTTPS_CA=system` (the platform + roots) stops pinning and validates like a browser: the chain to a trusted + root, the validity window, and that the certificate covers the name or IP the + client dialled. This removes the first-connection blind spot for a server + whose certificate comes from a CA (certbot/ACME, a private CA), and a + rotating certificate no longer invalidates a pin. It is a client choice per + process: the pin file is neither read nor written, an unusable or empty + bundle fails the connection (it never falls back to accept-new), an + unrecognized `SC_HTTPS_CA` value, both knobs at once, or a pre-pin + (`SC_HTTPS_FINGERPRINT`) together with CA trust is an error, and + `SC_HTTPS_STRICT` has no meaning in this mode. What it does not give: trust + is only as good as the CA set (the whole platform store for `system`), and + revocation (CRL/OCSP) is not checked. - **`sc+http://` (plaintext) still exists, and its boundary is now narrower and clearer: it applies only to loopback or explicitly `--allow-public` deployments.** A public (non-loopback) plaintext deployment protected by diff --git a/docs/adr/0054-tls-ca-validation.md b/docs/adr/0054-tls-ca-validation.md new file mode 100644 index 00000000..d9a23fd7 --- /dev/null +++ b/docs/adr/0054-tls-ca-validation.md @@ -0,0 +1,38 @@ +# ADR-0054: CA-path validation for `sc+https://` + +- **Status:** Accepted (built) +- **Date:** 2026-10-19 +- **Builds on:** ADR-0042 (in-binary TLS, accept-new TOFU pinning), ADR-0053 (pin management) + +## Context + +ADR-0042 shipped pin-only trust: the client pins `SHA-256(SPKI)` per host and ignores certificate names and validity. That fits a self-minted identity, but it fits a CA-issued certificate badly. A certbot/ACME certificate rotates every few weeks and usually brings a new key, so the pin breaks on each renewal (or the operator must reuse the key forever). And the first connection to any host is unverified by construction, even when the server presents a certificate a CA vouched for. ADR-0042 named CA-path validation, "an additive trust option for PEM-provisioned deployments", as a follow-on, and the server side already loads an operator PEM pair (`--tls-cert`/`--tls-key`). + +## Decision + +A client opts into CA validation with an environment variable, resolved once per connection by `TlsClientPolicy::from_env`: + +- `SC_HTTPS_CA_FILE=`: trust the CA certificates in this PEM bundle. +- `SC_HTTPS_CA=system`: trust the platform's root store (`rustls-native-certs`). + +When either is set the client validates like a browser (`rustls`/webpki through `scl_tlsio::client_connect_ca`): the chain to a trusted anchor, the validity window, and that the certificate covers the name or IP address the client dialled; handshake signatures are verified as always. The handshake completes before any application byte (the HTTP opening, the bearer token) is written, as in pin mode. + +- It **replaces** pinning for that connection. The pin file is neither read nor written, so a CA-validated host never accrues a pin, and `SC_HTTPS_STRICT` has no meaning. +- It **fails closed.** A bundle that cannot be read or holds no usable CA, an empty system store, an unrecognized `SC_HTTPS_CA` value (only `system` is accepted), both knobs set at once, or `SC_HTTPS_FINGERPRINT` (a pin) set together with CA trust is an error. Nothing falls back to accept-new. +- Pin mode is unchanged and remains the default. The server side is unchanged: `sc serve --tls-cert/--tls-key` already serves a CA-issued pair. + +`scl_tlsio` stays the only crate linking rustls: `CaTrust` (`from_pem_file`, `system`) and `client_connect_ca` live there; the repo layer carries the choice as `CaSource` in `TlsClientPolicy`. + +## Not decided here + +Revocation (CRL/OCSP) is not checked. Per-host choice of trust mode, and a CLI flag in place of the environment variables, are additive. Client certificates (mTLS) are out of scope. + +## Consequences + +- A CA-issued server needs no first-connect trust and survives certificate rotation. +- `system` trusts every CA in the platform store; an operator who wants less passes a bundle with `SC_HTTPS_CA_FILE`. +- Setting `SC_HTTPS_CA*` for a self-minted (self-signed) server fails by design: a self-signed certificate is not vouched for by any CA. Use pinning for those, or put the server's certificate in a bundle that names the dialled host. + +## Tests + +`scl_tlsio` end to end with a throwaway CA and a leaf it issued: a certificate from the trusted CA connects by DNS name and by IP and moves data; one from another CA is rejected; one issued for a different name is rejected even though its chain is valid; a bundle with no certificate or a missing file is an error. `scl_repo`: the env resolver fails closed on every bad combination, and a CA policy against a real TLS server refuses it, never creates the pin file, and fails closed on a missing or empty bundle. diff --git a/docs/adr/README.md b/docs/adr/README.md index 6ffbb7e3..4f0fa534 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -64,6 +64,7 @@ supersedes the old one and update the **Status** line of the superseded record. | [0051](0051-rotate-protected-paths.md) | Rotating protected paths (`sc rewrap --rotate`) | Accepted | — | | [0052](0052-secret-injection-by-fd.md) | Secret injection by file descriptor (`sc run --secrets-fd`) | Accepted | — | | [0053](0053-tls-pin-management.md) | TLS pin management (`sc tls`) | Accepted | — | +| [0054](0054-tls-ca-validation.md) | CA-path validation for `sc+https://` | Accepted | — | See [`ROADMAP.md`](../../ROADMAP.md) for the phase sequence. ADR numbers are assigned in creation order, so 0017 — the secret scanner — sequences as phase P5, From a61a5829320275c89052651f4514fbc6264814b8 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Mon, 19 Oct 2026 16:02:20 +0300 Subject: [PATCH 2/3] fix(tlsio,repo): harden CA mode after Sol review (no silent fallback to pinning) Sol review: a CA variable that is present but empty (an unset shell variable) or not valid UTF-8 read as absent and silently restored TOFU, which would send the bearer token to an unverified host; both are now errors, as is a non-UTF-8 SC_HTTPS_FINGERPRINT. A PEM bundle with a block that is not a certificate is refused instead of quietly shrunk; partial system-store load errors are reported as warnings (the loaded roots still validate); and CA mode no longer needs HOME/XDG/SC_HTTPS_KNOWN_HOSTS to resolve an unused pin file. Co-Authored-By: Claude Sonnet 5.5 --- crates/repo/src/http_transport.rs | 3 ++ crates/repo/src/tls_pins.rs | 83 +++++++++++++++++++++++------- crates/tlsio/src/trust.rs | 65 +++++++++++++++++++++-- docs/adr/0054-tls-ca-validation.md | 2 +- 4 files changed, 127 insertions(+), 26 deletions(-) diff --git a/crates/repo/src/http_transport.rs b/crates/repo/src/http_transport.rs index 8d0ed9ac..799c90c6 100644 --- a/crates/repo/src/http_transport.rs +++ b/crates/repo/src/http_transport.rs @@ -408,6 +408,9 @@ impl HttpTransport { crate::tls_pins::CaSource::File(f) => scl_tlsio::CaTrust::from_pem_file(f), crate::tls_pins::CaSource::System => scl_tlsio::CaTrust::system(), }?; + for w in trust.warnings() { + eprintln!("warning: sc+https CA trust: {w}"); + } let tls = scl_tlsio::client_connect_ca(stream, &url.host, &trust)?; let (rh, wh) = tls.split(); ( diff --git a/crates/repo/src/tls_pins.rs b/crates/repo/src/tls_pins.rs index cdc91e33..1c110544 100644 --- a/crates/repo/src/tls_pins.rs +++ b/crates/repo/src/tls_pins.rs @@ -39,16 +39,35 @@ pub enum CaSource { } /// Pure decision for the CA env knobs, factored out for the same reason as -/// [`strict_from`]. Fails closed: an unrecognized `SC_HTTPS_CA` value, both -/// knobs at once, or CA trust together with a pre-pin is an error, never a -/// silent fall back to pinning or accept-new. +/// [`strict_from`]. `file`/`mode` are the raw environment values (`None` = +/// the variable is absent). Fails closed: a security knob that is PRESENT but +/// empty (an unset shell variable in `SC_HTTPS_CA_FILE="$BUNDLE"`) or not +/// valid UTF-8 is an error, not an absence; so is an unrecognized `SC_HTTPS_CA` +/// value, both knobs at once, or CA trust together with a pre-pin. Nothing +/// here may quietly fall back to pinning or accept-new, which would send the +/// bearer token to an unverified host. fn ca_from( file: Option<&std::ffi::OsStr>, - mode: Option<&str>, + mode: Option<&std::ffi::OsStr>, has_pre_pin: bool, ) -> Result> { - let file = file.filter(|f| !f.is_empty()); - let mode = mode.filter(|m| !m.is_empty()); + if file.is_some_and(|f| f.is_empty()) { + return Err(Error::InvalidArgument( + "SC_HTTPS_CA_FILE is set but empty; unset it or point it at a PEM bundle".to_string(), + )); + } + let mode = + match mode { + None => None, + Some(m) => Some(m.to_str().ok_or_else(|| { + Error::InvalidArgument("SC_HTTPS_CA is not valid UTF-8".to_string()) + })?), + }; + if mode.is_some_and(|m| m.is_empty()) { + return Err(Error::InvalidArgument( + "SC_HTTPS_CA is set but empty; use `system` or unset it".to_string(), + )); + } let source = match (file, mode) { (None, None) => return Ok(None), (Some(_), Some(_)) => { @@ -74,17 +93,31 @@ fn ca_from( impl TlsClientPolicy { pub fn from_env() -> Result { - let known_hosts = known_hosts_path()?; + // A pre-pin that is present but not valid UTF-8 is an error, not an + // absent pin: ignoring it would drop an explicit trust decision (and + // its conflict check with CA trust). let pre_pin = match std::env::var("SC_HTTPS_FINGERPRINT") { Ok(s) if !s.is_empty() => Some(parse_fingerprint(&s)?), - _ => None, + Ok(_) | Err(std::env::VarError::NotPresent) => None, + Err(std::env::VarError::NotUnicode(_)) => { + return Err(Error::InvalidArgument( + "SC_HTTPS_FINGERPRINT is not valid UTF-8".to_string(), + )) + } }; let strict = strict_from(std::env::var("SC_HTTPS_STRICT").ok().as_deref()); let ca = ca_from( std::env::var_os("SC_HTTPS_CA_FILE").as_deref(), - std::env::var("SC_HTTPS_CA").ok().as_deref(), + std::env::var_os("SC_HTTPS_CA").as_deref(), pre_pin.is_some(), )?; + // CA mode never reads or writes the pin file, so a missing HOME (a + // service, a container) must not fail it. + let known_hosts = if ca.is_some() { + known_hosts_path().unwrap_or_default() + } else { + known_hosts_path()? + }; Ok(TlsClientPolicy { known_hosts, pre_pin, @@ -634,27 +667,37 @@ mod tests { #[test] fn ca_from_resolves_the_knobs_and_fails_closed() { use std::ffi::OsStr; + let os = OsStr::new; assert_eq!(ca_from(None, None, false).unwrap(), None); assert_eq!( - ca_from(Some(OsStr::new("")), Some(""), false).unwrap(), - None - ); - assert_eq!( - ca_from(Some(OsStr::new("/etc/ca.pem")), None, false).unwrap(), + ca_from(Some(os("/etc/ca.pem")), None, false).unwrap(), Some(CaSource::File("/etc/ca.pem".into())) ); assert_eq!( - ca_from(None, Some("system"), false).unwrap(), + ca_from(None, Some(os("system")), false).unwrap(), Some(CaSource::System) ); for bad in [ - ca_from(None, Some("yes"), false), - ca_from(None, Some("System"), false), - ca_from(Some(OsStr::new("/x")), Some("system"), false), - ca_from(None, Some("system"), true), - ca_from(Some(OsStr::new("/x")), None, true), + ca_from(None, Some(os("yes")), false), + ca_from(None, Some(os("System")), false), + ca_from(Some(os("/x")), Some(os("system")), false), + ca_from(None, Some(os("system")), true), + ca_from(Some(os("/x")), None, true), + // Present but empty: an unset shell variable, never an absence. + ca_from(Some(os("")), None, false), + ca_from(None, Some(os("")), false), + ca_from(Some(os("")), Some(os("system")), false), ] { assert!(bad.is_err(), "must fail closed, got {bad:?}"); } } + + /// A non-UTF-8 `SC_HTTPS_CA` must not read as "unset". + #[cfg(unix)] + #[test] + fn ca_from_rejects_a_non_utf8_mode() { + use std::os::unix::ffi::OsStrExt; + let bad = std::ffi::OsStr::from_bytes(b"sys\xffem"); + assert!(ca_from(None, Some(bad), false).is_err()); + } } diff --git a/crates/tlsio/src/trust.rs b/crates/tlsio/src/trust.rs index 28c32d9e..080e4478 100644 --- a/crates/tlsio/src/trust.rs +++ b/crates/tlsio/src/trust.rs @@ -24,18 +24,24 @@ pub struct CaTrust { roots: Arc, /// How many anchors were loaded (for the caller's diagnostics). count: usize, + /// Non-fatal problems loading the platform store (a directory that could + /// not be read, a certificate that did not parse). The anchors that did + /// load still validate; the caller decides whether to warn. + warnings: Vec, } impl CaTrust { /// Anchors from a PEM bundle (one or more `CERTIFICATE` blocks). A file /// with no usable certificate is an error, never an empty store that would - /// make every connection fail later with a confusing message. + /// make every connection fail later with a confusing message, and so is a + /// block that is not a valid certificate: an explicitly supplied bundle + /// must be whole, not quietly shrunk. pub fn from_pem_file(path: &Path) -> Result { let certs: Vec> = CertificateDer::pem_file_iter(path) .map_err(|e| Error::Mint(format!("read CA bundle {}: {e}", path.display())))? .collect::>() .map_err(|e| Error::Mint(format!("parse CA bundle {}: {e}", path.display())))?; - Self::from_der(certs, &path.display().to_string()) + Self::from_der(certs, &path.display().to_string(), true) } /// Anchors from the platform's trust store (system roots). @@ -51,20 +57,43 @@ impl CaTrust { "no system root certificates could be loaded{why}" ))); } - Self::from_der(loaded.certs, "the system trust store") + let mut trust = Self::from_der(loaded.certs, "the system trust store", false)?; + // Loading a real platform store routinely reports a stray unreadable + // entry; the roots that loaded still validate (a smaller trust set, + // never a larger one), so these are reported, not fatal. + trust + .warnings + .extend(loaded.errors.iter().map(|e| e.to_string())); + Ok(trust) } - fn from_der(certs: Vec>, from: &str) -> Result { + fn from_der( + certs: Vec>, + from: &str, + reject_unparsable: bool, + ) -> Result { let mut roots = RootCertStore::empty(); - let (added, _ignored) = roots.add_parsable_certificates(certs); + let (added, ignored) = roots.add_parsable_certificates(certs); if added == 0 { return Err(Error::Mint(format!( "{from} holds no usable CA certificate" ))); } + let mut warnings = Vec::new(); + if ignored > 0 { + if reject_unparsable { + return Err(Error::Mint(format!( + "{from} holds {ignored} certificate block(s) that are not valid CA certificates" + ))); + } + warnings.push(format!( + "{ignored} certificate(s) in {from} could not be parsed" + )); + } Ok(CaTrust { roots: Arc::new(roots), count: added, + warnings, }) } @@ -72,6 +101,11 @@ impl CaTrust { pub fn anchors(&self) -> usize { self.count } + + /// Non-fatal problems met while loading the anchors (system store only). + pub fn warnings(&self) -> &[String] { + &self.warnings + } } /// Connect-side wrap with CA validation: chain, validity and name must all @@ -261,4 +295,25 @@ mod tests { std::fs::remove_dir_all(&dir).unwrap(); assert!(!dir.exists()); } + + /// One valid CA plus a CERTIFICATE block that is not a certificate: the + /// bundle is refused, not silently shrunk. + #[test] + fn a_partially_invalid_bundle_is_refused() { + let dir = tmp("partial"); + let p = pki(&["localhost"]); + let bundle = format!( + "{}\n-----BEGIN CERTIFICATE-----\nAQID\n-----END CERTIFICATE-----\n", + p.ca_pem + ); + let f = dir.join("bundle.pem"); + std::fs::write(&f, bundle).unwrap(); + let err = CaTrust::from_pem_file(&f).err().expect("must fail"); + assert!( + err.to_string().contains("not valid CA certificates"), + "{err}" + ); + std::fs::remove_dir_all(&dir).unwrap(); + assert!(!dir.exists()); + } } diff --git a/docs/adr/0054-tls-ca-validation.md b/docs/adr/0054-tls-ca-validation.md index d9a23fd7..6beb1bf4 100644 --- a/docs/adr/0054-tls-ca-validation.md +++ b/docs/adr/0054-tls-ca-validation.md @@ -18,7 +18,7 @@ A client opts into CA validation with an environment variable, resolved once per When either is set the client validates like a browser (`rustls`/webpki through `scl_tlsio::client_connect_ca`): the chain to a trusted anchor, the validity window, and that the certificate covers the name or IP address the client dialled; handshake signatures are verified as always. The handshake completes before any application byte (the HTTP opening, the bearer token) is written, as in pin mode. - It **replaces** pinning for that connection. The pin file is neither read nor written, so a CA-validated host never accrues a pin, and `SC_HTTPS_STRICT` has no meaning. -- It **fails closed.** A bundle that cannot be read or holds no usable CA, an empty system store, an unrecognized `SC_HTTPS_CA` value (only `system` is accepted), both knobs set at once, or `SC_HTTPS_FINGERPRINT` (a pin) set together with CA trust is an error. Nothing falls back to accept-new. +- It **fails closed.** A CA variable that is present but empty (an unset shell variable in `SC_HTTPS_CA_FILE="$BUNDLE"`) or not valid UTF-8, a bundle that cannot be read, holds no usable CA or holds any block that is not a valid certificate, an empty system store, an unrecognized `SC_HTTPS_CA` value (only `system` is accepted), both knobs set at once, or `SC_HTTPS_FINGERPRINT` (a pin, also refused if not valid UTF-8) set together with CA trust is an error. Nothing falls back to accept-new, which would send the bearer token to an unverified host. A system store that loads some roots but reports others unreadable still validates with the roots that loaded (a smaller trust set, never a larger one) and prints a warning. CA mode does not need a pin-file location, so a missing `HOME` does not fail it. - Pin mode is unchanged and remains the default. The server side is unchanged: `sc serve --tls-cert/--tls-key` already serves a CA-issued pair. `scl_tlsio` stays the only crate linking rustls: `CaTrust` (`from_pem_file`, `system`) and `client_connect_ca` live there; the repo layer carries the choice as `CaSource` in `TlsClientPolicy`. From 5a410c63d93964d5e06b6ea0f92d4f74c58287af Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Mon, 19 Oct 2026 16:06:34 +0300 Subject: [PATCH 3/3] fix(repo): connect_with_pins refuses a policy with both a CA and a pre-pin Codex: from_env rejected the combination but the public env-free seam let CA validation silently win over a requested fingerprint. Co-Authored-By: Claude Sonnet 5.5 --- crates/repo/src/http_transport.rs | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/crates/repo/src/http_transport.rs b/crates/repo/src/http_transport.rs index 799c90c6..697d4b8b 100644 --- a/crates/repo/src/http_transport.rs +++ b/crates/repo/src/http_transport.rs @@ -374,6 +374,17 @@ impl HttpTransport { } } + // Two trust decisions in one policy is a caller bug: refuse it before + // any socket exists, so a caller cannot believe a pin is being checked + // while CA validation silently wins (`from_env` rejects it too). + if let Some(p) = policy { + if p.ca.is_some() && p.pre_pin.is_some() { + return Err(Error::InvalidArgument( + "a TLS policy cannot combine CA validation with a pre-pin".to_string(), + )); + } + } + let stream = TcpStream::connect(url.authority()) .map_err(|e| Error::ConnectionLost(format!("sc+http connect to {url:?}: {e}")))?; @@ -2328,6 +2339,18 @@ mod tests { Err(Error::Tls(_)) )); assert!(!kh.exists(), "still no pin written"); + + // A policy that asks for both trust decisions is refused up front. + let both = crate::tls_pins::TlsClientPolicy { + known_hosts: kh.clone(), + pre_pin: Some([0x11; 32]), + strict: false, + ca: Some(crate::tls_pins::CaSource::System), + }; + assert!(matches!( + HttpTransport::connect_with_pins(&url, None, Some(&both)), + Err(Error::InvalidArgument(m)) if m.contains("cannot combine") + )); std::fs::remove_dir_all(&dir).unwrap(); std::fs::remove_dir_all(&root).unwrap(); }