diff --git a/crates/twigpine-node/src/upstream_mirror.rs b/crates/twigpine-node/src/upstream_mirror.rs index 813c94fed..11ca47898 100644 --- a/crates/twigpine-node/src/upstream_mirror.rs +++ b/crates/twigpine-node/src/upstream_mirror.rs @@ -30,7 +30,7 @@ struct EgressPolicy; #[derive(Debug, Clone, PartialEq, Eq)] struct PinnedUpstream { url: String, - curlopt_resolve: Option, + curlopt_resolve: Vec, } impl EgressPolicy { @@ -52,7 +52,7 @@ impl EgressPolicy { url: url.to_string(), // An IP literal performs no DNS lookup, so there is no rebinding // window to pin. TLS still verifies the literal from the URL. - curlopt_resolve: None, + curlopt_resolve: Vec::new(), }); } @@ -70,17 +70,9 @@ impl EgressPolicy { let addresses: Vec = addresses.into_iter().collect(); self.validate_addresses(&policy_host, &addresses)?; - let pinned = addresses - .iter() - .map(|ip| match ip { - IpAddr::V4(v4) => v4.to_string(), - IpAddr::V6(v6) => format!("[{v6}]"), - }) - .collect::>() - .join(","); Ok(PinnedUpstream { url: url.to_string(), - curlopt_resolve: Some(format!("+{connect_host}:{port}:{pinned}")), + curlopt_resolve: resolve_pins(&connect_host, port, addresses), }) } @@ -99,6 +91,46 @@ impl EgressPolicy { } } +/// The `http.curloptResolve` entries pinning `host:port` to `addrs`, the +/// validated answer set. Callers must pass a non-empty set; nothing here +/// checks it, and [`EgressPolicy::resolve`], the only caller, refuses an empty +/// answer before calling. +/// +/// There is deliberately no `+` prefix: that expiring-entry form arrived in +/// libcurl 7.75, and an older libcurl reads the `+` as part of the hostname, +/// so the entry never matches and git falls back to DNS at connect time. The +/// worker's Git 2.37 floor does not imply a libcurl that understands `+`. +/// +/// A comma-separated address list needs libcurl 7.59; older versions reject +/// the whole entry and would re-resolve at connect time. Duplicate host:port +/// entries also have opposite semantics: libcurl 7.59/7.60 keep the first one, +/// while 7.61+ keep the last. Emit the full list at both ends with a single +/// checked address in the middle, so each generation keeps a valid pin: +/// pre-7.59 rejects both lists and keeps the single address, 7.59/7.60 keep +/// the first list, and 7.61+ keep the last. None can fall back to DNS. +/// +/// The single-address entry writes an IPv6 address without brackets: libcurl +/// before 7.57 rejects `[addr]`, which would leave an IPv6-only answer with no +/// pin, and every version accepts the bare form in a single-address entry. The +/// lists keep brackets because only 7.59+ reads them. +fn resolve_pins(host: &str, port: u16, mut addrs: Vec) -> Vec { + addrs.sort_unstable(); + let single = format!("{host}:{port}:{}", addrs[0]); + if addrs.len() == 1 { + return vec![single]; + } + let list = addrs + .iter() + .map(|ip| match ip { + IpAddr::V4(v4) => v4.to_string(), + IpAddr::V6(v6) => format!("[{v6}]"), + }) + .collect::>() + .join(","); + let full = format!("{host}:{port}:{list}"); + vec![full.clone(), single, full] +} + fn normalize_policy_host(host: &str) -> String { host.trim_end_matches('.').to_ascii_lowercase() } @@ -196,10 +228,10 @@ fn fetch_command(upstream: &PinnedUpstream) -> FetchCommand { (http_scope("saveCookies"), "false".to_string()), (http_scope("sslVerify"), "true".to_string()), ]; - if let Some(resolve) = &upstream.curlopt_resolve { + for pin in &upstream.curlopt_resolve { config.extend([ - ("http.curloptResolve".to_string(), resolve.clone()), - (http_scope("curloptResolve"), resolve.clone()), + ("http.curloptResolve".to_string(), pin.clone()), + (http_scope("curloptResolve"), pin.clone()), ]); } config.extend([ @@ -684,6 +716,67 @@ esac assert!((2, 36) < MIN_CURL_OPT_RESOLVE_GIT); } + #[test] + fn resolve_pins_work_across_libcurl_duplicate_semantics() { + // No leading `+`: it is parsed as part of the hostname before libcurl + // 7.75. The full list is repeated at both ends so first-wins (7.59/ + // 7.60) and last-wins (7.61+) libcurl both keep every checked address; + // the single address in the middle is what pre-7.59 keeps. + let pins = resolve_pins( + "github.example", + 443, + vec![ + "2606:4700:4700::1111".parse().unwrap(), + "8.8.8.8".parse().unwrap(), + ], + ); + assert_eq!( + pins, + vec![ + "github.example:443:8.8.8.8,[2606:4700:4700::1111]".to_string(), + "github.example:443:8.8.8.8".to_string(), + "github.example:443:8.8.8.8,[2606:4700:4700::1111]".to_string(), + ] + ); + assert!(pins.iter().all(|pin| !pin.starts_with('+'))); + + let single = resolve_pins("forge.example", 8080, vec!["8.8.4.4".parse().unwrap()]); + assert_eq!(single, vec!["forge.example:8080:8.8.4.4".to_string()]); + } + + #[test] + fn resolve_pins_keep_an_ipv6_only_answer_pinned_before_libcurl_7_57() { + // libcurl before 7.57 rejects `[addr]`, so a bracketed single entry + // leaves an IPv6-only answer with no pin at all. Every version accepts + // a bare IPv6 address in a single-address entry. + let pins = resolve_pins( + "v6.example", + 443, + vec![ + "2606:4700:4700::1111".parse().unwrap(), + "2606:4700:4700::1001".parse().unwrap(), + ], + ); + assert_eq!( + pins, + vec![ + "v6.example:443:[2606:4700:4700::1001],[2606:4700:4700::1111]".to_string(), + "v6.example:443:2606:4700:4700::1001".to_string(), + "v6.example:443:[2606:4700:4700::1001],[2606:4700:4700::1111]".to_string(), + ] + ); + + let single = resolve_pins( + "v6.example", + 443, + vec!["2606:4700:4700::1111".parse().unwrap()], + ); + assert_eq!( + single, + vec!["v6.example:443:2606:4700:4700::1111".to_string()] + ); + } + #[test] fn every_resolved_address_must_be_public() { let policy = EgressPolicy; @@ -753,7 +846,11 @@ esac fn fetch_command_pins_dns_and_only_updates_branches_and_tags() { let upstream = PinnedUpstream { url: "https://github.example/org/repo.git".to_string(), - curlopt_resolve: Some("+github.example:443:8.8.8.8,[2606:4700:4700::1111]".to_string()), + curlopt_resolve: vec![ + "github.example:443:8.8.8.8,[2606:4700:4700::1111]".to_string(), + "github.example:443:8.8.8.8".to_string(), + "github.example:443:8.8.8.8,[2606:4700:4700::1111]".to_string(), + ], }; let command = fetch_command(&upstream); let has_config = |key: &str, value: &str| { @@ -761,16 +858,30 @@ esac .config .contains(&(key.to_string(), value.to_string())) }; + let pins_for = |key: &str| -> Vec<&str> { + command + .config + .iter() + .filter(|(config_key, value)| config_key == key && !value.is_empty()) + .map(|(_, value)| value.as_str()) + .collect() + }; assert!(has_config("http.followRedirects", "false")); assert!(has_config("http.proxy", "")); assert!(has_config("http.extraHeader", "")); assert!(has_config("http.cookieFile", "")); assert!(has_config("http.saveCookies", "false")); assert!(has_config("http.sslVerify", "true")); - assert!(has_config( - "http.curloptResolve", - "+github.example:443:8.8.8.8,[2606:4700:4700::1111]" - )); + // The full list is first and last so both duplicate-entry generations + // keep it; pre-7.59 libcurl rejects those and keeps the single pin. + assert_eq!( + pins_for("http.curloptResolve"), + vec![ + "github.example:443:8.8.8.8,[2606:4700:4700::1111]", + "github.example:443:8.8.8.8", + "github.example:443:8.8.8.8,[2606:4700:4700::1111]", + ] + ); assert!(has_config( "http.https://github.example/org/repo.git.followRedirects", "false" @@ -783,10 +894,47 @@ esac "http.https://github.example/org/repo.git.extraHeader", "" )); - assert!(has_config( + assert_eq!( + pins_for("http.https://github.example/org/repo.git.curloptResolve"), + vec![ + "github.example:443:8.8.8.8,[2606:4700:4700::1111]", + "github.example:443:8.8.8.8", + "github.example:443:8.8.8.8,[2606:4700:4700::1111]", + ] + ); + assert!(command + .config + .iter() + .filter(|(key, value)| key.ends_with("curloptResolve") && !value.is_empty()) + .all(|(_, value)| !value.starts_with('+'))); + // An empty value clears git's multi-valued resolver list, so each + // scope's reset must come before that scope's first pin or it would + // silently drop every pin. + for key in [ + "http.curloptResolve", "http.https://github.example/org/repo.git.curloptResolve", - "+github.example:443:8.8.8.8,[2606:4700:4700::1111]" - )); + ] { + let position = |want_empty: bool| { + command + .config + .iter() + .position(|(k, v)| k == key && v.is_empty() == want_empty) + .unwrap_or_else(|| panic!("{key} entry missing")) + }; + assert!( + position(true) < position(false), + "{key} reset must precede its pins" + ); + assert_eq!( + command + .config + .iter() + .filter(|(k, v)| k == key && v.is_empty()) + .count(), + 1, + "{key} must be reset exactly once" + ); + } assert!(has_config( "credential.https://github.example/org/repo.git.helper", "" @@ -889,6 +1037,65 @@ esac assert!(error.to_string().contains("network or credential")); } + #[cfg(unix)] + #[test] + fn real_git_dials_the_pinned_address_for_an_unresolvable_host() { + // `pin.invalid` has no DNS answer, so the listener is reachable only + // through the resolver entries the fetch config carries. A pin that git + // or libcurl ignores falls back to DNS and the listener sees nothing. + // The two-address case binds the second address, so it passes only if + // libcurl kept the full list rather than the single lowest address + // (libcurl 7.59+; older versions keep the single entry by design). + for (bind, pinned) in [ + ("127.0.0.1", vec!["127.0.0.1"]), + ("127.0.0.2", vec!["127.0.0.1", "127.0.0.2"]), + ] { + let repo = tempfile::tempdir().unwrap(); + let init = fixture_git(repo.path()) + .args(["init", "--bare"]) + .output() + .unwrap(); + assert!(init.status.success()); + + let listener = std::net::TcpListener::bind((bind, 0)).unwrap(); + let port = listener.local_addr().unwrap().port(); + listener.set_nonblocking(true).unwrap(); + let accepted = std::thread::spawn(move || { + let deadline = Instant::now() + Duration::from_secs(3); + while Instant::now() < deadline { + match listener.accept() { + Ok(_) => return true, + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => { + std::thread::sleep(Duration::from_millis(10)); + } + Err(error) => panic!("accepting pinned-Git transport probe: {error}"), + } + } + false + }); + let upstream = PinnedUpstream { + url: format!("https://pin.invalid:{port}/org/repo.git"), + curlopt_resolve: resolve_pins( + "pin.invalid", + port, + pinned.iter().map(|ip| ip.parse().unwrap()).collect(), + ), + }; + let error = run_fetch( + "git", + repo.path(), + &upstream, + Duration::from_secs(5), + Instant::now() + Duration::from_secs(600), + ) + .unwrap_err(); + assert!( + accepted.join().unwrap(), + "real Git must dial the pinned {bind} for pin.invalid; got {error:#}" + ); + } + } + #[cfg(unix)] #[test] fn hardened_real_git_reaches_https_transport_for_equals_path() { @@ -922,7 +1129,7 @@ esac }); let upstream = PinnedUpstream { url: format!("https://127.0.0.1:{port}/org/repo=mirror.git"), - curlopt_resolve: None, + curlopt_resolve: Vec::new(), }; let error = run_fetch( "git", @@ -948,7 +1155,7 @@ esac .resolve(reqwest::Url::parse("https://8.8.8.8/org/repo.git").unwrap()) .await .unwrap(); - assert_eq!(allowed.curlopt_resolve, None); + assert!(allowed.curlopt_resolve.is_empty()); for denied in [ "127.0.0.1",