From faaa6f300ce6799bf0f1cb87d856af41da6626b9 Mon Sep 17 00:00:00 2001 From: Mari Date: Mon, 16 Nov 2026 21:08:24 +0000 Subject: [PATCH 1/7] add unit, integration and e2e tests for backend --- .config/nextest.toml | 16 + .github/workflows/git-tests.yml | 69 +++ .github/workflows/rust.yml | 4 +- Cargo.lock | 70 ++- README.md | 2 + docs/contributing/setup.mdx | 33 +- docs/development.mdx | 2 +- docs/self-hosting/configuration.mdx | 2 + gitarena/Cargo.toml | 6 + gitarena/src/database.rs | 25 +- gitarena/src/git/basic_auth.rs | 66 +++ gitarena/src/git/capabilities.rs | 34 ++ gitarena/src/git/history.rs | 107 ++++ gitarena/src/git/io/band.rs | 13 + gitarena/src/git/io/reader.rs | 57 ++ gitarena/src/git/io/writer.rs | 143 +++++ gitarena/src/git/ls_refs.rs | 168 ++++++ gitarena/src/git/mod.rs | 20 + gitarena/src/git/ref_update.rs | 114 ++++ gitarena/src/main.rs | 22 +- gitarena/src/queue.rs | 3 +- gitarena/src/ssh/key.rs | 73 +++ gitarena/src/ssh/server.rs | 148 +++++ gitarena/src/utils/oid.rs | 35 ++ gitarena/tests/common/mod.rs | 882 ++++++++++++++++++++++++++++ gitarena/tests/common/scenarios.rs | 313 ++++++++++ gitarena/tests/git_bug.rs | 369 ++++++++++++ gitarena/tests/git_bug_e2e.rs | 270 +++++++++ gitarena/tests/git_e2e.rs | 215 +++++++ gitarena/tests/git_http.rs | 216 +++++++ gitarena/tests/git_ssh.rs | 179 ++++++ 31 files changed, 3649 insertions(+), 27 deletions(-) create mode 100644 .config/nextest.toml create mode 100644 .github/workflows/git-tests.yml create mode 100644 gitarena/tests/common/mod.rs create mode 100644 gitarena/tests/common/scenarios.rs create mode 100644 gitarena/tests/git_bug.rs create mode 100644 gitarena/tests/git_bug_e2e.rs create mode 100644 gitarena/tests/git_e2e.rs create mode 100644 gitarena/tests/git_http.rs create mode 100644 gitarena/tests/git_ssh.rs diff --git a/.config/nextest.toml b/.config/nextest.toml new file mode 100644 index 00000000..505dc059 --- /dev/null +++ b/.config/nextest.toml @@ -0,0 +1,16 @@ +[profile.default] +slow-timeout = { period = "60s", terminate-after = 3 } + +[test-groups] +# every test boots its own server with a handful of Postgres connections, so this keeps the total under `max_connections` +git-server = { max-threads = 8 } + +[[profile.default.overrides]] +filter = "package(gitarena) & kind(test)" +test-group = "git-server" + +[profile.ci] +fail-fast = false + +[profile.ci.junit] +path = "junit.xml" diff --git a/.github/workflows/git-tests.yml b/.github/workflows/git-tests.yml new file mode 100644 index 00000000..8a8d8956 --- /dev/null +++ b/.github/workflows/git-tests.yml @@ -0,0 +1,69 @@ +name: Git Tests + +on: + - push + - pull_request + +permissions: + contents: read + +env: + CARGO_TERM_COLOR: always + DATABASE_URL: postgres://gitarena:gitarena@localhost:5432/gitarena + +jobs: + git-tests: + runs-on: ubuntu-latest + services: + postgres: + image: postgres:18.6-trixie + env: + POSTGRES_USER: gitarena + POSTGRES_PASSWORD: gitarena + POSTGRES_DB: gitarena + ports: + - 5432:5432 + options: >- + --health-cmd "pg_isready -U gitarena" + --health-interval 5s + --health-timeout 5s + --health-retries 10 + steps: + - name: checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: install rust toolchain + uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # v1 + with: + toolchain: stable + + - name: rust cache + uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + + - name: install cargo-nextest + uses: taiki-e/install-action@ab49d3c64680143e184118bed66a46419fc15519 # v2.90.5 + with: + tool: cargo-nextest + + - name: install git-bug v0.11.0 + run: | + curl --proto "=https" --tlsv1.2 -sSf -L https://github.com/git-bug/git-bug/releases/download/v0.11.0/git-bug_linux_amd64 -o /usr/local/bin/git-bug + chmod +x /usr/local/bin/git-bug + + - name: tool versions + run: | + git --version + ssh -V + git-bug version + + - name: test + run: cargo nextest run --locked -p gitarena --profile ci -E 'kind(test)' + + - name: upload test report + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: git-tests-junit + path: target/nextest/ci/junit.xml diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 5ebfed3e..098e7595 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -38,7 +38,9 @@ jobs: chmod +x /usr/local/bin/git-bug - name: test - run: cargo test --verbose + run: | + cargo test --verbose --workspace --exclude gitarena + cargo test --verbose -p gitarena --bins - name: clippy uses: auguwu/clippy-action@9817d076b82df0194935be9db6154c56ac07b317 # 1.5.0 diff --git a/Cargo.lock b/Cargo.lock index 3ac23f48..ce542a29 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -203,7 +203,7 @@ dependencies = [ "bytes", "bytestring", "cfg-if", - "cookie", + "cookie 0.16.2", "derive_more", "encoding_rs", "foldhash 0.2.0", @@ -732,7 +732,7 @@ dependencies = [ "base64 0.22.1", "bytes", "cfg-if", - "cookie", + "cookie 0.16.2", "derive_more", "futures-core", "futures-util", @@ -1524,6 +1524,35 @@ dependencies = [ "version_check", ] +[[package]] +name = "cookie" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a373e3602691c3cdea496d2f0ee5935151e6168fe87739483c463db1b2f2f87" +dependencies = [ + "percent-encoding", + "time", + "version_check", +] + +[[package]] +name = "cookie_store" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b2c103cf610ec6cae3da84a766285b42fd16aad564758459e6ecf128c75206" +dependencies = [ + "cookie 0.18.2", + "document-features", + "idna", + "log", + "publicsuffix", + "serde", + "serde_derive", + "serde_json", + "time", + "url", +] + [[package]] name = "core-foundation" version = "0.9.4" @@ -2157,6 +2186,15 @@ dependencies = [ "syn 2.0.106", ] +[[package]] +name = "document-features" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" +dependencies = [ + "litrs", +] + [[package]] name = "dotenvy" version = "0.15.7" @@ -2858,8 +2896,10 @@ dependencies = [ "opentelemetry-otlp", "opentelemetry-semantic-conventions", "opentelemetry_sdk", + "pretty_assertions", "qstring", "rand 0.10.3", + "reqwest 0.12.28", "russh", "rust-argon2", "rustls", @@ -2871,6 +2911,8 @@ dependencies = [ "strum", "sysinfo", "tar-codec", + "tempfile", + "test-with", "time", "tokei 15.0.0", "tokio", @@ -6216,6 +6258,12 @@ version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "241eaef5fd12c88705a01fc1066c48c4b36e0dd4377dcdc7ec3942cea7a69956" +[[package]] +name = "litrs" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11d3d7f243d5c5a8b9bb5d6dd2b1602c0cb0b9db1621bafc7ed66e35ff9fe092" + [[package]] name = "local-channel" version = "0.1.5" @@ -7547,6 +7595,22 @@ dependencies = [ "prost", ] +[[package]] +name = "psl-types" +version = "2.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33cb294fe86a74cbcf50d4445b37da762029549ebeea341421c7c70370f86cac" + +[[package]] +name = "publicsuffix" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f42ea446cab60335f76979ec15e12619a2165b5ae2c12166bef27d283a9fadf" +dependencies = [ + "idna", + "psl-types", +] + [[package]] name = "qstring" version = "0.7.2" @@ -7846,6 +7910,8 @@ checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" dependencies = [ "base64 0.22.1", "bytes", + "cookie 0.18.2", + "cookie_store", "futures-core", "futures-util", "h2 0.4.20", diff --git a/README.md b/README.md index eeef66c4..6433510c 100644 --- a/README.md +++ b/README.md @@ -140,6 +140,8 @@ In order to run the GitArena backend, the following environment variable needs t Optional environment variables: - `MAX_POOL_CONNECTIONS`: Max amount of connections the Postgres connection pool should keep open and ready to use. +- `MAX_QUEUE_POOL_CONNECTIONS`: Max amount of Postgres connections the background job queue should use +- `DISABLE_UPDATE_CHECK`: Set to any value to skip checking for a new GitArena version at startup - `NO_STDOUT_LOG`: Set to any value to only write logs to the log file (and Otel, if configured) - `OTEL_SERVICE_NAME`: Service name to be used for metrics, traces and logs diff --git a/docs/contributing/setup.mdx b/docs/contributing/setup.mdx index d5cb8abf..32a7a826 100644 --- a/docs/contributing/setup.mdx +++ b/docs/contributing/setup.mdx @@ -106,15 +106,38 @@ Then restart the backend. Zoekt indexing also needs `zoekt-git-index` on the hos ## Running tests +Unit tests need no services: + ```bash -# All tests -cargo test +# Every crate except the gitarena integration tests +cargo test --workspace --exclude gitarena + +# gitarena unit tests +cargo test -p gitarena --bins +``` + +### Git integration tests + +The tests in `gitarena/tests/` boot a real GitArena binary per test and drive it with `git`, `ssh`, and `git-bug` over Smart HTTP and SSH. Each test gets its own database, created by `#[sqlx::test]` from `DATABASE_URL`, so the user needs permission to create databases. Never point `DATABASE_URL` at a shared database for these tests. + +They need on your `PATH`: + +- `git` and OpenSSH (`ssh`, `ssh-keygen`, `ssh-agent`, `ssh-add`, `ssh-keyscan`) +- [git-bug](https://github.com/git-bug/git-bug) v0.11.0 for `git_bug.rs` and `git_bug_e2e.rs`. Without it those tests are ignored. The check runs at compile time, so rebuild after installing or removing it. +- [cargo-nextest](https://nexte.st), which applies the timeouts and concurrency limit from `.config/nextest.toml` + +```bash +docker compose -f docker-compose.dev.yml up -d postgres +export DATABASE_URL=postgres://gitarena:gitarena@localhost/gitarena + +# All git tests +cargo nextest run -p gitarena -E 'kind(test)' -# A specific crate -cargo test -p gitarena +# A single file +cargo nextest run -p gitarena --test git_ssh # A specific test by name -cargo test -p gitarena your_test_name +cargo nextest run -p gitarena your_test_name ``` ## Before submitting a PR diff --git a/docs/development.mdx b/docs/development.mdx index 282246b9..dbaa1f52 100644 --- a/docs/development.mdx +++ b/docs/development.mdx @@ -87,7 +87,7 @@ cargo check | `cargo build` | Debug build | | `cargo build --release` | Release build with LTO | | `cargo build -p gitarena` | Build a single crate | -| `cargo test` | Run all tests | +| `cargo test` | Run all tests (the git integration tests need PostgreSQL, see [running tests](/contributing/setup#running-tests)) | | `cargo test -p gitarena` | Test a single crate | | `cargo clippy` | Lint | | `cargo fmt` | Format (max width 160, set in `rustfmt.toml`) | diff --git a/docs/self-hosting/configuration.mdx b/docs/self-hosting/configuration.mdx index 205288d4..17ece942 100644 --- a/docs/self-hosting/configuration.mdx +++ b/docs/self-hosting/configuration.mdx @@ -32,6 +32,8 @@ Set these before starting GitArena. In Docker, pass them under `environment:` in | Variable | Description | |----------|-------------| | `MAX_POOL_CONNECTIONS` | Maximum number of Postgres connections to keep open. | +| `MAX_QUEUE_POOL_CONNECTIONS` | Maximum number of Postgres connections used by the background job queue. Defaults to the number of CPU threads + 1. | +| `DISABLE_UPDATE_CHECK` | Skip checking GitHub for a new GitArena version at startup when set. The admin panel update check still works. | | `NO_STDOUT_LOG` | Disable stdout logging when set. | | `DEBUG_FILE_LOG` | Enable rolling file logging in non-debug builds when set. | | `OTEL_EXPORTER_OTLP_ENDPOINT` | OTLP endpoint for traces, metrics and logs. Exporting is disabled unless this or a signal-specific `OTEL_EXPORTER_OTLP_*_ENDPOINT` is set. | diff --git a/gitarena/Cargo.toml b/gitarena/Cargo.toml index 52ace476..2a29101f 100644 --- a/gitarena/Cargo.toml +++ b/gitarena/Cargo.toml @@ -95,5 +95,11 @@ uuid = { workspace = true, features = ["v4", "v5", "v7"] } webauthn-rs = { version = "0.6.2", features = ["danger-allow-state-serialisation", "conditional-ui"] } zip = { version = "9.2.1", default-features = false, features = ["deflate", "time", "chrono"] } +[dev-dependencies] +pretty_assertions = { version = "=1.4.1", features = ["unstable"] } +reqwest = { version = "0.12.28", default-features = false, features = ["cookies", "json"] } +tempfile = "3.23.0" +test-with = { version = "0.17.2", default-features = false, features = ["executable"] } + [build-dependencies] vergen-gix = "10.0.3" diff --git a/gitarena/src/database.rs b/gitarena/src/database.rs index c07decf6..1b44e05d 100644 --- a/gitarena/src/database.rs +++ b/gitarena/src/database.rs @@ -18,9 +18,16 @@ pub type PoolOptions = sqlx::pool::PoolOptions; #[instrument(err)] pub async fn create_postgres_pool(max_conns: Option) -> Result { + let cpus = cpu_count()?; + + let max_connections = match max_conns { + Some(max_conns) => max_conns, + None => read_pool_size("MAX_POOL_CONNECTIONS", 5.max(cpus))?, + }; + let pool = PoolOptions::new() - .min_connections(num_cpus::get() as u32 + 1) - .max_connections(max_conns.ok_or(()).or_else(|()| get_max_connections())?) + .min_connections((cpus + 1).min(max_connections)) + .max_connections(max_connections) .acquire_timeout(Duration::from_secs(10)) .after_connect(move |connection, _meta| { Box::pin(async move { @@ -70,14 +77,18 @@ async fn read_database_config() -> Result { Ok(options) } -fn get_max_connections() -> Result { - Ok(match env::var("MAX_POOL_CONNECTIONS") { +pub(crate) fn read_pool_size(variable: &str, default: u32) -> Result { + Ok(match env::var(variable) { Ok(env_str) => env_str .parse::() - .context("Unable to parse MAX_POOL_CONNECTIONS environment variable into a u32")?, - Err(VarError::NotPresent) => 5.max(u32::try_from(num_cpus::get()).context("too many cpu threads to fit into u32")?), + .with_context(|| format!("Unable to parse {variable} environment variable into a u32"))?, + Err(VarError::NotPresent) => default, Err(VarError::NotUnicode(_)) => { - bail!("MAX_POOL_CONNECTIONS environment variable is not a valid unicode string") + bail!("{variable} environment variable is not a valid unicode string") } }) } + +pub(crate) fn cpu_count() -> Result { + u32::try_from(num_cpus::get()).context("too many cpu threads to fit into u32") +} diff --git a/gitarena/src/git/basic_auth.rs b/gitarena/src/git/basic_auth.rs index d7682f3a..379433b4 100644 --- a/gitarena/src/git/basic_auth.rs +++ b/gitarena/src/git/basic_auth.rs @@ -126,3 +126,69 @@ pub(crate) async fn parse_basic_auth(auth_header: &str) -> Result<(String, Strin pub(crate) fn is_present(request: &HttpRequest) -> bool { request.get_header("authorization").is_some() } + +#[cfg(test)] +mod tests { + use super::*; + use pretty_assertions::assert_eq; + + fn header(credentials: &str) -> String { + format!("Basic {}", BASE64_STANDARD.encode(credentials)) + } + + #[tokio::test] + async fn parses_username_and_password() -> Result<()> { + let (username, password) = parse_basic_auth(&header("alice:hunter22")).await?; + + assert_eq!(username, "alice"); + assert_eq!(password, "hunter22"); + Ok(()) + } + + #[tokio::test] + async fn password_may_contain_colons() -> Result<()> { + let (username, password) = parse_basic_auth(&header("alice:a:b:c")).await?; + + assert_eq!(username, "alice"); + assert_eq!(password, "a:b:c"); + Ok(()) + } + + #[tokio::test] + async fn empty_password_is_parsed() -> Result<()> { + let (username, password) = parse_basic_auth(&header("alice:")).await?; + + assert_eq!(username, "alice"); + assert_eq!(password, ""); + Ok(()) + } + + #[tokio::test] + async fn missing_scheme_is_rejected() { + assert!(parse_basic_auth(&BASE64_STANDARD.encode("alice:hunter22")).await.is_err()); + } + + #[tokio::test] + async fn non_basic_scheme_is_rejected() { + assert!(parse_basic_auth("Bearer abcdef").await.is_err()); + } + + #[tokio::test] + async fn invalid_base64_is_rejected() { + assert!(parse_basic_auth("Basic !!!not-base64!!!").await.is_err()); + } + + #[tokio::test] + async fn credentials_without_colon_are_rejected() { + assert!(parse_basic_auth(&header("alice")).await.is_err()); + } + + #[tokio::test] + async fn non_utf8_credentials_are_rejected() { + assert!( + parse_basic_auth(&format!("Basic {}", BASE64_STANDARD.encode([0xff, b':', 0xfe]))) + .await + .is_err() + ); + } +} diff --git a/gitarena/src/git/capabilities.rs b/gitarena/src/git/capabilities.rs index c0190e32..58a27917 100644 --- a/gitarena/src/git/capabilities.rs +++ b/gitarena/src/git/capabilities.rs @@ -26,3 +26,37 @@ pub(crate) async fn capabilities(service_header: Option<&str>) -> Result writer.serialize().await } + +#[cfg(test)] +mod tests { + use super::*; + use pretty_assertions::assert_eq; + + fn expected_capabilities() -> String { + let agent = concat!("agent=git/gitarena-", env!("CARGO_PKG_VERSION")); + + format!( + "000eversion 2\n{:04x}{agent}\n0013ls-refs=unborn\n000afetch\n0012server-option\n0017object-format=sha1\n0000", + agent.len() + 5 + ) + } + + #[tokio::test] + async fn without_service_header_only_capabilities_are_advertised() -> Result<()> { + let bytes = capabilities(None).await?; + + assert_eq!(String::from_utf8(bytes.to_vec())?, expected_capabilities()); + Ok(()) + } + + #[tokio::test] + async fn service_header_is_prepended_and_flushed() -> Result<()> { + let bytes = capabilities(Some("git-upload-pack")).await?; + + assert_eq!( + String::from_utf8(bytes.to_vec())?, + format!("001e# service=git-upload-pack\n0000{}", expected_capabilities()) + ); + Ok(()) + } +} diff --git a/gitarena/src/git/history.rs b/gitarena/src/git/history.rs index 26d6f480..f9c4682a 100644 --- a/gitarena/src/git/history.rs +++ b/gitarena/src/git/history.rs @@ -243,3 +243,110 @@ pub(crate) async fn all_tags(repo: &Git2Repository, prefix: Option<&str>) -> Res Ok(tags.iter().filter_map(|r| r.ok().flatten().map(ToOwned::to_owned)).collect()) } + +#[cfg(test)] +mod tests { + use super::*; + use git2::{Signature, Time}; + use pretty_assertions::assert_eq; + use tempfile::{TempDir, tempdir}; + + fn repo_with_history() -> Result<(TempDir, Git2Repository, Vec)> { + let dir = tempdir()?; + let repo = Git2Repository::init_bare(dir.path())?; + let mut commits = Vec::new(); + + { + let mut builder = repo.treebuilder(None)?; + + for index in 0..6_i64 { + let path = if index % 2 == 0 { "a.txt" } else { "b.txt" }; + builder.insert(path, repo.blob(format!("{index}\n").as_bytes())?, 0o100_644)?; + + let tree = repo.find_tree(builder.write()?)?; + let signature = Signature::new("tester", "tester@example.com", &Time::new(1_700_000_000 + index * 60, 0))?; + let parents = commits.last().map(|oid| repo.find_commit(*oid)).transpose()?; + + let oid = repo.commit( + Some("refs/heads/main"), + &signature, + &signature, + &format!("commit {index}"), + &tree, + parents.iter().collect::>().as_slice(), + )?; + + commits.push(oid); + } + } + + Ok((dir, repo, commits)) + } + + #[tokio::test] + async fn paged_commits_pages_newest_first() -> Result<()> { + let (_dir, repo, commits) = repo_with_history()?; + + let first = paged_commits(&repo, "refs/heads/main", 0, 2, false).await?; + let second = paged_commits(&repo, "refs/heads/main", 2, 2, false).await?; + let past_end = paged_commits(&repo, "refs/heads/main", 6, 2, false).await?; + + assert_eq!(first, vec![commits[5], commits[4]]); + assert_eq!(second, vec![commits[3], commits[2]]); + assert_eq!(past_end, Vec::::new()); + Ok(()) + } + + #[tokio::test] + async fn paged_commits_reverse_starts_with_oldest() -> Result<()> { + let (_dir, repo, commits) = repo_with_history()?; + + let page = paged_commits(&repo, "refs/heads/main", 1, 3, true).await?; + + assert_eq!(page, vec![commits[1], commits[2], commits[3]]); + Ok(()) + } + + #[tokio::test] + async fn paged_commits_accepts_oid_as_reference() -> Result<()> { + let (_dir, repo, commits) = repo_with_history()?; + + let page = paged_commits(&repo, &commits[2].to_string(), 0, 10, false).await?; + + assert_eq!(page, vec![commits[2], commits[1], commits[0]]); + Ok(()) + } + + #[tokio::test] + async fn paged_commits_for_path_only_returns_commits_touching_path() -> Result<()> { + let (_dir, repo, commits) = repo_with_history()?; + + let a = paged_commits_for_path(&repo, "refs/heads/main", "a.txt", 0, 10).await?; + let b = paged_commits_for_path(&repo, "refs/heads/main", "b.txt", 0, 10).await?; + + assert_eq!(a, vec![commits[4], commits[2], commits[0]]); + assert_eq!(b, vec![commits[5], commits[3], commits[1]]); + Ok(()) + } + + #[tokio::test] + async fn paged_commits_for_path_respects_offset_and_limit() -> Result<()> { + let (_dir, repo, commits) = repo_with_history()?; + + let page = paged_commits_for_path(&repo, "refs/heads/main", "a.txt", 1, 1).await?; + let past_end = paged_commits_for_path(&repo, "refs/heads/main", "a.txt", 3, 1).await?; + + assert_eq!(page, vec![commits[2]]); + assert_eq!(past_end, Vec::::new()); + Ok(()) + } + + #[tokio::test] + async fn paged_commits_for_unknown_reference_fails() -> Result<()> { + let (_dir, repo, _) = repo_with_history()?; + + assert!(paged_commits(&repo, "refs/heads/missing", 0, 1, false).await.is_err()); + assert!(paged_commits_for_path(&repo, "refs/heads/missing", "a.txt", 0, 1).await.is_err()); + Ok(()) + } +} diff --git a/gitarena/src/git/io/band.rs b/gitarena/src/git/io/band.rs index 9ea344e4..c4b3d0e4 100644 --- a/gitarena/src/git/io/band.rs +++ b/gitarena/src/git/io/band.rs @@ -16,3 +16,16 @@ impl Band { } } } + +#[cfg(test)] +mod tests { + use super::*; + use pretty_assertions::assert_eq; + + #[test] + fn bands_serialize_to_their_channel_byte() { + assert_eq!(Band::Data.serialize(), b"\x01"); + assert_eq!(Band::Progress.serialize(), b"\x02"); + assert_eq!(Band::Error.serialize(), b"\x03"); + } +} diff --git a/gitarena/src/git/io/reader.rs b/gitarena/src/git/io/reader.rs index edff2d86..423daabf 100644 --- a/gitarena/src/git/io/reader.rs +++ b/gitarena/src/git/io/reader.rs @@ -56,3 +56,60 @@ pub(crate) async fn read_data_lines(iter: &mut StreamingPeekableIter<&[u8]>) -> Ok(body) } + +#[cfg(test)] +mod tests { + use super::*; + use gix::protocol::transport::packetline::PacketLineRef; + use pretty_assertions::assert_eq; + + fn lines(input: &[&str]) -> Vec> { + input.iter().map(|line| line.as_bytes().to_vec()).collect() + } + + #[tokio::test] + async fn read_until_command_with_command_first_keeps_every_line() -> Result<()> { + let (command, body) = read_until_command(lines(&["command=ls-refs", "peel", "symrefs"])).await?; + + assert_eq!(command, "ls-refs"); + assert_eq!(body, lines(&["command=ls-refs", "peel", "symrefs"])); + Ok(()) + } + + #[tokio::test] + async fn read_until_command_strips_only_lines_before_command() -> Result<()> { + let body = lines(&["agent=git/2.43", "object-format=sha1", "command=fetch", "thin-pack", "ofs-delta"]); + let (command, body) = read_until_command(body).await?; + + assert_eq!(command, "fetch"); + assert_eq!(body, lines(&["command=fetch", "thin-pack", "ofs-delta"])); + Ok(()) + } + + #[tokio::test] + async fn read_until_command_without_command_fails() { + assert!(read_until_command(lines(&["agent=git/2.43", "peel"])).await.is_err()); + } + + #[tokio::test] + async fn read_data_lines_strips_one_trailing_lf() -> Result<()> { + let input = b"000ahello\n0009world000cdouble\n\n0000"; + let mut iter = StreamingPeekableIter::new(&input[..], &[PacketLineRef::Flush], false); + + let body = read_data_lines(&mut iter).await?; + + assert_eq!(body, lines(&["hello", "world", "double\n"])); + Ok(()) + } + + #[tokio::test] + async fn read_data_lines_skips_delimiters() -> Result<()> { + let input = b"0014command=ls-refs\n00010009peel\n0000"; + let mut iter = StreamingPeekableIter::new(&input[..], &[PacketLineRef::Flush], false); + + let body = read_data_lines(&mut iter).await?; + + assert_eq!(body, lines(&["command=ls-refs", "peel"])); + Ok(()) + } +} diff --git a/gitarena/src/git/io/writer.rs b/gitarena/src/git/io/writer.rs index 26cf0de8..c898d642 100644 --- a/gitarena/src/git/io/writer.rs +++ b/gitarena/src/git/io/writer.rs @@ -192,3 +192,146 @@ fn u16_to_hex(value: u16) -> [u8; 4] { hex::encode_to_slice(value.to_be_bytes(), &mut buffer).unwrap_or_log(); buffer } + +#[cfg(test)] +mod tests { + use super::*; + use pretty_assertions::assert_eq; + + async fn serialized(writer: GitWriter) -> Result> { + Ok(writer.serialize().await?.to_vec()) + } + + #[tokio::test] + async fn text_line_gets_length_prefix_and_newline() -> Result<()> { + let mut writer = GitWriter::new(); + writer.write_text("hello").await?; + + assert_eq!(serialized(writer).await?, b"000ahello\n"); + Ok(()) + } + + #[tokio::test] + async fn empty_text_line_is_rejected() { + let mut writer = GitWriter::new(); + + assert!(writer.write_text("").await.is_err()); + } + + #[tokio::test] + async fn text_sideband_prefixes_band_byte() -> Result<()> { + let mut writer = GitWriter::new(); + writer.write_text_sideband(Band::Progress, "hi").await?; + writer.write_text_sideband(Band::Error, "no").await?; + + assert_eq!(serialized(writer).await?, b"0008\x02hi\n0008\x03no\n"); + Ok(()) + } + + #[tokio::test] + async fn text_sideband_pktline_nests_a_pktline_in_band_one() -> Result<()> { + let mut writer = GitWriter::new(); + writer.write_text_sideband_pktline(Band::Data, "unpack ok").await?; + + assert_eq!(serialized(writer).await?, b"0013\x01000eunpack ok\n"); + Ok(()) + } + + #[tokio::test] + async fn no_good_without_sideband_is_plain_text() -> Result<()> { + let mut writer = GitWriter::new(); + writer.write_no_good(false, "refs/heads/main", "push contains secrets").await?; + + assert_eq!(serialized(writer).await?, b"002dng refs/heads/main push contains secrets\n"); + Ok(()) + } + + #[tokio::test] + async fn no_good_with_sideband_is_nested() -> Result<()> { + let mut writer = GitWriter::new(); + writer.write_no_good(true, "refs/heads/main", "nope").await?; + + assert_eq!(serialized(writer).await?, b"0021\x01001cng refs/heads/main nope\n"); + Ok(()) + } + + #[tokio::test] + async fn binary_sideband_has_no_newline_and_restores_text_mode() -> Result<()> { + let mut writer = GitWriter::new(); + writer.write_binary_sideband(Band::Data, b"PACK").await?; + writer.write_text("x").await?; + + assert_eq!(serialized(writer).await?, b"0009\x01PACK0006x\n"); + Ok(()) + } + + #[tokio::test] + async fn binary_sideband_chunked_splits_at_max_packet_size() -> Result<()> { + let payload = vec![b'a'; 65516]; + + let mut writer = GitWriter::new(); + writer.write_binary_sideband_chunked(Band::Data, &payload).await?; + writer.write_text("x").await?; + + let bytes = serialized(writer).await?; + + assert_eq!(&bytes[..5], b"fff0\x01"); + assert_eq!(&bytes[65520..65526], b"0006\x01a"); + assert_eq!(&bytes[65526..], b"0006x\n"); + Ok(()) + } + + #[tokio::test] + async fn binary_sideband_chunked_exact_chunk_is_one_packet() -> Result<()> { + let payload = vec![b'a'; 65515]; + + let mut writer = GitWriter::new(); + writer.write_binary_sideband_chunked(Band::Data, &payload).await?; + + let bytes = serialized(writer).await?; + + assert_eq!(bytes.len(), 65520); + assert_eq!(&bytes[..5], b"fff0\x01"); + Ok(()) + } + + #[tokio::test] + async fn special_packets() -> Result<()> { + let mut writer = GitWriter::new(); + writer.flush().await?; + writer.delimiter().await?; + writer.response_end().await?; + + assert_eq!(serialized(writer).await?, b"000000010002"); + Ok(()) + } + + #[tokio::test] + async fn flush_sideband_wraps_flush_in_band() -> Result<()> { + let mut writer = GitWriter::new(); + writer.flush_sideband(Band::Data).await?; + + assert_eq!(serialized(writer).await?, b"0009\x010000"); + Ok(()) + } + + #[tokio::test] + async fn raw_and_append_are_written_verbatim() -> Result<()> { + let mut other = GitWriter::new(); + other.write_text("b").await?; + + let mut writer = GitWriter::new(); + writer.write_raw(b"raw").await?; + writer.append(other).await?; + + assert_eq!(serialized(writer).await?, b"raw0006b\n"); + Ok(()) + } + + #[test] + fn u16_to_hex_is_lowercase_and_zero_padded() { + assert_eq!(&u16_to_hex(0), b"0000"); + assert_eq!(&u16_to_hex(0x0a), b"000a"); + assert_eq!(&u16_to_hex(0xfff0), b"fff0"); + } +} diff --git a/gitarena/src/git/ls_refs.rs b/gitarena/src/git/ls_refs.rs index 9d3b3a02..4d0c3836 100644 --- a/gitarena/src/git/ls_refs.rs +++ b/gitarena/src/git/ls_refs.rs @@ -194,3 +194,171 @@ impl LsRefs { self.prefixes.is_empty() || self.prefixes.iter().any(|prefix| name.starts_with(prefix.as_str())) } } + +#[cfg(test)] +mod tests { + use super::*; + use anyhow::Context; + use git2::{Oid, Signature, Time}; + use pretty_assertions::assert_eq; + use tempfile::{TempDir, tempdir}; + + fn args(input: &[&str]) -> Vec> { + input.iter().map(|line| line.as_bytes().to_vec()).collect() + } + + fn pkt_lines(bytes: &[u8]) -> Result> { + let mut lines = Vec::new(); + let mut rest = bytes; + + while !rest.is_empty() { + let length = usize::from_str_radix(str::from_utf8(&rest[..4])?, 16)?; + + if length == 0 { + lines.push("0000".to_owned()); + rest = &rest[4..]; + continue; + } + + lines.push(String::from_utf8(rest[4..length].to_vec())?.trim_end_matches('\n').to_owned()); + rest = &rest[length..]; + } + + Ok(lines) + } + + fn empty_repo() -> Result<(TempDir, Git2Repository)> { + let dir = tempdir()?; + let repo = Git2Repository::init_bare(dir.path())?; + repo.set_head("refs/heads/main")?; + + Ok((dir, repo)) + } + + fn repo_with_commit() -> Result<(TempDir, Git2Repository, Oid)> { + let (dir, repo) = empty_repo()?; + + let commit = { + let signature = Signature::new("tester", "tester@example.com", &Time::new(1_700_000_000, 0))?; + let blob = repo.blob(b"hello\n")?; + + let mut builder = repo.treebuilder(None)?; + builder.insert("README.md", blob, 0o100_644)?; + let tree = repo.find_tree(builder.write()?)?; + + repo.commit(Some("refs/heads/main"), &signature, &signature, "initial", &tree, &[])? + }; + + repo.reference("refs/tags/v1", commit, false, "lightweight tag")?; + + Ok((dir, repo, commit)) + } + + #[test] + fn empty_prefix_list_matches_everything() { + let options = LsRefs::default(); + + assert!(options.matches("HEAD")); + assert!(options.matches("refs/heads/main")); + } + + #[test] + fn prefixes_match_by_string_prefix() { + let options = LsRefs { + prefixes: vec!["refs/heads/".to_owned(), "HEAD".to_owned()], + ..LsRefs::default() + }; + + assert!(options.matches("HEAD")); + assert!(options.matches("refs/heads/main")); + assert!(!options.matches("refs/tags/v1")); + } + + #[tokio::test] + async fn without_prefixes_all_refs_are_listed() -> Result<()> { + let (_dir, repo, commit) = repo_with_commit()?; + + let mut lines = pkt_lines(&ls_refs(args(&["command=ls-refs", "symrefs"]), &repo).await?)?; + lines.sort(); + + assert_eq!( + lines, + vec![ + "0000".to_owned(), + format!("{commit} HEAD symref-target:refs/heads/main"), + format!("{commit} refs/heads/main"), + format!("{commit} refs/tags/v1"), + ] + ); + Ok(()) + } + + #[tokio::test] + async fn ref_prefix_filters_refs() -> Result<()> { + let (_dir, repo, commit) = repo_with_commit()?; + + let lines = pkt_lines(&ls_refs(args(&["ref-prefix refs/tags/"]), &repo).await?)?; + + assert_eq!(lines, vec![format!("{commit} refs/tags/v1"), "0000".to_owned()]); + Ok(()) + } + + #[tokio::test] + async fn head_prefix_lists_only_head() -> Result<()> { + let (_dir, repo, commit) = repo_with_commit()?; + + let lines = pkt_lines(&ls_refs(args(&["ref-prefix HEAD"]), &repo).await?)?; + + assert_eq!(lines, vec![format!("{commit} HEAD symref-target:refs/heads/main"), "0000".to_owned()]); + Ok(()) + } + + #[tokio::test] + async fn unborn_head_is_only_listed_when_requested() -> Result<()> { + let (_dir, repo) = empty_repo()?; + + let without = pkt_lines(&ls_refs(args(&["ref-prefix HEAD"]), &repo).await?)?; + let with = pkt_lines(&ls_refs(args(&["ref-prefix HEAD", "unborn"]), &repo).await?)?; + + assert_eq!(without, vec!["0000".to_owned()]); + assert_eq!(with, vec!["unborn HEAD symref-target:refs/heads/main".to_owned(), "0000".to_owned()]); + Ok(()) + } + + #[tokio::test] + async fn ls_refs_all_on_empty_repo_advertises_capabilities_line() -> Result<()> { + let (_dir, repo) = empty_repo()?; + + let lines = pkt_lines(&ls_refs_all(&repo, Some("git-receive-pack")).await?)?; + + assert_eq!(lines.len(), 4); + assert_eq!(lines[0], "# service=git-receive-pack"); + assert_eq!(lines[1], "0000"); + assert!( + lines[2].starts_with("0000000000000000000000000000000000000000 capabilities^{}\0report-status"), + "{}", + lines[2] + ); + assert_eq!(lines[3], "0000"); + Ok(()) + } + + #[tokio::test] + async fn ls_refs_all_puts_capabilities_on_first_ref_only() -> Result<()> { + let (_dir, repo, commit) = repo_with_commit()?; + + let lines = pkt_lines(&ls_refs_all_upload_pack(&repo, None).await?)?; + + let (_, capabilities) = lines[0].split_once('\0').context("first ref has no capabilities")?; + let mut refs = lines.iter().map(|line| line.split('\0').next().unwrap_or_default()).collect::>(); + refs.sort_unstable(); + + assert!(capabilities.contains("symref=HEAD:refs/heads/main"), "{capabilities}"); + assert!(!lines[1].contains('\0')); + assert_eq!( + refs, + vec!["0000".to_owned(), format!("{commit} refs/heads/main"), format!("{commit} refs/tags/v1")] + ); + Ok(()) + } +} diff --git a/gitarena/src/git/mod.rs b/gitarena/src/git/mod.rs index 53e4902f..7deae625 100644 --- a/gitarena/src/git/mod.rs +++ b/gitarena/src/git/mod.rs @@ -57,3 +57,23 @@ impl FromStr for GitProtocol { }) } } + +#[cfg(test)] +mod tests { + use super::*; + use pretty_assertions::assert_matches; + + #[test] + fn git_protocol_parses_known_versions() { + assert_matches!(GitProtocol::from_str("1"), Ok(GitProtocol::V1)); + assert_matches!(GitProtocol::from_str("2"), Ok(GitProtocol::V2)); + } + + #[test] + fn git_protocol_rejects_unknown_versions() { + assert!(GitProtocol::from_str("0").is_err()); + assert!(GitProtocol::from_str("3").is_err()); + assert!(GitProtocol::from_str("version=2").is_err()); + assert!(GitProtocol::from_str("").is_err()); + } +} diff --git a/gitarena/src/git/ref_update.rs b/gitarena/src/git/ref_update.rs index 0b4b33ad..6da7c79a 100644 --- a/gitarena/src/git/ref_update.rs +++ b/gitarena/src/git/ref_update.rs @@ -106,3 +106,117 @@ impl RefUpdateType { } } } + +#[cfg(test)] +mod tests { + use super::*; + use pretty_assertions::assert_eq; + + const NULL: &str = "0000000000000000000000000000000000000000"; + const OLD: &str = "b52f683ce73e8be06428b8c6cf0eb421eae21772"; + const NEW: &str = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"; + + fn update(old: Option<&str>, new: Option<&str>) -> RefUpdate { + RefUpdate { + old: old.map(ToOwned::to_owned), + new: new.map(ToOwned::to_owned), + target_ref: "refs/heads/main".to_owned(), + ..RefUpdate::default() + } + } + + #[tokio::test] + async fn parse_line_reads_old_new_and_ref() -> Result<()> { + let update = parse_line(format!("{OLD} {NEW} refs/heads/main").into_bytes()).await?; + + assert_eq!(update.old.as_deref(), Some(OLD)); + assert_eq!(update.new.as_deref(), Some(NEW)); + assert_eq!(update.target_ref, "refs/heads/main"); + assert!(!update.report_status); + assert!(!update.report_status_v2); + assert!(!update.side_band_64k); + assert_eq!(update.push_options, None); + Ok(()) + } + + #[tokio::test] + async fn parse_line_normalizes_null_oids() -> Result<()> { + let create = parse_line(format!("{NULL} {NEW} refs/heads/feature").into_bytes()).await?; + let delete = parse_line(format!("{OLD} {NULL} refs/heads/feature").into_bytes()).await?; + + assert_eq!(create.old, None); + assert_eq!(create.new.as_deref(), Some(NEW)); + assert_eq!(delete.old.as_deref(), Some(OLD)); + assert_eq!(delete.new, None); + Ok(()) + } + + #[tokio::test] + async fn parse_line_reads_capabilities_after_nul() -> Result<()> { + let line = format!("{NULL} {NEW} refs/heads/main\0 report-status report-status-v2 side-band-64k quiet agent=git/2.47.0"); + let update = parse_line(line.into_bytes()).await?; + + assert!(update.report_status); + assert!(update.report_status_v2); + assert!(update.side_band_64k); + assert_eq!(update.push_options, Some(vec!["quiet".to_owned(), "agent=git/2.47.0".to_owned()])); + Ok(()) + } + + #[tokio::test] + async fn parse_line_rejects_partial_ref_names() { + assert!(parse_line(format!("{OLD} {NEW} main").into_bytes()).await.is_err()); + } + + #[tokio::test] + async fn parse_line_rejects_truncated_lines() { + assert!(parse_line(Vec::new()).await.is_err()); + assert!(parse_line(OLD.as_bytes().to_vec()).await.is_err()); + assert!(parse_line(format!("{OLD} {NEW}").into_bytes()).await.is_err()); + } + + #[tokio::test] + async fn parse_line_rejects_invalid_utf8() { + assert!(parse_line(vec![0xff, 0xfe]).await.is_err()); + } + + #[test] + fn determinate_classifies_updates() { + assert!(matches!(RefUpdateType::determinate(&None, &Some(NEW.to_owned())), Ok(RefUpdateType::Create))); + assert!(matches!(RefUpdateType::determinate(&Some(OLD.to_owned()), &None), Ok(RefUpdateType::Delete))); + assert!(matches!( + RefUpdateType::determinate(&Some(OLD.to_owned()), &Some(NEW.to_owned())), + Ok(RefUpdateType::Update) + )); + assert!(RefUpdateType::determinate(&None, &None).is_err()); + } + + #[test] + fn is_only_deletions_requires_every_update_to_be_a_delete() -> Result<()> { + assert!(is_only_deletions(&[update(Some(OLD), None), update(Some(NEW), None)])?); + assert!(!is_only_deletions(&[update(Some(OLD), None), update(None, Some(NEW))])?); + assert!(!is_only_deletions(&[update(Some(OLD), Some(NEW))])?); + assert!(is_only_deletions(&[])?); + assert!(is_only_deletions(&[update(None, None)]).is_err()); + Ok(()) + } + + #[test] + fn propagate_capabilities_copies_first_line_flags() { + let mut first = update(None, Some(NEW)); + first.report_status = true; + first.side_band_64k = true; + + let mut second = update(Some(OLD), None); + second.report_status_v2 = true; + + let mut updates = [first, second, update(Some(OLD), Some(NEW))]; + propagate_capabilities(&mut updates); + + for update in &updates { + assert!(update.report_status); + assert!(!update.report_status_v2); + assert!(update.side_band_64k); + } + } +} diff --git a/gitarena/src/main.rs b/gitarena/src/main.rs index 3ee8e67c..8299c993 100644 --- a/gitarena/src/main.rs +++ b/gitarena/src/main.rs @@ -148,19 +148,21 @@ async fn main() -> Result<()> { let ssh_handle = ssh::init(db_pool.clone(), &bind_address).await?; - match LocalSet::new().run_until(update_check::check_github()).await { - Ok(update_info) if update_info.available => { - warn!(" "); - warn!("new update for gitarena available: v0.0.0-{}", update_info.new_version.unwrap_or_default()); + if env::var_os("DISABLE_UPDATE_CHECK").is_none() { + match LocalSet::new().run_until(update_check::check_github()).await { + Ok(update_info) if update_info.available => { + warn!(" "); + warn!("new update for gitarena available: v0.0.0-{}", update_info.new_version.unwrap_or_default()); + + if update_info.security_relevant.unwrap_or_default() { + warn!("note: the update contains security fixes, please update ASAP"); + } - if update_info.security_relevant.unwrap_or_default() { - warn!("note: the update contains security fixes, please update ASAP"); + warn!(" "); } - - warn!(" "); + Ok(_) => {} + Err(err) => warn!(?err, "update check failed"), } - Ok(_) => {} - Err(err) => warn!(?err, "update check failed"), } let server = HttpServer::new(move || { diff --git a/gitarena/src/queue.rs b/gitarena/src/queue.rs index 7f6cda39..f289748e 100644 --- a/gitarena/src/queue.rs +++ b/gitarena/src/queue.rs @@ -1,4 +1,5 @@ use crate::contributions::task::CONTRIBUTIONS_TASK_TYPE; +use crate::database::{cpu_count, read_pool_size}; use crate::git::hooks::post_update::POST_UPDATE_TASK_TYPE; use crate::mail::task::MAIL_TASK_TYPE; use crate::passkey::ExpiredWebAuthnChallengesRemovalTask; @@ -18,7 +19,7 @@ pub(crate) async fn init() -> Result { // todo: this makes `DATABASE_URL` mandatory let mut queue = AsyncQueue::builder() .uri(env::var("DATABASE_URL").context("unable to find mandatory `DATABASE_URL` env variable")?) - .max_pool_size(num_cpus::get() as u32 + 1) + .max_pool_size(read_pool_size("MAX_QUEUE_POOL_CONNECTIONS", cpu_count()? + 1)?) .build(); queue.connect().await.context("task queue failed to connect to postgres database")?; diff --git a/gitarena/src/ssh/key.rs b/gitarena/src/ssh/key.rs index 30659160..5b64f336 100644 --- a/gitarena/src/ssh/key.rs +++ b/gitarena/src/ssh/key.rs @@ -137,3 +137,76 @@ impl TryFrom<&Algorithm> for KeyType { }) } } + +#[cfg(test)] +mod tests { + use super::*; + use pretty_assertions::assert_eq; + use russh::keys::PrivateKey; + use russh::keys::ssh_encoding::Encode; + use uuid::Uuid; + + const KEY_TYPES: [&str; 9] = [ + "ssh-rsa", + "ecdsa-sha2-nistp256", + "ecdsa-sha2-nistp384", + "ecdsa-sha2-nistp521", + "ssh-ed25519", + "sk-ssh-ed25519@openssh.com", + "sk-ecdsa-sha2-nistp256@openssh.com", + "rsa-sha2-256", + "rsa-sha2-512", + ]; + + #[test] + fn key_type_round_trips_through_display() -> Result<()> { + for name in KEY_TYPES { + assert_eq!(KeyType::try_from(name)?.to_string(), name); + } + + Ok(()) + } + + #[test] + fn key_type_rejects_unknown_names() { + assert!(KeyType::try_from("ssh-dss").is_err()); + assert!(KeyType::try_from("").is_err()); + assert!(KeyType::try_from("SSH-ED25519").is_err()); + } + + #[test] + fn key_type_from_algorithm() -> Result<()> { + assert_eq!(KeyType::try_from(&Algorithm::Ed25519)?.to_string(), "ssh-ed25519"); + assert_eq!(KeyType::try_from(&Algorithm::SkEd25519)?.to_string(), "sk-ssh-ed25519@openssh.com"); + assert_eq!(KeyType::try_from(&Algorithm::Rsa { hash: None })?.to_string(), "ssh-rsa"); + assert_eq!(KeyType::try_from(&Algorithm::Rsa { hash: Some(HashAlg::Sha512) })?.to_string(), "rsa-sha2-512"); + assert_eq!( + KeyType::try_from(&Algorithm::Ecdsa { curve: EcdsaCurve::NistP384 })?.to_string(), + "ecdsa-sha2-nistp384" + ); + assert!(KeyType::try_from(&Algorithm::Dsa).is_err()); + Ok(()) + } + + #[test] + fn as_string_matches_openssh_public_key_format() -> Result<()> { + let private_key = PrivateKey::random(&mut rand::rng(), Algorithm::Ed25519)?; + let public_key = private_key.public_key(); + + let mut encoded = Vec::new(); + public_key.key_data().encode(&mut encoded)?; + + let key = SshKey { + id: Uuid::now_v7(), + owner: Uuid::now_v7(), + title: "laptop".to_owned(), + fingerprint: String::new(), + algorithm: KeyType::try_from(&public_key.algorithm())?, + key: encoded, + expires_at: None, + }; + + assert_eq!(key.as_string(), public_key.to_openssh()?); + Ok(()) + } +} diff --git a/gitarena/src/ssh/server.rs b/gitarena/src/ssh/server.rs index 6ea85ec0..dbeb1e94 100644 --- a/gitarena/src/ssh/server.rs +++ b/gitarena/src/ssh/server.rs @@ -534,3 +534,151 @@ async fn run_receive_pack(db_pool: Pool, repo: Repository, vec: Vec, actor_i Ok(output) } + +#[cfg(test)] +mod tests { + use super::*; + use pretty_assertions::assert_eq; + + const NULL: &str = "0000000000000000000000000000000000000000"; + const OLD: &str = "b52f683ce73e8be06428b8c6cf0eb421eae21772"; + const NEW: &str = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"; + + fn pkt(data: &str) -> Vec { + format!("{:04x}{data}", data.len() + 4).into_bytes() + } + + fn concat(parts: &[&[u8]]) -> Vec { + parts.concat() + } + + #[test] + fn v2_request_ends_at_flush() -> Result<()> { + let request = concat(&[&pkt("command=ls-refs\n"), b"0001", &pkt("peel\n"), b"0000"]); + + assert_eq!(next_request_length(&request, GitProtocol::V2)?, Some(request.len())); + Ok(()) + } + + #[test] + fn v2_request_without_flush_is_incomplete() -> Result<()> { + let request = concat(&[&pkt("command=ls-refs\n"), b"0001", &pkt("peel\n")]); + + assert_eq!(next_request_length(&request, GitProtocol::V2)?, None); + Ok(()) + } + + #[test] + fn partial_packet_line_is_incomplete() -> Result<()> { + let request = pkt("command=fetch\n"); + + assert_eq!(next_request_length(&request[..2], GitProtocol::V2)?, None); + assert_eq!(next_request_length(&request[..request.len() - 1], GitProtocol::V2)?, None); + assert_eq!(next_request_length(b"", GitProtocol::V2)?, None); + Ok(()) + } + + #[test] + fn v2_buffer_with_multiple_requests_returns_first_length() -> Result<()> { + let first = concat(&[&pkt("command=ls-refs\n"), b"0000"]); + let second = concat(&[&pkt("command=fetch\n"), b"0001", &pkt("done\n"), b"0000"]); + let mut buffer = concat(&[&first, &second]); + + assert_eq!(next_request_length(&buffer, GitProtocol::V2)?, Some(first.len())); + + buffer.drain(..first.len()); + + assert_eq!(next_request_length(&buffer, GitProtocol::V2)?, Some(second.len())); + Ok(()) + } + + #[test] + fn v1_request_ends_at_done() -> Result<()> { + let request = concat(&[ + &pkt(&format!("want {NEW} side-band-64k\n")), + b"0000", + &pkt(&format!("have {OLD}\n")), + &pkt("done\n"), + ]); + + assert_eq!(next_request_length(&request, GitProtocol::V1)?, Some(request.len())); + Ok(()) + } + + #[test] + fn v1_flush_does_not_end_request() -> Result<()> { + let request = concat(&[&pkt(&format!("want {NEW}\n")), b"0000", &pkt(&format!("have {OLD}\n")), b"0000"]); + + assert_eq!(next_request_length(&request, GitProtocol::V1)?, None); + Ok(()) + } + + #[test] + fn v1_done_without_newline_ends_request() -> Result<()> { + let request = concat(&[&pkt(&format!("want {NEW}\n")), b"0000", &pkt("done")]); + + assert_eq!(next_request_length(&request, GitProtocol::V1)?, Some(request.len())); + Ok(()) + } + + #[test] + fn invalid_length_prefix_is_an_error() { + assert!(next_request_length(b"zzzz", GitProtocol::V2).is_err()); + } + + #[tokio::test] + async fn delete_only_push_is_complete_after_flush() -> Result<()> { + let buffer = concat(&[&pkt(&format!("{OLD} {NULL} refs/heads/feature\0report-status side-band-64k")), b"0000"]); + + assert!(is_delete_only_push(&buffer).await?); + Ok(()) + } + + #[tokio::test] + async fn multiple_deletions_are_delete_only() -> Result<()> { + let buffer = concat(&[ + &pkt(&format!("{OLD} {NULL} refs/heads/feature\0report-status")), + &pkt(&format!("{NEW} {NULL} refs/tags/v1")), + b"0000", + ]); + + assert!(is_delete_only_push(&buffer).await?); + Ok(()) + } + + #[tokio::test] + async fn push_with_create_or_update_is_not_delete_only() -> Result<()> { + let create = concat(&[&pkt(&format!("{NULL} {NEW} refs/heads/feature\0report-status")), b"0000"]); + let mixed = concat(&[ + &pkt(&format!("{OLD} {NULL} refs/heads/old\0report-status")), + &pkt(&format!("{OLD} {NEW} refs/heads/main")), + b"0000", + ]); + + assert!(!is_delete_only_push(&create).await?); + assert!(!is_delete_only_push(&mixed).await?); + Ok(()) + } + + #[tokio::test] + async fn deletion_without_flush_is_incomplete() -> Result<()> { + let buffer = pkt(&format!("{OLD} {NULL} refs/heads/feature\0report-status")); + + assert!(!is_delete_only_push(&buffer).await?); + Ok(()) + } + + #[tokio::test] + async fn flush_without_commands_is_not_delete_only() -> Result<()> { + assert!(!is_delete_only_push(b"0000").await?); + Ok(()) + } + + #[tokio::test] + async fn invalid_command_completes_the_request() -> Result<()> { + let buffer = concat(&[&pkt(&format!("{OLD} {NULL} feature")), b"0000"]); + + assert!(is_delete_only_push(&buffer).await?); + Ok(()) + } +} diff --git a/gitarena/src/utils/oid.rs b/gitarena/src/utils/oid.rs index 96b67a43..0b6f3377 100644 --- a/gitarena/src/utils/oid.rs +++ b/gitarena/src/utils/oid.rs @@ -62,3 +62,38 @@ pub(crate) fn from_hex_str(option: Option<&str>) -> Result { None => Ok(ObjectId::null(GIT_HASH_KIND)), } } + +#[cfg(test)] +mod tests { + use super::*; + use pretty_assertions::assert_eq; + + const OID: &str = "b52f683ce73e8be06428b8c6cf0eb421eae21772"; + + #[test] + fn normalize_str_maps_null_oid_to_none() { + assert_eq!(normalize_str(Some(OID)), Some(OID)); + assert_eq!(normalize_str(Some("0000000000000000000000000000000000000000")), None); + assert_eq!(normalize_str(None), None); + } + + #[test] + fn from_hex_str_parses_valid_oids() -> Result<()> { + assert_eq!(from_hex_str(Some(OID))?.to_string(), OID); + Ok(()) + } + + #[test] + fn from_hex_str_maps_none_to_null_oid() -> Result<()> { + assert!(from_hex_str(None)?.is_null()); + Ok(()) + } + + #[test] + fn from_hex_str_rejects_invalid_input() { + assert!(from_hex_str(Some("invalid length string")).is_err()); + assert!(from_hex_str(Some("yZ0r3ny0K55qqxoz0HZhCWzqAdyFdZ3L9GmXG7EU")).is_err()); + assert!(from_hex_str(Some("b52f683c")).is_err()); + assert!(from_hex_str(Some("")).is_err()); + } +} diff --git a/gitarena/tests/common/mod.rs b/gitarena/tests/common/mod.rs new file mode 100644 index 00000000..f4ea3622 --- /dev/null +++ b/gitarena/tests/common/mod.rs @@ -0,0 +1,882 @@ +// every test binary only uses part of the harness +#![allow(dead_code)] + +pub mod scenarios; + +use anyhow::{Context, Result, anyhow, bail, ensure}; +use reqwest::{Client, Response, StatusCode}; +use serde::Deserialize; +use serde::de::DeserializeOwned; +use serde_json::{Value, json}; +use sqlx::PgPool; +use std::collections::BTreeMap; +use std::env; +use std::net::TcpListener; +use std::path::{Path, PathBuf}; +use std::process::{Output, Stdio}; +use std::time::Duration; +use tempfile::{TempDir, tempdir}; +use tokio::fs; +use tokio::io::AsyncWriteExt; +use tokio::net::TcpStream; +use tokio::process::{Child, Command}; +use tokio::time::{Instant, sleep, timeout}; +use url::Url; +use uuid::Uuid; + +const BOOT_ATTEMPTS: usize = 3; +const BOOT_TIMEOUT: Duration = Duration::from_secs(60); +const COMMAND_TIMEOUT: Duration = Duration::from_secs(120); +const AGENT_TIMEOUT: Duration = Duration::from_secs(10); + +pub const AUTHOR_NAME: &str = "Test Author"; +pub const AUTHOR_EMAIL: &str = "author@example.com"; + +#[derive(Debug, Clone, Copy)] +pub enum Transport { + Http, + Ssh, +} + +#[derive(Debug, Clone, Copy)] +pub enum Protocol { + V1, + V2, +} + +impl Protocol { + fn version(self) -> &'static str { + match self { + Protocol::V1 => "1", + Protocol::V2 => "2", + } + } +} + +#[derive(Debug, Clone, Copy)] +pub enum Visibility { + Public, + Private, +} + +impl Visibility { + fn as_str(self) -> &'static str { + match self { + Visibility::Public => "public", + Visibility::Private => "private", + } + } +} + +pub struct TestServer { + child: Child, + pub http_port: u16, + pub ssh_port: u16, + home: TempDir, + repos_dir: TempDir, +} + +impl TestServer { + pub async fn start(pool: &PgPool) -> Result { + let database_url = test_database_url(pool)?; + let repos_dir = tempdir()?; + let home = tempdir()?; + + let mut last_error = None; + + for _ in 0..BOOT_ATTEMPTS { + let http_port = free_port()?; + let ssh_port = free_port()?; + + seed_settings(pool, http_port, ssh_port, repos_dir.path()).await?; + + let mut child = Command::new(env!("CARGO_BIN_EXE_gitarena")) + .env_clear() + .env("PATH", env::var_os("PATH").unwrap_or_default()) + .env("HOME", home.path()) + .env("DATABASE_URL", &database_url) + .env("BIND_ADDRESS", format!("127.0.0.1:{http_port}")) + .env("RUST_LOG", "gitarena=debug") + .env("MAX_POOL_CONNECTIONS", "3") + .env("MAX_QUEUE_POOL_CONNECTIONS", "2") + .env("DISABLE_UPDATE_CHECK", "1") + .env("GIT_CONFIG_GLOBAL", "/dev/null") + .env("GIT_CONFIG_SYSTEM", "/dev/null") + .stdin(Stdio::null()) + .kill_on_drop(true) + .spawn() + .context("failed to spawn gitarena")?; + + match wait_until_ready(&mut child, http_port, ssh_port).await { + Ok(()) => { + return Ok(TestServer { + child, + http_port, + ssh_port, + home, + repos_dir, + }); + } + Err(err) => { + let _ = child.kill().await; + last_error = Some(err); + } + } + } + + Err(last_error.unwrap_or_else(|| anyhow!("gitarena did not start"))) + } + + pub fn base_url(&self) -> String { + format!("http://127.0.0.1:{}", self.http_port) + } + + pub fn remote(&self, transport: Transport, user: Option<&TestUser>, repo: &str) -> String { + match (transport, user) { + (Transport::Http, Some(user)) => format!("http://{}:{}@127.0.0.1:{}/{repo}.git", user.username, user.password, self.http_port), + (Transport::Http, None) => format!("http://127.0.0.1:{}/{repo}.git", self.http_port), + (Transport::Ssh, _) => format!("ssh://git@127.0.0.1:{}/{repo}.git", self.ssh_port), + } + } +} + +fn test_database_url(pool: &PgPool) -> Result { + let mut url = Url::parse(&env::var("DATABASE_URL").context("DATABASE_URL needs to be set to run the git tests")?)?; + let options = pool.connect_options(); + let database = options.get_database().context("sqlx test pool has no database name")?; + + url.set_path(database); + Ok(url.into()) +} + +fn free_port() -> Result { + Ok(TcpListener::bind("127.0.0.1:0")?.local_addr()?.port()) +} + +async fn seed_settings(pool: &PgPool, http_port: u16, ssh_port: u16, repos_dir: &Path) -> Result<()> { + let backend = format!("http://127.0.0.1:{http_port}"); + let repos_dir = repos_dir.to_str().context("temp dir is not valid unicode")?; + let ssh_port = ssh_port.to_string(); + + let settings = [ + ("domain.app", backend.as_str()), + ("domain.backend", backend.as_str()), + ("domain.user_email", "localhost"), + ("repositories.base_dir", repos_dir), + ("allow_registrations", "true"), + ("ssh.enabled", "true"), + ("ssh.port", ssh_port.as_str()), + ]; + + for (key, value) in settings { + let result = sqlx::query("update settings set value = $2 where key = $1") + .bind(key) + .bind(value) + .execute(pool) + .await?; + + ensure!(result.rows_affected() == 1, "setting {key} does not exist after migrations"); + } + + Ok(()) +} + +async fn wait_until_ready(child: &mut Child, http_port: u16, ssh_port: u16) -> Result<()> { + let client = Client::new(); + let deadline = Instant::now() + BOOT_TIMEOUT; + + loop { + if let Some(status) = child.try_wait()? { + bail!("gitarena exited during startup with {status}"); + } + + let healthy = client + .get(format!("http://127.0.0.1:{http_port}/healthz")) + .send() + .await + .is_ok_and(|response| response.status().is_success()); + + if healthy && TcpStream::connect(("127.0.0.1", ssh_port)).await.is_ok() { + return Ok(()); + } + + ensure!(Instant::now() < deadline, "gitarena did not become ready within {BOOT_TIMEOUT:?}"); + sleep(Duration::from_millis(100)).await; + } +} + +pub struct Fixture { + pub server: TestServer, + pub owner: TestUser, + pub repo: String, + pub transport: Transport, + pub dir: TempDir, +} + +impl Fixture { + pub async fn new(pool: &PgPool, transport: Transport, visibility: Visibility) -> Result { + let server = TestServer::start(pool).await?; + let owner = TestUser::with_ssh_key(&server, "alice").await?; + let repo = owner.create_repo("repo", visibility).await?; + + Ok(Fixture { + server, + owner, + repo, + transport, + dir: tempdir()?, + }) + } + + pub async fn user(&self, username: &str) -> Result { + TestUser::with_ssh_key(&self.server, username).await + } + + pub fn remote(&self, user: Option<&TestUser>) -> String { + self.server.remote(self.transport, user, &self.repo) + } + + pub fn owner_remote(&self) -> String { + self.remote(Some(&self.owner)) + } + + pub fn path(&self, name: &str) -> PathBuf { + self.dir.path().join(name) + } + + pub fn checkout(&self, user: &TestUser, name: &str) -> Git { + user.git(&self.path(name)) + } + + pub async fn push_seed(&self) -> Result<(Git, String)> { + let local = self.checkout(&self.owner, "seed"); + let head = local.seed().await?; + + local.ok(&["remote", "add", "origin", &self.owner_remote()]).await?; + local.ok(&["push", "--quiet", "--set-upstream", "origin", "main"]).await?; + + Ok((local, head)) + } + + pub async fn refs(&self) -> Result> { + self.owner.git(self.dir.path()).ls_remote(&self.owner_remote()).await + } + + pub async fn git_bug(&self, user: Option<&TestUser>, name: &str) -> Result { + self.git_bug_over(self.transport, user, name).await + } + + pub async fn git_bug_over(&self, transport: Transport, user: Option<&TestUser>, name: &str) -> Result { + let dir = self.path(name); + let home = self.path(&format!("{name}-home")); + fs::create_dir_all(&home).await?; + + let ssh = match (transport, user.and_then(|user| user.ssh_key.as_deref())) { + (Transport::Ssh, Some(key)) => Some(SshAuth::start(&home, key, self.server.ssh_port).await?), + _ => None, + }; + + let git_bug = GitBug { + git: user.map_or_else(|| Git::new(&dir), |user| user.git(&dir)), + home, + ssh, + }; + + git_bug.git.init().await?; + git_bug.set_remote(&self.server.remote(transport, user, &self.repo)).await?; + + Ok(git_bug) + } + + pub async fn forge_mail(&self, pool: &PgPool, user: &TestUser) -> Result { + let (id,): (Uuid,) = sqlx::query_as("select id from users where username = $1") + .bind(&user.username) + .fetch_one(pool) + .await?; + + Ok(format!("{}@localhost", bs58::encode(id.as_bytes()).into_string())) + } +} + +pub struct TestUser { + pub username: String, + pub password: String, + pub email: String, + pub client: Client, + pub ssh_key: Option, + base_url: String, + key_dir: TempDir, +} + +impl TestUser { + pub async fn register(server: &TestServer, username: &str) -> Result { + let user = TestUser { + username: username.to_owned(), + password: format!("password-{username}"), + email: format!("{username}@example.com"), + client: Client::builder().cookie_store(true).build()?, + ssh_key: None, + base_url: server.base_url(), + key_dir: tempdir()?, + }; + + let response = user + .client + .post(user.url("/api/user")) + .json(&json!({ "username": user.username, "email": user.email, "password": user.password })) + .send() + .await?; + + expect_status(response, StatusCode::OK).await?; + Ok(user) + } + + pub async fn with_ssh_key(server: &TestServer, username: &str) -> Result { + let mut user = TestUser::register(server, username).await?; + user.add_ssh_key().await?; + + Ok(user) + } + + pub async fn add_ssh_key(&mut self) -> Result<()> { + let (private_key, public_key) = generate_ssh_key(self.key_dir.path(), &self.username).await?; + + let response = self + .client + .put(self.url("/api/ssh-key")) + .json(&json!({ "title": format!("{} test key", self.username), "key": public_key })) + .send() + .await?; + + expect_status(response, StatusCode::CREATED).await?; + + self.ssh_key = Some(private_key); + Ok(()) + } + + pub async fn create_repo(&self, name: &str, visibility: Visibility) -> Result { + let response = self + .client + .post(self.url("/api/repo")) + .json(&json!({ + "namespace": self.username, + "name": name, + "description": "", + "visibility": visibility.as_str(), + "defaultBranch": "main", + })) + .send() + .await?; + + expect_status(response, StatusCode::OK).await?; + Ok(format!("{}/{name}", self.username)) + } + + pub fn git(&self, dir: &Path) -> Git { + let git = Git::new(dir); + + match &self.ssh_key { + Some(key) => git.with_ssh_key(key), + None => git, + } + } + + pub async fn create_issue(&self, repo: &str, title: &str, body: &str) -> Result { + let response = self + .client + .post(self.url(&format!("/api/repos/{repo}/issues"))) + .json(&json!({ "title": title, "body": body })) + .send() + .await?; + + expect_json(response, StatusCode::CREATED).await + } + + pub async fn update_issue(&self, repo: &str, index: i32, body: Value) -> Result<()> { + let response = self + .client + .patch(self.url(&format!("/api/repos/{repo}/issues/{index}"))) + .json(&body) + .send() + .await?; + + expect_status(response, StatusCode::OK).await?; + Ok(()) + } + + pub async fn delete_issue(&self, repo: &str, index: i32) -> Result<()> { + let response = self.client.delete(self.url(&format!("/api/repos/{repo}/issues/{index}"))).send().await?; + + expect_status(response, StatusCode::NO_CONTENT).await?; + Ok(()) + } + + pub async fn add_comment(&self, repo: &str, index: i32, body: &str) -> Result { + let response = self + .client + .post(self.url(&format!("/api/repos/{repo}/issues/{index}/comments"))) + .json(&json!({ "body": body })) + .send() + .await?; + + let comment: Value = expect_json(response, StatusCode::CREATED).await?; + Ok(comment["id"].as_str().context("comment response has no id")?.to_owned()) + } + + pub async fn edit_comment(&self, repo: &str, index: i32, comment_id: &str, body: &str) -> Result<()> { + let response = self + .client + .patch(self.url(&format!("/api/repos/{repo}/issues/{index}/comments/{comment_id}"))) + .json(&json!({ "body": body })) + .send() + .await?; + + expect_status(response, StatusCode::OK).await?; + Ok(()) + } + + pub async fn create_label(&self, repo: &str, name: &str) -> Result<()> { + let response = self + .client + .post(self.url(&format!("/api/repos/{repo}/labels"))) + .json(&json!({ "name": name, "color": "#ff0000" })) + .send() + .await?; + + expect_status(response, StatusCode::OK).await?; + Ok(()) + } + + pub async fn issue(&self, repo: &str, index: i32) -> Result { + let response = self.client.get(self.url(&format!("/api/repos/{repo}/issues/{index}"))).send().await?; + + expect_json(response, StatusCode::OK).await + } + + pub async fn timeline(&self, repo: &str, index: i32) -> Result> { + let response = self.client.get(self.url(&format!("/api/repos/{repo}/issues/{index}/timeline"))).send().await?; + + expect_json(response, StatusCode::OK).await + } + + fn url(&self, path: &str) -> String { + format!("{}{path}", self.base_url) + } +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Issue { + pub index: i32, + pub git_bug_id: String, +} + +async fn expect_status(response: Response, expected: StatusCode) -> Result { + let status = response.status(); + let url = response.url().clone(); + let body = response.text().await?; + + ensure!(status == expected, "{url} returned {status} instead of {expected}: {body}"); + Ok(body) +} + +async fn expect_json(response: Response, expected: StatusCode) -> Result { + let body = expect_status(response, expected).await?; + serde_json::from_str(&body).with_context(|| format!("response is not the expected json: {body}")) +} + +pub async fn generate_ssh_key(dir: &Path, comment: &str) -> Result<(PathBuf, String)> { + let path = dir.join("id_ed25519"); + + let output = Command::new("ssh-keygen") + .args(["-q", "-t", "ed25519", "-N", "", "-C", comment, "-f"]) + .arg(&path) + .stdin(Stdio::null()) + .output() + .await?; + + ensure!(output.status.success(), "ssh-keygen failed: {}", String::from_utf8_lossy(&output.stderr)); + + let public_key = fs::read_to_string(path.with_extension("pub")).await?; + Ok((path, public_key.trim().to_owned())) +} + +async fn run_with_timeout(command: &mut Command, input: Option<&[u8]>) -> Result { + command.kill_on_drop(true).stdout(Stdio::piped()).stderr(Stdio::piped()); + command.stdin(if input.is_some() { Stdio::piped() } else { Stdio::null() }); + + let mut child = command.spawn()?; + + if let Some(input) = input { + let mut stdin = child.stdin.take().context("child has no stdin")?; + stdin.write_all(input).await?; + } + + timeout(COMMAND_TIMEOUT, child.wait_with_output()) + .await + .with_context(|| format!("{command:?} did not finish within {COMMAND_TIMEOUT:?}"))? + .map_err(Into::into) +} + +pub struct GitOutput { + pub success: bool, + pub stdout: String, + pub stderr: String, +} + +impl From for GitOutput { + fn from(output: Output) -> Self { + GitOutput { + success: output.status.success(), + stdout: String::from_utf8_lossy(&output.stdout).into_owned(), + stderr: String::from_utf8_lossy(&output.stderr).into_owned(), + } + } +} + +#[derive(Clone)] +pub struct Git { + dir: PathBuf, + ssh_key: Option, + protocol: Option, +} + +impl Git { + pub fn new(dir: &Path) -> Git { + Git { + dir: dir.to_owned(), + ssh_key: None, + protocol: None, + } + } + + #[must_use] + pub fn with_ssh_key(mut self, key: &Path) -> Git { + self.ssh_key = Some(key.to_owned()); + self + } + + #[must_use] + pub fn with_protocol(mut self, protocol: Protocol) -> Git { + self.protocol = Some(protocol); + self + } + + pub fn dir(&self) -> &Path { + &self.dir + } + + fn command(&self) -> Command { + let ssh_command = match &self.ssh_key { + Some(key) => format!("{} -i {}", SSH_COMMAND, key.display()), + None => format!("{SSH_COMMAND} -o PubkeyAuthentication=no"), + }; + + let mut command = Command::new("git"); + + command + .current_dir(&self.dir) + .env_remove("SSH_AUTH_SOCK") + .env("GIT_CONFIG_GLOBAL", "/dev/null") + .env("GIT_CONFIG_SYSTEM", "/dev/null") + .env("GIT_TERMINAL_PROMPT", "0") + .env("GIT_AUTHOR_NAME", AUTHOR_NAME) + .env("GIT_AUTHOR_EMAIL", AUTHOR_EMAIL) + .env("GIT_COMMITTER_NAME", AUTHOR_NAME) + .env("GIT_COMMITTER_EMAIL", AUTHOR_EMAIL) + .env("GIT_SSH_COMMAND", ssh_command) + .env("GIT_CONFIG_COUNT", "2") + .env("GIT_CONFIG_KEY_0", "init.defaultBranch") + .env("GIT_CONFIG_VALUE_0", "main") + .env("GIT_CONFIG_KEY_1", "protocol.version") + .env("GIT_CONFIG_VALUE_1", self.protocol.unwrap_or(Protocol::V2).version()); + + command + } + + pub async fn run(&self, args: &[&str]) -> Result { + Ok(run_with_timeout(self.command().args(args), None).await?.into()) + } + + pub async fn run_with_input(&self, args: &[&str], input: &[u8]) -> Result { + Ok(run_with_timeout(self.command().args(args), Some(input)).await?.into()) + } + + pub async fn ok(&self, args: &[&str]) -> Result { + let output = self.run(args).await?; + ensure!(output.success, "git {args:?} failed:\n{}", output.stderr); + + Ok(output.stdout) + } + + pub async fn fails(&self, args: &[&str]) -> Result { + let output = self.run(args).await?; + ensure!(!output.success, "git {args:?} unexpectedly succeeded:\n{}", output.stderr); + + Ok(output.stderr) + } + + pub async fn init(&self) -> Result<()> { + fs::create_dir_all(&self.dir).await?; + self.ok(&["init", "--quiet"]).await?; + + Ok(()) + } + + pub async fn clone_into(&self, remote: &str) -> Result<()> { + self.clone_into_with(remote, &[]).await + } + + pub async fn clone_into_with(&self, remote: &str, args: &[&str]) -> Result<()> { + fs::create_dir_all(&self.dir).await?; + self.ok(&[&["clone", "--quiet"], args, &[remote, "."]].concat()).await?; + + Ok(()) + } + + pub async fn write_file(&self, path: &str, content: &[u8]) -> Result<()> { + let path = self.dir.join(path); + + if let Some(parent) = path.parent() { + fs::create_dir_all(parent).await?; + } + + fs::write(path, content).await?; + Ok(()) + } + + pub async fn read_file(&self, path: &str) -> Result { + Ok(fs::read_to_string(self.dir.join(path)).await?) + } + + pub async fn commit_all(&self, message: &str) -> Result { + self.ok(&["add", "--all"]).await?; + self.ok(&["commit", "--quiet", "--message", message]).await?; + + self.rev_parse("HEAD").await + } + + pub async fn commit_file(&self, path: &str, content: &str, message: &str) -> Result { + self.write_file(path, content.as_bytes()).await?; + self.commit_all(message).await + } + + pub async fn rev_parse(&self, rev: &str) -> Result { + Ok(self.ok(&["rev-parse", rev]).await?.trim().to_owned()) + } + + pub async fn rev_count(&self, rev: &str) -> Result { + Ok(self.ok(&["rev-list", "--count", rev]).await?.trim().parse()?) + } + + pub async fn ls_remote(&self, remote: &str) -> Result> { + let stdout = self.ok(&["ls-remote", remote]).await?; + + stdout + .lines() + .map(|line| { + let (oid, name) = line.split_once('\t').with_context(|| format!("malformed ls-remote line: {line}"))?; + Ok((name.to_owned(), oid.to_owned())) + }) + .collect() + } + + pub async fn fsck(&self) -> Result<()> { + self.ok(&["fsck", "--full", "--no-progress"]).await?; + Ok(()) + } + + pub async fn seed(&self) -> Result { + self.init().await?; + self.commit_file("README.md", "# test\n", "initial commit").await + } + + pub async fn fast_import(&self, commits: usize, large_blobs: usize, blob_size: usize) -> Result<()> { + self.init().await?; + + let output = self + .run_with_input(&["fast-import", "--quiet"], &fast_import_stream(commits, large_blobs, blob_size)) + .await?; + ensure!(output.success, "git fast-import failed:\n{}", output.stderr); + + Ok(()) + } +} + +// git-bug talks to the remote through go-git, which ignores `GIT_SSH_COMMAND` and only authenticates via an agent +pub struct SshAuth { + agent: Child, + socket: PathBuf, + known_hosts: PathBuf, +} + +impl SshAuth { + async fn start(dir: &Path, key: &Path, ssh_port: u16) -> Result { + let socket = dir.join("agent.sock"); + let known_hosts = dir.join("known_hosts"); + + let agent = Command::new("ssh-agent") + .arg("-D") + .arg("-a") + .arg(&socket) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .kill_on_drop(true) + .spawn() + .context("failed to spawn ssh-agent")?; + + let auth = SshAuth { agent, socket, known_hosts }; + + let deadline = Instant::now() + AGENT_TIMEOUT; + + while !fs::try_exists(&auth.socket).await? { + ensure!(Instant::now() < deadline, "ssh-agent did not create its socket within {AGENT_TIMEOUT:?}"); + sleep(Duration::from_millis(20)).await; + } + + let output = run_with_timeout(Command::new("ssh-add").arg("-q").arg(key).env("SSH_AUTH_SOCK", &auth.socket), None).await?; + ensure!(output.status.success(), "ssh-add failed: {}", String::from_utf8_lossy(&output.stderr)); + + let output = run_with_timeout(Command::new("ssh-keyscan").args(["-p", &ssh_port.to_string(), "127.0.0.1"]), None).await?; + ensure!( + output.status.success() && !output.stdout.is_empty(), + "ssh-keyscan failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + + fs::write(&auth.known_hosts, &output.stdout).await?; + Ok(auth) + } +} + +pub struct GitBug { + pub git: Git, + home: PathBuf, + ssh: Option, +} + +impl GitBug { + pub async fn set_remote(&self, remote: &str) -> Result<()> { + if !self.git.run(&["remote", "set-url", "origin", remote]).await?.success { + self.git.ok(&["remote", "add", "origin", remote]).await?; + } + + Ok(()) + } + + fn command(&self) -> Command { + let mut command = Command::new("git-bug"); + + command + .current_dir(self.git.dir()) + .env_clear() + .env("PATH", env::var_os("PATH").unwrap_or_default()) + .env("HOME", &self.home) + .env("GIT_CONFIG_GLOBAL", "/dev/null") + .env("GIT_CONFIG_SYSTEM", "/dev/null") + .env("GIT_TERMINAL_PROMPT", "0"); + + if let Some(ssh) = &self.ssh { + command.env("SSH_AUTH_SOCK", &ssh.socket).env("SSH_KNOWN_HOSTS", &ssh.known_hosts); + } + + command + } + + pub async fn run(&self, args: &[&str]) -> Result { + Ok(run_with_timeout(self.command().args(args), None).await?.into()) + } + + pub async fn ok(&self, args: &[&str]) -> Result { + let output = self.run(args).await?; + ensure!(output.success, "git-bug {args:?} failed:\n{}{}", output.stdout, output.stderr); + + Ok(output.stdout) + } + + pub async fn fails(&self, args: &[&str]) -> Result { + let output = self.run(args).await?; + ensure!(!output.success, "git-bug {args:?} unexpectedly succeeded:\n{}{}", output.stdout, output.stderr); + + Ok(format!("{}{}", output.stdout, output.stderr)) + } + + pub async fn pull(&self) -> Result<()> { + self.ok(&["pull", "origin"]).await?; + Ok(()) + } + + pub async fn create_identity(&self, name: &str) -> Result<()> { + self.ok(&["user", "new", "--non-interactive", "--name", name, "--email", &format!("{name}@example.com")]) + .await?; + + Ok(()) + } + + pub async fn create_bug(&self, title: &str) -> Result<()> { + self.ok(&["bug", "new", "--non-interactive", "--title", title, "--message", "local"]).await?; + Ok(()) + } + + pub async fn bugs(&self) -> Result> { + let stdout = self.ok(&["bug", "--format", "json"]).await?; + serde_json::from_str(&stdout).with_context(|| format!("git-bug bug output is not valid json: {stdout}")) + } + + pub async fn show(&self, id: &str) -> Result { + let stdout = self.ok(&["bug", "show", "--format", "json", id]).await?; + serde_json::from_str(&stdout).with_context(|| format!("git-bug bug show output is not valid json: {stdout}")) + } + + // `git bug user show` refuses to run until a local identity has been set, so the stored identity is read directly + pub async fn identity(&self, id: &str) -> Result { + let stdout = self.git.ok(&["cat-file", "blob", &format!("refs/identities/{id}:version")]).await?; + serde_json::from_str(&stdout).with_context(|| format!("identity {id} is not valid json: {stdout}")) + } + + pub async fn local_refs(&self, prefix: &str) -> Result> { + let stdout = self.git.ok(&["for-each-ref", "--format=%(refname)", prefix]).await?; + Ok(stdout.lines().map(ToOwned::to_owned).collect()) + } +} + +const SSH_COMMAND: &str = "ssh -F /dev/null -o IdentitiesOnly=yes -o IdentityAgent=none -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o BatchMode=yes -o LogLevel=ERROR"; + +fn fast_import_stream(commits: usize, large_blobs: usize, blob_size: usize) -> Vec { + let mut stream = Vec::new(); + let mut state = 0x2545_f491_4f6c_dd1d_u64; + + let data = |stream: &mut Vec, content: &[u8]| { + stream.extend_from_slice(format!("data {}\n", content.len()).as_bytes()); + stream.extend_from_slice(content); + stream.push(b'\n'); + }; + + for index in 0..commits { + stream.extend_from_slice(b"commit refs/heads/main\n"); + stream.extend_from_slice(format!("committer {AUTHOR_NAME} <{AUTHOR_EMAIL}> {} +0000\n", 1_700_000_000 + index * 60).as_bytes()); + data(&mut stream, format!("commit {index}").as_bytes()); + + let file = format!("M 100644 inline files/{}.txt\n", index % 50); + stream.extend_from_slice(file.as_bytes()); + data(&mut stream, format!("revision {index}\n").repeat(index % 7 + 1).as_bytes()); + + if index < large_blobs { + let blob = (0..blob_size) + .map(|_| { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state.to_le_bytes()[0] + }) + .collect::>(); + + stream.extend_from_slice(format!("M 100644 inline blobs/{index}.bin\n").as_bytes()); + data(&mut stream, &blob); + } + + stream.push(b'\n'); + } + + stream +} diff --git a/gitarena/tests/common/scenarios.rs b/gitarena/tests/common/scenarios.rs new file mode 100644 index 00000000..4c5bf049 --- /dev/null +++ b/gitarena/tests/common/scenarios.rs @@ -0,0 +1,313 @@ +use super::{Fixture, Protocol, Transport, Visibility}; +use anyhow::Result; +use pretty_assertions::assert_eq; +use sqlx::PgPool; + +pub const SECRET: &str = + "sk_gap_1955bd1d7e0759d3c7d41117fd42661e6ab51f8dd6d437cf6fc23bde26f32927179a9a7dfcc66706041ad94020fb132ef1cef931cc3f7825fa63661092fa57a4"; + +pub async fn clone_empty_repo(pool: PgPool, transport: Transport, protocol: Protocol) -> Result<()> { + let fixture = Fixture::new(&pool, transport, Visibility::Public).await?; + + let clone = fixture.checkout(&fixture.owner, "clone").with_protocol(protocol); + clone.clone_into(&fixture.owner_remote()).await?; + + assert_eq!(clone.ok(&["symbolic-ref", "HEAD"]).await?.trim(), "refs/heads/main"); + assert_eq!(clone.ok(&["rev-list", "--all"]).await?, ""); + Ok(()) +} + +pub async fn initial_push(pool: PgPool, transport: Transport) -> Result<()> { + let fixture = Fixture::new(&pool, transport, Visibility::Public).await?; + + let (_, head) = fixture.push_seed().await?; + let refs = fixture.refs().await?; + + assert_eq!(refs.get("refs/heads/main"), Some(&head)); + assert_eq!(refs.get("HEAD"), Some(&head)); + Ok(()) +} + +pub async fn clone_non_empty_repo(pool: PgPool, transport: Transport, protocol: Protocol) -> Result<()> { + let fixture = Fixture::new(&pool, transport, Visibility::Public).await?; + let (_, head) = fixture.push_seed().await?; + + let clone = fixture.checkout(&fixture.owner, "clone").with_protocol(protocol); + clone.clone_into(&fixture.owner_remote()).await?; + + assert_eq!(clone.rev_parse("HEAD").await?, head); + assert_eq!(clone.ok(&["symbolic-ref", "HEAD"]).await?.trim(), "refs/heads/main"); + assert_eq!(clone.read_file("README.md").await?, "# test\n"); + clone.fsck().await?; + Ok(()) +} + +pub async fn fetch_after_server_change(pool: PgPool, transport: Transport, protocol: Protocol) -> Result<()> { + let fixture = Fixture::new(&pool, transport, Visibility::Public).await?; + let (local, _) = fixture.push_seed().await?; + + let clone = fixture.checkout(&fixture.owner, "clone").with_protocol(protocol); + clone.clone_into(&fixture.owner_remote()).await?; + + let head = local.commit_file("second.txt", "second\n", "second commit").await?; + local.ok(&["push", "--quiet"]).await?; + + clone.ok(&["fetch", "--quiet"]).await?; + + assert_eq!(clone.rev_parse("origin/main").await?, head); + clone.ok(&["merge", "--quiet", "--ff-only", "origin/main"]).await?; + assert_eq!(clone.read_file("second.txt").await?, "second\n"); + Ok(()) +} + +pub async fn ls_remote_lists_all_refs(pool: PgPool, transport: Transport, protocol: Protocol) -> Result<()> { + let fixture = Fixture::new(&pool, transport, Visibility::Public).await?; + let (local, head) = fixture.push_seed().await?; + + local.ok(&["branch", "feature"]).await?; + local.ok(&["tag", "v1"]).await?; + local.ok(&["push", "--quiet", "origin", "feature", "v1"]).await?; + + let refs = fixture + .checkout(&fixture.owner, "query") + .with_protocol(protocol) + .ls_remote(&fixture.owner_remote()) + .await?; + + assert_eq!( + refs.into_iter().collect::>(), + vec![ + ("HEAD".to_owned(), head.clone()), + ("refs/heads/feature".to_owned(), head.clone()), + ("refs/heads/main".to_owned(), head.clone()), + ("refs/tags/v1".to_owned(), head), + ] + ); + Ok(()) +} + +pub async fn ls_remote_peels_annotated_tags(pool: PgPool, transport: Transport, protocol: Protocol) -> Result<()> { + let fixture = Fixture::new(&pool, transport, Visibility::Public).await?; + let (local, head) = fixture.push_seed().await?; + + local.ok(&["tag", "--annotate", "--message", "release", "v1"]).await?; + local.ok(&["push", "--quiet", "origin", "v1"]).await?; + + let refs = fixture + .checkout(&fixture.owner, "query") + .with_protocol(protocol) + .ls_remote(&fixture.owner_remote()) + .await?; + + assert_eq!(refs.get("refs/tags/v1"), Some(&local.rev_parse("v1").await?)); + assert_eq!(refs.get("refs/tags/v1^{}"), Some(&head)); + Ok(()) +} + +pub async fn push_new_branch(pool: PgPool, transport: Transport) -> Result<()> { + let fixture = Fixture::new(&pool, transport, Visibility::Public).await?; + let (local, _) = fixture.push_seed().await?; + + local.ok(&["switch", "--quiet", "--create", "feature"]).await?; + let feature = local.commit_file("feature.txt", "feature\n", "feature commit").await?; + local.ok(&["push", "--quiet", "origin", "feature"]).await?; + + assert_eq!(fixture.refs().await?.get("refs/heads/feature"), Some(&feature)); + Ok(()) +} + +pub async fn push_tags(pool: PgPool, transport: Transport) -> Result<()> { + let fixture = Fixture::new(&pool, transport, Visibility::Public).await?; + let (local, head) = fixture.push_seed().await?; + + local.ok(&["tag", "lightweight"]).await?; + local.ok(&["tag", "--annotate", "--message", "release", "annotated"]).await?; + local.ok(&["push", "--quiet", "origin", "--tags"]).await?; + + let refs = fixture.refs().await?; + assert_eq!(refs.get("refs/tags/lightweight"), Some(&head)); + assert_eq!(refs.get("refs/tags/annotated"), Some(&local.rev_parse("annotated").await?)); + + let clone = fixture.checkout(&fixture.owner, "clone"); + clone.clone_into(&fixture.owner_remote()).await?; + + assert_eq!(clone.ok(&["cat-file", "-t", "annotated"]).await?.trim(), "tag"); + assert_eq!(clone.rev_parse("annotated^{commit}").await?, head); + clone.fsck().await?; + Ok(()) +} + +pub async fn force_push(pool: PgPool, transport: Transport) -> Result<()> { + let fixture = Fixture::new(&pool, transport, Visibility::Public).await?; + let (local, base) = fixture.push_seed().await?; + + let pushed = local.commit_file("a.txt", "a\n", "pushed commit").await?; + local.ok(&["push", "--quiet"]).await?; + + local.ok(&["reset", "--quiet", "--hard", &base]).await?; + let rewritten = local.commit_file("b.txt", "b\n", "rewritten commit").await?; + + let stderr = local.fails(&["push", "origin", "main"]).await?; + assert!(stderr.contains("[rejected]"), "{stderr}"); + assert_eq!(fixture.refs().await?.get("refs/heads/main"), Some(&pushed)); + + local.ok(&["push", "--quiet", "--force", "origin", "main"]).await?; + assert_eq!(fixture.refs().await?.get("refs/heads/main"), Some(&rewritten)); + Ok(()) +} + +pub async fn delete_branch(pool: PgPool, transport: Transport) -> Result<()> { + let fixture = Fixture::new(&pool, transport, Visibility::Public).await?; + let (local, head) = fixture.push_seed().await?; + + local.ok(&["push", "--quiet", "origin", "main:refs/heads/feature"]).await?; + assert_eq!(fixture.refs().await?.get("refs/heads/feature"), Some(&head)); + + local.ok(&["push", "--quiet", "origin", "--delete", "feature"]).await?; + + let refs = fixture.refs().await?; + assert_eq!(refs.get("refs/heads/feature"), None); + assert_eq!(refs.get("refs/heads/main"), Some(&head)); + Ok(()) +} + +pub async fn delete_tag(pool: PgPool, transport: Transport) -> Result<()> { + let fixture = Fixture::new(&pool, transport, Visibility::Public).await?; + let (local, head) = fixture.push_seed().await?; + + local.ok(&["tag", "v1"]).await?; + local.ok(&["push", "--quiet", "origin", "v1"]).await?; + assert_eq!(fixture.refs().await?.get("refs/tags/v1"), Some(&head)); + + local.ok(&["push", "--quiet", "origin", "--delete", "refs/tags/v1"]).await?; + + assert_eq!(fixture.refs().await?.get("refs/tags/v1"), None); + Ok(()) +} + +pub async fn delete_multiple_refs_in_one_push(pool: PgPool, transport: Transport) -> Result<()> { + let fixture = Fixture::new(&pool, transport, Visibility::Public).await?; + let (local, head) = fixture.push_seed().await?; + + local.ok(&["tag", "v1"]).await?; + local.ok(&["push", "--quiet", "origin", "main:refs/heads/feature", "v1"]).await?; + + local.ok(&["push", "--quiet", "origin", "--delete", "feature", "refs/tags/v1"]).await?; + + let refs = fixture.refs().await?; + assert_eq!(refs.get("refs/heads/feature"), None); + assert_eq!(refs.get("refs/tags/v1"), None); + assert_eq!(refs.get("refs/heads/main"), Some(&head)); + Ok(()) +} + +pub async fn owner_can_clone_and_push_private_repo(pool: PgPool, transport: Transport, protocol: Protocol) -> Result<()> { + let fixture = Fixture::new(&pool, transport, Visibility::Private).await?; + let (_, head) = fixture.push_seed().await?; + + let clone = fixture.checkout(&fixture.owner, "clone").with_protocol(protocol); + clone.clone_into(&fixture.owner_remote()).await?; + assert_eq!(clone.rev_parse("HEAD").await?, head); + + let next = clone.commit_file("next.txt", "next\n", "next commit").await?; + clone.ok(&["push", "--quiet"]).await?; + + assert_eq!(fixture.refs().await?.get("refs/heads/main"), Some(&next)); + Ok(()) +} + +pub async fn other_user_can_clone_public_repo(pool: PgPool, transport: Transport, protocol: Protocol) -> Result<()> { + let fixture = Fixture::new(&pool, transport, Visibility::Public).await?; + let (_, head) = fixture.push_seed().await?; + let bob = fixture.user("bob").await?; + + let clone = fixture.checkout(&bob, "clone").with_protocol(protocol); + clone.clone_into(&fixture.remote(Some(&bob))).await?; + + assert_eq!(clone.rev_parse("HEAD").await?, head); + Ok(()) +} + +pub async fn other_user_cannot_push_to_public_repo(pool: PgPool, transport: Transport) -> Result<()> { + let fixture = Fixture::new(&pool, transport, Visibility::Public).await?; + let (_, head) = fixture.push_seed().await?; + let bob = fixture.user("bob").await?; + + let clone = fixture.checkout(&bob, "clone"); + clone.clone_into(&fixture.remote(Some(&bob))).await?; + clone.commit_file("bob.txt", "bob\n", "bob's commit").await?; + + clone.fails(&["push", "origin", "main"]).await?; + assert_eq!(fixture.refs().await?.get("refs/heads/main"), Some(&head)); + Ok(()) +} + +pub async fn other_user_cannot_clone_private_repo(pool: PgPool, transport: Transport, protocol: Protocol) -> Result<()> { + let fixture = Fixture::new(&pool, transport, Visibility::Private).await?; + fixture.push_seed().await?; + let bob = fixture.user("bob").await?; + + let clone = fixture.checkout(&bob, "clone").with_protocol(protocol); + clone.init().await?; + clone.fails(&["fetch", &fixture.remote(Some(&bob)), "main"]).await?; + Ok(()) +} + +pub async fn other_user_cannot_push_to_private_repo(pool: PgPool, transport: Transport) -> Result<()> { + let fixture = Fixture::new(&pool, transport, Visibility::Private).await?; + let (_, head) = fixture.push_seed().await?; + let bob = fixture.user("bob").await?; + + let local = fixture.checkout(&bob, "local"); + local.seed().await?; + + local.fails(&["push", &fixture.remote(Some(&bob)), "main:refs/heads/bob"]).await?; + + let refs = fixture.refs().await?; + assert_eq!(refs.get("refs/heads/bob"), None); + assert_eq!(refs.get("refs/heads/main"), Some(&head)); + Ok(()) +} + +pub async fn nonexistent_repo_fails(pool: PgPool, transport: Transport, protocol: Protocol) -> Result<()> { + let fixture = Fixture::new(&pool, transport, Visibility::Public).await?; + + let clone = fixture.checkout(&fixture.owner, "clone").with_protocol(protocol); + clone.init().await?; + + clone + .fails(&["fetch", &fixture.server.remote(transport, Some(&fixture.owner), "alice/missing")]) + .await?; + clone + .fails(&["fetch", &fixture.server.remote(transport, Some(&fixture.owner), "nobody/missing")]) + .await?; + Ok(()) +} + +pub async fn nonexistent_repo_push_fails(pool: PgPool, transport: Transport) -> Result<()> { + let fixture = Fixture::new(&pool, transport, Visibility::Public).await?; + + let local = fixture.checkout(&fixture.owner, "local"); + local.seed().await?; + + local + .fails(&["push", &fixture.server.remote(transport, Some(&fixture.owner), "alice/missing"), "main"]) + .await?; + Ok(()) +} + +pub async fn push_with_secret_is_rejected(pool: PgPool, transport: Transport) -> Result<()> { + let fixture = Fixture::new(&pool, transport, Visibility::Public).await?; + let (local, head) = fixture.push_seed().await?; + + local.commit_file("config.env", &format!("TOKEN={SECRET}\n"), "add config").await?; + + let stderr = local.fails(&["push", "origin", "main"]).await?; + + assert!(stderr.contains("SECRETS DETECTED IN PUSH"), "{stderr}"); + assert!(stderr.contains("GitArena Personal Access Token"), "{stderr}"); + assert!(stderr.contains("push contains secrets"), "{stderr}"); + assert!(!stderr.contains(SECRET), "{stderr}"); + assert_eq!(fixture.refs().await?.get("refs/heads/main"), Some(&head)); + Ok(()) +} diff --git a/gitarena/tests/git_bug.rs b/gitarena/tests/git_bug.rs new file mode 100644 index 00000000..09d5fa3c --- /dev/null +++ b/gitarena/tests/git_bug.rs @@ -0,0 +1,369 @@ +use anyhow::{Context, Result}; +use common::{Fixture, GitBug, Issue, Transport, Visibility}; +use pretty_assertions::assert_eq; +use serde_json::{Value, json}; +use sqlx::PgPool; + +mod common; + +async fn pulled_issue(pool: &PgPool, transport: Transport) -> Result<(Fixture, Issue, GitBug)> { + let fixture = Fixture::new(pool, transport, Visibility::Public).await?; + let issue = fixture.owner.create_issue(&fixture.repo, "first issue", "issue body").await?; + + let git_bug = fixture.git_bug(Some(&fixture.owner), "bugs").await?; + git_bug.pull().await?; + + Ok((fixture, issue, git_bug)) +} + +fn messages(show: &Value) -> Result> { + show["comments"] + .as_array() + .context("git-bug show has no comments array")? + .iter() + .map(|comment| comment["message"].as_str().map(ToOwned::to_owned).context("git-bug comment has no message")) + .collect() +} + +fn labels(show: &Value) -> Vec<&str> { + show["labels"] + .as_array() + .map_or_default(|labels| labels.iter().filter_map(Value::as_str).collect()) +} + +async fn pull_issue(pool: PgPool, transport: Transport) -> Result<()> { + let (fixture, issue, git_bug) = pulled_issue(&pool, transport).await?; + + let bugs = git_bug.bugs().await?; + assert_eq!(bugs.len(), 1); + + let show = git_bug.show(&issue.git_bug_id).await?; + assert_eq!(show["id"], issue.git_bug_id.as_str()); + assert_eq!(show["title"], "first issue"); + assert_eq!(show["status"], "open"); + assert_eq!(messages(&show)?, vec!["issue body"]); + assert_eq!(show["author"]["name"], "alice"); + + let author_id = show["author"]["id"].as_str().context("git-bug author has no id")?; + let identity = git_bug.identity(author_id).await?; + + assert_eq!(identity["name"], "alice"); + assert_eq!(identity["email"], fixture.forge_mail(&pool, &fixture.owner).await?.as_str()); + assert_eq!(git_bug.local_refs("refs/identities").await?, vec![format!("refs/identities/{author_id}")]); + Ok(()) +} + +#[test_with::executable(git-bug)] +#[sqlx::test(migrations = "../migrations")] +async fn pull_issue_http(pool: PgPool) -> Result<()> { + pull_issue(pool, Transport::Http).await +} + +#[test_with::executable(git-bug)] +#[sqlx::test(migrations = "../migrations")] +async fn pull_issue_ssh(pool: PgPool) -> Result<()> { + pull_issue(pool, Transport::Ssh).await +} + +async fn pull_added_comment(pool: PgPool, transport: Transport) -> Result<()> { + let (fixture, issue, git_bug) = pulled_issue(&pool, transport).await?; + + fixture.owner.add_comment(&fixture.repo, issue.index, "a comment").await?; + git_bug.pull().await?; + + assert_eq!(messages(&git_bug.show(&issue.git_bug_id).await?)?, vec!["issue body", "a comment"]); + Ok(()) +} + +#[test_with::executable(git-bug)] +#[sqlx::test(migrations = "../migrations")] +async fn pull_added_comment_http(pool: PgPool) -> Result<()> { + pull_added_comment(pool, Transport::Http).await +} + +#[test_with::executable(git-bug)] +#[sqlx::test(migrations = "../migrations")] +async fn pull_added_comment_ssh(pool: PgPool) -> Result<()> { + pull_added_comment(pool, Transport::Ssh).await +} + +async fn pull_edited_comment(pool: PgPool, transport: Transport) -> Result<()> { + let (fixture, issue, git_bug) = pulled_issue(&pool, transport).await?; + + let comment = fixture.owner.add_comment(&fixture.repo, issue.index, "a comment").await?; + git_bug.pull().await?; + + fixture.owner.edit_comment(&fixture.repo, issue.index, &comment, "an edited comment").await?; + git_bug.pull().await?; + + assert_eq!(messages(&git_bug.show(&issue.git_bug_id).await?)?, vec!["issue body", "an edited comment"]); + Ok(()) +} + +#[test_with::executable(git-bug)] +#[sqlx::test(migrations = "../migrations")] +async fn pull_edited_comment_http(pool: PgPool) -> Result<()> { + pull_edited_comment(pool, Transport::Http).await +} + +#[test_with::executable(git-bug)] +#[sqlx::test(migrations = "../migrations")] +async fn pull_edited_comment_ssh(pool: PgPool) -> Result<()> { + pull_edited_comment(pool, Transport::Ssh).await +} + +async fn pull_status_changes(pool: PgPool, transport: Transport) -> Result<()> { + let (fixture, issue, git_bug) = pulled_issue(&pool, transport).await?; + + fixture.owner.update_issue(&fixture.repo, issue.index, json!({ "status": "completed" })).await?; + git_bug.pull().await?; + assert_eq!(git_bug.show(&issue.git_bug_id).await?["status"], "closed"); + + fixture.owner.update_issue(&fixture.repo, issue.index, json!({ "status": "open" })).await?; + git_bug.pull().await?; + assert_eq!(git_bug.show(&issue.git_bug_id).await?["status"], "open"); + Ok(()) +} + +#[test_with::executable(git-bug)] +#[sqlx::test(migrations = "../migrations")] +async fn pull_status_changes_http(pool: PgPool) -> Result<()> { + pull_status_changes(pool, Transport::Http).await +} + +#[test_with::executable(git-bug)] +#[sqlx::test(migrations = "../migrations")] +async fn pull_status_changes_ssh(pool: PgPool) -> Result<()> { + pull_status_changes(pool, Transport::Ssh).await +} + +async fn pull_title_change(pool: PgPool, transport: Transport) -> Result<()> { + let (fixture, issue, git_bug) = pulled_issue(&pool, transport).await?; + + fixture + .owner + .update_issue(&fixture.repo, issue.index, json!({ "title": "renamed issue" })) + .await?; + git_bug.pull().await?; + + assert_eq!(git_bug.show(&issue.git_bug_id).await?["title"], "renamed issue"); + Ok(()) +} + +#[test_with::executable(git-bug)] +#[sqlx::test(migrations = "../migrations")] +async fn pull_title_change_http(pool: PgPool) -> Result<()> { + pull_title_change(pool, Transport::Http).await +} + +#[test_with::executable(git-bug)] +#[sqlx::test(migrations = "../migrations")] +async fn pull_title_change_ssh(pool: PgPool) -> Result<()> { + pull_title_change(pool, Transport::Ssh).await +} + +async fn pull_label_changes(pool: PgPool, transport: Transport) -> Result<()> { + let (fixture, issue, git_bug) = pulled_issue(&pool, transport).await?; + + fixture.owner.create_label(&fixture.repo, "bug").await?; + fixture.owner.create_label(&fixture.repo, "docs").await?; + + fixture + .owner + .update_issue(&fixture.repo, issue.index, json!({ "labelsAdd": ["bug", "docs"] })) + .await?; + git_bug.pull().await?; + assert_eq!(labels(&git_bug.show(&issue.git_bug_id).await?), vec!["bug", "docs"]); + + fixture + .owner + .update_issue(&fixture.repo, issue.index, json!({ "labelsRemove": ["bug"] })) + .await?; + git_bug.pull().await?; + assert_eq!(labels(&git_bug.show(&issue.git_bug_id).await?), vec!["docs"]); + Ok(()) +} + +#[test_with::executable(git-bug)] +#[sqlx::test(migrations = "../migrations")] +async fn pull_label_changes_http(pool: PgPool) -> Result<()> { + pull_label_changes(pool, Transport::Http).await +} + +#[test_with::executable(git-bug)] +#[sqlx::test(migrations = "../migrations")] +async fn pull_label_changes_ssh(pool: PgPool) -> Result<()> { + pull_label_changes(pool, Transport::Ssh).await +} + +async fn deleted_issue_ref_disappears(pool: PgPool, transport: Transport) -> Result<()> { + let fixture = Fixture::new(&pool, transport, Visibility::Public).await?; + let issue = fixture.owner.create_issue(&fixture.repo, "doomed", "body").await?; + let bug_ref = format!("refs/bugs/{}", issue.git_bug_id); + + assert!(fixture.refs().await?.contains_key(&bug_ref)); + + fixture.owner.delete_issue(&fixture.repo, issue.index).await?; + + assert!(!fixture.refs().await?.contains_key(&bug_ref)); + Ok(()) +} + +#[test_with::executable(git-bug)] +#[sqlx::test(migrations = "../migrations")] +async fn deleted_issue_ref_disappears_http(pool: PgPool) -> Result<()> { + deleted_issue_ref_disappears(pool, Transport::Http).await +} + +#[test_with::executable(git-bug)] +#[sqlx::test(migrations = "../migrations")] +async fn deleted_issue_ref_disappears_ssh(pool: PgPool) -> Result<()> { + deleted_issue_ref_disappears(pool, Transport::Ssh).await +} + +async fn push_of_local_bug_is_rejected(pool: PgPool, transport: Transport) -> Result<()> { + let (fixture, _, git_bug) = pulled_issue(&pool, transport).await?; + let before = fixture.refs().await?; + + git_bug.create_identity("local").await?; + git_bug.create_bug("local bug").await?; + git_bug.fails(&["push", "origin"]).await?; + + assert_eq!(fixture.refs().await?, before); + Ok(()) +} + +#[test_with::executable(git-bug)] +#[sqlx::test(migrations = "../migrations")] +async fn push_of_local_bug_is_rejected_http(pool: PgPool) -> Result<()> { + push_of_local_bug_is_rejected(pool, Transport::Http).await +} + +#[test_with::executable(git-bug)] +#[sqlx::test(migrations = "../migrations")] +async fn push_of_local_bug_is_rejected_ssh(pool: PgPool) -> Result<()> { + push_of_local_bug_is_rejected(pool, Transport::Ssh).await +} + +async fn push_of_local_identity_is_rejected(pool: PgPool, transport: Transport) -> Result<()> { + let (fixture, _, git_bug) = pulled_issue(&pool, transport).await?; + let before = fixture.refs().await?; + + git_bug.create_identity("local").await?; + git_bug.fails(&["push", "origin"]).await?; + + assert_eq!(fixture.refs().await?, before); + Ok(()) +} + +#[test_with::executable(git-bug)] +#[sqlx::test(migrations = "../migrations")] +async fn push_of_local_identity_is_rejected_http(pool: PgPool) -> Result<()> { + push_of_local_identity_is_rejected(pool, Transport::Http).await +} + +#[test_with::executable(git-bug)] +#[sqlx::test(migrations = "../migrations")] +async fn push_of_local_identity_is_rejected_ssh(pool: PgPool) -> Result<()> { + push_of_local_identity_is_rejected(pool, Transport::Ssh).await +} + +async fn plain_git_push_of_bug_refs_is_rejected(pool: PgPool, transport: Transport) -> Result<()> { + let (fixture, _, git_bug) = pulled_issue(&pool, transport).await?; + let before = fixture.refs().await?; + + git_bug.create_identity("local").await?; + git_bug.create_bug("local bug").await?; + + git_bug.git.fails(&["push", "origin", "refs/bugs/*:refs/bugs/*"]).await?; + git_bug.git.fails(&["push", "origin", "refs/identities/*:refs/identities/*"]).await?; + + assert_eq!(fixture.refs().await?, before); + Ok(()) +} + +#[test_with::executable(git-bug)] +#[sqlx::test(migrations = "../migrations")] +async fn plain_git_push_of_bug_refs_is_rejected_http(pool: PgPool) -> Result<()> { + plain_git_push_of_bug_refs_is_rejected(pool, Transport::Http).await +} + +#[test_with::executable(git-bug)] +#[sqlx::test(migrations = "../migrations")] +async fn plain_git_push_of_bug_refs_is_rejected_ssh(pool: PgPool) -> Result<()> { + plain_git_push_of_bug_refs_is_rejected(pool, Transport::Ssh).await +} + +async fn other_user_cannot_pull_private_repo(pool: PgPool, transport: Transport) -> Result<()> { + let fixture = Fixture::new(&pool, transport, Visibility::Private).await?; + fixture.owner.create_issue(&fixture.repo, "secret issue", "body").await?; + let bob = fixture.user("bob").await?; + + let git_bug = fixture.git_bug(Some(&bob), "bugs").await?; + git_bug.fails(&["pull", "origin"]).await?; + + assert_eq!(git_bug.local_refs("refs/bugs").await?, Vec::::new()); + Ok(()) +} + +#[test_with::executable(git-bug)] +#[sqlx::test(migrations = "../migrations")] +async fn other_user_cannot_pull_private_repo_http(pool: PgPool) -> Result<()> { + other_user_cannot_pull_private_repo(pool, Transport::Http).await +} + +#[test_with::executable(git-bug)] +#[sqlx::test(migrations = "../migrations")] +async fn other_user_cannot_pull_private_repo_ssh(pool: PgPool) -> Result<()> { + other_user_cannot_pull_private_repo(pool, Transport::Ssh).await +} + +async fn plain_clone_does_not_fetch_bug_refs(pool: PgPool, transport: Transport) -> Result<()> { + let fixture = Fixture::new(&pool, transport, Visibility::Public).await?; + fixture.push_seed().await?; + let issue = fixture.owner.create_issue(&fixture.repo, "issue", "body").await?; + + assert!(fixture.refs().await?.contains_key(&format!("refs/bugs/{}", issue.git_bug_id))); + + let clone = fixture.checkout(&fixture.owner, "clone"); + clone.clone_into(&fixture.owner_remote()).await?; + + assert_eq!(clone.ok(&["for-each-ref", "refs/bugs", "refs/identities"]).await?, ""); + Ok(()) +} + +#[sqlx::test(migrations = "../migrations")] +async fn plain_clone_does_not_fetch_bug_refs_http(pool: PgPool) -> Result<()> { + plain_clone_does_not_fetch_bug_refs(pool, Transport::Http).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn plain_clone_does_not_fetch_bug_refs_ssh(pool: PgPool) -> Result<()> { + plain_clone_does_not_fetch_bug_refs(pool, Transport::Ssh).await +} + +#[test_with::executable(git-bug)] +#[sqlx::test(migrations = "../migrations")] +async fn anonymous_pull_public_repo(pool: PgPool) -> Result<()> { + let fixture = Fixture::new(&pool, Transport::Http, Visibility::Public).await?; + let issue = fixture.owner.create_issue(&fixture.repo, "public issue", "body").await?; + + let git_bug = fixture.git_bug(None, "bugs").await?; + git_bug.pull().await?; + + assert_eq!(git_bug.show(&issue.git_bug_id).await?["title"], "public issue"); + Ok(()) +} + +#[test_with::executable(git-bug)] +#[sqlx::test(migrations = "../migrations")] +async fn anonymous_pull_private_repo_fails(pool: PgPool) -> Result<()> { + let fixture = Fixture::new(&pool, Transport::Http, Visibility::Private).await?; + fixture.owner.create_issue(&fixture.repo, "secret issue", "body").await?; + + let git_bug = fixture.git_bug(None, "bugs").await?; + git_bug.fails(&["pull", "origin"]).await?; + + assert_eq!(git_bug.local_refs("refs/bugs").await?, Vec::::new()); + Ok(()) +} diff --git a/gitarena/tests/git_bug_e2e.rs b/gitarena/tests/git_bug_e2e.rs new file mode 100644 index 00000000..5471bd46 --- /dev/null +++ b/gitarena/tests/git_bug_e2e.rs @@ -0,0 +1,270 @@ +use anyhow::{Context, Result}; +use common::{Fixture, Transport, Visibility}; +use pretty_assertions::assert_eq; +use serde_json::{Value, json}; +use sqlx::PgPool; +use std::collections::BTreeSet; + +mod common; + +fn comments(show: &Value) -> Result> { + show["comments"] + .as_array() + .context("git-bug show has no comments array")? + .iter() + .map(|comment| { + let author = comment["author"]["name"].as_str().context("git-bug comment has no author")?; + let message = comment["message"].as_str().context("git-bug comment has no message")?; + + Ok((author.to_owned(), message.to_owned())) + }) + .collect() +} + +fn string_set(value: &Value) -> BTreeSet { + value + .as_array() + .map_or_default(|values| values.iter().filter_map(Value::as_str).map(ToOwned::to_owned).collect()) +} + +async fn issue_lifecycle(pool: PgPool, transport: Transport) -> Result<()> { + let fixture = Fixture::new(&pool, transport, Visibility::Public).await?; + let issue = fixture.owner.create_issue(&fixture.repo, "lifecycle", "issue body").await?; + + let git_bug = fixture.git_bug(Some(&fixture.owner), "bugs").await?; + git_bug.pull().await?; + assert_eq!(git_bug.show(&issue.git_bug_id).await?["status"], "open"); + + fixture.owner.create_label(&fixture.repo, "bug").await?; + fixture.owner.add_comment(&fixture.repo, issue.index, "first comment").await?; + fixture.owner.update_issue(&fixture.repo, issue.index, json!({ "labelsAdd": ["bug"] })).await?; + fixture + .owner + .update_issue(&fixture.repo, issue.index, json!({ "title": "lifecycle renamed" })) + .await?; + fixture.owner.add_comment(&fixture.repo, issue.index, "second comment").await?; + fixture.owner.update_issue(&fixture.repo, issue.index, json!({ "status": "completed" })).await?; + + git_bug.pull().await?; + + let show = git_bug.show(&issue.git_bug_id).await?; + let detail = fixture.owner.issue(&fixture.repo, issue.index).await?; + let timeline = fixture.owner.timeline(&fixture.repo, issue.index).await?; + + let rest_comments = detail["comments"] + .as_array() + .context("issue detail has no comments")? + .iter() + .map(|comment| comment["body"].as_str().map(ToOwned::to_owned).context("comment has no body")) + .collect::>>()?; + + let pulled = comments(&show)?; + assert_eq!(pulled[0], ("alice".to_owned(), "issue body".to_owned())); + assert_eq!(pulled[1..].iter().map(|(_, message)| message.clone()).collect::>(), rest_comments); + + let kinds = timeline.iter().filter_map(|event| event["type"].as_str()).collect::>(); + assert_eq!(kinds, vec!["created", "label_added", "title_changed", "status_changed"]); + + assert_eq!(show["title"], detail["issue"]["title"]); + assert_eq!(show["title"], timeline[2]["newTitle"]); + assert_eq!(show["status"], timeline[3]["status"]); + assert_eq!( + string_set(&show["labels"]), + BTreeSet::from([timeline[1]["label"].as_str().context("label event has no label")?.to_owned()]) + ); + assert_eq!(string_set(&show["labels"]), string_set(&detail["issue"]["labels"])); + Ok(()) +} + +#[test_with::executable(git-bug)] +#[sqlx::test(migrations = "../migrations")] +async fn issue_lifecycle_http(pool: PgPool) -> Result<()> { + issue_lifecycle(pool, Transport::Http).await +} + +#[test_with::executable(git-bug)] +#[sqlx::test(migrations = "../migrations")] +async fn issue_lifecycle_ssh(pool: PgPool) -> Result<()> { + issue_lifecycle(pool, Transport::Ssh).await +} + +async fn multi_user(pool: PgPool, transport: Transport) -> Result<()> { + let fixture = Fixture::new(&pool, transport, Visibility::Public).await?; + let bob = fixture.user("bob").await?; + let carol = fixture.user("carol").await?; + + let issue = fixture.owner.create_issue(&fixture.repo, "shared", "opened by alice").await?; + bob.add_comment(&fixture.repo, issue.index, "comment by bob").await?; + fixture.owner.add_comment(&fixture.repo, issue.index, "reply by alice").await?; + fixture.owner.update_issue(&fixture.repo, issue.index, json!({ "status": "completed" })).await?; + + let git_bug = fixture.git_bug(Some(&carol), "carol").await?; + git_bug.pull().await?; + + let show = git_bug.show(&issue.git_bug_id).await?; + + assert_eq!( + comments(&show)?, + vec![ + ("alice".to_owned(), "opened by alice".to_owned()), + ("bob".to_owned(), "comment by bob".to_owned()), + ("alice".to_owned(), "reply by alice".to_owned()), + ] + ); + assert_eq!(show["status"], "closed"); + + let mut identities = BTreeSet::new(); + + for reference in git_bug.local_refs("refs/identities").await? { + let id = reference.trim_start_matches("refs/identities/"); + let identity = git_bug.identity(id).await?; + + identities.insert(( + identity["name"].as_str().context("identity has no name")?.to_owned(), + identity["email"].as_str().context("identity has no email")?.to_owned(), + )); + } + + assert_eq!( + identities, + BTreeSet::from([ + ("alice".to_owned(), fixture.forge_mail(&pool, &fixture.owner).await?), + ("bob".to_owned(), fixture.forge_mail(&pool, &bob).await?), + ]) + ); + Ok(()) +} + +#[test_with::executable(git-bug)] +#[sqlx::test(migrations = "../migrations")] +async fn multi_user_http(pool: PgPool) -> Result<()> { + multi_user(pool, Transport::Http).await +} + +#[test_with::executable(git-bug)] +#[sqlx::test(migrations = "../migrations")] +async fn multi_user_ssh(pool: PgPool) -> Result<()> { + multi_user(pool, Transport::Ssh).await +} + +async fn code_and_issues(pool: PgPool, transport: Transport) -> Result<()> { + let fixture = Fixture::new(&pool, transport, Visibility::Public).await?; + let (local, _) = fixture.push_seed().await?; + + let first = fixture.owner.create_issue(&fixture.repo, "first", "body").await?; + let second = fixture.owner.create_issue(&fixture.repo, "second", "body").await?; + + let clone = fixture.checkout(&fixture.owner, "clone"); + clone.clone_into(&fixture.owner_remote()).await?; + + let git_bug = fixture.git_bug(Some(&fixture.owner), "clone").await?; + git_bug.pull().await?; + + let ids = |bugs: Vec| bugs.iter().filter_map(|bug| bug["id"].as_str().map(ToOwned::to_owned)).collect::>(); + let expected = BTreeSet::from([first.git_bug_id.clone(), second.git_bug_id.clone()]); + + assert_eq!(ids(git_bug.bugs().await?), expected); + assert_eq!(clone.read_file("README.md").await?, "# test\n"); + + let head = local.commit_file("later.txt", "later\n", "later commit").await?; + local.ok(&["push", "--quiet"]).await?; + + clone.ok(&["pull", "--quiet", "--ff-only"]).await?; + + assert_eq!(clone.rev_parse("HEAD").await?, head); + assert_eq!(ids(git_bug.bugs().await?), expected); + assert_eq!(git_bug.show(&first.git_bug_id).await?["title"], "first"); + clone.fsck().await?; + Ok(()) +} + +#[test_with::executable(git-bug)] +#[sqlx::test(migrations = "../migrations")] +async fn code_and_issues_http(pool: PgPool) -> Result<()> { + code_and_issues(pool, Transport::Http).await +} + +#[test_with::executable(git-bug)] +#[sqlx::test(migrations = "../migrations")] +async fn code_and_issues_ssh(pool: PgPool) -> Result<()> { + code_and_issues(pool, Transport::Ssh).await +} + +async fn mixed_transport(pool: PgPool, first: Transport, second: Transport) -> Result<()> { + let fixture = Fixture::new(&pool, Transport::Ssh, Visibility::Public).await?; + let issue = fixture.owner.create_issue(&fixture.repo, "mixed", "issue body").await?; + + let git_bug = fixture.git_bug(Some(&fixture.owner), "bugs").await?; + + git_bug.set_remote(&fixture.server.remote(first, Some(&fixture.owner), &fixture.repo)).await?; + git_bug.pull().await?; + + fixture.owner.add_comment(&fixture.repo, issue.index, "between pulls").await?; + + git_bug.set_remote(&fixture.server.remote(second, Some(&fixture.owner), &fixture.repo)).await?; + git_bug.pull().await?; + + let messages = comments(&git_bug.show(&issue.git_bug_id).await?)? + .into_iter() + .map(|(_, message)| message) + .collect::>(); + assert_eq!(messages, vec!["issue body", "between pulls"]); + Ok(()) +} + +#[test_with::executable(git-bug)] +#[sqlx::test(migrations = "../migrations")] +async fn pull_over_http_then_ssh(pool: PgPool) -> Result<()> { + mixed_transport(pool, Transport::Http, Transport::Ssh).await +} + +#[test_with::executable(git-bug)] +#[sqlx::test(migrations = "../migrations")] +async fn pull_over_ssh_then_http(pool: PgPool) -> Result<()> { + mixed_transport(pool, Transport::Ssh, Transport::Http).await +} + +async fn many_issues(pool: PgPool, transport: Transport) -> Result<()> { + let fixture = Fixture::new(&pool, transport, Visibility::Public).await?; + let mut issues = Vec::new(); + + for index in 0..50 { + let issue = fixture + .owner + .create_issue(&fixture.repo, &format!("issue {index}"), &format!("body {index}")) + .await?; + fixture.owner.add_comment(&fixture.repo, issue.index, &format!("comment {index}")).await?; + + issues.push(issue); + } + + let git_bug = fixture.git_bug(Some(&fixture.owner), "bugs").await?; + git_bug.pull().await?; + + assert_eq!(git_bug.bugs().await?.len(), 50); + + for (index, issue) in issues.iter().enumerate().step_by(7) { + let show = git_bug.show(&issue.git_bug_id).await?; + + assert_eq!(show["title"], format!("issue {index}").as_str()); + assert_eq!( + comments(&show)?.into_iter().map(|(_, message)| message).collect::>(), + vec![format!("body {index}"), format!("comment {index}")] + ); + } + + git_bug.git.fsck().await?; + Ok(()) +} + +#[test_with::executable(git-bug)] +#[sqlx::test(migrations = "../migrations")] +async fn many_issues_http(pool: PgPool) -> Result<()> { + many_issues(pool, Transport::Http).await +} + +#[test_with::executable(git-bug)] +#[sqlx::test(migrations = "../migrations")] +async fn many_issues_ssh(pool: PgPool) -> Result<()> { + many_issues(pool, Transport::Ssh).await +} diff --git a/gitarena/tests/git_e2e.rs b/gitarena/tests/git_e2e.rs new file mode 100644 index 00000000..7852f4a8 --- /dev/null +++ b/gitarena/tests/git_e2e.rs @@ -0,0 +1,215 @@ +use anyhow::Result; +use common::{Fixture, Transport, Visibility}; +use pretty_assertions::assert_eq; +use sqlx::PgPool; + +mod common; + +async fn full_lifecycle(pool: PgPool, transport: Transport) -> Result<()> { + let fixture = Fixture::new(&pool, transport, Visibility::Public).await?; + let (first, _) = fixture.push_seed().await?; + + let second = fixture.checkout(&fixture.owner, "second"); + second.clone_into(&fixture.owner_remote()).await?; + + let from_first = first.commit_file("first.txt", "first\n", "commit from first").await?; + first.ok(&["push", "--quiet"]).await?; + + second.commit_file("second.txt", "second\n", "commit from second").await?; + + let stderr = second.fails(&["push", "origin", "main"]).await?; + assert!(stderr.contains("[rejected]"), "{stderr}"); + + second.ok(&["pull", "--quiet", "--rebase"]).await?; + assert_eq!(second.rev_parse("HEAD~1").await?, from_first); + + let rebased = second.rev_parse("HEAD").await?; + second.ok(&["push", "--quiet"]).await?; + + first.ok(&["pull", "--quiet", "--ff-only"]).await?; + + assert_eq!(first.rev_parse("HEAD").await?, rebased); + assert_eq!(first.read_file("second.txt").await?, "second\n"); + assert_eq!(fixture.refs().await?.get("refs/heads/main"), Some(&rebased)); + + first.fsck().await?; + second.fsck().await?; + Ok(()) +} + +#[sqlx::test(migrations = "../migrations")] +async fn full_lifecycle_http(pool: PgPool) -> Result<()> { + full_lifecycle(pool, Transport::Http).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn full_lifecycle_ssh(pool: PgPool) -> Result<()> { + full_lifecycle(pool, Transport::Ssh).await +} + +async fn branching_workflow(pool: PgPool, transport: Transport) -> Result<()> { + let fixture = Fixture::new(&pool, transport, Visibility::Public).await?; + let (local, _) = fixture.push_seed().await?; + + local.ok(&["switch", "--quiet", "--create", "feature"]).await?; + local.commit_file("feature.txt", "feature\n", "add feature").await?; + local.ok(&["push", "--quiet", "--set-upstream", "origin", "feature"]).await?; + + local.ok(&["switch", "--quiet", "main"]).await?; + local.commit_file("main.txt", "main\n", "work on main").await?; + local.ok(&["merge", "--quiet", "--no-ff", "--message", "merge feature", "feature"]).await?; + local.ok(&["push", "--quiet", "origin", "main"]).await?; + + local.ok(&["push", "--quiet", "origin", "--delete", "feature"]).await?; + local.ok(&["branch", "--quiet", "--delete", "feature"]).await?; + + local.ok(&["tag", "--annotate", "--message", "release 1.0", "v1.0"]).await?; + local.ok(&["push", "--quiet", "origin", "v1.0"]).await?; + + let head = local.rev_parse("HEAD").await?; + let refs = fixture.refs().await?; + + assert_eq!(refs.get("refs/heads/feature"), None); + assert_eq!(refs.get("refs/heads/main"), Some(&head)); + assert_eq!(refs.get("refs/tags/v1.0"), Some(&local.rev_parse("v1.0").await?)); + + let clone = fixture.checkout(&fixture.owner, "clone"); + clone.clone_into(&fixture.owner_remote()).await?; + + assert_eq!(clone.rev_parse("HEAD").await?, head); + assert_eq!(clone.rev_parse("v1.0^{commit}").await?, head); + assert_eq!(clone.rev_count("HEAD").await?, local.rev_count("HEAD").await?); + assert_eq!( + clone.ok(&["rev-list", "--parents", "--max-count=1", "HEAD"]).await?.split_whitespace().count(), + 3 + ); + assert_eq!(clone.ok(&["branch", "--remotes", "--list", "origin/feature"]).await?, ""); + assert_eq!(clone.read_file("feature.txt").await?, "feature\n"); + clone.fsck().await?; + Ok(()) +} + +#[sqlx::test(migrations = "../migrations")] +async fn branching_workflow_http(pool: PgPool) -> Result<()> { + branching_workflow(pool, Transport::Http).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn branching_workflow_ssh(pool: PgPool) -> Result<()> { + branching_workflow(pool, Transport::Ssh).await +} + +async fn collaboration(pool: PgPool, transport: Transport) -> Result<()> { + let fixture = Fixture::new(&pool, transport, Visibility::Public).await?; + let (alice, _) = fixture.push_seed().await?; + + alice.ok(&["push", "--quiet", "origin", "main:refs/heads/other"]).await?; + + let bob = fixture.user("bob").await?; + let clone = fixture.checkout(&bob, "bob"); + clone + .clone_into_with(&fixture.remote(Some(&bob)), &["--single-branch", "--branch", "main"]) + .await?; + + let rejected = clone.commit_file("bob.txt", "bob\n", "bob's change").await?; + clone.fails(&["push", "origin", "main"]).await?; + assert!(fixture.refs().await?.values().all(|oid| oid != &rejected)); + + clone.ok(&["reset", "--quiet", "--hard", "origin/main"]).await?; + + for round in 0..3 { + let count = clone.rev_count("origin/main").await?; + + alice + .commit_file(&format!("round-{round}.txt"), &"line\n".repeat(1000 * (round + 1)), &format!("round {round}")) + .await?; + let head = alice.commit_file("shared.txt", &format!("{round}\n").repeat(500), "update shared").await?; + alice.ok(&["push", "--quiet"]).await?; + + clone.ok(&["fetch", "--quiet"]).await?; + + assert_eq!(clone.rev_parse("origin/main").await?, head); + assert_eq!(clone.rev_count("origin/main").await?, count + 2); + } + + assert_eq!( + clone.ok(&["for-each-ref", "--format=%(refname)", "refs/remotes"]).await?.trim(), + "refs/remotes/origin/main" + ); + + clone.ok(&["merge", "--quiet", "--ff-only", "origin/main"]).await?; + assert_eq!(clone.read_file("shared.txt").await?, "2\n".repeat(500)); + clone.fsck().await?; + Ok(()) +} + +#[sqlx::test(migrations = "../migrations")] +async fn collaboration_http(pool: PgPool) -> Result<()> { + collaboration(pool, Transport::Http).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn collaboration_ssh(pool: PgPool) -> Result<()> { + collaboration(pool, Transport::Ssh).await +} + +async fn large_repo_round_trip(pool: PgPool, transport: Transport) -> Result<()> { + let fixture = Fixture::new(&pool, transport, Visibility::Public).await?; + + let local = fixture.checkout(&fixture.owner, "large"); + local.fast_import(500, 3, 4 * 1024 * 1024).await?; + local.ok(&["push", "--quiet", &fixture.owner_remote(), "main"]).await?; + + let clone = fixture.checkout(&fixture.owner, "clone"); + clone.clone_into(&fixture.owner_remote()).await?; + + assert_eq!(clone.rev_count("HEAD").await?, 500); + assert_eq!(clone.rev_parse("HEAD").await?, local.rev_parse("main").await?); + assert_eq!(clone.rev_parse("HEAD^{tree}").await?, local.rev_parse("main^{tree}").await?); + clone.fsck().await?; + Ok(()) +} + +#[sqlx::test(migrations = "../migrations")] +async fn large_repo_round_trip_http(pool: PgPool) -> Result<()> { + large_repo_round_trip(pool, Transport::Http).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn large_repo_round_trip_ssh(pool: PgPool) -> Result<()> { + large_repo_round_trip(pool, Transport::Ssh).await +} + +async fn mixed_transport(pool: PgPool, push_over: Transport, clone_over: Transport) -> Result<()> { + let fixture = Fixture::new(&pool, push_over, Visibility::Public).await?; + let (local, _) = fixture.push_seed().await?; + let head = local.commit_file("more.txt", "more\n", "second commit").await?; + local.ok(&["push", "--quiet"]).await?; + + let clone = fixture.checkout(&fixture.owner, "clone"); + clone + .clone_into(&fixture.server.remote(clone_over, Some(&fixture.owner), &fixture.repo)) + .await?; + + assert_eq!(clone.rev_parse("HEAD").await?, head); + + let from_clone = clone.commit_file("from-clone.txt", "clone\n", "commit from clone").await?; + clone.ok(&["push", "--quiet"]).await?; + + local.ok(&["pull", "--quiet", "--ff-only"]).await?; + assert_eq!(local.rev_parse("HEAD").await?, from_clone); + + clone.fsck().await?; + local.fsck().await?; + Ok(()) +} + +#[sqlx::test(migrations = "../migrations")] +async fn push_over_http_clone_over_ssh(pool: PgPool) -> Result<()> { + mixed_transport(pool, Transport::Http, Transport::Ssh).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn push_over_ssh_clone_over_http(pool: PgPool) -> Result<()> { + mixed_transport(pool, Transport::Ssh, Transport::Http).await +} diff --git a/gitarena/tests/git_http.rs b/gitarena/tests/git_http.rs new file mode 100644 index 00000000..29653e65 --- /dev/null +++ b/gitarena/tests/git_http.rs @@ -0,0 +1,216 @@ +use anyhow::Result; +use common::scenarios; +use common::{Fixture, Git, Protocol, Transport, Visibility}; +use pretty_assertions::assert_eq; +use sqlx::PgPool; + +mod common; + +#[sqlx::test(migrations = "../migrations")] +async fn clone_empty_repo_v1(pool: PgPool) -> Result<()> { + scenarios::clone_empty_repo(pool, Transport::Http, Protocol::V1).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn clone_empty_repo_v2(pool: PgPool) -> Result<()> { + scenarios::clone_empty_repo(pool, Transport::Http, Protocol::V2).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn clone_non_empty_repo_v1(pool: PgPool) -> Result<()> { + scenarios::clone_non_empty_repo(pool, Transport::Http, Protocol::V1).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn clone_non_empty_repo_v2(pool: PgPool) -> Result<()> { + scenarios::clone_non_empty_repo(pool, Transport::Http, Protocol::V2).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn fetch_after_server_change_v1(pool: PgPool) -> Result<()> { + scenarios::fetch_after_server_change(pool, Transport::Http, Protocol::V1).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn fetch_after_server_change_v2(pool: PgPool) -> Result<()> { + scenarios::fetch_after_server_change(pool, Transport::Http, Protocol::V2).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn ls_remote_lists_all_refs_v1(pool: PgPool) -> Result<()> { + scenarios::ls_remote_lists_all_refs(pool, Transport::Http, Protocol::V1).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn ls_remote_lists_all_refs_v2(pool: PgPool) -> Result<()> { + scenarios::ls_remote_lists_all_refs(pool, Transport::Http, Protocol::V2).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn ls_remote_peels_annotated_tags_v1(pool: PgPool) -> Result<()> { + scenarios::ls_remote_peels_annotated_tags(pool, Transport::Http, Protocol::V1).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn ls_remote_peels_annotated_tags_v2(pool: PgPool) -> Result<()> { + scenarios::ls_remote_peels_annotated_tags(pool, Transport::Http, Protocol::V2).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn owner_can_clone_and_push_private_repo_v1(pool: PgPool) -> Result<()> { + scenarios::owner_can_clone_and_push_private_repo(pool, Transport::Http, Protocol::V1).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn owner_can_clone_and_push_private_repo_v2(pool: PgPool) -> Result<()> { + scenarios::owner_can_clone_and_push_private_repo(pool, Transport::Http, Protocol::V2).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn other_user_can_clone_public_repo_v1(pool: PgPool) -> Result<()> { + scenarios::other_user_can_clone_public_repo(pool, Transport::Http, Protocol::V1).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn other_user_can_clone_public_repo_v2(pool: PgPool) -> Result<()> { + scenarios::other_user_can_clone_public_repo(pool, Transport::Http, Protocol::V2).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn other_user_cannot_clone_private_repo_v1(pool: PgPool) -> Result<()> { + scenarios::other_user_cannot_clone_private_repo(pool, Transport::Http, Protocol::V1).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn other_user_cannot_clone_private_repo_v2(pool: PgPool) -> Result<()> { + scenarios::other_user_cannot_clone_private_repo(pool, Transport::Http, Protocol::V2).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn nonexistent_repo_fails_v1(pool: PgPool) -> Result<()> { + scenarios::nonexistent_repo_fails(pool, Transport::Http, Protocol::V1).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn nonexistent_repo_fails_v2(pool: PgPool) -> Result<()> { + scenarios::nonexistent_repo_fails(pool, Transport::Http, Protocol::V2).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn initial_push(pool: PgPool) -> Result<()> { + scenarios::initial_push(pool, Transport::Http).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn push_new_branch(pool: PgPool) -> Result<()> { + scenarios::push_new_branch(pool, Transport::Http).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn push_tags(pool: PgPool) -> Result<()> { + scenarios::push_tags(pool, Transport::Http).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn force_push(pool: PgPool) -> Result<()> { + scenarios::force_push(pool, Transport::Http).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn delete_branch(pool: PgPool) -> Result<()> { + scenarios::delete_branch(pool, Transport::Http).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn delete_tag(pool: PgPool) -> Result<()> { + scenarios::delete_tag(pool, Transport::Http).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn delete_multiple_refs_in_one_push(pool: PgPool) -> Result<()> { + scenarios::delete_multiple_refs_in_one_push(pool, Transport::Http).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn other_user_cannot_push_to_public_repo(pool: PgPool) -> Result<()> { + scenarios::other_user_cannot_push_to_public_repo(pool, Transport::Http).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn other_user_cannot_push_to_private_repo(pool: PgPool) -> Result<()> { + scenarios::other_user_cannot_push_to_private_repo(pool, Transport::Http).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn nonexistent_repo_push_fails(pool: PgPool) -> Result<()> { + scenarios::nonexistent_repo_push_fails(pool, Transport::Http).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn push_with_secret_is_rejected(pool: PgPool) -> Result<()> { + scenarios::push_with_secret_is_rejected(pool, Transport::Http).await +} + +async fn anonymous_clone_public_repo(pool: PgPool, protocol: Protocol) -> Result<()> { + let fixture = Fixture::new(&pool, Transport::Http, Visibility::Public).await?; + let (_, head) = fixture.push_seed().await?; + + let clone = Git::new(&fixture.path("clone")).with_protocol(protocol); + clone.clone_into(&fixture.remote(None)).await?; + + assert_eq!(clone.rev_parse("HEAD").await?, head); + Ok(()) +} + +#[sqlx::test(migrations = "../migrations")] +async fn anonymous_clone_public_repo_v1(pool: PgPool) -> Result<()> { + anonymous_clone_public_repo(pool, Protocol::V1).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn anonymous_clone_public_repo_v2(pool: PgPool) -> Result<()> { + anonymous_clone_public_repo(pool, Protocol::V2).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn anonymous_clone_private_repo_fails(pool: PgPool) -> Result<()> { + let fixture = Fixture::new(&pool, Transport::Http, Visibility::Private).await?; + fixture.push_seed().await?; + + let clone = Git::new(&fixture.path("clone")); + clone.init().await?; + + let stderr = clone.fails(&["fetch", &fixture.remote(None), "main"]).await?; + assert!(stderr.contains("could not read Username"), "{stderr}"); + Ok(()) +} + +#[sqlx::test(migrations = "../migrations")] +async fn anonymous_push_fails(pool: PgPool) -> Result<()> { + let fixture = Fixture::new(&pool, Transport::Http, Visibility::Public).await?; + let (_, head) = fixture.push_seed().await?; + + let clone = Git::new(&fixture.path("clone")); + clone.clone_into(&fixture.remote(None)).await?; + clone.commit_file("anonymous.txt", "anonymous\n", "anonymous commit").await?; + + let stderr = clone.fails(&["push", "origin", "main"]).await?; + assert!(stderr.contains("could not read Username"), "{stderr}"); + assert_eq!(fixture.refs().await?.get("refs/heads/main"), Some(&head)); + Ok(()) +} + +#[sqlx::test(migrations = "../migrations")] +async fn wrong_password_fails(pool: PgPool) -> Result<()> { + let fixture = Fixture::new(&pool, Transport::Http, Visibility::Private).await?; + fixture.push_seed().await?; + + let remote = format!("http://alice:wrong-password@127.0.0.1:{}/{}.git", fixture.server.http_port, fixture.repo); + + let clone = Git::new(&fixture.path("clone")); + clone.init().await?; + + let stderr = clone.fails(&["fetch", &remote, "main"]).await?; + assert!(stderr.contains("Authentication failed") || stderr.contains("401"), "{stderr}"); + Ok(()) +} diff --git a/gitarena/tests/git_ssh.rs b/gitarena/tests/git_ssh.rs new file mode 100644 index 00000000..61489b12 --- /dev/null +++ b/gitarena/tests/git_ssh.rs @@ -0,0 +1,179 @@ +use anyhow::Result; +use common::scenarios; +use common::{Fixture, Git, Protocol, Transport, Visibility, generate_ssh_key}; +use sqlx::PgPool; + +mod common; + +#[sqlx::test(migrations = "../migrations")] +async fn clone_empty_repo_v1(pool: PgPool) -> Result<()> { + scenarios::clone_empty_repo(pool, Transport::Ssh, Protocol::V1).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn clone_empty_repo_v2(pool: PgPool) -> Result<()> { + scenarios::clone_empty_repo(pool, Transport::Ssh, Protocol::V2).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn clone_non_empty_repo_v1(pool: PgPool) -> Result<()> { + scenarios::clone_non_empty_repo(pool, Transport::Ssh, Protocol::V1).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn clone_non_empty_repo_v2(pool: PgPool) -> Result<()> { + scenarios::clone_non_empty_repo(pool, Transport::Ssh, Protocol::V2).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn fetch_after_server_change_v1(pool: PgPool) -> Result<()> { + scenarios::fetch_after_server_change(pool, Transport::Ssh, Protocol::V1).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn fetch_after_server_change_v2(pool: PgPool) -> Result<()> { + scenarios::fetch_after_server_change(pool, Transport::Ssh, Protocol::V2).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn ls_remote_lists_all_refs_v1(pool: PgPool) -> Result<()> { + scenarios::ls_remote_lists_all_refs(pool, Transport::Ssh, Protocol::V1).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn ls_remote_lists_all_refs_v2(pool: PgPool) -> Result<()> { + scenarios::ls_remote_lists_all_refs(pool, Transport::Ssh, Protocol::V2).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn ls_remote_peels_annotated_tags_v1(pool: PgPool) -> Result<()> { + scenarios::ls_remote_peels_annotated_tags(pool, Transport::Ssh, Protocol::V1).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn ls_remote_peels_annotated_tags_v2(pool: PgPool) -> Result<()> { + scenarios::ls_remote_peels_annotated_tags(pool, Transport::Ssh, Protocol::V2).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn owner_can_clone_and_push_private_repo_v1(pool: PgPool) -> Result<()> { + scenarios::owner_can_clone_and_push_private_repo(pool, Transport::Ssh, Protocol::V1).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn owner_can_clone_and_push_private_repo_v2(pool: PgPool) -> Result<()> { + scenarios::owner_can_clone_and_push_private_repo(pool, Transport::Ssh, Protocol::V2).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn other_user_can_clone_public_repo_v1(pool: PgPool) -> Result<()> { + scenarios::other_user_can_clone_public_repo(pool, Transport::Ssh, Protocol::V1).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn other_user_can_clone_public_repo_v2(pool: PgPool) -> Result<()> { + scenarios::other_user_can_clone_public_repo(pool, Transport::Ssh, Protocol::V2).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn other_user_cannot_clone_private_repo_v1(pool: PgPool) -> Result<()> { + scenarios::other_user_cannot_clone_private_repo(pool, Transport::Ssh, Protocol::V1).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn other_user_cannot_clone_private_repo_v2(pool: PgPool) -> Result<()> { + scenarios::other_user_cannot_clone_private_repo(pool, Transport::Ssh, Protocol::V2).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn nonexistent_repo_fails_v1(pool: PgPool) -> Result<()> { + scenarios::nonexistent_repo_fails(pool, Transport::Ssh, Protocol::V1).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn nonexistent_repo_fails_v2(pool: PgPool) -> Result<()> { + scenarios::nonexistent_repo_fails(pool, Transport::Ssh, Protocol::V2).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn initial_push(pool: PgPool) -> Result<()> { + scenarios::initial_push(pool, Transport::Ssh).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn push_new_branch(pool: PgPool) -> Result<()> { + scenarios::push_new_branch(pool, Transport::Ssh).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn push_tags(pool: PgPool) -> Result<()> { + scenarios::push_tags(pool, Transport::Ssh).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn force_push(pool: PgPool) -> Result<()> { + scenarios::force_push(pool, Transport::Ssh).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn delete_branch(pool: PgPool) -> Result<()> { + scenarios::delete_branch(pool, Transport::Ssh).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn delete_tag(pool: PgPool) -> Result<()> { + scenarios::delete_tag(pool, Transport::Ssh).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn delete_multiple_refs_in_one_push(pool: PgPool) -> Result<()> { + scenarios::delete_multiple_refs_in_one_push(pool, Transport::Ssh).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn other_user_cannot_push_to_public_repo(pool: PgPool) -> Result<()> { + scenarios::other_user_cannot_push_to_public_repo(pool, Transport::Ssh).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn other_user_cannot_push_to_private_repo(pool: PgPool) -> Result<()> { + scenarios::other_user_cannot_push_to_private_repo(pool, Transport::Ssh).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn nonexistent_repo_push_fails(pool: PgPool) -> Result<()> { + scenarios::nonexistent_repo_push_fails(pool, Transport::Ssh).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn push_with_secret_is_rejected(pool: PgPool) -> Result<()> { + scenarios::push_with_secret_is_rejected(pool, Transport::Ssh).await +} + +#[sqlx::test(migrations = "../migrations")] +async fn unregistered_key_fails(pool: PgPool) -> Result<()> { + let fixture = Fixture::new(&pool, Transport::Ssh, Visibility::Public).await?; + fixture.push_seed().await?; + + let (key, _) = generate_ssh_key(fixture.dir.path(), "unregistered").await?; + + let clone = Git::new(&fixture.path("clone")).with_ssh_key(&key); + clone.init().await?; + + let stderr = clone.fails(&["fetch", &fixture.remote(None), "main"]).await?; + assert!(stderr.contains("Permission denied"), "{stderr}"); + Ok(()) +} + +#[sqlx::test(migrations = "../migrations")] +async fn no_key_fails(pool: PgPool) -> Result<()> { + let fixture = Fixture::new(&pool, Transport::Ssh, Visibility::Public).await?; + fixture.push_seed().await?; + + let clone = Git::new(&fixture.path("clone")); + clone.init().await?; + + let stderr = clone.fails(&["fetch", &fixture.remote(None), "main"]).await?; + assert!(stderr.contains("Permission denied"), "{stderr}"); + Ok(()) +} From 12aa0faf8eb77ecce1a572e3a7039cfe92e02db5 Mon Sep 17 00:00:00 2001 From: Mari Date: Mon, 16 Nov 2026 22:36:04 +0000 Subject: [PATCH 2/7] review --- README.md | 1 + docs/self-hosting/configuration.mdx | 1 + gitarena/src/git/hooks/detect_license.rs | 4 ++++ gitarena/src/licenses.rs | 4 ++++ gitarena/src/main.rs | 4 +++- gitarena/tests/common/mod.rs | 24 +++++++++++++++--------- gitarena/tests/common/scenarios.rs | 6 ++++-- 7 files changed, 32 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 6433510c..9fec8943 100644 --- a/README.md +++ b/README.md @@ -141,6 +141,7 @@ Optional environment variables: - `MAX_POOL_CONNECTIONS`: Max amount of connections the Postgres connection pool should keep open and ready to use. - `MAX_QUEUE_POOL_CONNECTIONS`: Max amount of Postgres connections the background job queue should use +- `DISABLE_LICENSE_DETECTION`: Set to any value to skip loading the license database at startup and detecting repository licenses on push - `DISABLE_UPDATE_CHECK`: Set to any value to skip checking for a new GitArena version at startup - `NO_STDOUT_LOG`: Set to any value to only write logs to the log file (and Otel, if configured) - `OTEL_SERVICE_NAME`: Service name to be used for metrics, traces and logs diff --git a/docs/self-hosting/configuration.mdx b/docs/self-hosting/configuration.mdx index 17ece942..2fa09fda 100644 --- a/docs/self-hosting/configuration.mdx +++ b/docs/self-hosting/configuration.mdx @@ -33,6 +33,7 @@ Set these before starting GitArena. In Docker, pass them under `environment:` in |----------|-------------| | `MAX_POOL_CONNECTIONS` | Maximum number of Postgres connections to keep open. | | `MAX_QUEUE_POOL_CONNECTIONS` | Maximum number of Postgres connections used by the background job queue. Defaults to the number of CPU threads + 1. | +| `DISABLE_LICENSE_DETECTION` | Skip loading the license database at startup and detecting repository licenses on push when set. | | `DISABLE_UPDATE_CHECK` | Skip checking GitHub for a new GitArena version at startup when set. The admin panel update check still works. | | `NO_STDOUT_LOG` | Disable stdout logging when set. | | `DEBUG_FILE_LOG` | Enable rolling file logging in non-debug builds when set. | diff --git a/gitarena/src/git/hooks/detect_license.rs b/gitarena/src/git/hooks/detect_license.rs index 077fc902..1b21ef3c 100644 --- a/gitarena/src/git/hooks/detect_license.rs +++ b/gitarena/src/git/hooks/detect_license.rs @@ -14,6 +14,10 @@ use tracing::{debug, instrument}; #[instrument(err, skip(store))] pub(crate) async fn detect_license(store: Arc, gitoxide_repo: &gix::Repository, repo: &mut Repository) -> Result<()> { + if !licenses::is_loaded() { + return Ok(()); + } + let mut buffer = Vec::::new(); let tree = repo_files_at_head(store.clone(), gitoxide_repo, &mut buffer).await?; diff --git a/gitarena/src/licenses.rs b/gitarena/src/licenses.rs index c6c79db3..55ee237f 100644 --- a/gitarena/src/licenses.rs +++ b/gitarena/src/licenses.rs @@ -20,6 +20,10 @@ fn init_askalono() -> Store { Store::from_cache(&bytes[..]).expect_or_log("Failed to parse askalono cache file") } +pub(crate) fn is_loaded() -> bool { + LICENSE_STORE.get().is_some() +} + pub(crate) fn store() -> &'static Store { LICENSE_STORE.get().unwrap_or_log() } diff --git a/gitarena/src/main.rs b/gitarena/src/main.rs index 8299c993..f131498f 100644 --- a/gitarena/src/main.rs +++ b/gitarena/src/main.rs @@ -103,7 +103,9 @@ async fn main() -> Result<()> { events::init(&db_pool).await?; - licenses::init(); + if env::var_os("DISABLE_LICENSE_DETECTION").is_none() { + licenses::init(); + } system::init()?; diff --git a/gitarena/tests/common/mod.rs b/gitarena/tests/common/mod.rs index f4ea3622..4c860296 100644 --- a/gitarena/tests/common/mod.rs +++ b/gitarena/tests/common/mod.rs @@ -27,6 +27,7 @@ use uuid::Uuid; const BOOT_ATTEMPTS: usize = 3; const BOOT_TIMEOUT: Duration = Duration::from_secs(60); const COMMAND_TIMEOUT: Duration = Duration::from_secs(120); +const HEALTH_TIMEOUT: Duration = Duration::from_secs(2); const AGENT_TIMEOUT: Duration = Duration::from_secs(10); pub const AUTHOR_NAME: &str = "Test Author"; @@ -100,6 +101,7 @@ impl TestServer { .env("MAX_POOL_CONNECTIONS", "3") .env("MAX_QUEUE_POOL_CONNECTIONS", "2") .env("DISABLE_UPDATE_CHECK", "1") + .env("DISABLE_LICENSE_DETECTION", "1") .env("GIT_CONFIG_GLOBAL", "/dev/null") .env("GIT_CONFIG_SYSTEM", "/dev/null") .stdin(Stdio::null()) @@ -154,7 +156,8 @@ fn free_port() -> Result { } async fn seed_settings(pool: &PgPool, http_port: u16, ssh_port: u16, repos_dir: &Path) -> Result<()> { - let backend = format!("http://127.0.0.1:{http_port}"); + // webauthn uses the domain as its relying party id, which has to be a hostname and not an ip + let backend = format!("http://localhost:{http_port}"); let repos_dir = repos_dir.to_str().context("temp dir is not valid unicode")?; let ssh_port = ssh_port.to_string(); @@ -182,7 +185,7 @@ async fn seed_settings(pool: &PgPool, http_port: u16, ssh_port: u16, repos_dir: } async fn wait_until_ready(child: &mut Child, http_port: u16, ssh_port: u16) -> Result<()> { - let client = Client::new(); + let client = Client::builder().timeout(HEALTH_TIMEOUT).build()?; let deadline = Instant::now() + BOOT_TIMEOUT; loop { @@ -314,7 +317,7 @@ impl TestUser { username: username.to_owned(), password: format!("password-{username}"), email: format!("{username}@example.com"), - client: Client::builder().cookie_store(true).build()?, + client: Client::builder().cookie_store(true).timeout(COMMAND_TIMEOUT).build()?, ssh_key: None, base_url: server.base_url(), key_dir: tempdir()?, @@ -507,15 +510,18 @@ async fn run_with_timeout(command: &mut Command, input: Option<&[u8]>) -> Result let mut child = command.spawn()?; - if let Some(input) = input { - let mut stdin = child.stdin.take().context("child has no stdin")?; - stdin.write_all(input).await?; - } + let run = async { + if let Some(input) = input { + let mut stdin = child.stdin.take().context("child has no stdin")?; + stdin.write_all(input).await?; + } + + Ok(child.wait_with_output().await?) + }; - timeout(COMMAND_TIMEOUT, child.wait_with_output()) + timeout(COMMAND_TIMEOUT, run) .await .with_context(|| format!("{command:?} did not finish within {COMMAND_TIMEOUT:?}"))? - .map_err(Into::into) } pub struct GitOutput { diff --git a/gitarena/tests/common/scenarios.rs b/gitarena/tests/common/scenarios.rs index 4c5bf049..2f82f9fc 100644 --- a/gitarena/tests/common/scenarios.rs +++ b/gitarena/tests/common/scenarios.rs @@ -69,7 +69,8 @@ pub async fn ls_remote_lists_all_refs(pool: PgPool, transport: Transport, protoc local.ok(&["push", "--quiet", "origin", "feature", "v1"]).await?; let refs = fixture - .checkout(&fixture.owner, "query") + .owner + .git(fixture.dir.path()) .with_protocol(protocol) .ls_remote(&fixture.owner_remote()) .await?; @@ -94,7 +95,8 @@ pub async fn ls_remote_peels_annotated_tags(pool: PgPool, transport: Transport, local.ok(&["push", "--quiet", "origin", "v1"]).await?; let refs = fixture - .checkout(&fixture.owner, "query") + .owner + .git(fixture.dir.path()) .with_protocol(protocol) .ls_remote(&fixture.owner_remote()) .await?; From e00880a0cf621601fbaefb86fd8f908543c764bb Mon Sep 17 00:00:00 2001 From: Mari Date: Tue, 17 Nov 2026 01:03:03 +0000 Subject: [PATCH 3/7] fix tests --- gitarena/tests/git_e2e.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/gitarena/tests/git_e2e.rs b/gitarena/tests/git_e2e.rs index 7852f4a8..dfc04beb 100644 --- a/gitarena/tests/git_e2e.rs +++ b/gitarena/tests/git_e2e.rs @@ -132,9 +132,11 @@ async fn collaboration(pool: PgPool, transport: Transport) -> Result<()> { assert_eq!(clone.rev_count("origin/main").await?, count + 2); } + let remote_refs = clone.ok(&["for-each-ref", "--format=%(refname)", "refs/remotes"]).await?; + assert_eq!( - clone.ok(&["for-each-ref", "--format=%(refname)", "refs/remotes"]).await?.trim(), - "refs/remotes/origin/main" + remote_refs.lines().filter(|name| *name != "refs/remotes/origin/HEAD").collect::>(), + vec!["refs/remotes/origin/main"] ); clone.ok(&["merge", "--quiet", "--ff-only", "origin/main"]).await?; From 645f1642b02e6f688cc3a70b9e29ba41c7789065 Mon Sep 17 00:00:00 2001 From: Mari Date: Sat, 21 Nov 2026 02:20:47 +0000 Subject: [PATCH 4/7] set warning to error --- gitarena/tests/common/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gitarena/tests/common/mod.rs b/gitarena/tests/common/mod.rs index 4c860296..6af4b32c 100644 --- a/gitarena/tests/common/mod.rs +++ b/gitarena/tests/common/mod.rs @@ -97,7 +97,7 @@ impl TestServer { .env("HOME", home.path()) .env("DATABASE_URL", &database_url) .env("BIND_ADDRESS", format!("127.0.0.1:{http_port}")) - .env("RUST_LOG", "gitarena=debug") + .env("RUST_LOG", "gitarena=debug,gitarena::git::io::reader=error") .env("MAX_POOL_CONNECTIONS", "3") .env("MAX_QUEUE_POOL_CONNECTIONS", "2") .env("DISABLE_UPDATE_CHECK", "1") From 5117d167ac373c037e5af04238a1f13fec5e63b6 Mon Sep 17 00:00:00 2001 From: Mari Date: Sat, 21 Nov 2026 03:01:26 +0000 Subject: [PATCH 5/7] display test results --- .github/workflows/git-tests.yml | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/.github/workflows/git-tests.yml b/.github/workflows/git-tests.yml index 8a8d8956..c782fb77 100644 --- a/.github/workflows/git-tests.yml +++ b/.github/workflows/git-tests.yml @@ -6,6 +6,8 @@ on: permissions: contents: read + actions: read + checks: write env: CARGO_TERM_COLOR: always @@ -62,8 +64,16 @@ jobs: run: cargo nextest run --locked -p gitarena --profile ci -E 'kind(test)' - name: upload test report - if: always() + if: ${{ !cancelled() }} uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: git-tests-junit path: target/nextest/ci/junit.xml + + - name: display test report + uses: dorny/test-reporter@a43b3a5f7366b97d083190328d2c652e1a8b6aa2 # v3.0.0 + if: ${{ !cancelled() }} + with: + name: Backend tests + path: target/nextest/ci/junit.xml + reporter: java-junit From 73eff12aecea8dac8ae6100e824ddd3e5bccbe30 Mon Sep 17 00:00:00 2001 From: Mari Date: Mon, 23 Nov 2026 18:08:30 +0000 Subject: [PATCH 6/7] merge regression fix --- gitarena/src/git/io/reader.rs | 4 +--- gitarena/src/git/io/writer.rs | 4 ++-- gitarena/src/git/ls_refs.rs | 44 +++++++++++++++++++++++++++------- gitarena/src/git/ref_update.rs | 6 ++--- gitarena/src/ssh/server.rs | 32 ++++++++++++++++--------- 5 files changed, 62 insertions(+), 28 deletions(-) diff --git a/gitarena/src/git/io/reader.rs b/gitarena/src/git/io/reader.rs index 193749a1..038ee754 100644 --- a/gitarena/src/git/io/reader.rs +++ b/gitarena/src/git/io/reader.rs @@ -16,9 +16,7 @@ pub(crate) async fn read_until_command(mut body: Vec>) -> Result<(String continue; } - for i in 0..index { - body.remove(i); - } + body.drain(..index); return Ok((value.to_owned(), body)); } diff --git a/gitarena/src/git/io/writer.rs b/gitarena/src/git/io/writer.rs index 62f11722..8b7965ab 100644 --- a/gitarena/src/git/io/writer.rs +++ b/gitarena/src/git/io/writer.rs @@ -268,7 +268,7 @@ mod tests { let payload = vec![b'a'; 65516]; let mut writer = GitWriter::new(); - writer.write_binary_sideband_chunked(Band::Data, &payload).await?; + writer.write_binary_sideband_chunked(Band::Data, &payload, 65515).await?; writer.write_text("x").await?; let bytes = serialized(writer).await?; @@ -284,7 +284,7 @@ mod tests { let payload = vec![b'a'; 65515]; let mut writer = GitWriter::new(); - writer.write_binary_sideband_chunked(Band::Data, &payload).await?; + writer.write_binary_sideband_chunked(Band::Data, &payload, 65515).await?; let bytes = serialized(writer).await?; diff --git a/gitarena/src/git/ls_refs.rs b/gitarena/src/git/ls_refs.rs index 9096f18d..f6f58caa 100644 --- a/gitarena/src/git/ls_refs.rs +++ b/gitarena/src/git/ls_refs.rs @@ -317,7 +317,7 @@ mod tests { async fn without_prefixes_all_refs_are_listed() -> Result<()> { let (_dir, repo, commit) = repo_with_commit()?; - let mut lines = pkt_lines(&ls_refs(args(&["command=ls-refs", "symrefs"]), &repo).await?)?; + let mut lines = pkt_lines(&ls_refs(args(&["command=ls-refs", "symrefs"]), &repo, &HashSet::new()).await?)?; lines.sort(); assert_eq!( @@ -336,7 +336,7 @@ mod tests { async fn ref_prefix_filters_refs() -> Result<()> { let (_dir, repo, commit) = repo_with_commit()?; - let lines = pkt_lines(&ls_refs(args(&["ref-prefix refs/tags/"]), &repo).await?)?; + let lines = pkt_lines(&ls_refs(args(&["ref-prefix refs/tags/"]), &repo, &HashSet::new()).await?)?; assert_eq!(lines, vec![format!("{commit} refs/tags/v1"), "0000".to_owned()]); Ok(()) @@ -346,7 +346,17 @@ mod tests { async fn head_prefix_lists_only_head() -> Result<()> { let (_dir, repo, commit) = repo_with_commit()?; - let lines = pkt_lines(&ls_refs(args(&["ref-prefix HEAD"]), &repo).await?)?; + let lines = pkt_lines(&ls_refs(args(&["ref-prefix HEAD"]), &repo, &HashSet::new()).await?)?; + + assert_eq!(lines, vec![format!("{commit} HEAD"), "0000".to_owned()]); + Ok(()) + } + + #[tokio::test] + async fn symrefs_adds_symref_target() -> Result<()> { + let (_dir, repo, commit) = repo_with_commit()?; + + let lines = pkt_lines(&ls_refs(args(&["symrefs", "ref-prefix HEAD"]), &repo, &HashSet::new()).await?)?; assert_eq!(lines, vec![format!("{commit} HEAD symref-target:refs/heads/main"), "0000".to_owned()]); Ok(()) @@ -356,19 +366,29 @@ mod tests { async fn unborn_head_is_only_listed_when_requested() -> Result<()> { let (_dir, repo) = empty_repo()?; - let without = pkt_lines(&ls_refs(args(&["ref-prefix HEAD"]), &repo).await?)?; - let with = pkt_lines(&ls_refs(args(&["ref-prefix HEAD", "unborn"]), &repo).await?)?; + let without = pkt_lines(&ls_refs(args(&["symrefs", "ref-prefix HEAD"]), &repo, &HashSet::new()).await?)?; + let with = pkt_lines(&ls_refs(args(&["symrefs", "ref-prefix HEAD", "unborn"]), &repo, &HashSet::new()).await?)?; assert_eq!(without, vec!["0000".to_owned()]); assert_eq!(with, vec!["unborn HEAD symref-target:refs/heads/main".to_owned(), "0000".to_owned()]); Ok(()) } + #[tokio::test] + async fn unborn_head_requires_symrefs() -> Result<()> { + let (_dir, repo) = empty_repo()?; + + let lines = pkt_lines(&ls_refs(args(&["ref-prefix HEAD", "unborn"]), &repo, &HashSet::new()).await?)?; + + assert_eq!(lines, vec!["0000".to_owned()]); + Ok(()) + } + #[tokio::test] async fn ls_refs_all_on_empty_repo_advertises_capabilities_line() -> Result<()> { let (_dir, repo) = empty_repo()?; - let lines = pkt_lines(&ls_refs_all(&repo, Some("git-receive-pack")).await?)?; + let lines = pkt_lines(&ls_refs_all(&repo, Some("git-receive-pack"), GitProtocol::V0, &HashSet::new()).await?)?; assert_eq!(lines.len(), 4); assert_eq!(lines[0], "# service=git-receive-pack"); @@ -386,17 +406,23 @@ mod tests { async fn ls_refs_all_puts_capabilities_on_first_ref_only() -> Result<()> { let (_dir, repo, commit) = repo_with_commit()?; - let lines = pkt_lines(&ls_refs_all_upload_pack(&repo, None).await?)?; + let lines = pkt_lines(&ls_refs_all_upload_pack(&repo, None, GitProtocol::V0, &HashSet::new()).await?)?; - let (_, capabilities) = lines[0].split_once('\0').context("first ref has no capabilities")?; + let (first_ref, capabilities) = lines[0].split_once('\0').context("first ref has no capabilities")?; let mut refs = lines.iter().map(|line| line.split('\0').next().unwrap_or_default()).collect::>(); refs.sort_unstable(); + assert_eq!(first_ref, format!("{commit} HEAD")); assert!(capabilities.contains("symref=HEAD:refs/heads/main"), "{capabilities}"); assert!(!lines[1].contains('\0')); assert_eq!( refs, - vec!["0000".to_owned(), format!("{commit} refs/heads/main"), format!("{commit} refs/tags/v1")] + vec![ + "0000".to_owned(), + format!("{commit} HEAD"), + format!("{commit} refs/heads/main"), + format!("{commit} refs/tags/v1") + ] ); Ok(()) } diff --git a/gitarena/src/git/ref_update.rs b/gitarena/src/git/ref_update.rs index 6da7c79a..be49bcee 100644 --- a/gitarena/src/git/ref_update.rs +++ b/gitarena/src/git/ref_update.rs @@ -153,13 +153,13 @@ mod tests { #[tokio::test] async fn parse_line_reads_capabilities_after_nul() -> Result<()> { - let line = format!("{NULL} {NEW} refs/heads/main\0 report-status report-status-v2 side-band-64k quiet agent=git/2.47.0"); + let line = format!("{NULL} {NEW} refs/heads/main\0 report-status-v2 side-band-64k quiet object-format=sha1 agent=git/2.56.0-Linux"); let update = parse_line(line.into_bytes()).await?; - assert!(update.report_status); + assert!(!update.report_status); assert!(update.report_status_v2); assert!(update.side_band_64k); - assert_eq!(update.push_options, Some(vec!["quiet".to_owned(), "agent=git/2.47.0".to_owned()])); + assert_eq!(update.push_options, None); Ok(()) } diff --git a/gitarena/src/ssh/server.rs b/gitarena/src/ssh/server.rs index b7319fb1..37ef7c1b 100644 --- a/gitarena/src/ssh/server.rs +++ b/gitarena/src/ssh/server.rs @@ -628,21 +628,25 @@ mod tests { } #[test] - fn v1_request_ends_at_done() -> Result<()> { - let request = concat(&[ - &pkt(&format!("want {NEW} side-band-64k\n")), - b"0000", - &pkt(&format!("have {OLD}\n")), - &pkt("done\n"), - ]); + fn v1_wants_and_each_have_batch_end_at_flush() -> Result<()> { + let wants = concat(&[&pkt(&format!("want {NEW} multi_ack_detailed side-band-64k\n")), b"0000"]); + let haves = concat(&[&pkt(&format!("have {OLD}\n")), b"0000"]); + let done = pkt("done\n"); + let mut buffer = concat(&[&wants, &haves, &done]); - assert_eq!(next_request_length(&request, GitProtocol::V1)?, Some(request.len())); + assert_eq!(next_request_length(&buffer, GitProtocol::V1)?, Some(wants.len())); + + buffer.drain(..wants.len()); + assert_eq!(next_request_length(&buffer, GitProtocol::V1)?, Some(haves.len())); + + buffer.drain(..haves.len()); + assert_eq!(next_request_length(&buffer, GitProtocol::V1)?, Some(done.len())); Ok(()) } #[test] - fn v1_flush_does_not_end_request() -> Result<()> { - let request = concat(&[&pkt(&format!("want {NEW}\n")), b"0000", &pkt(&format!("have {OLD}\n")), b"0000"]); + fn v1_haves_without_flush_or_done_are_incomplete() -> Result<()> { + let request = pkt(&format!("have {OLD}\n")); assert_eq!(next_request_length(&request, GitProtocol::V1)?, None); Ok(()) @@ -650,12 +654,18 @@ mod tests { #[test] fn v1_done_without_newline_ends_request() -> Result<()> { - let request = concat(&[&pkt(&format!("want {NEW}\n")), b"0000", &pkt("done")]); + let request = concat(&[&pkt(&format!("have {OLD}\n")), &pkt("done")]); assert_eq!(next_request_length(&request, GitProtocol::V1)?, Some(request.len())); Ok(()) } + #[test] + fn v1_up_to_date_fetch_is_a_lone_flush() -> Result<()> { + assert_eq!(next_request_length(b"0000", GitProtocol::V1)?, Some(4)); + Ok(()) + } + #[test] fn invalid_length_prefix_is_an_error() { assert!(next_request_length(b"zzzz", GitProtocol::V2).is_err()); From 6a26b17a590459628b7bee22876e3c1580e9a083 Mon Sep 17 00:00:00 2001 From: Mari Date: Tue, 24 Nov 2026 22:18:27 +0000 Subject: [PATCH 7/7] run tests only in test workflow --- .github/workflows/git-tests.yml | 2 +- .github/workflows/publish-issues.yml | 3 --- .github/workflows/rust.yml | 10 ---------- 3 files changed, 1 insertion(+), 14 deletions(-) diff --git a/.github/workflows/git-tests.yml b/.github/workflows/git-tests.yml index c782fb77..5284a62c 100644 --- a/.github/workflows/git-tests.yml +++ b/.github/workflows/git-tests.yml @@ -61,7 +61,7 @@ jobs: git-bug version - name: test - run: cargo nextest run --locked -p gitarena --profile ci -E 'kind(test)' + run: cargo nextest run --locked --workspace --profile ci - name: upload test report if: ${{ !cancelled() }} diff --git a/.github/workflows/publish-issues.yml b/.github/workflows/publish-issues.yml index c9c9b883..bc69f219 100644 --- a/.github/workflows/publish-issues.yml +++ b/.github/workflows/publish-issues.yml @@ -46,9 +46,6 @@ jobs: - name: rust cache uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 - - name: test - run: cargo test -p gitarena-issues --all-features - - name: check if version is already published id: version run: | diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 098e7595..f4f56ce6 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -32,16 +32,6 @@ jobs: - name: build run: cargo build --locked --verbose --release - - name: install git-bug v0.11.0 for tests - run: | - curl --proto "=https" --tlsv1.2 -sSf -L https://github.com/git-bug/git-bug/releases/download/v0.11.0/git-bug_linux_amd64 -o /usr/local/bin/git-bug - chmod +x /usr/local/bin/git-bug - - - name: test - run: | - cargo test --verbose --workspace --exclude gitarena - cargo test --verbose -p gitarena --bins - - name: clippy uses: auguwu/clippy-action@9817d076b82df0194935be9db6154c56ac07b317 # 1.5.0 continue-on-error: true