forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.09.4 MiBe587be7Tahinli1 day ago323 commits

mirror.rs748 lines, 24.5 KiBHistoryRawDownload
1//! Pull and push mirrors: `git fetch` from a remote URL into a repo, and `git push` of a repo's
2//! refs to a remote URL. Only `refs/heads/*` and `refs/tags/*` are synced, with prune.
3//!
4//! Safety for every remote call: protocols are limited to https (and http when the caller allows
5//! it), redirects are not followed, no credential helper runs, and a prompt is never shown. The
6//! credentials travel only in the child environment (`GIT_CONFIG_*` for an `http.extraHeader`),
7//! never in argv, the URL or an error. Errors are scrubbed before they leave this module.
8
9use std::fmt;
10use std::future::Future;
11use std::net::IpAddr;
12use std::path::Path;
13use std::time::Duration;
14
15use base64::Engine;
16use base64::engine::general_purpose::STANDARD;
17
18use crate::command::{GitCommand, GitEnv};
19use crate::error::{Error, Result};
20
21/// The refspecs both directions sync. Never `refs/pull/*`.
22pub const MIRROR_REFSPECS: [&str; 2] = ["+refs/heads/*:refs/heads/*", "+refs/tags/*:refs/tags/*"];
23
24/// Most git stderr kept in an error, in bytes.
25const MAX_STDERR_BYTES: usize = 2 * 1024;
26const REDACTED: &str = "[redacted]";
27
28/// A username and password or token for a remote. The secret is never printed: the `Debug`
29/// impl redacts it.
30#[derive(Clone, PartialEq, Eq)]
31pub struct RemoteAuth {
32 pub username: String,
33 pub secret: Vec<u8>,
34}
35
36impl fmt::Debug for RemoteAuth {
37 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38 f.debug_struct("RemoteAuth")
39 .field("username", &self.username)
40 .field("secret", &REDACTED)
41 .finish()
42 }
43}
44
45/// A host and the one address it was checked to resolve to. Git is told to connect to that address
46/// (`http.curloptResolve`), so the connection cannot be sent somewhere a second DNS lookup returns.
47#[derive(Clone, Debug, PartialEq, Eq)]
48pub struct PinnedHost {
49 pub host: String,
50 pub port: u16,
51 pub ip: IpAddr,
52}
53
54impl PinnedHost {
55 /// The `-c` pair for git: `http.curloptResolve=host:port:ip`, with an IPv6 address in brackets.
56 /// The host must be a plain DNS name, so the value cannot smuggle in another option.
57 pub fn config_pair(&self) -> Result<String> {
58 let plain_host = !self.host.is_empty()
59 && self
60 .host
61 .bytes()
62 .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'.');
63 if !plain_host {
64 return Err(Error::InvalidInput(
65 "pinned host must be a plain DNS name".into(),
66 ));
67 }
68 let ip = match self.ip {
69 IpAddr::V4(v4) => v4.to_string(),
70 IpAddr::V6(v6) => format!("[{v6}]"),
71 };
72 Ok(format!(
73 "http.curloptResolve={}:{}:{ip}",
74 self.host, self.port
75 ))
76 }
77}
78
79impl RemoteAuth {
80 /// The `Authorization` header value, Basic over `username:secret`.
81 fn header_value(&self) -> String {
82 let mut raw = self.username.as_bytes().to_vec();
83 raw.push(b':');
84 raw.extend_from_slice(&self.secret);
85 format!("Authorization: Basic {}", STANDARD.encode(raw))
86 }
87}
88
89/// Fetches the mirror refs of `url` into the bare repo at `repo`, then points HEAD at the remote's
90/// default branch when our HEAD's branch is missing. With `pin`, git connects to the pinned
91/// address. Times out after `timeout`, killing git.
92pub async fn mirror_fetch(
93 env: &GitEnv,
94 repo: &Path,
95 url: &str,
96 auth: Option<&RemoteAuth>,
97 allow_http: bool,
98 pin: Option<&PinnedHost>,
99 timeout: Duration,
100) -> Result<()> {
101 check_url(url, allow_http)?;
102 with_timeout(timeout, fetch(env, repo, url, auth, allow_http, pin, false)).await
103}
104
105/// Fetches the mirror refs of a local path over the file transport. This exists so callers' tests
106/// can import from a bare repo on disk; the web code never calls it, because every user-supplied
107/// URL goes through [`mirror_fetch`], which refuses `file://`.
108#[doc(hidden)]
109pub async fn mirror_fetch_local(
110 env: &GitEnv,
111 repo: &Path,
112 source: &str,
113 timeout: Duration,
114) -> Result<()> {
115 with_timeout(timeout, fetch(env, repo, source, None, false, None, true)).await
116}
117
118/// Pushes the mirror refs of the bare repo at `repo` to `url`, with prune. With `pin`, git connects
119/// to the pinned address. Times out after `timeout`, killing git.
120pub async fn mirror_push(
121 env: &GitEnv,
122 repo: &Path,
123 url: &str,
124 auth: Option<&RemoteAuth>,
125 allow_http: bool,
126 pin: Option<&PinnedHost>,
127 timeout: Duration,
128) -> Result<()> {
129 check_url(url, allow_http)?;
130 with_timeout(timeout, push(env, repo, url, auth, allow_http, pin, false)).await
131}
132
133/// Only https, or http when allowed. No userinfo, whitespace or control characters. Never
134/// `file://`, `ssh://` or `ext::`.
135fn check_url(url: &str, allow_http: bool) -> Result<()> {
136 let rest = if let Some(rest) = url.strip_prefix("https://") {
137 rest
138 } else if let Some(rest) = url.strip_prefix("http://").filter(|_| allow_http) {
139 rest
140 } else {
141 return Err(Error::InvalidInput(
142 "mirror URL must use https (or http when allowed)".into(),
143 ));
144 };
145 let authority = rest.split('/').next().unwrap_or_default();
146 if authority.is_empty() || authority.contains('@') {
147 return Err(Error::InvalidInput(
148 "mirror URL needs a host and must not contain credentials".into(),
149 ));
150 }
151 if url.chars().any(|c| c.is_whitespace() || c.is_control()) {
152 return Err(Error::InvalidInput(
153 "mirror URL contains whitespace or control characters".into(),
154 ));
155 }
156 Ok(())
157}
158
159async fn with_timeout<T>(timeout: Duration, fut: impl Future<Output = Result<T>>) -> Result<T> {
160 match tokio::time::timeout(timeout, fut).await {
161 Ok(result) => result,
162 Err(_) => Err(Error::Failed(format!(
163 "git timed out after {} seconds",
164 timeout.as_secs()
165 ))),
166 }
167}
168
169/// The git invocation with the safety flags, the optional repo and the optional credentials.
170/// `local` allows the file transport; only unit tests pass true.
171fn base_command(
172 env: &GitEnv,
173 repo: Option<&Path>,
174 subcommand: &'static str,
175 auth: Option<&RemoteAuth>,
176 allow_http: bool,
177 pin: Option<&PinnedHost>,
178 local: bool,
179) -> Result<GitCommand> {
180 let mut cmd = GitCommand::new(env, subcommand)
181 .config("protocol.allow=never")
182 .config("protocol.https.allow=always")
183 .config("http.followRedirects=false")
184 .config("credential.helper=");
185 if allow_http {
186 cmd = cmd.config("protocol.http.allow=always");
187 }
188 if let Some(pin) = pin {
189 cmd = cmd.config_checked(pin.config_pair()?)?;
190 }
191 if let Some(repo) = repo {
192 cmd = cmd.git_dir(repo);
193 }
194 if local {
195 cmd = cmd.allow_local_transport();
196 }
197 if let Some(auth) = auth {
198 cmd = cmd
199 .env("GIT_CONFIG_COUNT", "1")
200 .env("GIT_CONFIG_KEY_0", "http.extraHeader")
201 .env("GIT_CONFIG_VALUE_0", auth.header_value());
202 }
203 Ok(cmd)
204}
205
206async fn fetch(
207 env: &GitEnv,
208 repo: &Path,
209 url: &str,
210 auth: Option<&RemoteAuth>,
211 allow_http: bool,
212 pin: Option<&PinnedHost>,
213 local: bool,
214) -> Result<()> {
215 let mut revs = vec![url];
216 revs.extend(MIRROR_REFSPECS);
217 let cmd = base_command(env, Some(repo), "fetch", auth, allow_http, pin, local)?
218 .arg("--prune")
219 .arg("--no-recurse-submodules")
220 .user_revs(&revs)?;
221 run_checked(cmd, "fetch", auth, url).await?;
222
223 let head = base_command(env, Some(repo), "ls-remote", auth, allow_http, pin, local)?
224 .arg("--symref")
225 .user_revs(&[url, "HEAD"])?;
226 let Ok(listing) = run_checked(head, "ls-remote", auth, url).await else {
227 return Ok(());
228 };
229 let listing = String::from_utf8_lossy(&listing);
230 let Some(default_ref) = remote_default_branch(&listing) else {
231 return Ok(());
232 };
233 point_head_at_default(env, repo, &default_ref).await;
234 Ok(())
235}
236
237/// The `refs/heads/...` target of the remote HEAD symref in `ls-remote --symref` output.
238fn remote_default_branch(listing: &str) -> Option<String> {
239 listing.lines().find_map(|line| {
240 let (target, name) = line.strip_prefix("ref: ")?.split_once('\t')?;
241 (name == "HEAD" && target.starts_with("refs/heads/")).then(|| target.to_string())
242 })
243}
244
245/// Sets HEAD to `default_ref` when HEAD's branch does not exist and `default_ref` does. Best
246/// effort: failures leave HEAD as it was.
247async fn point_head_at_default(env: &GitEnv, repo: &Path, default_ref: &str) {
248 let current = GitCommand::new(env, "symbolic-ref")
249 .git_dir(repo)
250 .arg("-q")
251 .arg("HEAD")
252 .output()
253 .await
254 .ok()
255 .map(|out| String::from_utf8_lossy(&out).trim().to_string());
256 if let Some(current) = current
257 && ref_exists(env, repo, &current).await
258 {
259 return;
260 }
261 if !ref_exists(env, repo, default_ref).await {
262 return;
263 }
264 let set = GitCommand::new(env, "symbolic-ref")
265 .git_dir(repo)
266 .arg("HEAD")
267 .user_arg(default_ref);
268 if let Ok(cmd) = set {
269 let _ = cmd.output().await;
270 }
271}
272
273/// True when `refname` is a valid ref name that exists in `repo`.
274async fn ref_exists(env: &GitEnv, repo: &Path, refname: &str) -> bool {
275 let Ok(cmd) = GitCommand::new(env, "show-ref")
276 .git_dir(repo)
277 .arg("--verify")
278 .arg("--quiet")
279 .user_arg(refname)
280 else {
281 return false;
282 };
283 cmd.output().await.is_ok()
284}
285
286async fn push(
287 env: &GitEnv,
288 repo: &Path,
289 url: &str,
290 auth: Option<&RemoteAuth>,
291 allow_http: bool,
292 pin: Option<&PinnedHost>,
293 local: bool,
294) -> Result<()> {
295 let mut revs = vec![url];
296 revs.extend(MIRROR_REFSPECS);
297 let cmd = base_command(env, Some(repo), "push", auth, allow_http, pin, local)?
298 .arg("--prune")
299 .arg("--force")
300 .user_revs(&revs)?;
301 run_checked(cmd, "push", auth, url).await?;
302 Ok(())
303}
304
305/// Runs the command and returns stdout. A failure carries git's scrubbed stderr.
306async fn run_checked(
307 cmd: GitCommand,
308 what: &str,
309 auth: Option<&RemoteAuth>,
310 url: &str,
311) -> Result<Vec<u8>> {
312 let out = cmd.into_tokio().output().await?;
313 if out.status.success() {
314 return Ok(out.stdout);
315 }
316 let stderr = scrub(&String::from_utf8_lossy(&out.stderr), auth, url);
317 Err(Error::Failed(format!(
318 "git {what} exited with {}: {}",
319 out.status,
320 truncate(stderr.trim())
321 )))
322}
323
324/// Removes credentials from text that may reach an error: the secret and its encoded form, any
325/// `Authorization:` line, and any `user:pass@` in a URL.
326fn scrub(text: &str, auth: Option<&RemoteAuth>, url: &str) -> String {
327 let mut out = text.to_string();
328 if let Some(auth) = auth {
329 let secret = String::from_utf8_lossy(&auth.secret).into_owned();
330 if !secret.is_empty() {
331 out = out.replace(&secret, REDACTED);
332 }
333 let header = auth.header_value();
334 out = out.replace(&header, REDACTED);
335 if let Some(encoded) = header.strip_prefix("Authorization: Basic ") {
336 out = out.replace(encoded, REDACTED);
337 }
338 }
339 out = out
340 .lines()
341 .map(|line| {
342 if line.to_ascii_lowercase().contains("authorization:") {
343 format!("Authorization: {REDACTED}")
344 } else {
345 line.to_string()
346 }
347 })
348 .collect::<Vec<_>>()
349 .join("\n");
350 let mut stripped = strip_userinfo(&out);
351 if url.contains('@') {
352 stripped = stripped.replace(url, REDACTED);
353 }
354 stripped
355}
356
357/// Replaces `user:pass@` after each `://` with `***@`.
358fn strip_userinfo(text: &str) -> String {
359 let mut out = String::with_capacity(text.len());
360 let mut rest = text;
361 while let Some(pos) = rest.find("://") {
362 let (head, tail) = rest.split_at(pos + 3);
363 out.push_str(head);
364 let authority_end = tail
365 .find(|c: char| c == '/' || c.is_whitespace())
366 .unwrap_or(tail.len());
367 let authority = &tail[..authority_end];
368 match authority.rfind('@') {
369 Some(at) => {
370 out.push_str("***");
371 out.push_str(&authority[at..]);
372 }
373 None => out.push_str(authority),
374 }
375 rest = &tail[authority_end..];
376 }
377 out.push_str(rest);
378 out
379}
380
381/// At most [`MAX_STDERR_BYTES`], cut at a character boundary.
382fn truncate(text: &str) -> String {
383 if text.len() <= MAX_STDERR_BYTES {
384 return text.to_string();
385 }
386 let mut end = MAX_STDERR_BYTES;
387 while !text.is_char_boundary(end) {
388 end -= 1;
389 }
390 format!("{}...", &text[..end])
391}
392
393#[cfg(test)]
394mod tests {
395 use super::*;
396
397 fn env(dir: &Path) -> GitEnv {
398 GitEnv {
399 git_bin: "git".into(),
400 data_dir: dir.to_path_buf(),
401 }
402 }
403
404 fn auth() -> RemoteAuth {
405 RemoteAuth {
406 username: "mirror-bot".into(),
407 secret: b"s3cret-token-XYZ".to_vec(),
408 }
409 }
410
411 /// Runs plain git against a git dir for test setup.
412 fn plumbing(git_dir: &Path, args: &[&str]) -> String {
413 let out = std::process::Command::new("git")
414 .arg(format!("--git-dir={}", git_dir.display()))
415 .args(args)
416 .env("GIT_AUTHOR_NAME", "t")
417 .env("GIT_AUTHOR_EMAIL", "t@example.com")
418 .env("GIT_COMMITTER_NAME", "t")
419 .env("GIT_COMMITTER_EMAIL", "t@example.com")
420 .output()
421 .expect("git runs");
422 assert!(out.status.success(), "git {args:?}: {out:?}");
423 String::from_utf8_lossy(&out.stdout).trim().to_string()
424 }
425
426 /// A bare repo whose `main` and tag `v1` point at one empty commit.
427 fn source_repo(dir: &Path) -> std::path::PathBuf {
428 let git_dir = dir.join("source.git");
429 plumbing(dir, &["init", "--bare", "-q", git_dir.to_str().unwrap()]);
430 let tree = plumbing(&git_dir, &["hash-object", "-t", "tree", "-w", "--stdin"]);
431 let commit = plumbing(&git_dir, &["commit-tree", &tree, "-m", "first"]);
432 plumbing(&git_dir, &["update-ref", "refs/heads/main", &commit]);
433 plumbing(&git_dir, &["symbolic-ref", "HEAD", "refs/heads/main"]);
434 plumbing(&git_dir, &["update-ref", "refs/tags/v1", &commit]);
435 git_dir
436 }
437
438 fn file_url(path: &Path) -> String {
439 path.to_str().unwrap().to_string()
440 }
441
442 fn refs(git_dir: &Path) -> String {
443 plumbing(git_dir, &["for-each-ref", "--format=%(refname)"])
444 }
445
446 #[test]
447 fn urls_are_limited_to_https_without_credentials() {
448 assert!(check_url("https://example.com/a.git", false).is_ok());
449 assert!(check_url("http://example.com/a.git", false).is_err());
450 assert!(check_url("http://example.com/a.git", true).is_ok());
451 assert!(check_url("file:///etc/passwd", true).is_err());
452 assert!(check_url("ssh://example.com/a.git", true).is_err());
453 assert!(check_url("ext::sh -c x", true).is_err());
454 assert!(check_url("https://user:pw@example.com/a.git", false).is_err());
455 assert!(check_url("https://example.com/a b.git", false).is_err());
456 }
457
458 #[test]
459 fn credentials_stay_out_of_argv() {
460 let dir = tempfile::tempdir().unwrap();
461 let a = auth();
462 let cmd = base_command(
463 &env(dir.path()),
464 Some(dir.path()),
465 "fetch",
466 Some(&a),
467 false,
468 None,
469 false,
470 )
471 .expect("command builds")
472 .arg("--prune")
473 .user_revs(&["https://example.com/a.git", "+refs/heads/*:refs/heads/*"])
474 .unwrap();
475 let std_cmd = cmd.into_tokio();
476 let std_cmd = std_cmd.as_std();
477 let argv: Vec<String> = std_cmd
478 .get_args()
479 .map(|a| a.to_string_lossy().into_owned())
480 .collect();
481 let joined = argv.join(" ");
482 assert!(!joined.contains("s3cret"), "{joined}");
483 assert!(!joined.contains("Authorization"), "{joined}");
484 assert!(!joined.contains(&STANDARD.encode(b"mirror-bot:s3cret-token-XYZ")));
485 // The header travels in the environment instead.
486 let env_value = std_cmd
487 .get_envs()
488 .find(|(k, _)| *k == "GIT_CONFIG_VALUE_0")
489 .and_then(|(_, v)| v.map(|v| v.to_string_lossy().into_owned()))
490 .expect("header in env");
491 assert_eq!(env_value, a.header_value());
492 assert!(env_value.starts_with("Authorization: Basic "));
493 }
494
495 #[test]
496 fn scrub_removes_secret_header_and_userinfo() {
497 let a = auth();
498 let encoded = STANDARD.encode(b"mirror-bot:s3cret-token-XYZ");
499 let stderr = format!(
500 "fatal: unable to access 'https://mirror-bot:s3cret-token-XYZ@h.example/x.git/': \
501 Authorization: Basic {encoded}\nerror: s3cret-token-XYZ rejected"
502 );
503 let scrubbed = scrub(&stderr, Some(&a), "https://h.example/x.git");
504 assert!(!scrubbed.contains("s3cret"), "{scrubbed}");
505 assert!(!scrubbed.contains(&encoded), "{scrubbed}");
506 assert!(!scrubbed.contains("Basic"), "{scrubbed}");
507 assert!(scrubbed.contains("h.example"), "{scrubbed}");
508 assert!(scrubbed.contains(REDACTED), "{scrubbed}");
509 }
510
511 #[test]
512 fn debug_hides_the_secret() {
513 let shown = format!("{:?}", auth());
514 assert!(!shown.contains("s3cret"), "{shown}");
515 assert!(shown.contains("mirror-bot"), "{shown}");
516 }
517
518 #[test]
519 fn truncation_is_bounded_and_on_a_boundary() {
520 let long = "é".repeat(4000);
521 let t = truncate(&long);
522 assert!(t.len() <= MAX_STDERR_BYTES + 3);
523 assert!(t.ends_with("..."));
524 }
525
526 #[test]
527 fn remote_head_symref_is_parsed() {
528 let listing = "ref: refs/heads/trunk\tHEAD\nabc\tHEAD\nabc\trefs/heads/trunk\n";
529 assert_eq!(
530 remote_default_branch(listing).as_deref(),
531 Some("refs/heads/trunk")
532 );
533 assert_eq!(remote_default_branch("abc\tHEAD\n"), None);
534 }
535
536 #[tokio::test]
537 async fn mirror_fetch_and_push_sync_heads_and_tags_with_prune() {
538 let dir = tempfile::tempdir().unwrap();
539 let source = source_repo(dir.path());
540 let env = env(dir.path());
541 let timeout = Duration::from_secs(60);
542
543 // Pull: fetch the source into an empty bare repo, through the local transport that
544 // only unit tests may use.
545 let pulled = dir.path().join("pulled.git");
546 plumbing(
547 dir.path(),
548 &["init", "--bare", "-q", pulled.to_str().unwrap()],
549 );
550 fetch(&env, &pulled, &file_url(&source), None, false, None, true)
551 .await
552 .unwrap();
553 let fetched = refs(&pulled);
554 assert!(fetched.contains("refs/heads/main"), "{fetched}");
555 assert!(fetched.contains("refs/tags/v1"), "{fetched}");
556 assert_eq!(
557 plumbing(&pulled, &["symbolic-ref", "HEAD"]),
558 "refs/heads/main"
559 );
560
561 // A branch that the remote no longer has is pruned by the next fetch.
562 let head = plumbing(&source, &["rev-parse", "refs/heads/main"]);
563 plumbing(&pulled, &["update-ref", "refs/heads/gone", &head]);
564 plumbing(&source, &["update-ref", "refs/heads/new", &head]);
565 fetch(&env, &pulled, &file_url(&source), None, false, None, true)
566 .await
567 .unwrap();
568 let fetched = refs(&pulled);
569 assert!(fetched.contains("refs/heads/new"), "{fetched}");
570 assert!(!fetched.contains("refs/heads/gone"), "{fetched}");
571
572 // Push: mirror our refs to an empty bare remote, then prune a stale branch there.
573 let remote = dir.path().join("remote.git");
574 plumbing(
575 dir.path(),
576 &["init", "--bare", "-q", remote.to_str().unwrap()],
577 );
578 plumbing(
579 &remote,
580 &[
581 "fetch",
582 "-q",
583 source.to_str().unwrap(),
584 "refs/heads/main:refs/heads/stale",
585 ],
586 );
587 push(&env, &pulled, &file_url(&remote), None, false, None, true)
588 .await
589 .unwrap();
590 let pushed = refs(&remote);
591 assert!(pushed.contains("refs/heads/main"), "{pushed}");
592 assert!(pushed.contains("refs/tags/v1"), "{pushed}");
593 assert!(!pushed.contains("refs/heads/stale"), "{pushed}");
594
595 // The public entry points reject the file transport outright.
596 assert!(
597 mirror_fetch(
598 &env,
599 &pulled,
600 &file_url(&source),
601 None,
602 false,
603 None,
604 timeout
605 )
606 .await
607 .is_err()
608 );
609 assert!(
610 mirror_push(
611 &env,
612 &pulled,
613 &file_url(&remote),
614 None,
615 false,
616 None,
617 timeout
618 )
619 .await
620 .is_err()
621 );
622 }
623
624 #[tokio::test]
625 async fn failure_text_never_carries_the_secret() {
626 let dir = tempfile::tempdir().unwrap();
627 let env = env(dir.path());
628 let pulled = dir.path().join("pulled.git");
629 plumbing(
630 dir.path(),
631 &["init", "--bare", "-q", pulled.to_str().unwrap()],
632 );
633 let a = auth();
634 // Port 9 on loopback refuses the connection, so git fails with its own error text.
635 let url = "https://127.0.0.1:9/x.git";
636 let err = mirror_fetch(
637 &env,
638 &pulled,
639 url,
640 Some(&a),
641 false,
642 None,
643 Duration::from_secs(60),
644 )
645 .await
646 .unwrap_err();
647 let text = err.to_string();
648 assert!(!text.contains("s3cret"), "{text}");
649 assert!(
650 !text.contains(&STANDARD.encode(b"mirror-bot:s3cret-token-XYZ")),
651 "{text}"
652 );
653 }
654
655 fn pin(ip: &str) -> PinnedHost {
656 PinnedHost {
657 host: "pin.invalid".into(),
658 port: 443,
659 ip: ip.parse().expect("ip"),
660 }
661 }
662
663 #[test]
664 fn pinned_config_pair_formats_ipv4_and_ipv6() {
665 let v4 = PinnedHost {
666 host: "example.com".into(),
667 port: 443,
668 ip: "93.184.216.34".parse().expect("ip"),
669 };
670 assert_eq!(
671 v4.config_pair().expect("pair"),
672 "http.curloptResolve=example.com:443:93.184.216.34"
673 );
674 let v6 = PinnedHost {
675 host: "example.com".into(),
676 port: 80,
677 ip: "2001:db8::1".parse().expect("ip"),
678 };
679 assert_eq!(
680 v6.config_pair().expect("pair"),
681 "http.curloptResolve=example.com:80:[2001:db8::1]"
682 );
683 }
684
685 #[test]
686 fn pinned_host_must_be_a_plain_name() {
687 for host in ["", "a b", "[::1]", "x,y", "evil\nname"] {
688 let bad = PinnedHost {
689 host: host.into(),
690 port: 443,
691 ip: "93.184.216.34".parse().expect("ip"),
692 };
693 assert!(bad.config_pair().is_err(), "{host:?}");
694 }
695 }
696
697 #[test]
698 fn pin_becomes_a_checked_config_arg() {
699 let dir = tempfile::tempdir().expect("tempdir");
700 let cmd = base_command(
701 &env(dir.path()),
702 None,
703 "ls-remote",
704 None,
705 false,
706 Some(&pin("127.0.0.1")),
707 false,
708 )
709 .expect("command builds");
710 let std_cmd = cmd.into_tokio();
711 let argv: Vec<String> = std_cmd
712 .as_std()
713 .get_args()
714 .map(|a| a.to_string_lossy().into_owned())
715 .collect();
716 let at = argv
717 .iter()
718 .position(|a| a == "http.curloptResolve=pin.invalid:443:127.0.0.1")
719 .expect("pinned config arg present");
720 assert_eq!(argv[at - 1], "-c", "{argv:?}");
721 }
722
723 #[tokio::test]
724 async fn fetch_connects_to_the_pinned_address() {
725 let dir = tempfile::tempdir().expect("tempdir");
726 let env = env(dir.path());
727 let pulled = dir.path().join("pulled.git");
728 plumbing(
729 dir.path(),
730 &["init", "--bare", "-q", pulled.to_str().expect("utf8 path")],
731 );
732 // The host never resolves, so only the pin can get git past name lookup. Nothing listens
733 // on loopback port 443, so the run fails at connect, not at resolve.
734 let err = mirror_fetch(
735 &env,
736 &pulled,
737 "https://pin.invalid/x.git",
738 None,
739 false,
740 Some(&pin("127.0.0.1")),
741 Duration::from_secs(60),
742 )
743 .await
744 .unwrap_err()
745 .to_string();
746 assert!(!err.contains("Could not resolve host"), "{err}");
747 }
748}