| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | use std::fmt; |
| 10 | use std::future::Future; |
| 11 | use std::net::IpAddr; |
| 12 | use std::path::Path; |
| 13 | use std::time::Duration; |
| 14 | |
| 15 | use base64::Engine; |
| 16 | use base64::engine::general_purpose::STANDARD; |
| 17 | |
| 18 | use crate::command::{GitCommand, GitEnv}; |
| 19 | use crate::error::{Error, Result}; |
| 20 | |
| 21 | |
| 22 | pub const MIRROR_REFSPECS: [&str; 2] = ["+refs/heads/*:refs/heads/*", "+refs/tags/*:refs/tags/*"]; |
| 23 | |
| 24 | |
| 25 | const MAX_STDERR_BYTES: usize = 2 * 1024; |
| 26 | const REDACTED: &str = "[redacted]"; |
| 27 | |
| 28 | |
| 29 | |
| 30 | #[derive(Clone, PartialEq, Eq)] |
| 31 | pub struct RemoteAuth { |
| 32 | pub username: String, |
| 33 | pub secret: Vec<u8>, |
| 34 | } |
| 35 | |
| 36 | impl 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 | |
| 46 | |
| 47 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 48 | pub struct PinnedHost { |
| 49 | pub host: String, |
| 50 | pub port: u16, |
| 51 | pub ip: IpAddr, |
| 52 | } |
| 53 | |
| 54 | impl PinnedHost { |
| 55 | |
| 56 | |
| 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 | |
| 79 | impl RemoteAuth { |
| 80 | |
| 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 | |
| 90 | |
| 91 | |
| 92 | pub 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 | |
| 106 | |
| 107 | |
| 108 | #[doc(hidden)] |
| 109 | pub 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 | |
| 119 | |
| 120 | pub 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 | |
| 134 | |
| 135 | fn 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 | |
| 159 | async 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 | |
| 170 | |
| 171 | fn 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 | |
| 206 | async 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 listing = run_checked(head, "ls-remote", auth, url).await?; |
| 227 | let listing = String::from_utf8_lossy(&listing); |
| 228 | let Some(default_ref) = remote_default_branch(&listing) else { |
| 229 | return Ok(()); |
| 230 | }; |
| 231 | point_head_at_default(env, repo, &default_ref).await; |
| 232 | Ok(()) |
| 233 | } |
| 234 | |
| 235 | |
| 236 | fn remote_default_branch(listing: &str) -> Option<String> { |
| 237 | listing.lines().find_map(|line| { |
| 238 | let (target, name) = line.strip_prefix("ref: ")?.split_once('\t')?; |
| 239 | (name == "HEAD" && target.starts_with("refs/heads/")).then(|| target.to_string()) |
| 240 | }) |
| 241 | } |
| 242 | |
| 243 | |
| 244 | |
| 245 | async fn point_head_at_default(env: &GitEnv, repo: &Path, default_ref: &str) { |
| 246 | let current = GitCommand::new(env, "symbolic-ref") |
| 247 | .git_dir(repo) |
| 248 | .arg("-q") |
| 249 | .arg("HEAD") |
| 250 | .output() |
| 251 | .await |
| 252 | .ok() |
| 253 | .map(|out| String::from_utf8_lossy(&out).trim().to_string()); |
| 254 | if let Some(current) = current |
| 255 | && ref_exists(env, repo, ¤t).await |
| 256 | { |
| 257 | return; |
| 258 | } |
| 259 | if !ref_exists(env, repo, default_ref).await { |
| 260 | return; |
| 261 | } |
| 262 | let set = GitCommand::new(env, "symbolic-ref") |
| 263 | .git_dir(repo) |
| 264 | .arg("HEAD") |
| 265 | .user_arg(default_ref); |
| 266 | if let Ok(cmd) = set { |
| 267 | let _ = cmd.output().await; |
| 268 | } |
| 269 | } |
| 270 | |
| 271 | |
| 272 | async fn ref_exists(env: &GitEnv, repo: &Path, refname: &str) -> bool { |
| 273 | let Ok(cmd) = GitCommand::new(env, "show-ref") |
| 274 | .git_dir(repo) |
| 275 | .arg("--verify") |
| 276 | .arg("--quiet") |
| 277 | .user_arg(refname) |
| 278 | else { |
| 279 | return false; |
| 280 | }; |
| 281 | cmd.output().await.is_ok() |
| 282 | } |
| 283 | |
| 284 | async fn push( |
| 285 | env: &GitEnv, |
| 286 | repo: &Path, |
| 287 | url: &str, |
| 288 | auth: Option<&RemoteAuth>, |
| 289 | allow_http: bool, |
| 290 | pin: Option<&PinnedHost>, |
| 291 | local: bool, |
| 292 | ) -> Result<()> { |
| 293 | let mut revs = vec![url]; |
| 294 | revs.extend(MIRROR_REFSPECS); |
| 295 | let cmd = base_command(env, Some(repo), "push", auth, allow_http, pin, local)? |
| 296 | .arg("--prune") |
| 297 | .arg("--force") |
| 298 | .user_revs(&revs)?; |
| 299 | run_checked(cmd, "push", auth, url).await?; |
| 300 | Ok(()) |
| 301 | } |
| 302 | |
| 303 | |
| 304 | async fn run_checked( |
| 305 | cmd: GitCommand, |
| 306 | what: &str, |
| 307 | auth: Option<&RemoteAuth>, |
| 308 | url: &str, |
| 309 | ) -> Result<Vec<u8>> { |
| 310 | let out = cmd.into_tokio().output().await?; |
| 311 | if out.status.success() { |
| 312 | return Ok(out.stdout); |
| 313 | } |
| 314 | let stderr = scrub(&String::from_utf8_lossy(&out.stderr), auth, url); |
| 315 | Err(Error::Failed(format!( |
| 316 | "git {what} exited with {}: {}", |
| 317 | out.status, |
| 318 | truncate(stderr.trim()) |
| 319 | ))) |
| 320 | } |
| 321 | |
| 322 | |
| 323 | |
| 324 | fn scrub(text: &str, auth: Option<&RemoteAuth>, url: &str) -> String { |
| 325 | let mut out = text.to_string(); |
| 326 | if let Some(auth) = auth { |
| 327 | let secret = String::from_utf8_lossy(&auth.secret).into_owned(); |
| 328 | if !secret.is_empty() { |
| 329 | out = out.replace(&secret, REDACTED); |
| 330 | } |
| 331 | let header = auth.header_value(); |
| 332 | out = out.replace(&header, REDACTED); |
| 333 | if let Some(encoded) = header.strip_prefix("Authorization: Basic ") { |
| 334 | out = out.replace(encoded, REDACTED); |
| 335 | } |
| 336 | } |
| 337 | out = out |
| 338 | .lines() |
| 339 | .map(|line| { |
| 340 | if line.to_ascii_lowercase().contains("authorization:") { |
| 341 | format!("Authorization: {REDACTED}") |
| 342 | } else { |
| 343 | line.to_string() |
| 344 | } |
| 345 | }) |
| 346 | .collect::<Vec<_>>() |
| 347 | .join("\n"); |
| 348 | let mut stripped = strip_userinfo(&out); |
| 349 | if url.contains('@') { |
| 350 | stripped = stripped.replace(url, REDACTED); |
| 351 | } |
| 352 | stripped |
| 353 | } |
| 354 | |
| 355 | |
| 356 | fn strip_userinfo(text: &str) -> String { |
| 357 | let mut out = String::with_capacity(text.len()); |
| 358 | let mut rest = text; |
| 359 | while let Some(pos) = rest.find("://") { |
| 360 | let (head, tail) = rest.split_at(pos + 3); |
| 361 | out.push_str(head); |
| 362 | let authority_end = tail |
| 363 | .find(|c: char| c == '/' || c.is_whitespace()) |
| 364 | .unwrap_or(tail.len()); |
| 365 | let authority = &tail[..authority_end]; |
| 366 | match authority.rfind('@') { |
| 367 | Some(at) => { |
| 368 | out.push_str("***"); |
| 369 | out.push_str(&authority[at..]); |
| 370 | } |
| 371 | None => out.push_str(authority), |
| 372 | } |
| 373 | rest = &tail[authority_end..]; |
| 374 | } |
| 375 | out.push_str(rest); |
| 376 | out |
| 377 | } |
| 378 | |
| 379 | |
| 380 | fn truncate(text: &str) -> String { |
| 381 | if text.len() <= MAX_STDERR_BYTES { |
| 382 | return text.to_string(); |
| 383 | } |
| 384 | let mut end = MAX_STDERR_BYTES; |
| 385 | while !text.is_char_boundary(end) { |
| 386 | end -= 1; |
| 387 | } |
| 388 | format!("{}...", &text[..end]) |
| 389 | } |
| 390 | |
| 391 | #[cfg(test)] |
| 392 | mod tests { |
| 393 | use super::*; |
| 394 | |
| 395 | fn env(dir: &Path) -> GitEnv { |
| 396 | GitEnv { |
| 397 | git_bin: "git".into(), |
| 398 | data_dir: dir.to_path_buf(), |
| 399 | } |
| 400 | } |
| 401 | |
| 402 | fn auth() -> RemoteAuth { |
| 403 | RemoteAuth { |
| 404 | username: "mirror-bot".into(), |
| 405 | secret: b"s3cret-token-XYZ".to_vec(), |
| 406 | } |
| 407 | } |
| 408 | |
| 409 | |
| 410 | fn plumbing(git_dir: &Path, args: &[&str]) -> String { |
| 411 | let out = std::process::Command::new("git") |
| 412 | .arg(format!("--git-dir={}", git_dir.display())) |
| 413 | .args(args) |
| 414 | .env("GIT_AUTHOR_NAME", "t") |
| 415 | .env("GIT_AUTHOR_EMAIL", "t@example.com") |
| 416 | .env("GIT_COMMITTER_NAME", "t") |
| 417 | .env("GIT_COMMITTER_EMAIL", "t@example.com") |
| 418 | .output() |
| 419 | .expect("git runs"); |
| 420 | assert!(out.status.success(), "git {args:?}: {out:?}"); |
| 421 | String::from_utf8_lossy(&out.stdout).trim().to_string() |
| 422 | } |
| 423 | |
| 424 | |
| 425 | fn source_repo(dir: &Path) -> std::path::PathBuf { |
| 426 | let git_dir = dir.join("source.git"); |
| 427 | plumbing(dir, &["init", "--bare", "-q", git_dir.to_str().unwrap()]); |
| 428 | let tree = plumbing(&git_dir, &["hash-object", "-t", "tree", "-w", "--stdin"]); |
| 429 | let commit = plumbing(&git_dir, &["commit-tree", &tree, "-m", "first"]); |
| 430 | plumbing(&git_dir, &["update-ref", "refs/heads/main", &commit]); |
| 431 | plumbing(&git_dir, &["symbolic-ref", "HEAD", "refs/heads/main"]); |
| 432 | plumbing(&git_dir, &["update-ref", "refs/tags/v1", &commit]); |
| 433 | git_dir |
| 434 | } |
| 435 | |
| 436 | fn file_url(path: &Path) -> String { |
| 437 | path.to_str().unwrap().to_string() |
| 438 | } |
| 439 | |
| 440 | fn refs(git_dir: &Path) -> String { |
| 441 | plumbing(git_dir, &["for-each-ref", "--format=%(refname)"]) |
| 442 | } |
| 443 | |
| 444 | #[test] |
| 445 | fn urls_are_limited_to_https_without_credentials() { |
| 446 | assert!(check_url("https://example.com/a.git", false).is_ok()); |
| 447 | assert!(check_url("http://example.com/a.git", false).is_err()); |
| 448 | assert!(check_url("http://example.com/a.git", true).is_ok()); |
| 449 | assert!(check_url("file:///etc/passwd", true).is_err()); |
| 450 | assert!(check_url("ssh://example.com/a.git", true).is_err()); |
| 451 | assert!(check_url("ext::sh -c x", true).is_err()); |
| 452 | assert!(check_url("https://user:pw@example.com/a.git", false).is_err()); |
| 453 | assert!(check_url("https://example.com/a b.git", false).is_err()); |
| 454 | } |
| 455 | |
| 456 | #[test] |
| 457 | fn credentials_stay_out_of_argv() { |
| 458 | let dir = tempfile::tempdir().unwrap(); |
| 459 | let a = auth(); |
| 460 | let cmd = base_command( |
| 461 | &env(dir.path()), |
| 462 | Some(dir.path()), |
| 463 | "fetch", |
| 464 | Some(&a), |
| 465 | false, |
| 466 | None, |
| 467 | false, |
| 468 | ) |
| 469 | .expect("command builds") |
| 470 | .arg("--prune") |
| 471 | .user_revs(&["https://example.com/a.git", "+refs/heads/*:refs/heads/*"]) |
| 472 | .unwrap(); |
| 473 | let std_cmd = cmd.into_tokio(); |
| 474 | let std_cmd = std_cmd.as_std(); |
| 475 | let argv: Vec<String> = std_cmd |
| 476 | .get_args() |
| 477 | .map(|a| a.to_string_lossy().into_owned()) |
| 478 | .collect(); |
| 479 | let joined = argv.join(" "); |
| 480 | assert!(!joined.contains("s3cret"), "{joined}"); |
| 481 | assert!(!joined.contains("Authorization"), "{joined}"); |
| 482 | assert!(!joined.contains(&STANDARD.encode(b"mirror-bot:s3cret-token-XYZ"))); |
| 483 | |
| 484 | let env_value = std_cmd |
| 485 | .get_envs() |
| 486 | .find(|(k, _)| *k == "GIT_CONFIG_VALUE_0") |
| 487 | .and_then(|(_, v)| v.map(|v| v.to_string_lossy().into_owned())) |
| 488 | .expect("header in env"); |
| 489 | assert_eq!(env_value, a.header_value()); |
| 490 | assert!(env_value.starts_with("Authorization: Basic ")); |
| 491 | } |
| 492 | |
| 493 | #[test] |
| 494 | fn scrub_removes_secret_header_and_userinfo() { |
| 495 | let a = auth(); |
| 496 | let encoded = STANDARD.encode(b"mirror-bot:s3cret-token-XYZ"); |
| 497 | let stderr = format!( |
| 498 | "fatal: unable to access 'https://mirror-bot:s3cret-token-XYZ@h.example/x.git/': \ |
| 499 | Authorization: Basic {encoded}\nerror: s3cret-token-XYZ rejected" |
| 500 | ); |
| 501 | let scrubbed = scrub(&stderr, Some(&a), "https://h.example/x.git"); |
| 502 | assert!(!scrubbed.contains("s3cret"), "{scrubbed}"); |
| 503 | assert!(!scrubbed.contains(&encoded), "{scrubbed}"); |
| 504 | assert!(!scrubbed.contains("Basic"), "{scrubbed}"); |
| 505 | assert!(scrubbed.contains("h.example"), "{scrubbed}"); |
| 506 | assert!(scrubbed.contains(REDACTED), "{scrubbed}"); |
| 507 | } |
| 508 | |
| 509 | #[test] |
| 510 | fn debug_hides_the_secret() { |
| 511 | let shown = format!("{:?}", auth()); |
| 512 | assert!(!shown.contains("s3cret"), "{shown}"); |
| 513 | assert!(shown.contains("mirror-bot"), "{shown}"); |
| 514 | } |
| 515 | |
| 516 | #[test] |
| 517 | fn truncation_is_bounded_and_on_a_boundary() { |
| 518 | let long = "é".repeat(4000); |
| 519 | let t = truncate(&long); |
| 520 | assert!(t.len() <= MAX_STDERR_BYTES + 3); |
| 521 | assert!(t.ends_with("...")); |
| 522 | } |
| 523 | |
| 524 | #[test] |
| 525 | fn remote_head_symref_is_parsed() { |
| 526 | let listing = "ref: refs/heads/trunk\tHEAD\nabc\tHEAD\nabc\trefs/heads/trunk\n"; |
| 527 | assert_eq!( |
| 528 | remote_default_branch(listing).as_deref(), |
| 529 | Some("refs/heads/trunk") |
| 530 | ); |
| 531 | assert_eq!(remote_default_branch("abc\tHEAD\n"), None); |
| 532 | } |
| 533 | |
| 534 | #[tokio::test] |
| 535 | async fn mirror_fetch_and_push_sync_heads_and_tags_with_prune() { |
| 536 | let dir = tempfile::tempdir().unwrap(); |
| 537 | let source = source_repo(dir.path()); |
| 538 | let env = env(dir.path()); |
| 539 | let timeout = Duration::from_secs(60); |
| 540 | |
| 541 | |
| 542 | |
| 543 | let pulled = dir.path().join("pulled.git"); |
| 544 | plumbing( |
| 545 | dir.path(), |
| 546 | &["init", "--bare", "-q", pulled.to_str().unwrap()], |
| 547 | ); |
| 548 | fetch(&env, &pulled, &file_url(&source), None, false, None, true) |
| 549 | .await |
| 550 | .unwrap(); |
| 551 | let fetched = refs(&pulled); |
| 552 | assert!(fetched.contains("refs/heads/main"), "{fetched}"); |
| 553 | assert!(fetched.contains("refs/tags/v1"), "{fetched}"); |
| 554 | assert_eq!( |
| 555 | plumbing(&pulled, &["symbolic-ref", "HEAD"]), |
| 556 | "refs/heads/main" |
| 557 | ); |
| 558 | |
| 559 | |
| 560 | let head = plumbing(&source, &["rev-parse", "refs/heads/main"]); |
| 561 | plumbing(&pulled, &["update-ref", "refs/heads/gone", &head]); |
| 562 | plumbing(&source, &["update-ref", "refs/heads/new", &head]); |
| 563 | fetch(&env, &pulled, &file_url(&source), None, false, None, true) |
| 564 | .await |
| 565 | .unwrap(); |
| 566 | let fetched = refs(&pulled); |
| 567 | assert!(fetched.contains("refs/heads/new"), "{fetched}"); |
| 568 | assert!(!fetched.contains("refs/heads/gone"), "{fetched}"); |
| 569 | |
| 570 | |
| 571 | let remote = dir.path().join("remote.git"); |
| 572 | plumbing( |
| 573 | dir.path(), |
| 574 | &["init", "--bare", "-q", remote.to_str().unwrap()], |
| 575 | ); |
| 576 | plumbing( |
| 577 | &remote, |
| 578 | &[ |
| 579 | "fetch", |
| 580 | "-q", |
| 581 | source.to_str().unwrap(), |
| 582 | "refs/heads/main:refs/heads/stale", |
| 583 | ], |
| 584 | ); |
| 585 | push(&env, &pulled, &file_url(&remote), None, false, None, true) |
| 586 | .await |
| 587 | .unwrap(); |
| 588 | let pushed = refs(&remote); |
| 589 | assert!(pushed.contains("refs/heads/main"), "{pushed}"); |
| 590 | assert!(pushed.contains("refs/tags/v1"), "{pushed}"); |
| 591 | assert!(!pushed.contains("refs/heads/stale"), "{pushed}"); |
| 592 | |
| 593 | |
| 594 | assert!( |
| 595 | mirror_fetch( |
| 596 | &env, |
| 597 | &pulled, |
| 598 | &file_url(&source), |
| 599 | None, |
| 600 | false, |
| 601 | None, |
| 602 | timeout |
| 603 | ) |
| 604 | .await |
| 605 | .is_err() |
| 606 | ); |
| 607 | assert!( |
| 608 | mirror_push( |
| 609 | &env, |
| 610 | &pulled, |
| 611 | &file_url(&remote), |
| 612 | None, |
| 613 | false, |
| 614 | None, |
| 615 | timeout |
| 616 | ) |
| 617 | .await |
| 618 | .is_err() |
| 619 | ); |
| 620 | } |
| 621 | |
| 622 | #[tokio::test] |
| 623 | async fn failure_text_never_carries_the_secret() { |
| 624 | let dir = tempfile::tempdir().unwrap(); |
| 625 | let env = env(dir.path()); |
| 626 | let pulled = dir.path().join("pulled.git"); |
| 627 | plumbing( |
| 628 | dir.path(), |
| 629 | &["init", "--bare", "-q", pulled.to_str().unwrap()], |
| 630 | ); |
| 631 | let a = auth(); |
| 632 | |
| 633 | let url = "https://127.0.0.1:9/x.git"; |
| 634 | let err = mirror_fetch( |
| 635 | &env, |
| 636 | &pulled, |
| 637 | url, |
| 638 | Some(&a), |
| 639 | false, |
| 640 | None, |
| 641 | Duration::from_secs(60), |
| 642 | ) |
| 643 | .await |
| 644 | .unwrap_err(); |
| 645 | let text = err.to_string(); |
| 646 | assert!(!text.contains("s3cret"), "{text}"); |
| 647 | assert!( |
| 648 | !text.contains(&STANDARD.encode(b"mirror-bot:s3cret-token-XYZ")), |
| 649 | "{text}" |
| 650 | ); |
| 651 | } |
| 652 | |
| 653 | fn pin(ip: &str) -> PinnedHost { |
| 654 | PinnedHost { |
| 655 | host: "pin.invalid".into(), |
| 656 | port: 443, |
| 657 | ip: ip.parse().expect("ip"), |
| 658 | } |
| 659 | } |
| 660 | |
| 661 | #[test] |
| 662 | fn pinned_config_pair_formats_ipv4_and_ipv6() { |
| 663 | let v4 = PinnedHost { |
| 664 | host: "example.com".into(), |
| 665 | port: 443, |
| 666 | ip: "93.184.216.34".parse().expect("ip"), |
| 667 | }; |
| 668 | assert_eq!( |
| 669 | v4.config_pair().expect("pair"), |
| 670 | "http.curloptResolve=example.com:443:93.184.216.34" |
| 671 | ); |
| 672 | let v6 = PinnedHost { |
| 673 | host: "example.com".into(), |
| 674 | port: 80, |
| 675 | ip: "2001:db8::1".parse().expect("ip"), |
| 676 | }; |
| 677 | assert_eq!( |
| 678 | v6.config_pair().expect("pair"), |
| 679 | "http.curloptResolve=example.com:80:[2001:db8::1]" |
| 680 | ); |
| 681 | } |
| 682 | |
| 683 | #[test] |
| 684 | fn pinned_host_must_be_a_plain_name() { |
| 685 | for host in ["", "a b", "[::1]", "x,y", "evil\nname"] { |
| 686 | let bad = PinnedHost { |
| 687 | host: host.into(), |
| 688 | port: 443, |
| 689 | ip: "93.184.216.34".parse().expect("ip"), |
| 690 | }; |
| 691 | assert!(bad.config_pair().is_err(), "{host:?}"); |
| 692 | } |
| 693 | } |
| 694 | |
| 695 | #[test] |
| 696 | fn pin_becomes_a_checked_config_arg() { |
| 697 | let dir = tempfile::tempdir().expect("tempdir"); |
| 698 | let cmd = base_command( |
| 699 | &env(dir.path()), |
| 700 | None, |
| 701 | "ls-remote", |
| 702 | None, |
| 703 | false, |
| 704 | Some(&pin("127.0.0.1")), |
| 705 | false, |
| 706 | ) |
| 707 | .expect("command builds"); |
| 708 | let std_cmd = cmd.into_tokio(); |
| 709 | let argv: Vec<String> = std_cmd |
| 710 | .as_std() |
| 711 | .get_args() |
| 712 | .map(|a| a.to_string_lossy().into_owned()) |
| 713 | .collect(); |
| 714 | let at = argv |
| 715 | .iter() |
| 716 | .position(|a| a == "http.curloptResolve=pin.invalid:443:127.0.0.1") |
| 717 | .expect("pinned config arg present"); |
| 718 | assert_eq!(argv[at - 1], "-c", "{argv:?}"); |
| 719 | } |
| 720 | |
| 721 | #[tokio::test] |
| 722 | async fn fetch_connects_to_the_pinned_address() { |
| 723 | let dir = tempfile::tempdir().expect("tempdir"); |
| 724 | let env = env(dir.path()); |
| 725 | let pulled = dir.path().join("pulled.git"); |
| 726 | plumbing( |
| 727 | dir.path(), |
| 728 | &["init", "--bare", "-q", pulled.to_str().expect("utf8 path")], |
| 729 | ); |
| 730 | |
| 731 | |
| 732 | let err = mirror_fetch( |
| 733 | &env, |
| 734 | &pulled, |
| 735 | "https://pin.invalid/x.git", |
| 736 | None, |
| 737 | false, |
| 738 | Some(&pin("127.0.0.1")), |
| 739 | Duration::from_secs(60), |
| 740 | ) |
| 741 | .await |
| 742 | .unwrap_err() |
| 743 | .to_string(); |
| 744 | assert!(!err.contains("Could not resolve host"), "{err}"); |
| 745 | } |
| 746 | } |