steid

@jamesgill /

Rust35.2 KBCode·Blame·History·Raw
1//! Mirroring a repository in from somewhere else.
2
3use std::{
4 ffi::{OsStr, OsString},
5 net::IpAddr,
6 path::{Path, PathBuf},
7 process::{Output, Stdio},
8 sync::{Arc, Mutex},
9};
10
11use tokio::process::Command;
12
13use crate::{
14 application::port::{GitImport, GitImportError},
15 domain::{ImportSource, OrgName, RepoName, is_public},
16 infrastructure::metrics::metrics,
17};
18
19use super::{
20 count_spawn, git_command,
21 merge::{CURLOPT_RESOLVE_SINCE, GitFeatures},
22};
23
24// --- Importing from elsewhere -----------------------------------------------------
25
26/// How long a `git clone --mirror` may run before it is killed.
27///
28/// Ten minutes, far above the read timeout in `git_query.rs` and for the opposite
29/// reason: this is a network transfer of a whole repository with nobody waiting on a
30/// page, so the cost of being generous is a background task, not a held worker. It is
31/// bounded at all because a stalled TLS connection to a host that accepts and then says
32/// nothing would otherwise hold a task for the life of the process.
33const IMPORT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(600);
34
35/// The environment variables git and curl take a proxy from.
36///
37/// Removed from every import's git, because through a proxy curl never resolves the
38/// host itself — the proxy does — and the pin in [`clone_args`] is a pin on curl's own
39/// lookup. A proxy in the service's environment would quietly put the address check
40/// back on the far side of a lookup Steid never sees. `http.proxy` in a config file
41/// cannot do the same: [`git_command`] reads no global or system config.
42const 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/// `git clone --mirror` into the same layout [`DiskGitStorage`] uses.
52///
53/// **This adapter is where the second half of the server-side request forgery check
54/// lives.** [`ImportSource`] refused a literal address that is not on the public
55/// internet, but `evil.example.com` resolving to `127.0.0.1` passes every syntactic
56/// rule there is. Only the thing about to open the connection can look, so it looks
57/// here, immediately before spawning git — and then hands git the addresses it looked
58/// at, so git connects to those and does not look again.
59#[derive(Debug, Clone)]
60pub struct DiskGitImport {
61 data_dir: PathBuf,
62 /// What this machine's git can do, read once at boot. An import needs
63 /// [`pinned_resolve`](GitFeatures::pinned_resolve) and is refused without it.
64 features: GitFeatures,
65}
66
67impl 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 /// Where a repository lives, matching `DiskGitStorage`'s layout.
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
83impl GitImport for DiskGitImport {
84 async fn mirror(
85 &self,
86 handle: &OrgName,
87 name: &RepoName,
88 source: &ImportSource,
89 ) -> Result<(), GitImportError> {
90 // Counted here rather than where the task is spawned, because this is the only
91 // place that sees an import's real outcome: `application::run_import` answers
92 // `Ok(())` for a *failed* import — the failure is data on the repository — so a
93 // counter on its return value would say every import succeeded.
94 //
95 // "Started" therefore means the clone was attempted. An import still waiting for
96 // a permit has not started, and is visible on `steid_active_imports` instead.
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
110impl DiskGitImport {
111 /// [`mirror`](GitImport::mirror) itself, with the counting split off so that every
112 /// early return is counted too — a `?` past a recording line records nothing.
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 // `git clone` refuses a non-empty destination, so an orphan left by an earlier
126 // attempt surfaces as a failed import rather than being adopted. Checked here
127 // as well so the message says something a person can act on.
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/// Refuses an import on a git that cannot pin it, in words the owner can act on.
141///
142/// The same stance as the merge box below 2.38, for the same reason: an older git does
143/// not fail, it does something else. Here that is ignoring `http.curloptResolve` and
144/// resolving the name again, which is DNS rebinding left open. The reason lands on the
145/// repository's failed-import panel, where the owner who asked for the import reads it.
146fn 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/// The arguments of the clone itself.
165///
166/// Split out so a test can read back what git is told; the clone needs a public HTTPS
167/// host, which a unit test cannot stand up.
168fn clone_args(source: &ImportSource, addresses: &[IpAddr], destination: &Path) -> Vec<OsString> {
169 let mut args: Vec<OsString> = vec![
170 // **The other half of the redirect rule** — see `resolve_public_host`. git's own
171 // default is `initial`, which lets the *first* request be redirected, and it
172 // re-resolves whatever host it is sent to. So a perfectly public source
173 // answering `302 Location: http://169.254.169.254/…` walked the clone straight
174 // past the check. Off entirely: a clone URL that needs a redirect is one whose
175 // real address the person can paste instead, and the failure says so.
176 "-c".into(),
177 "http.followRedirects=false".into(),
178 ];
179
180 // **The pin, which closes DNS rebinding.** Without it git resolves the name again
181 // when it connects, and a name with a short TTL can answer public to the check and
182 // private to the clone. curl keeps the `Host` header, SNI and the certificate check
183 // on the name, and takes only the socket address from the pin.
184 //
185 // A literal address is not pinned: it has no name to rebind, curl never looks one
186 // up, and an IPv6 host would need a spelling of its own in the pin's `host:port`.
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 // `--mirror` is the whole reason this is one command: it fetches every ref into
200 // the same name it has on the source, sets `HEAD` to the source's default
201 // branch, and makes the result bare. A plain `--bare` clone would bring one
202 // branch and lose every tag.
203 "clone".into(),
204 "--mirror".into(),
205 "--quiet".into(),
206 // Everything after this is data. The URL is already https-only and space-free,
207 // but a destination that could be read as a flag is exactly the class of bug
208 // `RepoName` exists to prevent, so it is closed here too where it costs nothing.
209 "--".into(),
210 source.as_str().into(),
211 destination.as_os_str().to_owned(),
212 ]);
213
214 args
215}
216
217/// The value of `http.curloptResolve` that pins `host:port` to the checked addresses.
218///
219/// curl's `CURLOPT_RESOLVE` format, `HOST:PORT:ADDRESS[,ADDRESS]…`, with each IPv6
220/// address in brackets. curl tries each address in turn, so every one that passed the
221/// check is handed over and no other.
222///
223/// The host is passed exactly as the URL spells it: curl matches a pin to the URL's own
224/// `host:port`, and the port must be the one git dials — see [`ImportSource::port`].
225fn 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/// Turns a fresh `--mirror` clone into an ordinary Steid repository.
239///
240/// Split out from [`DiskGitImport::mirror`] so it can be tested against a fixture: the
241/// clone itself needs a public HTTPS host, and everything that could plausibly be wrong
242/// is on this side of it.
243async fn finish_mirror(path: &std::path::Path) -> Result<(), GitImportError> {
244 // A mirror keeps its remote and its `remote.origin.mirror` flag, so the result
245 // would be a repository that fetches from somewhere else on the next `git remote
246 // update`. Removing it is what turns the clone into an ordinary Steid repository,
247 // and it takes the mirror refspec with it.
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 // **`git clone` leaves no reflog either**, exactly as `git init --bare` does, and an
259 // import never goes through `init_bare` — so without this an imported repository
260 // records nobody as having pushed to it until the next boot sweep picks it up. Found
261 // by that sweep reporting six repositories on a development instance where every
262 // repository had been created by the current code: the six were the imports.
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 // `--mirror` puts branches under `refs/heads` already. This is the belt to that
274 // braces: a source whose own layout is unusual — itself a mirror of a mirror — can
275 // leave `refs/remotes`, and a branch nobody can see is worse than one moved to
276 // where every other page expects it.
277 promote_remote_refs(path).await
278}
279
280/// Moves anything under `refs/remotes/origin/` to `refs/heads/`, and drops the rest.
281///
282/// A no-op for every ordinary mirror, which is why it is written to cost one `git`
283/// process and stop: `for-each-ref` on a prefix with nothing under it exits 0 with no
284/// output.
285///
286/// Object ids are read alongside the names and written back as ids. `update-ref` takes
287/// a value, not a reference, and asking it to resolve one is how this was got wrong the
288/// first time.
289async 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 // `origin/HEAD` is a symbolic pointer, not a branch, and `--mirror` has already
308 // set the real `HEAD` from the source. Anything under another remote's name is
309 // somebody else's tracking ref and means nothing here. Both are simply dropped.
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/// Resolves a host and refuses it unless every address it answers with is on the public
340/// internet, and answers with those addresses.
341///
342/// **Every address, not the first.** A host that answers with one public address and
343/// one loopback address is a host that can be made to connect to loopback, because
344/// which one git picks is not ours to decide.
345///
346/// The addresses are returned so the clone can be pinned to them — see [`pin`]. A check
347/// that only answered yes or no left git to resolve the name again when it connected,
348/// and a record whose TTL expired in between could change underneath it (DNS
349/// rebinding, closed by launch 2.18).
350///
351/// It is only part of the rule on its own: git would otherwise follow a redirect on its
352/// first request and re-resolve wherever it was sent, so the clone passes
353/// `http.followRedirects=false` — see [`clone_args`].
354async 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/// Runs one `git` command on behalf of an import.
383///
384/// Separate from [`run_git`] for two reasons rather than one: the timeout is ten
385/// minutes instead of unbounded, and `GIT_TERMINAL_PROMPT=0` turns a private repository
386/// into a failed import instead of a subprocess sitting forever on a username prompt
387/// nobody can answer.
388async fn run_import<I, S>(args: I, repo: Option<&std::path::Path>) -> Result<Output, GitImportError>
389where
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 // git's own words, trimmed to the last line: the earlier lines of a clone
415 // failure are progress, and the last one is the reason.
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/// The `git` an import runs, before its arguments.
429///
430/// [`git_command`]'s isolation, plus what only a network fetch needs: no proxy, no
431/// prompt, and death with the task.
432fn import_command() -> Command {
433 let mut command = git_command();
434
435 // See `PROXY_VARS`: through a proxy, the pin would not be what git dials.
436 for variable in PROXY_VARS {
437 command.env_remove(variable);
438 }
439
440 command
441 .stdin(Stdio::null())
442 // Without this git blocks on a credential prompt for anything that asks for
443 // authentication — a private repository, or a typo'd path on a host that
444 // challenges rather than 404s.
445 .env("GIT_TERMINAL_PROMPT", "0")
446 // A killed clone must take the process with it, or a timed-out import keeps
447 // pulling a repository nobody is waiting for.
448 .kill_on_drop(true);
449
450 command
451}
452
453/// Imports recorded in memory, for testing use cases without a network.
454///
455/// The counterpart to [`DiskGitImport`], the way [`InMemoryGitStorage`] is to
456/// [`DiskGitStorage`]. It can be told to fail, because the failure path — recording the
457/// reason and removing the half-clone — is the half most worth testing.
458#[derive(Debug, Default, Clone)]
459pub struct InMemoryGitImport {
460 requests: Arc<Mutex<Vec<(String, String, String)>>>,
461 failure: Option<String>,
462}
463
464impl InMemoryGitImport {
465 pub fn new() -> Self {
466 Self::default()
467 }
468
469 /// One that always fails with `reason`.
470 pub fn failing(reason: impl Into<String>) -> Self {
471 Self {
472 requests: Arc::default(),
473 failure: Some(reason.into()),
474 }
475 }
476
477 /// What was asked for, as `(handle, name, source)`.
478 pub fn requests(&self) -> Vec<(String, String, String)> {
479 self.requests.lock().expect("lock poisoned").clone()
480 }
481}
482
483impl 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)]
504mod 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 // --- Importing ------------------------------------------------------------------
512
513 /// A source repository on disk with two branches and an annotated tag, so a mirror
514 /// has something to lose.
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 /// The shape an import has to leave behind, exercised end to end minus the network.
556 ///
557 /// The clone is run against a local path because `ImportSource` allows only public
558 /// HTTPS, which cannot be stood up in a unit test. Everything the adapter decides
559 /// after the transfer — the refs, `HEAD`, and the remote — is the same either way,
560 /// and it is the half that could plausibly be wrong.
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 // Every branch, under `refs/heads` — where every other page in Steid looks.
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 // Tags too, annotated ones included.
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 // Nothing left under `refs/remotes`, and no remote to fetch from.
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 // `HEAD` follows the source's default branch, so the landing page opens on it.
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 // And a reflog, so the first push into an imported repository records who made
622 // it. `git clone` leaves this off exactly as `git init --bare` does, and an
623 // import never goes through `init_bare`.
624 assert_eq!(
625 git_says(&destination, &["config", "--get", "core.logAllRefUpdates"]),
626 "true"
627 );
628 }
629
630 /// A source whose branches arrived under `refs/remotes` — the case `--mirror`
631 /// normally makes impossible, which is exactly why nothing else would catch it.
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 // A plain `--bare` clone with a fetch refspec that writes remote-tracking refs,
639 // which is what a non-mirror clone of a mirror can leave.
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 // Stage the shape by hand: a branch only under `refs/remotes`.
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 /// The DNS half of the server-side request forgery check, which `ImportSource`
697 /// cannot make: `localhost` is a name, and only resolving it says where it goes.
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 // A literal, so the answer needs no network: what passed is what the clone is
722 // pinned to.
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 // A `-c` before the subcommand, which is where git reads one.
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 /// **git dials the pin, not the name.** `.invalid` is reserved and never resolves,
781 /// so the only way `ls-remote` can reach the listener is through the pinned address
782 /// — and the request still names the host, so nothing had to be set by hand.
783 ///
784 /// **Needs git 2.37 or newer**, which is when `http.curloptResolve` arrived. An older
785 /// git ignores a configuration key it does not know, tries to resolve the name, and
786 /// fails this test — which is the same reason an older git is refused an import.
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 // A 404 is all `ls-remote` needs to stop.
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 // Expected to fail: the listener answers 404. What matters is where it went.
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 /// git's last line is the reason; the lines before it are progress.
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 /// A git new enough to pin, whatever the machine running the test has.
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 // Ubuntu 22.04's git.
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}