steid

@jamesgill /

1//! The `git` binary, behind the ports the application declares.
2//!
3//! One module owns *how* Steid invokes git — see [`run_git`] — so that isolation and
4//! error handling cannot drift between call sites. Milestone 4's protocol commands
5//! belong here too rather than growing a second recipe.
6
7use std::{
8 collections::{HashMap, HashSet},
9 ffi::OsStr,
10 io,
11 path::PathBuf,
12 process::{Output, Stdio},
13 sync::{Arc, Mutex},
14 time::SystemTime,
15};
16
17use tokio::{
18 io::{AsyncBufReadExt, AsyncReadExt, BufReader},
19 process::{ChildStdout, Command},
20};
21
22use crate::{
23 application::{
24 blame::Blame,
25 port::{
26 ArchiveRequest, Blob, ByteStream, GitArchive, GitArchiveError, GitImport,
27 GitImportError, GitMethod, GitProtocolError, GitProtocolServer, GitQuery,
28 GitQueryError, GitRequest, GitResponse, GitStorage, GitStorageError, RawDiff,
29 },
30 },
31 domain::{
32 BranchRow, CommitDetail, CommitSummary, GitRef, GrepHit, ImportSource, ObjectId, OrgName,
33 RefKind, RefName, RepoName, RepoPath, TagRow, TagSummary, TreeEntry, is_public,
34 },
35};
36
37/// The most CGI headers `git http-backend` will ever emit, with room to spare.
38///
39/// A guard rather than a real expectation: the header block is read before anything is
40/// streamed, and an unbounded read of a subprocess's stdout is a hang waiting to happen.
41const MAX_CGI_HEADERS: usize = 64;
42
43/// Environment variables that redirect where git reads and writes data.
44///
45/// Steid's own environment must not reach into a repository's layout. These are set
46/// whenever a process is spawned from inside a git hook, which is exactly the shape
47/// Milestone 5 will have, and the failure is silent — objects land somewhere else and
48/// the repository looks empty.
49const REDIRECTING_VARS: &[&str] = &[
50 "GIT_ALTERNATE_OBJECT_DIRECTORIES",
51 "GIT_DIR",
52 "GIT_INDEX_FILE",
53 "GIT_OBJECT_DIRECTORY",
54 "GIT_WORK_TREE",
55];
56
57/// Bare repositories on disk, laid out as `{data_dir}/{handle}/{name}.git`.
58#[derive(Debug, Clone)]
59pub struct DiskGitStorage {
60 data_dir: PathBuf,
61}
62
63impl DiskGitStorage {
64 pub fn new(data_dir: impl Into<PathBuf>) -> Self {
65 Self {
66 data_dir: data_dir.into(),
67 }
68 }
69}
70
71impl GitStorage for DiskGitStorage {
72 async fn init_bare(&self, handle: &OrgName, name: &RepoName) -> Result<(), GitStorageError> {
73 let path = self.repo_path(handle, name);
74
75 // `git init` on an existing repository exits 0 and re-initialises in silence,
76 // so this check has to be ours. A directory with no matching record is an
77 // orphan from a create that died between the two writes; adopting it would
78 // resurface a private repository's objects under a fresh record.
79 if path.exists() {
80 return Err(GitStorageError::AlreadyExists);
81 }
82
83 // No `create_dir_all` for the parent: `git init` creates missing directories.
84 run_git([
85 OsStr::new("init"),
86 OsStr::new("--bare"),
87 OsStr::new("--quiet"),
88 // Skip the template directory, which otherwise seeds every repository with
89 // sixteen `.sample` hooks. Steid installs its own hooks later, and they
90 // would be noise to work around.
91 OsStr::new("--template="),
92 // Explicit, so the host's `init.defaultBranch` cannot decide what the
93 // default branch of a Steid repository is.
94 OsStr::new("--initial-branch=main"),
95 // `RepoName` already forbids a leading hyphen; this makes it impossible for
96 // a path to be read as a flag at the boundary where it costs nothing.
97 OsStr::new("--"),
98 path.as_os_str(),
99 ])
100 .await?;
101
102 // A second process, once per repository ever created — creation is not a hot
103 // path. `git init --bare` leaves `core.logAllRefUpdates` off, so a bare
104 // repository keeps no reflog at all and `REMOTE_USER` has nowhere to be
105 // recorded: `git reflog show main` answers nothing, and who moved a ref is
106 // unknowable even though Steid knew at the time.
107 //
108 // Set here rather than passed as `git -c … init`, because `-c` configures that
109 // one invocation and is not written into the repository it creates.
110 //
111 // Repositories created before this stay without one. `git config
112 // core.logAllRefUpdates true` in the bare repo is the whole of the fix.
113 run_git([
114 OsStr::new("--git-dir"),
115 path.as_os_str(),
116 OsStr::new("config"),
117 OsStr::new("core.logAllRefUpdates"),
118 OsStr::new("true"),
119 ])
120 .await
121 .map(|_| ())
122 }
123
124 async fn remove(&self, handle: &OrgName, name: &RepoName) -> Result<(), GitStorageError> {
125 let path = self.repo_path(handle, name);
126
127 // `tokio::fs` rather than `std::fs`: removing a repository with real history
128 // walks every loose object, which is long enough to stall a runtime worker.
129 match tokio::fs::remove_dir_all(&path).await {
130 Ok(()) => Ok(()),
131 // Compensation must not fail because there was nothing left to undo.
132 Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
133 Err(error) => Err(GitStorageError::backend(error)),
134 }
135 }
136
137 async fn rename(
138 &self,
139 handle: &OrgName,
140 from: &RepoName,
141 to: &RepoName,
142 ) -> Result<(), GitStorageError> {
143 let source = self.repo_path(handle, from);
144 let destination = self.repo_path(handle, to);
145
146 // Checked rather than left to `rename`, which on Unix replaces an existing
147 // empty directory and refuses a non-empty one with a bare `ENOTEMPTY`. Neither
148 // is an answer a use case can explain, and the first one loses a repository.
149 if destination.exists() {
150 return Err(GitStorageError::AlreadyExists);
151 }
152
153 // A rename within one handle's directory, so both sides are on the same
154 // filesystem and this is a metadata update rather than a copy — which is why
155 // the record write can be compensated by moving it straight back.
156 tokio::fs::rename(&source, &destination)
157 .await
158 .map_err(GitStorageError::backend)
159 }
160
161 async fn set_default_branch(
162 &self,
163 handle: &OrgName,
164 name: &RepoName,
165 branch: &RefName,
166 ) -> Result<(), GitStorageError> {
167 let path = self.repo_path(handle, name);
168
169 // `symbolic-ref` writes `HEAD` without needing the branch to exist, which is
170 // exactly why the use case checks that first. The full `refs/heads/` spelling is
171 // built here rather than accepted from the caller, so nothing can point `HEAD`
172 // at a tag or at some other ref namespace.
173 run_git([
174 OsStr::new("--git-dir"),
175 path.as_os_str(),
176 OsStr::new("symbolic-ref"),
177 OsStr::new("HEAD"),
178 OsStr::new(&format!("refs/heads/{branch}")),
179 ])
180 .await
181 .map(|_| ())
182 }
183
184 fn repo_path(&self, handle: &OrgName, name: &RepoName) -> PathBuf {
185 // Nothing is sanitised here. `OrgName` and `RepoName` already made traversal
186 // impossible, and re-checking at the call site is how that responsibility gets
187 // diffused until nobody owns it.
188 self.data_dir
189 .join(handle.as_str())
190 .join(format!("{name}.git"))
191 }
192}
193
194/// A `git` command isolated from the host.
195///
196/// The one place that decides what git inherits: no ambient configuration, no
197/// redirected object storage. Both the lifecycle commands and the protocol backend
198/// build on this, which is the point — 0006 exists because these flags are exactly what
199/// drifts silently between call sites.
200pub(crate) fn git_command() -> Command {
201 let mut command = Command::new("git");
202
203 // Host configuration must not leak into repositories Steid creates, for the same
204 // reason `--initial-branch` is passed explicitly.
205 command
206 .env("GIT_CONFIG_GLOBAL", "/dev/null")
207 .env("GIT_CONFIG_SYSTEM", "/dev/null");
208
209 for variable in REDIRECTING_VARS {
210 command.env_remove(variable);
211 }
212
213 command
214}
215
216/// Runs `git` and fails on a non-zero exit.
217///
218/// The single place that decides how Steid invokes git, so every call site gets the
219/// same isolation from the host: no ambient configuration, no redirected object
220/// storage, no inherited stdin. Never depends on the working directory — callers pass
221/// absolute paths.
222async fn run_git<I, S>(args: I) -> Result<Output, GitStorageError>
223where
224 I: IntoIterator<Item = S>,
225 S: AsRef<OsStr>,
226{
227 let mut command = git_command();
228 command.args(args).stdin(Stdio::null());
229
230 // `output()` pipes stdout and stderr and waits without blocking the runtime.
231 let output = command
232 .output()
233 .await
234 .map_err(|error| GitStorageError::backend(format!("could not run git: {error}")))?;
235
236 if !output.status.success() {
237 // Carry git's own words. "command failed" sends the next person to read this
238 // code instead of reading the error.
239 return Err(GitStorageError::backend(format!(
240 "git exited with {}: {}",
241 output.status,
242 String::from_utf8_lossy(&output.stderr).trim()
243 )));
244 }
245
246 Ok(output)
247}
248
249/// Bare repositories tracked in memory, for testing use cases without touching disk.
250///
251/// The counterpart to [`DiskGitStorage`], the way `StubHasher` is the counterpart to
252/// the real Argon2 hasher. It enforces the same `AlreadyExists` rule, because a use
253/// case that only passes against a permissive fake proves nothing about the real one.
254#[derive(Debug, Default, Clone)]
255pub struct InMemoryGitStorage {
256 created: Arc<Mutex<HashSet<PathBuf>>>,
257 /// Where each repository's `HEAD` points, for asserting on a default-branch change.
258 heads: Arc<Mutex<HashMap<PathBuf, RefName>>>,
259}
260
261impl InMemoryGitStorage {
262 pub fn new() -> Self {
263 Self::default()
264 }
265
266 /// Whether a repository exists, for assertions.
267 pub fn contains(&self, handle: &OrgName, name: &RepoName) -> bool {
268 self.created
269 .lock()
270 .expect("lock poisoned")
271 .contains(&self.repo_path(handle, name))
272 }
273
274 /// Which branch `HEAD` names, for assertions. `None` until something sets it.
275 pub fn head(&self, handle: &OrgName, name: &RepoName) -> Option<RefName> {
276 self.heads
277 .lock()
278 .expect("lock poisoned")
279 .get(&self.repo_path(handle, name))
280 .cloned()
281 }
282
283 /// How many repositories exist, for asserting that nothing was created.
284 pub fn len(&self) -> usize {
285 self.created.lock().expect("lock poisoned").len()
286 }
287
288 pub fn is_empty(&self) -> bool {
289 self.len() == 0
290 }
291}
292
293impl GitStorage for InMemoryGitStorage {
294 async fn init_bare(&self, handle: &OrgName, name: &RepoName) -> Result<(), GitStorageError> {
295 let mut created = self.created.lock().expect("lock poisoned");
296
297 if !created.insert(self.repo_path(handle, name)) {
298 return Err(GitStorageError::AlreadyExists);
299 }
300
301 Ok(())
302 }
303
304 async fn remove(&self, handle: &OrgName, name: &RepoName) -> Result<(), GitStorageError> {
305 self.created
306 .lock()
307 .expect("lock poisoned")
308 .remove(&self.repo_path(handle, name));
309
310 Ok(())
311 }
312
313 async fn rename(
314 &self,
315 handle: &OrgName,
316 from: &RepoName,
317 to: &RepoName,
318 ) -> Result<(), GitStorageError> {
319 let mut created = self.created.lock().expect("lock poisoned");
320 let destination = self.repo_path(handle, to);
321
322 // The same refusal `DiskGitStorage` makes, so a use case cannot pass here and
323 // clobber a directory there.
324 if created.contains(&destination) {
325 return Err(GitStorageError::AlreadyExists);
326 }
327
328 let source = self.repo_path(handle, from);
329 created.remove(&source);
330 created.insert(destination.clone());
331
332 // `HEAD` travels with the directory, as it does on disk.
333 let mut heads = self.heads.lock().expect("lock poisoned");
334 if let Some(head) = heads.remove(&source) {
335 heads.insert(destination, head);
336 }
337
338 Ok(())
339 }
340
341 async fn set_default_branch(
342 &self,
343 handle: &OrgName,
344 name: &RepoName,
345 branch: &RefName,
346 ) -> Result<(), GitStorageError> {
347 self.heads
348 .lock()
349 .expect("lock poisoned")
350 .insert(self.repo_path(handle, name), branch.clone());
351
352 Ok(())
353 }
354
355 fn repo_path(&self, handle: &OrgName, name: &RepoName) -> PathBuf {
356 PathBuf::from("/in-memory")
357 .join(handle.as_str())
358 .join(format!("{name}.git"))
359 }
360}
361
362/// The git smart-HTTP protocol, served by `git http-backend`.
363///
364/// The binary is a CGI: it takes an environment and a request body on stdin, and writes
365/// CRLF-terminated headers, a blank line, then the response body. Its contract was
366/// probed rather than assumed — see `plans/progress.md` under Milestone 4a.
367#[derive(Debug, Clone)]
368pub struct GitHttpBackend {
369 data_dir: PathBuf,
370}
371
372impl GitHttpBackend {
373 pub fn new(data_dir: impl Into<PathBuf>) -> Self {
374 Self {
375 data_dir: data_dir.into(),
376 }
377 }
378}
379
380impl GitProtocolServer for GitHttpBackend {
381 async fn serve(&self, request: GitRequest) -> Result<GitResponse, GitProtocolError> {
382 let mut command = git_command();
383
384 // Before the subcommand: `git -c … http-backend`. Pushes are refused by the
385 // backend unless this says otherwise, and it is set only for a request the use
386 // case already authorized — so a bug in Steid's rules meets git's refusal rather
387 // than an open door.
388 if request.allow_receive_pack {
389 command.arg("-c").arg("http.receivepack=true");
390 }
391
392 command
393 .arg("http-backend")
394 .env("GIT_PROJECT_ROOT", &self.data_dir)
395 // Steid decides visibility from the `repositories` table, in the use case.
396 // Without this, git applies its own rule and refuses everything lacking a
397 // `git-daemon-export-ok` marker file — a second source of truth for the same
398 // question, free to drift from the first.
399 .env("GIT_HTTP_EXPORT_ALL", "1")
400 .env("PATH_INFO", &request.path_info)
401 .env("QUERY_STRING", &request.query)
402 .env("REQUEST_METHOD", request.method.as_str())
403 .stdin(Stdio::piped())
404 .stdout(Stdio::piped())
405 .stderr(Stdio::piped());
406
407 // CGI gives only Content-Type and Content-Length unprefixed names; every other
408 // request header arrives `HTTP_`-prefixed. Passing `CONTENT_ENCODING` instead of
409 // `HTTP_CONTENT_ENCODING` makes the backend hand a still-gzipped body to
410 // upload-pack, and the client reports `expected 'packfile'` with nothing naming
411 // the cause. Measured, not guessed.
412 // `REMOTE_USER` is CGI's name for the authenticated caller, and git reads it to
413 // write `pusher <name>` into the reflog. Unprefixed like `CONTENT_TYPE`, because
414 // it is a CGI variable rather than a forwarded request header — and it comes
415 // from Steid's own authentication, never from anything the client sent.
416 for (variable, value) in [
417 ("CONTENT_TYPE", &request.content_type),
418 ("CONTENT_LENGTH", &request.content_length),
419 ("HTTP_CONTENT_ENCODING", &request.content_encoding),
420 ("HTTP_GIT_PROTOCOL", &request.git_protocol),
421 ("REMOTE_USER", &request.remote_user),
422 ] {
423 if let Some(value) = value {
424 command.env(variable, value);
425 }
426 }
427
428 let mut child = command
429 .spawn()
430 .map_err(|error| GitProtocolError::new(format!("could not run git: {error}")))?;
431
432 let mut stdin = child.stdin.take().expect("stdin was piped");
433 let stdout = child.stdout.take().expect("stdout was piped");
434 let mut stderr = child.stderr.take().expect("stderr was piped");
435 let mut body = request.body;
436
437 // The request body streams in while the response streams out; a push is far too
438 // large to buffer, and a fetch would otherwise wait for a body it already has.
439 // Dropping stdin closes the pipe, which is what tells the backend the request is
440 // complete — an error here is the client having gone away, which the backend
441 // then sees as EOF.
442 tokio::spawn(async move {
443 let _ = tokio::io::copy(&mut body, &mut stdin).await;
444 });
445
446 // Reaps the child and surfaces its complaint. This cannot gate the response: a
447 // protocol failure exits non-zero *after* a complete, successful-looking header
448 // block has already been written, so by the time the status is known it has been
449 // sent. Draining stderr is not optional either — an unread pipe fills and blocks
450 // the backend mid-transfer.
451 tokio::spawn(async move {
452 let mut complaint = String::new();
453 let _ = stderr.read_to_string(&mut complaint).await;
454
455 match child.wait().await {
456 Ok(status) if status.success() => {}
457 Ok(status) => eprintln!(
458 "steid: git http-backend exited with {status}: {}",
459 complaint.trim()
460 ),
461 Err(error) => eprintln!("steid: could not wait for git http-backend: {error}"),
462 }
463 });
464
465 // `BufReader` keeps whatever it read past the header block, and handing the
466 // reader itself back as the body is what makes that safe — the first bytes of
467 // the pack are already buffered inside it.
468 let mut reader = BufReader::new(stdout);
469 let (status, headers) = read_cgi_headers(&mut reader).await?;
470
471 Ok(GitResponse {
472 status,
473 headers,
474 body: Box::pin(reader),
475 })
476 }
477}
478
479/// Reads the CGI header block, stopping at the blank line that ends it.
480///
481/// `Status:` is git's way of reporting failure and appears only then, so its absence
482/// means 200. It is translated into the response status rather than forwarded as a
483/// header, which would be meaningless to a client.
484async fn read_cgi_headers(
485 reader: &mut BufReader<ChildStdout>,
486) -> Result<(u16, Vec<(String, String)>), GitProtocolError> {
487 let mut status = 200;
488 let mut headers = Vec::new();
489 let mut line = Vec::new();
490
491 loop {
492 line.clear();
493
494 let read = reader
495 .read_until(b'\n', &mut line)
496 .await
497 .map_err(|error| GitProtocolError::new(format!("reading git's headers: {error}")))?;
498
499 if read == 0 {
500 return Err(GitProtocolError::new(
501 "git http-backend produced no headers before closing",
502 ));
503 }
504
505 // Tolerates a bare LF as well as the CRLF actually observed: a header reader
506 // that hangs on an unexpected line ending is a bad way to find out.
507 let text = String::from_utf8_lossy(&line);
508 let text = text.trim_end_matches(['\r', '\n']);
509
510 if text.is_empty() {
511 return Ok((status, headers));
512 }
513
514 let Some((name, value)) = text.split_once(": ") else {
515 return Err(GitProtocolError::new(format!(
516 "git http-backend wrote an unparseable header: {text:?}"
517 )));
518 };
519
520 if name.eq_ignore_ascii_case("status") {
521 status = value
522 .split_whitespace()
523 .next()
524 .and_then(|code| code.parse().ok())
525 .ok_or_else(|| {
526 GitProtocolError::new(format!("git http-backend wrote a bad status: {value:?}"))
527 })?;
528 } else {
529 headers.push((name.to_owned(), value.to_owned()));
530 }
531
532 if headers.len() > MAX_CGI_HEADERS {
533 return Err(GitProtocolError::new(
534 "git http-backend wrote more headers than a CGI response can plausibly have",
535 ));
536 }
537 }
538}
539
540/// What a [`InMemoryGitProtocol`] was asked for, minus the body.
541///
542/// The body is a stream and comparing it would mean draining it; every rule worth
543/// asserting on lives in the metadata anyway.
544#[derive(Debug, Clone, PartialEq, Eq)]
545pub struct RecordedGitRequest {
546 pub method: GitMethod,
547 pub path_info: String,
548 pub query: String,
549 pub git_protocol: Option<String>,
550 pub content_encoding: Option<String>,
551 pub allow_receive_pack: bool,
552 pub remote_user: Option<String>,
553}
554
555/// A git protocol that records what it was asked and never runs git.
556///
557/// The counterpart to [`GitHttpBackend`]. What it is really for is proving a negative:
558/// that a use case refused *before* reaching the protocol. `was_called` is how a test
559/// says "and no bytes flowed".
560#[derive(Debug, Default, Clone)]
561pub struct InMemoryGitProtocol {
562 requests: Arc<Mutex<Vec<RecordedGitRequest>>>,
563}
564
565impl InMemoryGitProtocol {
566 pub fn new() -> Self {
567 Self::default()
568 }
569
570 pub fn requests(&self) -> Vec<RecordedGitRequest> {
571 self.requests.lock().expect("lock poisoned").clone()
572 }
573
574 /// Whether the protocol was reached at all.
575 pub fn was_called(&self) -> bool {
576 !self.requests.lock().expect("lock poisoned").is_empty()
577 }
578}
579
580impl GitProtocolServer for InMemoryGitProtocol {
581 async fn serve(&self, request: GitRequest) -> Result<GitResponse, GitProtocolError> {
582 self.requests
583 .lock()
584 .expect("lock poisoned")
585 .push(RecordedGitRequest {
586 method: request.method,
587 path_info: request.path_info,
588 query: request.query,
589 git_protocol: request.git_protocol,
590 content_encoding: request.content_encoding,
591 allow_receive_pack: request.allow_receive_pack,
592 remote_user: request.remote_user,
593 });
594
595 Ok(GitResponse {
596 status: 200,
597 headers: vec![(
598 "Content-Type".to_owned(),
599 "application/x-git-upload-pack-advertisement".to_owned(),
600 )],
601 body: Box::pin(std::io::Cursor::new(b"0000".to_vec())),
602 })
603 }
604}
605
606/// `git archive`, streamed.
607///
608/// Beside the protocol server rather than beside the read queries because it has the
609/// protocol's shape, not theirs: the output is as large as the repository and is handed
610/// on as it arrives. `DiskGitQuery`'s contract — bounded bytes, collected — is exactly
611/// what an archive must not do.
612#[derive(Debug, Clone)]
613pub struct DiskGitArchive {
614 data_dir: PathBuf,
615}
616
617impl DiskGitArchive {
618 pub fn new(data_dir: impl Into<PathBuf>) -> Self {
619 Self {
620 data_dir: data_dir.into(),
621 }
622 }
623
624 /// Where a repository lives, matching `DiskGitStorage`'s layout.
625 fn repo_path(&self, handle: &OrgName, name: &RepoName) -> PathBuf {
626 self.data_dir
627 .join(handle.as_str())
628 .join(format!("{name}.git"))
629 }
630}
631
632impl GitArchive for DiskGitArchive {
633 async fn archive(&self, request: ArchiveRequest) -> Result<ByteStream, GitArchiveError> {
634 let repo = self.repo_path(&request.handle, &request.name);
635
636 // Both values are the use case's own construction — a resolved object id and a
637 // prefix built from the repository's name — so nothing from a URL reaches git's
638 // revision parser here. They are still written `--flag=value` rather than as
639 // separate arguments, so neither can be read as a flag of its own.
640 let mut command = git_command();
641 command
642 .arg("-C")
643 .arg(&repo)
644 .arg("archive")
645 .arg(format!("--format={}", request.format.as_str()))
646 .arg(format!("--prefix={}", request.prefix))
647 .arg(request.commit.as_str())
648 .stdin(Stdio::null())
649 .stdout(Stdio::piped())
650 .stderr(Stdio::piped())
651 // A client that gives up mid-download must take the packing with it;
652 // without this, git finishes compressing a repository for nobody.
653 .kill_on_drop(true);
654
655 let mut child = command
656 .spawn()
657 .map_err(|error| GitArchiveError::new(format!("could not run git: {error}")))?;
658
659 let stdout = child.stdout.take().expect("stdout was piped");
660 let mut stderr = child.stderr.take().expect("stderr was piped");
661
662 // The child is reaped in its own task, exactly as the protocol server's is, and
663 // for the same two reasons: dropping a `Child` with `kill_on_drop` would kill
664 // the process the response body is still reading from, and an unread stderr pipe
665 // eventually fills and stalls the transfer. The exit status cannot gate the
666 // response — by the time it is known, bytes have been sent — so a late failure
667 // is a truncated download and a line in the log.
668 tokio::spawn(async move {
669 let mut complaint = String::new();
670 let _ = stderr.read_to_string(&mut complaint).await;
671
672 match child.wait().await {
673 Ok(status) if status.success() => {}
674 Ok(status) => {
675 eprintln!(
676 "steid: git archive exited with {status}: {}",
677 complaint.trim()
678 )
679 }
680 Err(error) => eprintln!("steid: could not wait for git archive: {error}"),
681 }
682 });
683
684 Ok(Box::pin(stdout))
685 }
686}
687
688/// What an [`InMemoryGitArchive`] was asked for.
689///
690/// The request minus nothing: unlike a protocol request there is no body, so every
691/// field is worth asserting on.
692#[derive(Debug, Clone, PartialEq, Eq)]
693pub struct RecordedArchive {
694 pub handle: OrgName,
695 pub name: RepoName,
696 pub format: crate::application::port::ArchiveFormat,
697 pub commit: ObjectId,
698 pub prefix: String,
699}
700
701/// An archive port that records what it was asked and never runs git.
702///
703/// Like [`InMemoryGitProtocol`], what it is really for is proving a negative: that a
704/// use case refused before a single byte was packed.
705#[derive(Debug, Default, Clone)]
706pub struct InMemoryGitArchive {
707 requests: Arc<Mutex<Vec<RecordedArchive>>>,
708}
709
710impl InMemoryGitArchive {
711 pub fn new() -> Self {
712 Self::default()
713 }
714
715 pub fn requests(&self) -> Vec<RecordedArchive> {
716 self.requests.lock().expect("lock poisoned").clone()
717 }
718
719 /// Whether anything was ever packed.
720 pub fn was_called(&self) -> bool {
721 !self.requests.lock().expect("lock poisoned").is_empty()
722 }
723}
724
725impl GitArchive for InMemoryGitArchive {
726 async fn archive(&self, request: ArchiveRequest) -> Result<ByteStream, GitArchiveError> {
727 self.requests
728 .lock()
729 .expect("lock poisoned")
730 .push(RecordedArchive {
731 handle: request.handle,
732 name: request.name,
733 format: request.format,
734 commit: request.commit,
735 prefix: request.prefix,
736 });
737
738 Ok(Box::pin(std::io::Cursor::new(b"archive".to_vec())))
739 }
740}
741
742/// A repository's contents, held in memory, for testing use cases and pages.
743///
744/// The counterpart to `DiskGitQuery`. Seeded with exactly what a test needs rather than
745/// pretending to be a git implementation: it answers the questions the port asks and
746/// knows nothing about how a real repository stores them.
747#[derive(Debug, Default, Clone)]
748pub struct InMemoryGitQuery {
749 default_branch: Option<RefName>,
750 /// Keyed `rev\0path`, because a tree only means anything at a revision.
751 trees: HashMap<String, Vec<TreeEntry>>,
752 blobs: HashMap<String, Vec<u8>>,
753 commits: Vec<CommitSummary>,
754 /// Branches and tags, in whatever order a test seeded them — the real adapter makes
755 /// no ordering promise either.
756 refs: Vec<GitRef>,
757 /// Overrides the count derived from the seeded log, for a test that wants a
758 /// repository with more history than it wants to write out.
759 commit_count: Option<u64>,
760 latest_tag: Option<TagSummary>,
761 /// The branches and tags pages' richer rows, seeded separately from `refs`: the two
762 /// answer different questions and a test usually wants only one of them.
763 branch_rows: Vec<BranchRow>,
764 tag_rows: Vec<TagRow>,
765 /// What any grep answers with, regardless of the query — a fake that matched text
766 /// would be a second, worse implementation of `git grep`.
767 grep_hits: Vec<GrepHit>,
768 /// Makes the next grep report the read timeout, which is a page state rather than
769 /// a failure and therefore worth a test.
770 slow_grep: bool,
771 /// The one commit `commit` answers with, whatever revision it is asked for. A fake
772 /// of git's object store is not what these tests are about.
773 detail: Option<CommitDetail>,
774 /// The raw patch `diff` answers with, and whether the fake should call it truncated.
775 diff: Option<RawDiff>,
776 /// The merge base of any two commits, because a fake has no graph to walk.
777 merge_base: Option<ObjectId>,
778 /// What a ref snapshot answers with. Seeded separately from `refs`, and mutable
779 /// through [`InMemoryGitQuery::set_ref_snapshot`], because the whole point of a
780 /// snapshot is that it differs before and after a push.
781 snapshot: Arc<Mutex<Vec<(RefName, ObjectId)>>>,
782
783 /// Keyed the same way trees and blobs are, because a blame only means anything at a
784 /// revision either.
785 blames: HashMap<String, Blame>,
786}
787
788impl InMemoryGitQuery {
789 /// An empty repository: no default branch, so nothing has been pushed.
790 pub fn empty() -> Self {
791 Self::default()
792 }
793
794 /// A repository whose default branch is `main`.
795 pub fn new() -> Self {
796 Self {
797 default_branch: Some(RefName::from_trusted("main")),
798 ..Self::default()
799 }
800 }
801
802 fn key(rev: &RefName, path: &RepoPath) -> String {
803 format!("{}\0{}", rev.as_str(), path.as_str())
804 }
805
806 pub fn with_tree(mut self, rev: &str, path: &str, entries: Vec<TreeEntry>) -> Self {
807 self.trees.insert(
808 Self::key(&RefName::from_trusted(rev), &RepoPath::from_trusted(path)),
809 entries,
810 );
811 self
812 }
813
814 pub fn with_blob(mut self, rev: &str, path: &str, content: impl Into<Vec<u8>>) -> Self {
815 self.blobs.insert(
816 Self::key(&RefName::from_trusted(rev), &RepoPath::from_trusted(path)),
817 content.into(),
818 );
819 self
820 }
821
822 pub fn with_log(mut self, commits: Vec<CommitSummary>) -> Self {
823 self.commits = commits;
824 self
825 }
826
827 pub fn with_branch(self, name: &str) -> Self {
828 self.with_ref(name, RefKind::Branch)
829 }
830
831 pub fn with_tag(self, name: &str) -> Self {
832 self.with_ref(name, RefKind::Tag)
833 }
834
835 pub fn with_commit_count(mut self, count: u64) -> Self {
836 self.commit_count = Some(count);
837 self
838 }
839
840 pub fn with_latest_tag(mut self, name: &str, created_at: SystemTime) -> Self {
841 self.latest_tag = Some(TagSummary {
842 name: RefName::from_trusted(name),
843 created_at,
844 });
845 self
846 }
847
848 /// One row of the branches page. `is_default` is what git's `%(HEAD)` marks.
849 pub fn with_branch_row(
850 mut self,
851 name: &str,
852 is_default: bool,
853 committed_at: SystemTime,
854 ) -> Self {
855 self.branch_rows.push(BranchRow {
856 name: RefName::from_trusted(name),
857 is_default,
858 commit: ObjectId::from_trusted("2".repeat(40)),
859 summary: format!("work on {name}"),
860 committed_at,
861 });
862 self
863 }
864
865 /// One row of the tags page. An annotated tag carries a message; a lightweight one
866 /// has none of its own.
867 pub fn with_tag_row(mut self, name: &str, annotated: bool, created_at: SystemTime) -> Self {
868 self.tag_rows.push(TagRow {
869 name: RefName::from_trusted(name),
870 commit: ObjectId::from_trusted("3".repeat(40)),
871 message: annotated.then(|| format!("release {name}")),
872 annotated,
873 created_at,
874 });
875 self
876 }
877
878 /// Seeds what a search finds. Order is kept, because grouping by file depends on
879 /// git's ordering and a fake that reordered would hide that.
880 pub fn with_grep_hits(mut self, hits: Vec<GrepHit>) -> Self {
881 self.grep_hits = hits;
882 self
883 }
884
885 /// A repository whose grep is killed by the timeout.
886 pub fn with_slow_grep(mut self) -> Self {
887 self.slow_grep = true;
888 self
889 }
890
891 pub fn with_commit(mut self, detail: CommitDetail) -> Self {
892 self.detail = Some(detail);
893 self
894 }
895
896 pub fn with_diff(mut self, patch: impl Into<Vec<u8>>, numstat: impl Into<Vec<u8>>) -> Self {
897 self.diff = Some(RawDiff {
898 numstat: numstat.into(),
899 patch: patch.into(),
900 truncated: false,
901 });
902 self
903 }
904
905 pub fn with_merge_base(mut self, id: &str) -> Self {
906 self.merge_base = Some(ObjectId::from_trusted(id));
907 self
908 }
909
910 pub fn with_blame(mut self, rev: &str, path: &str, blame: Blame) -> Self {
911 self.blames.insert(
912 Self::key(&RefName::from_trusted(rev), &RepoPath::from_trusted(path)),
913 blame,
914 );
915 self
916 }
917
918 /// Seeds the refs a snapshot reports.
919 pub fn with_ref_snapshot(self, refs: &[(&str, &str)]) -> Self {
920 self.set_ref_snapshot(refs);
921 self
922 }
923
924 /// Replaces what a snapshot reports, standing in for a push having landed.
925 ///
926 /// Takes `&self` so a test can move the refs *between* two reads of the same fake,
927 /// which is the sequence the real push path performs.
928 pub fn set_ref_snapshot(&self, refs: &[(&str, &str)]) {
929 *self.snapshot.lock().expect("lock poisoned") = refs
930 .iter()
931 .map(|(name, id)| {
932 (
933 RefName::from_trusted(*name),
934 ObjectId::from_trusted(format!("{id:0>40}")),
935 )
936 })
937 .collect();
938 }
939
940 fn with_ref(mut self, name: &str, kind: RefKind) -> Self {
941 self.refs.push(GitRef {
942 name: RefName::from_trusted(name),
943 kind,
944 });
945 self
946 }
947}
948
949impl GitQuery for InMemoryGitQuery {
950 async fn default_branch(
951 &self,
952 _handle: &OrgName,
953 _name: &RepoName,
954 ) -> Result<Option<RefName>, GitQueryError> {
955 Ok(self.default_branch.clone())
956 }
957
958 async fn resolve(
959 &self,
960 _handle: &OrgName,
961 _name: &RepoName,
962 _rev: &RefName,
963 ) -> Result<Option<ObjectId>, GitQueryError> {
964 Ok(self
965 .default_branch
966 .as_ref()
967 .map(|_| ObjectId::from_trusted("0".repeat(40))))
968 }
969
970 async fn list_tree(
971 &self,
972 _handle: &OrgName,
973 _name: &RepoName,
974 rev: &RefName,
975 path: &RepoPath,
976 ) -> Result<Option<Vec<TreeEntry>>, GitQueryError> {
977 Ok(self.trees.get(&Self::key(rev, path)).cloned())
978 }
979
980 async fn read_blob(
981 &self,
982 _handle: &OrgName,
983 _name: &RepoName,
984 rev: &RefName,
985 path: &RepoPath,
986 max_bytes: u64,
987 ) -> Result<Option<Blob>, GitQueryError> {
988 Ok(self.blobs.get(&Self::key(rev, path)).map(|content| {
989 let size = content.len() as u64;
990
991 Blob {
992 id: ObjectId::from_trusted("1".repeat(40)),
993 size,
994 // The same cap the real adapter applies, so a test can exercise the
995 // too-large path without a megabyte of fixture.
996 content: (size <= max_bytes).then(|| content.clone()),
997 }
998 }))
999 }
1000
1001 async fn log(
1002 &self,
1003 _handle: &OrgName,
1004 _name: &RepoName,
1005 _rev: &RefName,
1006 limit: usize,
1007 ) -> Result<Vec<CommitSummary>, GitQueryError> {
1008 Ok(self.commits.iter().take(limit).cloned().collect())
1009 }
1010
1011 async fn list_refs(
1012 &self,
1013 _handle: &OrgName,
1014 _name: &RepoName,
1015 ) -> Result<Vec<GitRef>, GitQueryError> {
1016 Ok(self.refs.clone())
1017 }
1018
1019 async fn count_commits(
1020 &self,
1021 _handle: &OrgName,
1022 _name: &RepoName,
1023 _rev: &RefName,
1024 ) -> Result<u64, GitQueryError> {
1025 Ok(self.commit_count.unwrap_or(self.commits.len() as u64))
1026 }
1027
1028 async fn latest_tag(
1029 &self,
1030 _handle: &OrgName,
1031 _name: &RepoName,
1032 ) -> Result<Option<TagSummary>, GitQueryError> {
1033 Ok(self.latest_tag.clone())
1034 }
1035
1036 async fn branches(
1037 &self,
1038 _handle: &OrgName,
1039 _name: &RepoName,
1040 ) -> Result<Vec<BranchRow>, GitQueryError> {
1041 Ok(self.branch_rows.clone())
1042 }
1043
1044 async fn tags(
1045 &self,
1046 _handle: &OrgName,
1047 _name: &RepoName,
1048 ) -> Result<Vec<TagRow>, GitQueryError> {
1049 Ok(self.tag_rows.clone())
1050 }
1051
1052 async fn grep(
1053 &self,
1054 _handle: &OrgName,
1055 _name: &RepoName,
1056 _commit: &ObjectId,
1057 _query: &str,
1058 limit: usize,
1059 ) -> Result<Vec<GrepHit>, GitQueryError> {
1060 if self.slow_grep {
1061 return Err(GitQueryError::timed_out(std::time::Duration::from_secs(20)));
1062 }
1063
1064 Ok(self.grep_hits.iter().take(limit).cloned().collect())
1065 }
1066
1067 async fn commit(
1068 &self,
1069 _handle: &OrgName,
1070 _name: &RepoName,
1071 _rev: &RefName,
1072 ) -> Result<Option<CommitDetail>, GitQueryError> {
1073 Ok(self.detail.clone())
1074 }
1075
1076 async fn diff(
1077 &self,
1078 _handle: &OrgName,
1079 _name: &RepoName,
1080 _base: Option<&ObjectId>,
1081 _head: &ObjectId,
1082 _max_bytes: u64,
1083 ) -> Result<RawDiff, GitQueryError> {
1084 Ok(self.diff.clone().unwrap_or_default())
1085 }
1086
1087 async fn merge_base(
1088 &self,
1089 _handle: &OrgName,
1090 _name: &RepoName,
1091 _base: &ObjectId,
1092 _head: &ObjectId,
1093 ) -> Result<Option<ObjectId>, GitQueryError> {
1094 Ok(self.merge_base.clone())
1095 }
1096
1097 async fn log_between(
1098 &self,
1099 _handle: &OrgName,
1100 _name: &RepoName,
1101 _base: Option<&ObjectId>,
1102 _head: &ObjectId,
1103 limit: usize,
1104 ) -> Result<Vec<CommitSummary>, GitQueryError> {
1105 Ok(self.commits.iter().take(limit).cloned().collect())
1106 }
1107
1108 async fn blame(
1109 &self,
1110 _handle: &OrgName,
1111 _name: &RepoName,
1112 rev: &RefName,
1113 path: &RepoPath,
1114 ) -> Result<Option<Blame>, GitQueryError> {
1115 Ok(self.blames.get(&Self::key(rev, path)).cloned())
1116 }
1117
1118 async fn ref_snapshot(
1119 &self,
1120 _handle: &OrgName,
1121 _name: &RepoName,
1122 ) -> Result<Vec<(RefName, ObjectId)>, GitQueryError> {
1123 Ok(self.snapshot.lock().expect("lock poisoned").clone())
1124 }
1125}
1126
1127// --- Importing from elsewhere -----------------------------------------------------
1128
1129/// How long a `git clone --mirror` may run before it is killed.
1130///
1131/// Ten minutes, far above the read timeout in `git_query.rs` and for the opposite
1132/// reason: this is a network transfer of a whole repository with nobody waiting on a
1133/// page, so the cost of being generous is a background task, not a held worker. It is
1134/// bounded at all because a stalled TLS connection to a host that accepts and then says
1135/// nothing would otherwise hold a task for the life of the process.
1136const IMPORT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(600);
1137
1138/// The port git connects to when a URL does not name one. Used only to resolve the
1139/// host — nothing dials this socket directly.
1140const HTTPS_PORT: u16 = 443;
1141
1142/// `git clone --mirror` into the same layout [`DiskGitStorage`] uses.
1143///
1144/// **This adapter is where the second half of the server-side request forgery check
1145/// lives.** [`ImportSource`] refused a literal address that is not on the public
1146/// internet, but `evil.example.com` resolving to `127.0.0.1` passes every syntactic
1147/// rule there is. Only the thing about to open the connection can look, so it looks
1148/// here, immediately before spawning git.
1149#[derive(Debug, Clone)]
1150pub struct DiskGitImport {
1151 data_dir: PathBuf,
1152}
1153
1154impl DiskGitImport {
1155 pub fn new(data_dir: impl Into<PathBuf>) -> Self {
1156 Self {
1157 data_dir: data_dir.into(),
1158 }
1159 }
1160
1161 /// Where a repository lives, matching `DiskGitStorage`'s layout.
1162 fn repo_path(&self, handle: &OrgName, name: &RepoName) -> PathBuf {
1163 self.data_dir
1164 .join(handle.as_str())
1165 .join(format!("{name}.git"))
1166 }
1167}
1168
1169impl GitImport for DiskGitImport {
1170 async fn mirror(
1171 &self,
1172 handle: &OrgName,
1173 name: &RepoName,
1174 source: &ImportSource,
1175 ) -> Result<(), GitImportError> {
1176 resolve_public_host(source.host()).await?;
1177
1178 let path = self.repo_path(handle, name);
1179
1180 // `git clone` refuses a non-empty destination, so an orphan left by an earlier
1181 // attempt surfaces as a failed import rather than being adopted. Checked here
1182 // as well so the message says something a person can act on.
1183 if path.exists() {
1184 return Err(GitImportError::new(
1185 "something is already on disk at this repository's path",
1186 ));
1187 }
1188
1189 // `--mirror` is the whole reason this is one command: it fetches every ref into
1190 // the same name it has on the source, sets `HEAD` to the source's default
1191 // branch, and makes the result bare. A plain `--bare` clone would bring one
1192 // branch and lose every tag.
1193 run_import(
1194 [
1195 OsStr::new("clone"),
1196 OsStr::new("--mirror"),
1197 OsStr::new("--quiet"),
1198 // Everything after this is data. The URL is already https-only and
1199 // space-free, but a destination that could be read as a flag is exactly
1200 // the class of bug `RepoName` exists to prevent, so it is closed here
1201 // too where it costs nothing.
1202 OsStr::new("--"),
1203 OsStr::new(source.as_str()),
1204 path.as_os_str(),
1205 ],
1206 None,
1207 )
1208 .await?;
1209
1210 finish_mirror(&path).await
1211 }
1212}
1213
1214/// Turns a fresh `--mirror` clone into an ordinary Steid repository.
1215///
1216/// Split out from [`DiskGitImport::mirror`] so it can be tested against a fixture: the
1217/// clone itself needs a public HTTPS host, and everything that could plausibly be wrong
1218/// is on this side of it.
1219async fn finish_mirror(path: &std::path::Path) -> Result<(), GitImportError> {
1220 // A mirror keeps its remote and its `remote.origin.mirror` flag, so the result
1221 // would be a repository that fetches from somewhere else on the next `git remote
1222 // update`. Removing it is what turns the clone into an ordinary Steid repository,
1223 // and it takes the mirror refspec with it.
1224 run_import(
1225 [
1226 OsStr::new("remote"),
1227 OsStr::new("remove"),
1228 OsStr::new("origin"),
1229 ],
1230 Some(path),
1231 )
1232 .await?;
1233
1234 // `--mirror` puts branches under `refs/heads` already. This is the belt to that
1235 // braces: a source whose own layout is unusual — itself a mirror of a mirror — can
1236 // leave `refs/remotes`, and a branch nobody can see is worse than one moved to
1237 // where every other page expects it.
1238 promote_remote_refs(path).await
1239}
1240
1241/// Moves anything under `refs/remotes/origin/` to `refs/heads/`, and drops the rest.
1242///
1243/// A no-op for every ordinary mirror, which is why it is written to cost one `git`
1244/// process and stop: `for-each-ref` on a prefix with nothing under it exits 0 with no
1245/// output.
1246///
1247/// Object ids are read alongside the names and written back as ids. `update-ref` takes
1248/// a value, not a reference, and asking it to resolve one is how this was got wrong the
1249/// first time.
1250async fn promote_remote_refs(path: &std::path::Path) -> Result<(), GitImportError> {
1251 let listed = run_import(
1252 [
1253 OsStr::new("for-each-ref"),
1254 OsStr::new("--format=%(objectname) %(refname)"),
1255 OsStr::new("refs/remotes/"),
1256 ],
1257 Some(path),
1258 )
1259 .await?;
1260
1261 let listed = String::from_utf8_lossy(&listed.stdout);
1262
1263 for line in listed.lines() {
1264 let Some((id, reference)) = line.trim().split_once(' ') else {
1265 continue;
1266 };
1267
1268 // `origin/HEAD` is a symbolic pointer, not a branch, and `--mirror` has already
1269 // set the real `HEAD` from the source. Anything under another remote's name is
1270 // somebody else's tracking ref and means nothing here. Both are simply dropped.
1271 if let Some(branch) = reference
1272 .strip_prefix("refs/remotes/origin/")
1273 .filter(|branch| *branch != "HEAD")
1274 {
1275 run_import(
1276 [
1277 OsStr::new("update-ref"),
1278 OsStr::new(&format!("refs/heads/{branch}")),
1279 OsStr::new(id),
1280 ],
1281 Some(path),
1282 )
1283 .await?;
1284 }
1285
1286 run_import(
1287 [
1288 OsStr::new("update-ref"),
1289 OsStr::new("-d"),
1290 OsStr::new(reference),
1291 ],
1292 Some(path),
1293 )
1294 .await?;
1295 }
1296
1297 Ok(())
1298}
1299
1300/// Resolves a host and refuses it unless every address it answers with is on the public
1301/// internet.
1302///
1303/// **Every address, not the first.** A host that answers with one public address and
1304/// one loopback address is a host that can be made to connect to loopback, because
1305/// which one git picks is not ours to decide.
1306///
1307/// This leaves one hole, deliberately and knowingly: git resolves the name again when
1308/// it connects, so a record whose TTL expires between the two lookups can change
1309/// underneath us. Closing that means resolving here and handing git a literal address
1310/// with the hostname forced for TLS and SNI, which is a larger change than this step —
1311/// recorded rather than pretended away.
1312async fn resolve_public_host(host: &str) -> Result<(), GitImportError> {
1313 let refused = || {
1314 GitImportError::new(format!(
1315 "{host} resolves to an address that is not on the public internet"
1316 ))
1317 };
1318
1319 let addresses = tokio::net::lookup_host((host, HTTPS_PORT))
1320 .await
1321 .map_err(|error| GitImportError::new(format!("could not resolve {host}: {error}")))?;
1322
1323 let mut any = false;
1324
1325 for address in addresses {
1326 any = true;
1327
1328 if !is_public(address.ip()) {
1329 return Err(refused());
1330 }
1331 }
1332
1333 if !any {
1334 return Err(GitImportError::new(format!("{host} resolves to nothing")));
1335 }
1336
1337 Ok(())
1338}
1339
1340/// Runs one `git` command on behalf of an import.
1341///
1342/// Separate from [`run_git`] for two reasons rather than one: the timeout is ten
1343/// minutes instead of unbounded, and `GIT_TERMINAL_PROMPT=0` turns a private repository
1344/// into a failed import instead of a subprocess sitting forever on a username prompt
1345/// nobody can answer.
1346async fn run_import<I, S>(args: I, repo: Option<&std::path::Path>) -> Result<Output, GitImportError>
1347where
1348 I: IntoIterator<Item = S>,
1349 S: AsRef<OsStr>,
1350{
1351 let mut command = git_command();
1352
1353 if let Some(repo) = repo {
1354 command.arg("-C").arg(repo);
1355 }
1356
1357 command
1358 .args(args)
1359 .stdin(Stdio::null())
1360 // Without this git blocks on a credential prompt for anything that asks for
1361 // authentication — a private repository, or a typo'd path on a host that
1362 // challenges rather than 404s.
1363 .env("GIT_TERMINAL_PROMPT", "0")
1364 // A killed clone must take the process with it, or a timed-out import keeps
1365 // pulling a repository nobody is waiting for.
1366 .kill_on_drop(true);
1367
1368 let output = match tokio::time::timeout(IMPORT_TIMEOUT, command.output()).await {
1369 Ok(result) => {
1370 result.map_err(|error| GitImportError::new(format!("could not run git: {error}")))?
1371 }
1372 Err(_elapsed) => {
1373 return Err(GitImportError::new(format!(
1374 "the import did not finish within {IMPORT_TIMEOUT:?}"
1375 )));
1376 }
1377 };
1378
1379 if !output.status.success() {
1380 // git's own words, trimmed to the last line: the earlier lines of a clone
1381 // failure are progress, and the last one is the reason.
1382 let stderr = String::from_utf8_lossy(&output.stderr);
1383 let reason = stderr.lines().rev().find(|line| !line.trim().is_empty());
1384
1385 return Err(GitImportError::new(match reason {
1386 Some(reason) => reason.trim().to_owned(),
1387 None => format!("git exited with {}", output.status),
1388 }));
1389 }
1390
1391 Ok(output)
1392}
1393
1394/// Imports recorded in memory, for testing use cases without a network.
1395///
1396/// The counterpart to [`DiskGitImport`], the way [`InMemoryGitStorage`] is to
1397/// [`DiskGitStorage`]. It can be told to fail, because the failure path — recording the
1398/// reason and removing the half-clone — is the half most worth testing.
1399#[derive(Debug, Default, Clone)]
1400pub struct InMemoryGitImport {
1401 requests: Arc<Mutex<Vec<(String, String, String)>>>,
1402 failure: Option<String>,
1403}
1404
1405impl InMemoryGitImport {
1406 pub fn new() -> Self {
1407 Self::default()
1408 }
1409
1410 /// One that always fails with `reason`.
1411 pub fn failing(reason: impl Into<String>) -> Self {
1412 Self {
1413 requests: Arc::default(),
1414 failure: Some(reason.into()),
1415 }
1416 }
1417
1418 /// What was asked for, as `(handle, name, source)`.
1419 pub fn requests(&self) -> Vec<(String, String, String)> {
1420 self.requests.lock().expect("lock poisoned").clone()
1421 }
1422}
1423
1424impl GitImport for InMemoryGitImport {
1425 async fn mirror(
1426 &self,
1427 handle: &OrgName,
1428 name: &RepoName,
1429 source: &ImportSource,
1430 ) -> Result<(), GitImportError> {
1431 self.requests.lock().expect("lock poisoned").push((
1432 handle.to_string(),
1433 name.to_string(),
1434 source.as_str().to_owned(),
1435 ));
1436
1437 match &self.failure {
1438 Some(reason) => Err(GitImportError::new(reason.clone())),
1439 None => Ok(()),
1440 }
1441 }
1442}
1443
1444#[cfg(test)]
1445mod tests {
1446 use std::path::Path;
1447
1448 use tempfile::TempDir;
1449
1450 use tokio::io::AsyncReadExt;
1451
1452 use super::*;
1453 use crate::application::port::ArchiveFormat;
1454
1455 /// The `TempDir` is returned alongside the storage because dropping it deletes the
1456 /// data directory — binding it to `_` would remove the fixture mid-test.
1457 fn storage() -> (TempDir, DiskGitStorage) {
1458 let dir = TempDir::new().expect("temp dir");
1459 let storage = DiskGitStorage::new(dir.path());
1460 (dir, storage)
1461 }
1462
1463 fn handle() -> OrgName {
1464 OrgName::new("jamesgill").expect("valid handle")
1465 }
1466
1467 fn repo_name(value: &str) -> RepoName {
1468 RepoName::new(value).expect("valid repository name")
1469 }
1470
1471 /// Asks git about a repository, so assertions test what git believes rather than
1472 /// what the directory looks like.
1473 fn git_says(path: &Path, args: &[&str]) -> String {
1474 let output = std::process::Command::new("git")
1475 .arg("-C")
1476 .arg(path)
1477 .args(args)
1478 .output()
1479 .expect("git should be on PATH");
1480
1481 assert!(
1482 output.status.success(),
1483 "git {args:?} failed: {}",
1484 String::from_utf8_lossy(&output.stderr)
1485 );
1486
1487 String::from_utf8_lossy(&output.stdout).trim().to_owned()
1488 }
1489
1490 // --- Importing ------------------------------------------------------------------
1491
1492 /// A source repository on disk with two branches and an annotated tag, so a mirror
1493 /// has something to lose.
1494 fn source_repo() -> (TempDir, PathBuf) {
1495 let dir = TempDir::new().expect("temp dir");
1496 let path = dir.path().join("source");
1497
1498 std::fs::create_dir(&path).expect("create");
1499
1500 let run = |args: &[&str]| {
1501 let output = std::process::Command::new("git")
1502 .arg("-C")
1503 .arg(&path)
1504 .args(args)
1505 .env("GIT_CONFIG_GLOBAL", "/dev/null")
1506 .env("GIT_CONFIG_SYSTEM", "/dev/null")
1507 .env("GIT_AUTHOR_NAME", "Ada")
1508 .env("GIT_AUTHOR_EMAIL", "ada@example.com")
1509 .env("GIT_COMMITTER_NAME", "Ada")
1510 .env("GIT_COMMITTER_EMAIL", "ada@example.com")
1511 .output()
1512 .expect("git should be on PATH");
1513 assert!(
1514 output.status.success(),
1515 "git {args:?} failed: {}",
1516 String::from_utf8_lossy(&output.stderr)
1517 );
1518 };
1519
1520 run(&["init", "--quiet", "--initial-branch=main"]);
1521 std::fs::write(path.join("README.md"), "# source\n").expect("write");
1522 run(&["add", "README.md"]);
1523 run(&["commit", "--quiet", "-m", "first"]);
1524 run(&["tag", "-a", "v0.1.0", "-m", "first"]);
1525 run(&["checkout", "--quiet", "-b", "side"]);
1526 std::fs::write(path.join("more.md"), "more\n").expect("write");
1527 run(&["add", "more.md"]);
1528 run(&["commit", "--quiet", "-m", "second"]);
1529 run(&["checkout", "--quiet", "main"]);
1530
1531 (dir, path)
1532 }
1533
1534 /// The shape an import has to leave behind, exercised end to end minus the network.
1535 ///
1536 /// The clone is run against a local path because `ImportSource` allows only public
1537 /// HTTPS, which cannot be stood up in a unit test. Everything the adapter decides
1538 /// after the transfer — the refs, `HEAD`, and the remote — is the same either way,
1539 /// and it is the half that could plausibly be wrong.
1540 #[tokio::test]
1541 async fn a_mirror_lands_as_an_ordinary_bare_repository() {
1542 let (_source_dir, source) = source_repo();
1543 let (dest_dir, _storage) = storage();
1544 let destination = dest_dir.path().join("mirrored.git");
1545
1546 run_import(
1547 [
1548 OsStr::new("clone"),
1549 OsStr::new("--mirror"),
1550 OsStr::new("--quiet"),
1551 OsStr::new("--"),
1552 source.as_os_str(),
1553 destination.as_os_str(),
1554 ],
1555 None,
1556 )
1557 .await
1558 .expect("the clone should succeed");
1559
1560 finish_mirror(&destination)
1561 .await
1562 .expect("the mirror should finish");
1563
1564 // Every branch, under `refs/heads` — where every other page in Steid looks.
1565 let branches = git_says(
1566 &destination,
1567 &["for-each-ref", "--format=%(refname)", "refs/heads/"],
1568 );
1569 assert_eq!(branches, "refs/heads/main\nrefs/heads/side");
1570
1571 // Tags too, annotated ones included.
1572 assert_eq!(
1573 git_says(
1574 &destination,
1575 &["for-each-ref", "--format=%(refname)", "refs/tags/"]
1576 ),
1577 "refs/tags/v0.1.0"
1578 );
1579
1580 // Nothing left under `refs/remotes`, and no remote to fetch from.
1581 assert_eq!(
1582 git_says(
1583 &destination,
1584 &["for-each-ref", "--format=%(refname)", "refs/remotes/"]
1585 ),
1586 ""
1587 );
1588 assert_eq!(git_says(&destination, &["remote"]), "");
1589
1590 // `HEAD` follows the source's default branch, so the landing page opens on it.
1591 assert_eq!(
1592 git_says(&destination, &["symbolic-ref", "HEAD"]),
1593 "refs/heads/main"
1594 );
1595 assert_eq!(
1596 git_says(&destination, &["rev-parse", "--is-bare-repository"]),
1597 "true"
1598 );
1599 }
1600
1601 /// A source whose branches arrived under `refs/remotes` — the case `--mirror`
1602 /// normally makes impossible, which is exactly why nothing else would catch it.
1603 #[tokio::test]
1604 async fn branches_left_under_refs_remotes_are_moved_to_refs_heads() {
1605 let (_source_dir, source) = source_repo();
1606 let (dest_dir, _storage) = storage();
1607 let destination = dest_dir.path().join("remotes.git");
1608
1609 // A plain `--bare` clone with a fetch refspec that writes remote-tracking refs,
1610 // which is what a non-mirror clone of a mirror can leave.
1611 run_import(
1612 [
1613 OsStr::new("clone"),
1614 OsStr::new("--bare"),
1615 OsStr::new("--quiet"),
1616 OsStr::new("--"),
1617 source.as_os_str(),
1618 destination.as_os_str(),
1619 ],
1620 None,
1621 )
1622 .await
1623 .expect("clone");
1624
1625 // Stage the shape by hand: a branch only under `refs/remotes`.
1626 run_import(
1627 [
1628 OsStr::new("update-ref"),
1629 OsStr::new("refs/remotes/origin/side"),
1630 OsStr::new("refs/heads/main"),
1631 ],
1632 Some(&destination),
1633 )
1634 .await
1635 .expect("stage a remote-tracking ref");
1636 run_import(
1637 [
1638 OsStr::new("symbolic-ref"),
1639 OsStr::new("refs/remotes/origin/HEAD"),
1640 OsStr::new("refs/remotes/origin/side"),
1641 ],
1642 Some(&destination),
1643 )
1644 .await
1645 .expect("stage origin/HEAD");
1646
1647 finish_mirror(&destination).await.expect("finish");
1648
1649 let branches = git_says(
1650 &destination,
1651 &["for-each-ref", "--format=%(refname)", "refs/heads/"],
1652 );
1653 assert!(
1654 branches.contains("refs/heads/side"),
1655 "expected the remote-tracking branch to become a branch, got {branches:?}"
1656 );
1657 assert_eq!(
1658 git_says(
1659 &destination,
1660 &["for-each-ref", "--format=%(refname)", "refs/remotes/"]
1661 ),
1662 "",
1663 "origin/HEAD is a pointer, not a branch, and must not survive either"
1664 );
1665 }
1666
1667 /// The DNS half of the server-side request forgery check, which `ImportSource`
1668 /// cannot make: `localhost` is a name, and only resolving it says where it goes.
1669 #[tokio::test]
1670 async fn a_host_that_resolves_to_loopback_is_refused() {
1671 let error = resolve_public_host("localhost")
1672 .await
1673 .expect_err("localhost must never be dialled");
1674
1675 assert!(
1676 error.message().contains("not on the public internet"),
1677 "{error}"
1678 );
1679 }
1680
1681 #[tokio::test]
1682 async fn a_host_that_does_not_resolve_is_a_failed_import_not_a_panic() {
1683 let error = resolve_public_host("no-such-host.invalid")
1684 .await
1685 .expect_err("`.invalid` never resolves");
1686
1687 assert!(error.message().contains("no-such-host.invalid"), "{error}");
1688 }
1689
1690 /// git's last line is the reason; the lines before it are progress.
1691 #[tokio::test]
1692 async fn a_failed_git_command_carries_gits_own_last_word() {
1693 let (dir, _storage) = storage();
1694
1695 let error = run_import(
1696 [OsStr::new("rev-parse"), OsStr::new("HEAD")],
1697 Some(dir.path()),
1698 )
1699 .await
1700 .expect_err("an empty directory is not a repository");
1701
1702 assert!(
1703 error.message().contains("not a git repository"),
1704 "expected git's own words, got {error}"
1705 );
1706 }
1707
1708 #[tokio::test]
1709 async fn an_import_refuses_a_path_that_is_already_occupied() {
1710 let (dir, storage) = storage();
1711 let importer = DiskGitImport::new(dir.path());
1712
1713 storage
1714 .init_bare(&handle(), &repo_name("taken"))
1715 .await
1716 .expect("seed");
1717
1718 let error = importer
1719 .mirror(
1720 &handle(),
1721 &repo_name("taken"),
1722 &ImportSource::new("https://example.com/taken.git").expect("valid"),
1723 )
1724 .await
1725 .expect_err("must not adopt what is already there");
1726
1727 assert!(error.message().contains("already on disk"), "{error}");
1728 }
1729
1730 #[tokio::test]
1731 async fn the_in_memory_importer_records_what_it_was_asked_for() {
1732 let importer = InMemoryGitImport::new();
1733 let source = ImportSource::new("https://example.com/thing.git").expect("valid");
1734
1735 importer
1736 .mirror(&handle(), &repo_name("thing"), &source)
1737 .await
1738 .expect("succeeds");
1739
1740 assert_eq!(
1741 importer.requests(),
1742 vec![(
1743 "jamesgill".to_owned(),
1744 "thing".to_owned(),
1745 "https://example.com/thing.git".to_owned()
1746 )]
1747 );
1748 }
1749
1750 #[tokio::test]
1751 async fn a_created_repository_keeps_a_reflog() {
1752 // Without this, `REMOTE_USER` has nowhere to land: a bare repository logs no ref
1753 // updates by default, so who moved a branch is unknowable even though Steid knew.
1754 let dir = TempDir::new().expect("temp dir");
1755 let storage = DiskGitStorage::new(dir.path());
1756
1757 storage
1758 .init_bare(&handle(), &repo_name("steid"))
1759 .await
1760 .expect("should create");
1761
1762 let config = std::fs::read_to_string(
1763 storage
1764 .repo_path(&handle(), &repo_name("steid"))
1765 .join("config"),
1766 )
1767 .expect("read config");
1768
1769 assert!(
1770 config.to_lowercase().contains("logallrefupdates = true"),
1771 "a bare repository needs reflogs turned on: {config}"
1772 );
1773 }
1774
1775 #[tokio::test]
1776 async fn init_bare_creates_a_bare_repository() {
1777 let (_dir, storage) = storage();
1778
1779 storage
1780 .init_bare(&handle(), &repo_name("steid"))
1781 .await
1782 .expect("should create");
1783
1784 let path = storage.repo_path(&handle(), &repo_name("steid"));
1785 assert!(path.is_dir(), "expected a repository at {path:?}");
1786 assert_eq!(
1787 git_says(&path, &["rev-parse", "--is-bare-repository"]),
1788 "true"
1789 );
1790 }
1791
1792 #[tokio::test]
1793 async fn a_new_repository_is_empty() {
1794 // Empty, like GitHub: no initial commit and no branch yet.
1795 let (_dir, storage) = storage();
1796 storage
1797 .init_bare(&handle(), &repo_name("steid"))
1798 .await
1799 .expect("should create");
1800
1801 let path = storage.repo_path(&handle(), &repo_name("steid"));
1802
1803 assert_eq!(git_says(&path, &["for-each-ref"]), "");
1804 }
1805
1806 #[tokio::test]
1807 async fn a_new_repository_defaults_to_main() {
1808 // Pinned so the host's `init.defaultBranch` cannot decide this. It currently
1809 // agrees on this machine, which is exactly why a drift would go unnoticed.
1810 let (_dir, storage) = storage();
1811 storage
1812 .init_bare(&handle(), &repo_name("steid"))
1813 .await
1814 .expect("should create");
1815
1816 let path = storage.repo_path(&handle(), &repo_name("steid"));
1817
1818 assert_eq!(
1819 git_says(&path, &["symbolic-ref", "HEAD"]),
1820 "refs/heads/main"
1821 );
1822 }
1823
1824 #[tokio::test]
1825 async fn no_sample_hooks_are_installed() {
1826 // Pins `--template=`. A default init seeds sixteen `.sample` files.
1827 let (_dir, storage) = storage();
1828 storage
1829 .init_bare(&handle(), &repo_name("steid"))
1830 .await
1831 .expect("should create");
1832
1833 let hooks = storage
1834 .repo_path(&handle(), &repo_name("steid"))
1835 .join("hooks");
1836
1837 let samples = std::fs::read_dir(&hooks)
1838 .map(|entries| entries.count())
1839 .unwrap_or(0);
1840 assert_eq!(samples, 0, "expected no templated hooks in {hooks:?}");
1841 }
1842
1843 #[tokio::test]
1844 async fn init_bare_creates_the_handle_directory() {
1845 let (dir, storage) = storage();
1846 assert!(!dir.path().join("jamesgill").exists());
1847
1848 storage
1849 .init_bare(&handle(), &repo_name("steid"))
1850 .await
1851 .expect("should create");
1852
1853 assert!(dir.path().join("jamesgill").is_dir());
1854 }
1855
1856 #[tokio::test]
1857 async fn one_handle_can_own_several_repositories() {
1858 let (_dir, storage) = storage();
1859
1860 for name in ["steid", "foo.js", ".github"] {
1861 storage
1862 .init_bare(&handle(), &repo_name(name))
1863 .await
1864 .unwrap_or_else(|error| panic!("{name} should create: {error}"));
1865 }
1866
1867 for name in ["steid", "foo.js", ".github"] {
1868 assert!(storage.repo_path(&handle(), &repo_name(name)).is_dir());
1869 }
1870 }
1871
1872 #[tokio::test]
1873 async fn init_bare_refuses_a_repository_that_already_exists() {
1874 let (_dir, storage) = storage();
1875 storage
1876 .init_bare(&handle(), &repo_name("steid"))
1877 .await
1878 .expect("should create");
1879
1880 let error = storage
1881 .init_bare(&handle(), &repo_name("steid"))
1882 .await
1883 .expect_err("should refuse");
1884
1885 assert!(matches!(error, GitStorageError::AlreadyExists));
1886 }
1887
1888 #[tokio::test]
1889 async fn a_refused_init_leaves_the_existing_repository_alone() {
1890 // git would happily re-initialise in place. The point of refusing is that
1891 // whatever is already there is not touched.
1892 let (_dir, storage) = storage();
1893 storage
1894 .init_bare(&handle(), &repo_name("steid"))
1895 .await
1896 .expect("should create");
1897
1898 let path = storage.repo_path(&handle(), &repo_name("steid"));
1899 let marker = path.join("objects").join("marker");
1900 std::fs::write(&marker, b"existing data").expect("write marker");
1901
1902 let _ = storage.init_bare(&handle(), &repo_name("steid")).await;
1903
1904 assert_eq!(
1905 std::fs::read(&marker).expect("marker should survive"),
1906 b"existing data"
1907 );
1908 }
1909
1910 #[tokio::test]
1911 async fn repo_path_creates_nothing() {
1912 let (dir, storage) = storage();
1913
1914 let path = storage.repo_path(&handle(), &repo_name("never-created"));
1915
1916 assert!(!path.exists());
1917 assert_eq!(
1918 std::fs::read_dir(dir.path())
1919 .expect("data dir should exist")
1920 .count(),
1921 0,
1922 "repo_path must be pure"
1923 );
1924 }
1925
1926 #[tokio::test]
1927 async fn repo_path_lands_under_the_data_directory() {
1928 let (dir, storage) = storage();
1929
1930 let path = storage.repo_path(&handle(), &repo_name("steid"));
1931
1932 assert_eq!(path, dir.path().join("jamesgill").join("steid.git"));
1933 }
1934
1935 #[tokio::test]
1936 async fn remove_deletes_the_repository() {
1937 let (_dir, storage) = storage();
1938 storage
1939 .init_bare(&handle(), &repo_name("steid"))
1940 .await
1941 .expect("should create");
1942
1943 storage
1944 .remove(&handle(), &repo_name("steid"))
1945 .await
1946 .expect("should remove");
1947
1948 assert!(!storage.repo_path(&handle(), &repo_name("steid")).exists());
1949 }
1950
1951 #[tokio::test]
1952 async fn removing_what_is_not_there_succeeds() {
1953 // Compensation runs when a create failed, which may be before anything landed.
1954 let (_dir, storage) = storage();
1955
1956 storage
1957 .remove(&handle(), &repo_name("never-created"))
1958 .await
1959 .expect("should succeed with nothing to do");
1960 }
1961
1962 #[tokio::test]
1963 async fn a_compensated_create_can_be_retried() {
1964 // The whole point of `remove`: create, fail to record it, undo, try again.
1965 let (_dir, storage) = storage();
1966
1967 storage
1968 .init_bare(&handle(), &repo_name("steid"))
1969 .await
1970 .expect("should create");
1971 storage
1972 .remove(&handle(), &repo_name("steid"))
1973 .await
1974 .expect("should remove");
1975 storage
1976 .init_bare(&handle(), &repo_name("steid"))
1977 .await
1978 .expect("should create again");
1979 }
1980
1981 #[tokio::test]
1982 async fn removing_one_repository_leaves_its_neighbours() {
1983 let (_dir, storage) = storage();
1984 storage
1985 .init_bare(&handle(), &repo_name("steid"))
1986 .await
1987 .expect("should create");
1988 storage
1989 .init_bare(&handle(), &repo_name("keeper"))
1990 .await
1991 .expect("should create");
1992
1993 storage
1994 .remove(&handle(), &repo_name("steid"))
1995 .await
1996 .expect("should remove");
1997
1998 assert!(storage.repo_path(&handle(), &repo_name("keeper")).is_dir());
1999 }
2000
2001 #[tokio::test]
2002 async fn a_failing_git_invocation_carries_gits_own_message() {
2003 let error = run_git(["not-a-real-subcommand"])
2004 .await
2005 .expect_err("should fail");
2006
2007 let message = error.to_string();
2008 assert!(
2009 message.contains("not-a-real-subcommand"),
2010 "expected git's own words, got: {message}"
2011 );
2012 }
2013
2014 // --- GitHttpBackend --------------------------------------------------------
2015
2016 /// A data directory holding one bare repository at `acme/steid.git`.
2017 async fn backend() -> (TempDir, GitHttpBackend) {
2018 let dir = TempDir::new().expect("temp dir");
2019 let storage = DiskGitStorage::new(dir.path());
2020
2021 let acme = OrgName::new("acme").expect("valid handle");
2022 storage
2023 .init_bare(&acme, &repo_name("steid"))
2024 .await
2025 .expect("init bare");
2026
2027 let backend = GitHttpBackend::new(dir.path());
2028 (dir, backend)
2029 }
2030
2031 fn advertisement(path_info: &str) -> GitRequest {
2032 GitRequest {
2033 method: GitMethod::Get,
2034 path_info: path_info.to_owned(),
2035 query: "service=git-upload-pack".to_owned(),
2036 content_type: None,
2037 content_encoding: None,
2038 content_length: None,
2039 git_protocol: None,
2040 allow_receive_pack: false,
2041 remote_user: None,
2042 body: Box::pin(tokio::io::empty()),
2043 }
2044 }
2045
2046 async fn drain(response: GitResponse) -> Vec<u8> {
2047 let mut body = response.body;
2048 let mut bytes = Vec::new();
2049 body.read_to_end(&mut bytes).await.expect("read body");
2050 bytes
2051 }
2052
2053 #[tokio::test]
2054 async fn the_backend_advertises_refs() {
2055 let (_dir, backend) = backend().await;
2056
2057 let response = backend
2058 .serve(advertisement("/acme/steid.git/info/refs"))
2059 .await
2060 .expect("should serve");
2061
2062 assert_eq!(response.status, 200);
2063 assert!(
2064 response
2065 .headers
2066 .iter()
2067 .any(|(name, value)| name == "Content-Type"
2068 && value == "application/x-git-upload-pack-advertisement"),
2069 "git sets its own content type and we forward it: {:?}",
2070 response.headers
2071 );
2072
2073 // The pkt-line the smart protocol opens with. Getting this from git rather than
2074 // writing it is the whole reason the backend is a subprocess.
2075 let body = drain(response).await;
2076 assert!(
2077 body.starts_with(b"001e# service=git-upload-pack\n"),
2078 "unexpected advertisement: {:?}",
2079 String::from_utf8_lossy(&body[..body.len().min(40)])
2080 );
2081 }
2082
2083 #[tokio::test]
2084 async fn a_missing_repository_is_reported_as_404_not_as_a_failure() {
2085 // Failure arrives in the CGI stream, not the exit code: git exits 0 here and
2086 // says 404 in a header. Keying off the exit code instead would answer 200.
2087 let (_dir, backend) = backend().await;
2088
2089 let response = backend
2090 .serve(advertisement("/acme/nothing-here.git/info/refs"))
2091 .await
2092 .expect("serving should not itself fail");
2093
2094 assert_eq!(response.status, 404);
2095 }
2096
2097 #[tokio::test]
2098 async fn the_status_header_is_translated_rather_than_forwarded() {
2099 let (_dir, backend) = backend().await;
2100
2101 let response = backend
2102 .serve(advertisement("/acme/nothing-here.git/info/refs"))
2103 .await
2104 .expect("should serve");
2105
2106 assert!(
2107 !response
2108 .headers
2109 .iter()
2110 .any(|(name, _)| name.eq_ignore_ascii_case("status")),
2111 "Status: is CGI's, and means nothing to an HTTP client: {:?}",
2112 response.headers
2113 );
2114 }
2115
2116 #[tokio::test]
2117 async fn the_protocol_version_reaches_upload_pack() {
2118 // Protocol v2 answers an advertisement with a capability list rather than refs.
2119 // If `HTTP_GIT_PROTOCOL` is dropped the exchange silently falls back to v0, which
2120 // still works — so nothing fails, it just quietly gets worse.
2121 let (_dir, backend) = backend().await;
2122
2123 let mut request = advertisement("/acme/steid.git/info/refs");
2124 request.git_protocol = Some("version=2".to_owned());
2125
2126 let body = drain(backend.serve(request).await.expect("should serve")).await;
2127
2128 assert!(
2129 String::from_utf8_lossy(&body).contains("version 2"),
2130 "expected a v2 capability advertisement: {:?}",
2131 String::from_utf8_lossy(&body[..body.len().min(80)])
2132 );
2133 }
2134
2135 #[tokio::test]
2136 async fn the_in_memory_protocol_records_what_it_was_asked() {
2137 let protocol = InMemoryGitProtocol::new();
2138
2139 protocol
2140 .serve(advertisement("/acme/steid.git/info/refs"))
2141 .await
2142 .expect("should serve");
2143
2144 assert_eq!(
2145 protocol.requests(),
2146 vec![RecordedGitRequest {
2147 method: GitMethod::Get,
2148 path_info: "/acme/steid.git/info/refs".to_owned(),
2149 query: "service=git-upload-pack".to_owned(),
2150 git_protocol: None,
2151 content_encoding: None,
2152 allow_receive_pack: false,
2153 remote_user: None,
2154 }]
2155 );
2156 assert!(protocol.was_called());
2157 }
2158
2159 // --- git archive ---------------------------------------------------------------
2160
2161 /// A bare repository with one commit in it, packed the way a real one is.
2162 ///
2163 /// Built by pushing from a working copy rather than by writing objects directly,
2164 /// for the same reason `git_query`'s fixture is: it is what actually happens.
2165 fn archivable() -> (TempDir, DiskGitArchive, ObjectId) {
2166 let dir = TempDir::new().expect("temp dir");
2167 let storage = DiskGitStorage::new(dir.path());
2168 let repo = storage.repo_path(&handle(), &repo_name("steid"));
2169 let work = dir.path().join("work");
2170
2171 let git = |at: &Path, args: &[&str]| {
2172 let output = std::process::Command::new("git")
2173 .arg("-C")
2174 .arg(at)
2175 .args(args)
2176 .env("GIT_CONFIG_GLOBAL", "/dev/null")
2177 .env("GIT_CONFIG_SYSTEM", "/dev/null")
2178 .env("GIT_AUTHOR_NAME", "Ada Lovelace")
2179 .env("GIT_AUTHOR_EMAIL", "ada@example.com")
2180 .env("GIT_COMMITTER_NAME", "Ada Lovelace")
2181 .env("GIT_COMMITTER_EMAIL", "ada@example.com")
2182 .output()
2183 .expect("git should be on PATH");
2184
2185 assert!(
2186 output.status.success(),
2187 "git {args:?} failed: {}",
2188 String::from_utf8_lossy(&output.stderr)
2189 );
2190
2191 String::from_utf8_lossy(&output.stdout).trim().to_owned()
2192 };
2193
2194 std::fs::create_dir_all(&work).expect("create work tree");
2195 git(
2196 dir.path(),
2197 &[
2198 "init",
2199 "--bare",
2200 "--quiet",
2201 "--template=",
2202 "--initial-branch=main",
2203 "--",
2204 repo.to_str().expect("utf-8 fixture path"),
2205 ],
2206 );
2207 git(&work, &["init", "--quiet", "-b", "main"]);
2208 std::fs::write(work.join("README.md"), b"hello\n").expect("write");
2209 git(&work, &["add", "-A"]);
2210 git(&work, &["commit", "--quiet", "-m", "first"]);
2211 git(
2212 &work,
2213 &["push", "--quiet", repo.to_str().expect("utf-8"), "main"],
2214 );
2215
2216 let head = git(&repo, &["rev-parse", "main"]);
2217 let archives = DiskGitArchive::new(dir.path());
2218
2219 (
2220 dir,
2221 archives,
2222 ObjectId::new(head).expect("a real object id"),
2223 )
2224 }
2225
2226 async fn packed(format: ArchiveFormat) -> Vec<u8> {
2227 let (dir, archives, commit) = archivable();
2228
2229 let mut stream = archives
2230 .archive(ArchiveRequest {
2231 handle: handle(),
2232 name: repo_name("steid"),
2233 format,
2234 commit,
2235 prefix: "steid-main/".to_owned(),
2236 })
2237 .await
2238 .expect("should pack");
2239
2240 let mut bytes = Vec::new();
2241 stream.read_to_end(&mut bytes).await.expect("should stream");
2242
2243 // Held until the bytes are read: dropping the fixture deletes the repository
2244 // git is still reading from.
2245 drop(dir);
2246
2247 bytes
2248 }
2249
2250 #[tokio::test]
2251 async fn a_tarball_carries_the_prefix_directory() {
2252 let bytes = packed(ArchiveFormat::TarGz).await;
2253
2254 // The gzip magic number, so the format flag is doing something rather than
2255 // silently producing an uncompressed tar.
2256 assert_eq!(&bytes[..2], &[0x1f, 0x8b], "expected gzip");
2257 assert!(bytes.len() > 100, "expected a real archive");
2258 }
2259
2260 #[tokio::test]
2261 async fn a_zip_is_a_zip() {
2262 let bytes = packed(ArchiveFormat::Zip).await;
2263
2264 assert_eq!(&bytes[..2], b"PK", "expected a zip");
2265 // The prefix is stored as part of every entry name, uncompressed in the
2266 // central directory, so it is readable in the raw bytes.
2267 assert!(
2268 bytes.windows(11).any(|window| window == b"steid-main/"),
2269 "expected the prefix directory in the archive"
2270 );
2271 }
2272}