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