forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.09.7 MiB37e985dTahinli3 hours ago363 commits

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