| 1 | |
| 2 | |
| 3 | use std::{ |
| 4 | ffi::{OsStr, OsString}, |
| 5 | net::IpAddr, |
| 6 | path::{Path, PathBuf}, |
| 7 | process::{Output, Stdio}, |
| 8 | sync::{Arc, Mutex}, |
| 9 | }; |
| 10 | |
| 11 | use tokio::process::Command; |
| 12 | |
| 13 | use crate::{ |
| 14 | application::port::{GitImport, GitImportError}, |
| 15 | domain::{ImportSource, OrgName, RepoName, is_public}, |
| 16 | infrastructure::metrics::metrics, |
| 17 | }; |
| 18 | |
| 19 | use super::{ |
| 20 | count_spawn, git_command, |
| 21 | merge::{CURLOPT_RESOLVE_SINCE, GitFeatures}, |
| 22 | }; |
| 23 | |
| 24 | |
| 25 | |
| 26 | |
| 27 | |
| 28 | |
| 29 | |
| 30 | |
| 31 | |
| 32 | |
| 33 | const IMPORT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(600); |
| 34 | |
| 35 | |
| 36 | |
| 37 | |
| 38 | |
| 39 | |
| 40 | |
| 41 | |
| 42 | const PROXY_VARS: [&str; 6] = [ |
| 43 | "http_proxy", |
| 44 | "HTTP_PROXY", |
| 45 | "https_proxy", |
| 46 | "HTTPS_PROXY", |
| 47 | "all_proxy", |
| 48 | "ALL_PROXY", |
| 49 | ]; |
| 50 | |
| 51 | |
| 52 | |
| 53 | |
| 54 | |
| 55 | |
| 56 | |
| 57 | |
| 58 | |
| 59 | #[derive(Debug, Clone)] |
| 60 | pub struct DiskGitImport { |
| 61 | data_dir: PathBuf, |
| 62 | |
| 63 | |
| 64 | features: GitFeatures, |
| 65 | } |
| 66 | |
| 67 | impl DiskGitImport { |
| 68 | pub fn new(data_dir: impl Into<PathBuf>, features: GitFeatures) -> Self { |
| 69 | Self { |
| 70 | data_dir: data_dir.into(), |
| 71 | features, |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | |
| 76 | fn repo_path(&self, handle: &OrgName, name: &RepoName) -> PathBuf { |
| 77 | self.data_dir |
| 78 | .join(handle.as_str()) |
| 79 | .join(format!("{name}.git")) |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | impl GitImport for DiskGitImport { |
| 84 | async fn mirror( |
| 85 | &self, |
| 86 | handle: &OrgName, |
| 87 | name: &RepoName, |
| 88 | source: &ImportSource, |
| 89 | ) -> Result<(), GitImportError> { |
| 90 | |
| 91 | |
| 92 | |
| 93 | |
| 94 | |
| 95 | |
| 96 | |
| 97 | metrics().record_import_started(); |
| 98 | |
| 99 | let outcome = self.mirror_inner(handle, name, source).await; |
| 100 | |
| 101 | match &outcome { |
| 102 | Ok(()) => metrics().record_import_finished(), |
| 103 | Err(_) => metrics().record_import_failed(), |
| 104 | } |
| 105 | |
| 106 | outcome |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | impl DiskGitImport { |
| 111 | |
| 112 | |
| 113 | async fn mirror_inner( |
| 114 | &self, |
| 115 | handle: &OrgName, |
| 116 | name: &RepoName, |
| 117 | source: &ImportSource, |
| 118 | ) -> Result<(), GitImportError> { |
| 119 | refuse_unpinnable(self.features)?; |
| 120 | |
| 121 | let addresses = resolve_public_host(source.host(), source.port()).await?; |
| 122 | |
| 123 | let path = self.repo_path(handle, name); |
| 124 | |
| 125 | |
| 126 | |
| 127 | |
| 128 | if path.exists() { |
| 129 | return Err(GitImportError::new( |
| 130 | "something is already on disk at this repository's path", |
| 131 | )); |
| 132 | } |
| 133 | |
| 134 | run_import(clone_args(source, &addresses, &path), None).await?; |
| 135 | |
| 136 | finish_mirror(&path).await |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | |
| 141 | |
| 142 | |
| 143 | |
| 144 | |
| 145 | |
| 146 | fn refuse_unpinnable(features: GitFeatures) -> Result<(), GitImportError> { |
| 147 | if features.pinned_resolve { |
| 148 | return Ok(()); |
| 149 | } |
| 150 | |
| 151 | let (major, minor) = CURLOPT_RESOLVE_SINCE; |
| 152 | |
| 153 | Err(GitImportError::new(match features.version_string() { |
| 154 | Some(version) => { |
| 155 | format!("Importing needs git {major}.{minor} or newer; this server has {version}") |
| 156 | } |
| 157 | None => format!( |
| 158 | "Importing needs git {major}.{minor} or newer; this server's git version could \ |
| 159 | not be read" |
| 160 | ), |
| 161 | })) |
| 162 | } |
| 163 | |
| 164 | |
| 165 | |
| 166 | |
| 167 | |
| 168 | fn clone_args(source: &ImportSource, addresses: &[IpAddr], destination: &Path) -> Vec<OsString> { |
| 169 | let mut args: Vec<OsString> = vec![ |
| 170 | |
| 171 | |
| 172 | |
| 173 | |
| 174 | |
| 175 | |
| 176 | "-c".into(), |
| 177 | "http.followRedirects=false".into(), |
| 178 | ]; |
| 179 | |
| 180 | |
| 181 | |
| 182 | |
| 183 | |
| 184 | |
| 185 | |
| 186 | |
| 187 | if source.host().parse::<IpAddr>().is_err() { |
| 188 | args.push("-c".into()); |
| 189 | args.push( |
| 190 | format!( |
| 191 | "http.curloptResolve={}", |
| 192 | pin(source.host(), source.port(), addresses) |
| 193 | ) |
| 194 | .into(), |
| 195 | ); |
| 196 | } |
| 197 | |
| 198 | args.extend([ |
| 199 | |
| 200 | |
| 201 | |
| 202 | |
| 203 | "clone".into(), |
| 204 | "--mirror".into(), |
| 205 | "--quiet".into(), |
| 206 | |
| 207 | |
| 208 | |
| 209 | "--".into(), |
| 210 | source.as_str().into(), |
| 211 | destination.as_os_str().to_owned(), |
| 212 | ]); |
| 213 | |
| 214 | args |
| 215 | } |
| 216 | |
| 217 | |
| 218 | |
| 219 | |
| 220 | |
| 221 | |
| 222 | |
| 223 | |
| 224 | |
| 225 | fn pin(host: &str, port: u16, addrs: &[IpAddr]) -> String { |
| 226 | let addresses = addrs |
| 227 | .iter() |
| 228 | .map(|address| match address { |
| 229 | IpAddr::V4(v4) => v4.to_string(), |
| 230 | IpAddr::V6(v6) => format!("[{v6}]"), |
| 231 | }) |
| 232 | .collect::<Vec<_>>() |
| 233 | .join(","); |
| 234 | |
| 235 | format!("{host}:{port}:{addresses}") |
| 236 | } |
| 237 | |
| 238 | |
| 239 | |
| 240 | |
| 241 | |
| 242 | |
| 243 | async fn finish_mirror(path: &std::path::Path) -> Result<(), GitImportError> { |
| 244 | |
| 245 | |
| 246 | |
| 247 | |
| 248 | run_import( |
| 249 | [ |
| 250 | OsStr::new("remote"), |
| 251 | OsStr::new("remove"), |
| 252 | OsStr::new("origin"), |
| 253 | ], |
| 254 | Some(path), |
| 255 | ) |
| 256 | .await?; |
| 257 | |
| 258 | |
| 259 | |
| 260 | |
| 261 | |
| 262 | |
| 263 | run_import( |
| 264 | [ |
| 265 | OsStr::new("config"), |
| 266 | OsStr::new("core.logAllRefUpdates"), |
| 267 | OsStr::new("true"), |
| 268 | ], |
| 269 | Some(path), |
| 270 | ) |
| 271 | .await?; |
| 272 | |
| 273 | |
| 274 | |
| 275 | |
| 276 | |
| 277 | promote_remote_refs(path).await |
| 278 | } |
| 279 | |
| 280 | |
| 281 | |
| 282 | |
| 283 | |
| 284 | |
| 285 | |
| 286 | |
| 287 | |
| 288 | |
| 289 | async fn promote_remote_refs(path: &std::path::Path) -> Result<(), GitImportError> { |
| 290 | let listed = run_import( |
| 291 | [ |
| 292 | OsStr::new("for-each-ref"), |
| 293 | OsStr::new("--format=%(objectname) %(refname)"), |
| 294 | OsStr::new("refs/remotes/"), |
| 295 | ], |
| 296 | Some(path), |
| 297 | ) |
| 298 | .await?; |
| 299 | |
| 300 | let listed = String::from_utf8_lossy(&listed.stdout); |
| 301 | |
| 302 | for line in listed.lines() { |
| 303 | let Some((id, reference)) = line.trim().split_once(' ') else { |
| 304 | continue; |
| 305 | }; |
| 306 | |
| 307 | |
| 308 | |
| 309 | |
| 310 | if let Some(branch) = reference |
| 311 | .strip_prefix("refs/remotes/origin/") |
| 312 | .filter(|branch| *branch != "HEAD") |
| 313 | { |
| 314 | run_import( |
| 315 | [ |
| 316 | OsStr::new("update-ref"), |
| 317 | OsStr::new(&format!("refs/heads/{branch}")), |
| 318 | OsStr::new(id), |
| 319 | ], |
| 320 | Some(path), |
| 321 | ) |
| 322 | .await?; |
| 323 | } |
| 324 | |
| 325 | run_import( |
| 326 | [ |
| 327 | OsStr::new("update-ref"), |
| 328 | OsStr::new("-d"), |
| 329 | OsStr::new(reference), |
| 330 | ], |
| 331 | Some(path), |
| 332 | ) |
| 333 | .await?; |
| 334 | } |
| 335 | |
| 336 | Ok(()) |
| 337 | } |
| 338 | |
| 339 | |
| 340 | |
| 341 | |
| 342 | |
| 343 | |
| 344 | |
| 345 | |
| 346 | |
| 347 | |
| 348 | |
| 349 | |
| 350 | |
| 351 | |
| 352 | |
| 353 | |
| 354 | async fn resolve_public_host(host: &str, port: u16) -> Result<Vec<IpAddr>, GitImportError> { |
| 355 | let addresses = tokio::net::lookup_host((host, port)) |
| 356 | .await |
| 357 | .map_err(|error| GitImportError::new(format!("could not resolve {host}: {error}")))?; |
| 358 | |
| 359 | let mut checked = Vec::new(); |
| 360 | |
| 361 | for address in addresses { |
| 362 | let ip = address.ip(); |
| 363 | |
| 364 | if !is_public(ip) { |
| 365 | return Err(GitImportError::new(format!( |
| 366 | "{host} resolves to an address that is not on the public internet" |
| 367 | ))); |
| 368 | } |
| 369 | |
| 370 | if !checked.contains(&ip) { |
| 371 | checked.push(ip); |
| 372 | } |
| 373 | } |
| 374 | |
| 375 | if checked.is_empty() { |
| 376 | return Err(GitImportError::new(format!("{host} resolves to nothing"))); |
| 377 | } |
| 378 | |
| 379 | Ok(checked) |
| 380 | } |
| 381 | |
| 382 | |
| 383 | |
| 384 | |
| 385 | |
| 386 | |
| 387 | |
| 388 | async fn run_import<I, S>(args: I, repo: Option<&std::path::Path>) -> Result<Output, GitImportError> |
| 389 | where |
| 390 | I: IntoIterator<Item = S>, |
| 391 | S: AsRef<OsStr>, |
| 392 | { |
| 393 | let mut command = import_command(); |
| 394 | |
| 395 | if let Some(repo) = repo { |
| 396 | command.arg("-C").arg(repo); |
| 397 | } |
| 398 | |
| 399 | command.args(args); |
| 400 | count_spawn(&command); |
| 401 | |
| 402 | let output = match tokio::time::timeout(IMPORT_TIMEOUT, command.output()).await { |
| 403 | Ok(result) => { |
| 404 | result.map_err(|error| GitImportError::new(format!("could not run git: {error}")))? |
| 405 | } |
| 406 | Err(_elapsed) => { |
| 407 | return Err(GitImportError::new(format!( |
| 408 | "the import did not finish within {IMPORT_TIMEOUT:?}" |
| 409 | ))); |
| 410 | } |
| 411 | }; |
| 412 | |
| 413 | if !output.status.success() { |
| 414 | |
| 415 | |
| 416 | let stderr = String::from_utf8_lossy(&output.stderr); |
| 417 | let reason = stderr.lines().rev().find(|line| !line.trim().is_empty()); |
| 418 | |
| 419 | return Err(GitImportError::new(match reason { |
| 420 | Some(reason) => reason.trim().to_owned(), |
| 421 | None => format!("git exited with {}", output.status), |
| 422 | })); |
| 423 | } |
| 424 | |
| 425 | Ok(output) |
| 426 | } |
| 427 | |
| 428 | |
| 429 | |
| 430 | |
| 431 | |
| 432 | fn import_command() -> Command { |
| 433 | let mut command = git_command(); |
| 434 | |
| 435 | |
| 436 | for variable in PROXY_VARS { |
| 437 | command.env_remove(variable); |
| 438 | } |
| 439 | |
| 440 | command |
| 441 | .stdin(Stdio::null()) |
| 442 | |
| 443 | |
| 444 | |
| 445 | .env("GIT_TERMINAL_PROMPT", "0") |
| 446 | |
| 447 | |
| 448 | .kill_on_drop(true); |
| 449 | |
| 450 | command |
| 451 | } |
| 452 | |
| 453 | |
| 454 | |
| 455 | |
| 456 | |
| 457 | |
| 458 | #[derive(Debug, Default, Clone)] |
| 459 | pub struct InMemoryGitImport { |
| 460 | requests: Arc<Mutex<Vec<(String, String, String)>>>, |
| 461 | failure: Option<String>, |
| 462 | } |
| 463 | |
| 464 | impl InMemoryGitImport { |
| 465 | pub fn new() -> Self { |
| 466 | Self::default() |
| 467 | } |
| 468 | |
| 469 | |
| 470 | pub fn failing(reason: impl Into<String>) -> Self { |
| 471 | Self { |
| 472 | requests: Arc::default(), |
| 473 | failure: Some(reason.into()), |
| 474 | } |
| 475 | } |
| 476 | |
| 477 | |
| 478 | pub fn requests(&self) -> Vec<(String, String, String)> { |
| 479 | self.requests.lock().expect("lock poisoned").clone() |
| 480 | } |
| 481 | } |
| 482 | |
| 483 | impl GitImport for InMemoryGitImport { |
| 484 | async fn mirror( |
| 485 | &self, |
| 486 | handle: &OrgName, |
| 487 | name: &RepoName, |
| 488 | source: &ImportSource, |
| 489 | ) -> Result<(), GitImportError> { |
| 490 | self.requests.lock().expect("lock poisoned").push(( |
| 491 | handle.to_string(), |
| 492 | name.to_string(), |
| 493 | source.as_str().to_owned(), |
| 494 | )); |
| 495 | |
| 496 | match &self.failure { |
| 497 | Some(reason) => Err(GitImportError::new(reason.clone())), |
| 498 | None => Ok(()), |
| 499 | } |
| 500 | } |
| 501 | } |
| 502 | |
| 503 | #[cfg(test)] |
| 504 | mod tests { |
| 505 | use tempfile::TempDir; |
| 506 | |
| 507 | use super::*; |
| 508 | use crate::application::port::GitStorage; |
| 509 | use crate::infrastructure::git::fixture::{git_says, handle, repo_name, storage}; |
| 510 | |
| 511 | |
| 512 | |
| 513 | |
| 514 | |
| 515 | fn source_repo() -> (TempDir, PathBuf) { |
| 516 | let dir = TempDir::new().expect("temp dir"); |
| 517 | let path = dir.path().join("source"); |
| 518 | |
| 519 | std::fs::create_dir(&path).expect("create"); |
| 520 | |
| 521 | let run = |args: &[&str]| { |
| 522 | let output = std::process::Command::new("git") |
| 523 | .arg("-C") |
| 524 | .arg(&path) |
| 525 | .args(args) |
| 526 | .env("GIT_CONFIG_GLOBAL", "/dev/null") |
| 527 | .env("GIT_CONFIG_SYSTEM", "/dev/null") |
| 528 | .env("GIT_AUTHOR_NAME", "Ada") |
| 529 | .env("GIT_AUTHOR_EMAIL", "ada@example.com") |
| 530 | .env("GIT_COMMITTER_NAME", "Ada") |
| 531 | .env("GIT_COMMITTER_EMAIL", "ada@example.com") |
| 532 | .output() |
| 533 | .expect("git should be on PATH"); |
| 534 | assert!( |
| 535 | output.status.success(), |
| 536 | "git {args:?} failed: {}", |
| 537 | String::from_utf8_lossy(&output.stderr) |
| 538 | ); |
| 539 | }; |
| 540 | |
| 541 | run(&["init", "--quiet", "--initial-branch=main"]); |
| 542 | std::fs::write(path.join("README.md"), "# source\n").expect("write"); |
| 543 | run(&["add", "README.md"]); |
| 544 | run(&["commit", "--quiet", "-m", "first"]); |
| 545 | run(&["tag", "-a", "v0.1.0", "-m", "first"]); |
| 546 | run(&["checkout", "--quiet", "-b", "side"]); |
| 547 | std::fs::write(path.join("more.md"), "more\n").expect("write"); |
| 548 | run(&["add", "more.md"]); |
| 549 | run(&["commit", "--quiet", "-m", "second"]); |
| 550 | run(&["checkout", "--quiet", "main"]); |
| 551 | |
| 552 | (dir, path) |
| 553 | } |
| 554 | |
| 555 | |
| 556 | |
| 557 | |
| 558 | |
| 559 | |
| 560 | |
| 561 | #[tokio::test] |
| 562 | async fn a_mirror_lands_as_an_ordinary_bare_repository() { |
| 563 | let (_source_dir, source) = source_repo(); |
| 564 | let (dest_dir, _storage) = storage(); |
| 565 | let destination = dest_dir.path().join("mirrored.git"); |
| 566 | |
| 567 | run_import( |
| 568 | [ |
| 569 | OsStr::new("clone"), |
| 570 | OsStr::new("--mirror"), |
| 571 | OsStr::new("--quiet"), |
| 572 | OsStr::new("--"), |
| 573 | source.as_os_str(), |
| 574 | destination.as_os_str(), |
| 575 | ], |
| 576 | None, |
| 577 | ) |
| 578 | .await |
| 579 | .expect("the clone should succeed"); |
| 580 | |
| 581 | finish_mirror(&destination) |
| 582 | .await |
| 583 | .expect("the mirror should finish"); |
| 584 | |
| 585 | |
| 586 | let branches = git_says( |
| 587 | &destination, |
| 588 | &["for-each-ref", "--format=%(refname)", "refs/heads/"], |
| 589 | ); |
| 590 | assert_eq!(branches, "refs/heads/main\nrefs/heads/side"); |
| 591 | |
| 592 | |
| 593 | assert_eq!( |
| 594 | git_says( |
| 595 | &destination, |
| 596 | &["for-each-ref", "--format=%(refname)", "refs/tags/"] |
| 597 | ), |
| 598 | "refs/tags/v0.1.0" |
| 599 | ); |
| 600 | |
| 601 | |
| 602 | assert_eq!( |
| 603 | git_says( |
| 604 | &destination, |
| 605 | &["for-each-ref", "--format=%(refname)", "refs/remotes/"] |
| 606 | ), |
| 607 | "" |
| 608 | ); |
| 609 | assert_eq!(git_says(&destination, &["remote"]), ""); |
| 610 | |
| 611 | |
| 612 | assert_eq!( |
| 613 | git_says(&destination, &["symbolic-ref", "HEAD"]), |
| 614 | "refs/heads/main" |
| 615 | ); |
| 616 | assert_eq!( |
| 617 | git_says(&destination, &["rev-parse", "--is-bare-repository"]), |
| 618 | "true" |
| 619 | ); |
| 620 | |
| 621 | |
| 622 | |
| 623 | |
| 624 | assert_eq!( |
| 625 | git_says(&destination, &["config", "--get", "core.logAllRefUpdates"]), |
| 626 | "true" |
| 627 | ); |
| 628 | } |
| 629 | |
| 630 | |
| 631 | |
| 632 | #[tokio::test] |
| 633 | async fn branches_left_under_refs_remotes_are_moved_to_refs_heads() { |
| 634 | let (_source_dir, source) = source_repo(); |
| 635 | let (dest_dir, _storage) = storage(); |
| 636 | let destination = dest_dir.path().join("remotes.git"); |
| 637 | |
| 638 | |
| 639 | |
| 640 | run_import( |
| 641 | [ |
| 642 | OsStr::new("clone"), |
| 643 | OsStr::new("--bare"), |
| 644 | OsStr::new("--quiet"), |
| 645 | OsStr::new("--"), |
| 646 | source.as_os_str(), |
| 647 | destination.as_os_str(), |
| 648 | ], |
| 649 | None, |
| 650 | ) |
| 651 | .await |
| 652 | .expect("clone"); |
| 653 | |
| 654 | |
| 655 | run_import( |
| 656 | [ |
| 657 | OsStr::new("update-ref"), |
| 658 | OsStr::new("refs/remotes/origin/side"), |
| 659 | OsStr::new("refs/heads/main"), |
| 660 | ], |
| 661 | Some(&destination), |
| 662 | ) |
| 663 | .await |
| 664 | .expect("stage a remote-tracking ref"); |
| 665 | run_import( |
| 666 | [ |
| 667 | OsStr::new("symbolic-ref"), |
| 668 | OsStr::new("refs/remotes/origin/HEAD"), |
| 669 | OsStr::new("refs/remotes/origin/side"), |
| 670 | ], |
| 671 | Some(&destination), |
| 672 | ) |
| 673 | .await |
| 674 | .expect("stage origin/HEAD"); |
| 675 | |
| 676 | finish_mirror(&destination).await.expect("finish"); |
| 677 | |
| 678 | let branches = git_says( |
| 679 | &destination, |
| 680 | &["for-each-ref", "--format=%(refname)", "refs/heads/"], |
| 681 | ); |
| 682 | assert!( |
| 683 | branches.contains("refs/heads/side"), |
| 684 | "expected the remote-tracking branch to become a branch, got {branches:?}" |
| 685 | ); |
| 686 | assert_eq!( |
| 687 | git_says( |
| 688 | &destination, |
| 689 | &["for-each-ref", "--format=%(refname)", "refs/remotes/"] |
| 690 | ), |
| 691 | "", |
| 692 | "origin/HEAD is a pointer, not a branch, and must not survive either" |
| 693 | ); |
| 694 | } |
| 695 | |
| 696 | |
| 697 | |
| 698 | #[tokio::test] |
| 699 | async fn a_host_that_resolves_to_loopback_is_refused() { |
| 700 | let error = resolve_public_host("localhost", 443) |
| 701 | .await |
| 702 | .expect_err("localhost must never be dialled"); |
| 703 | |
| 704 | assert!( |
| 705 | error.message().contains("not on the public internet"), |
| 706 | "{error}" |
| 707 | ); |
| 708 | } |
| 709 | |
| 710 | #[tokio::test] |
| 711 | async fn a_host_that_does_not_resolve_is_a_failed_import_not_a_panic() { |
| 712 | let error = resolve_public_host("no-such-host.invalid", 443) |
| 713 | .await |
| 714 | .expect_err("`.invalid` never resolves"); |
| 715 | |
| 716 | assert!(error.message().contains("no-such-host.invalid"), "{error}"); |
| 717 | } |
| 718 | |
| 719 | #[tokio::test] |
| 720 | async fn the_addresses_checked_are_the_addresses_returned() { |
| 721 | |
| 722 | |
| 723 | assert_eq!( |
| 724 | resolve_public_host("93.184.216.34", 443) |
| 725 | .await |
| 726 | .expect("a public address"), |
| 727 | vec!["93.184.216.34".parse::<IpAddr>().expect("an address")] |
| 728 | ); |
| 729 | } |
| 730 | |
| 731 | #[test] |
| 732 | fn a_pin_names_the_host_the_port_and_every_address() { |
| 733 | let v4: IpAddr = "93.184.216.34".parse().expect("v4"); |
| 734 | let v6: IpAddr = "2606:2800:220:1:248:1893:25c8:1946".parse().expect("v6"); |
| 735 | |
| 736 | assert_eq!( |
| 737 | pin("example.com", 443, &[v4]), |
| 738 | "example.com:443:93.184.216.34" |
| 739 | ); |
| 740 | assert_eq!( |
| 741 | pin("git.example.com", 8443, &[v4, v6]), |
| 742 | "git.example.com:8443:93.184.216.34,[2606:2800:220:1:248:1893:25c8:1946]" |
| 743 | ); |
| 744 | } |
| 745 | |
| 746 | #[test] |
| 747 | fn the_clone_is_pinned_to_the_checked_addresses_on_the_urls_port() { |
| 748 | let source = ImportSource::new("https://git.example.com:8443/thing.git").expect("valid"); |
| 749 | let address: IpAddr = "93.184.216.34".parse().expect("v4"); |
| 750 | |
| 751 | let args = clone_args(&source, &[address], Path::new("/data/acme/thing.git")); |
| 752 | let args: Vec<_> = args.iter().map(|arg| arg.to_string_lossy()).collect(); |
| 753 | |
| 754 | |
| 755 | let clone = args.iter().position(|arg| arg == "clone").expect("clone"); |
| 756 | let pinned = args |
| 757 | .iter() |
| 758 | .position(|arg| arg == "http.curloptResolve=git.example.com:8443:93.184.216.34") |
| 759 | .expect("the pin"); |
| 760 | |
| 761 | assert_eq!(args[pinned - 1], "-c"); |
| 762 | assert!(pinned < clone, "{args:?}"); |
| 763 | } |
| 764 | |
| 765 | #[test] |
| 766 | fn a_literal_address_is_not_pinned() { |
| 767 | let source = ImportSource::new("https://[2606:4700::1111]/thing.git").expect("valid"); |
| 768 | let address: IpAddr = "2606:4700::1111".parse().expect("v6"); |
| 769 | |
| 770 | let args = clone_args(&source, &[address], Path::new("/data/acme/thing.git")); |
| 771 | |
| 772 | assert!( |
| 773 | !args |
| 774 | .iter() |
| 775 | .any(|arg| arg.to_string_lossy().starts_with("http.curloptResolve")), |
| 776 | "{args:?}" |
| 777 | ); |
| 778 | } |
| 779 | |
| 780 | |
| 781 | |
| 782 | |
| 783 | |
| 784 | |
| 785 | |
| 786 | |
| 787 | #[tokio::test] |
| 788 | async fn git_connects_to_the_pinned_address() { |
| 789 | let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind loopback"); |
| 790 | listener.set_nonblocking(true).expect("nonblocking"); |
| 791 | let port = listener.local_addr().expect("local address").port(); |
| 792 | |
| 793 | let received = std::thread::spawn(move || { |
| 794 | use std::io::{Read, Write}; |
| 795 | |
| 796 | let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20); |
| 797 | |
| 798 | let mut stream = loop { |
| 799 | match listener.accept() { |
| 800 | Ok((stream, _)) => break stream, |
| 801 | Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => { |
| 802 | if std::time::Instant::now() > deadline { |
| 803 | return String::new(); |
| 804 | } |
| 805 | std::thread::sleep(std::time::Duration::from_millis(10)); |
| 806 | } |
| 807 | Err(error) => panic!("accept failed: {error}"), |
| 808 | } |
| 809 | }; |
| 810 | |
| 811 | stream.set_nonblocking(false).expect("blocking"); |
| 812 | stream |
| 813 | .set_read_timeout(Some(std::time::Duration::from_secs(5))) |
| 814 | .expect("timeout"); |
| 815 | |
| 816 | let mut head = Vec::new(); |
| 817 | let mut buffer = [0u8; 1024]; |
| 818 | |
| 819 | while !head.windows(4).any(|window| window == b"\r\n\r\n") { |
| 820 | let read = stream.read(&mut buffer).expect("read the request"); |
| 821 | if read == 0 { |
| 822 | break; |
| 823 | } |
| 824 | head.extend_from_slice(&buffer[..read]); |
| 825 | } |
| 826 | |
| 827 | |
| 828 | stream |
| 829 | .write_all( |
| 830 | b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", |
| 831 | ) |
| 832 | .expect("answer"); |
| 833 | |
| 834 | String::from_utf8_lossy(&head).into_owned() |
| 835 | }); |
| 836 | |
| 837 | let loopback: IpAddr = "127.0.0.1".parse().expect("v4"); |
| 838 | |
| 839 | |
| 840 | let _ = run_import( |
| 841 | [ |
| 842 | "-c".to_owned(), |
| 843 | format!( |
| 844 | "http.curloptResolve={}", |
| 845 | pin("pinned.invalid", port, &[loopback]) |
| 846 | ), |
| 847 | "ls-remote".to_owned(), |
| 848 | "--".to_owned(), |
| 849 | format!("http://pinned.invalid:{port}/thing.git"), |
| 850 | ], |
| 851 | None, |
| 852 | ) |
| 853 | .await; |
| 854 | |
| 855 | let head = received.join().expect("the listener thread"); |
| 856 | |
| 857 | assert!( |
| 858 | head.starts_with("GET /thing.git/info/refs"), |
| 859 | "nothing reached the pinned address — is this git older than 2.37? got {head:?}" |
| 860 | ); |
| 861 | assert!( |
| 862 | head.contains(&format!("\r\nHost: pinned.invalid:{port}\r\n")), |
| 863 | "{head:?}" |
| 864 | ); |
| 865 | } |
| 866 | |
| 867 | #[test] |
| 868 | fn an_imports_git_takes_no_proxy_from_the_environment() { |
| 869 | let command = import_command(); |
| 870 | let removed: Vec<_> = command |
| 871 | .as_std() |
| 872 | .get_envs() |
| 873 | .filter(|(_, value)| value.is_none()) |
| 874 | .map(|(name, _)| name.to_string_lossy().into_owned()) |
| 875 | .collect(); |
| 876 | |
| 877 | for variable in PROXY_VARS { |
| 878 | assert!( |
| 879 | removed.iter().any(|name| name == variable), |
| 880 | "{variable} must be removed, removed: {removed:?}" |
| 881 | ); |
| 882 | } |
| 883 | } |
| 884 | |
| 885 | |
| 886 | #[tokio::test] |
| 887 | async fn a_failed_git_command_carries_gits_own_last_word() { |
| 888 | let (dir, _storage) = storage(); |
| 889 | |
| 890 | let error = run_import( |
| 891 | [OsStr::new("rev-parse"), OsStr::new("HEAD")], |
| 892 | Some(dir.path()), |
| 893 | ) |
| 894 | .await |
| 895 | .expect_err("an empty directory is not a repository"); |
| 896 | |
| 897 | assert!( |
| 898 | error.message().contains("not a git repository"), |
| 899 | "expected git's own words, got {error}" |
| 900 | ); |
| 901 | } |
| 902 | |
| 903 | #[tokio::test] |
| 904 | async fn an_import_refuses_a_path_that_is_already_occupied() { |
| 905 | let (dir, storage) = storage(); |
| 906 | let importer = DiskGitImport::new(dir.path(), able_to_pin()); |
| 907 | |
| 908 | storage |
| 909 | .init_bare(&handle(), &repo_name("taken")) |
| 910 | .await |
| 911 | .expect("seed"); |
| 912 | |
| 913 | let error = importer |
| 914 | .mirror( |
| 915 | &handle(), |
| 916 | &repo_name("taken"), |
| 917 | &ImportSource::new("https://example.com/taken.git").expect("valid"), |
| 918 | ) |
| 919 | .await |
| 920 | .expect_err("must not adopt what is already there"); |
| 921 | |
| 922 | assert!(error.message().contains("already on disk"), "{error}"); |
| 923 | } |
| 924 | |
| 925 | |
| 926 | fn able_to_pin() -> GitFeatures { |
| 927 | GitFeatures { |
| 928 | pinned_resolve: true, |
| 929 | ..GitFeatures::default() |
| 930 | } |
| 931 | } |
| 932 | |
| 933 | #[tokio::test] |
| 934 | async fn an_import_on_a_git_too_old_to_pin_is_refused_and_says_why() { |
| 935 | let (dir, _storage) = storage(); |
| 936 | |
| 937 | |
| 938 | let importer = DiskGitImport::new(dir.path(), GitFeatures::of_version(Some((2, 34)))); |
| 939 | |
| 940 | let error = importer |
| 941 | .mirror( |
| 942 | &handle(), |
| 943 | &repo_name("thing"), |
| 944 | &ImportSource::new("https://example.com/thing.git").expect("valid"), |
| 945 | ) |
| 946 | .await |
| 947 | .expect_err("an unpinned clone is the hole this closes"); |
| 948 | |
| 949 | assert_eq!( |
| 950 | error.message(), |
| 951 | "Importing needs git 2.37 or newer; this server has 2.34" |
| 952 | ); |
| 953 | assert!( |
| 954 | !dir.path().join("jamesgill").join("thing.git").exists(), |
| 955 | "nothing may be cloned" |
| 956 | ); |
| 957 | } |
| 958 | |
| 959 | #[test] |
| 960 | fn a_git_whose_version_could_not_be_read_is_refused_too() { |
| 961 | let error = refuse_unpinnable(GitFeatures::default()).expect_err("cannot pin"); |
| 962 | |
| 963 | assert_eq!( |
| 964 | error.message(), |
| 965 | "Importing needs git 2.37 or newer; this server's git version could not be read" |
| 966 | ); |
| 967 | assert!(refuse_unpinnable(GitFeatures::of_version(Some((2, 37)))).is_ok()); |
| 968 | } |
| 969 | |
| 970 | #[tokio::test] |
| 971 | async fn the_in_memory_importer_records_what_it_was_asked_for() { |
| 972 | let importer = InMemoryGitImport::new(); |
| 973 | let source = ImportSource::new("https://example.com/thing.git").expect("valid"); |
| 974 | |
| 975 | importer |
| 976 | .mirror(&handle(), &repo_name("thing"), &source) |
| 977 | .await |
| 978 | .expect("succeeds"); |
| 979 | |
| 980 | assert_eq!( |
| 981 | importer.requests(), |
| 982 | vec![( |
| 983 | "jamesgill".to_owned(), |
| 984 | "thing".to_owned(), |
| 985 | "https://example.com/thing.git".to_owned() |
| 986 | )] |
| 987 | ); |
| 988 | } |
| 989 | } |