Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

Dev mode reads any git repo (0.7.3 any-git G1–G3) (#366)

Oleksandr Ivanchenko70f661fad9e1
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b2ebd716..d0e1afb3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
### Added
- NVIDIA preset for custom servers: free models from build.nvidia.com (#365).
+- **Dev mode reads any git repo.** Repos on GitLab, Gitea or any git server, and team folders with no remote, are watched with git, and what lands there shows on the Dev desk. Reviews, CI checks and Post to GitHub still work on GitHub repos only. The server needs git 2.31 or newer; without it, the desk says "Needs git on the server". (#366, #368)
+
+### Changed
+- **Dev mode reads commit history with git, not GitHub's API.** Each watched repo gets a copy in kwant's data folder, up to 1 GB each; a bigger repo reads "Too big to read". Repo addresses that point at this server, link-local addresses or cloud metadata addresses are refused, and https reads are pinned to the address that was checked. A team folder whose .git points somewhere else is refused. GitHub PRs, checks and logins still come from GitHub. (#366)
### Fixed
- A custom server's models that have no name now show their id in the model picker instead of "[redacted]" (#365).
diff --git a/docker/kwnt.Dockerfile b/docker/kwnt.Dockerfile
index 90853847..7e51428e 100644
--- a/docker/kwnt.Dockerfile
+++ b/docker/kwnt.Dockerfile
@@ -41,10 +41,11 @@ RUN set -eu; mkdir -p /opt/clis/bin; \
FROM debian:bookworm-slim
ARG KWNT_CLIS=""
-# The CLIs' own tools want git and a few basics; kwnt alone needs only CA certificates.
+# kwnt needs CA certificates, and git (2.31+) with ssh for Dev mode, which reads every watched repo
+# with git; the CLIs' own tools want a few more basics.
RUN apt-get update \
- && apt-get install -y --no-install-recommends ca-certificates \
- $(if [ -n "$KWNT_CLIS" ]; then echo git curl procps ripgrep less; fi) \
+ && apt-get install -y --no-install-recommends ca-certificates git openssh-client \
+ $(if [ -n "$KWNT_CLIS" ]; then echo curl procps ripgrep less; fi) \
&& rm -rf /var/lib/apt/lists/* \
&& useradd --uid 10001 --create-home --home-dir /home/kwnt --shell /bin/bash kwnt \
&& mkdir -p /data && chown kwnt:kwnt /data
diff --git a/docs/dev-mode.md b/docs/dev-mode.md
index 921689b5..b36f7e7c 100644
--- a/docs/dev-mode.md
+++ b/docs/dev-mode.md
@@ -74,8 +74,9 @@ reply carries a `check` that says why. A `branch` the repo doesn't have is a 400
is added or changed in Loose ends, every space that is on with no repo binds the repo it finds
and polls soon, with no off and on. The `GET` does the same if nothing else did (at most every
30 s per space). A repo the person typed or picked is never replaced.
- - `other_host`: only GitLab, Gitea or other non-GitHub sources, or `local` ones. These are read
- from 0.7.3.
+ - `no_git`: only GitLab, Gitea or other non-GitHub sources, or `local` ones, and no git 2.31+ on
+ the server to read them. The reply adds `install_hint`. (0.7.2's `other_host` is retired in
+ 0.7.3: git reads those repos now, so they show `watching`.)
- `new_reviews`: review cards ready to read that were made since the desk was last opened (open
ones only, never landed cards or floor approvals), every watched repo's together: one count for
the space, with one seen time. A space never opened counts 0.
@@ -101,8 +102,10 @@ and newest tag. The full contract is in the team's `dev-mode/team-repos/api.md`;
- **At most 10 repos a space.** A team source past the cap shows `too_many` and has no row; a hand repo
past it is a 409 `too_many`.
- **`GET` and the `PUT` reply** have `repos[]`: one entry per repo, in team order then hand rows, with
- `key`, `repo`, `host`, `team`, `team_id`, `from`, `branch`, `status` (`watching`, `not_connected`,
- `other_host`, `error`, `too_many`), `poll_error`, `polled_at`, `last_tag` and `added_by`. The
+ `key`, `repo`, `host`, `team`, `team_id`, `from`, `provider` (0.7.3: `github` when it's read
+ through a GitHub connection, GitHub Enterprise too, `git` when git alone reads it), `branch`, `status` (`watching`, `not_connected`,
+ `no_git`, `error`, `too_many`; 0.7.2 also had `other_host`), `poll_error`, `poll_code` (0.7.3: `too_big` for a repo over the mirror cap or an answer from git too big to read, else null),
+ `polled_at`, `last_tag` and `added_by`. The
top-level `repo`, `branch`, `deploy_hint`, `last_seen_sha`, `polled_at` and `poll_error` are the
first watched repo's, kept for one release only (deprecated). Top-level `status` is `watching` when
any repo is.
@@ -135,6 +138,93 @@ its own `dev_repos.last_seen_sha` (0.7.1 never writes that table), so what lande
once. A repo changed by hand while on 0.7.1 is not carried over (0.7.1 writes it to
`dev_mode_spaces.repo`); teams' repo links are.
+### Any git repo (0.7.3)
+
+Dev mode reads every watched repo's history with git (any-git.md G1-G3). kwant keeps a bare mirror
+of each repo at `<data>/dev/<space>/<key>-<hash>.git` (deleted when the repo stops being watched; its
+cards stay), or reads a `local` team folder's own `.git` in place, never touching its working tree.
+Commits, diffs, file text, tags, path history and the root's names come from git; on GitHub, pull
+requests, checks and review cards still come from the API, and the API answers when a fetch fails.
+A team's repo on GitLab, Gitea, a bare git server or a folder with no remote now gets a row too
+(`provider: "git"`, with the URL git fetches from in `git_url`) and landed cards, with no PR, CI or
+review cards until its forge is added (G4, G5).
+
+Git runs as kwant's own user, so its SSH keys and credential helpers work. A GitHub token goes to git
+only as an `http.extraHeader` in `GIT_CONFIG_*` environment variables, never in argv, a file or a
+log; URL userinfo is stripped before anything else. http(s) and git:// addresses lose all of it;
+ssh keeps a user name (`ssh://deploy@host/x.git`, `deploy@host:x.git`) and never a password, and
+`git_url` is never logged. Each call has no terminal prompt, a timeout,
+`nice` and its own process group, which is killed when it runs over. The Docker image installs git
+and openssh-client. Without git 2.31+, the status is `no_git`.
+
+A remote read from a team's folder or repo link is fetched only over https, http, ssh or git, and
+never from this machine or a link-local address (`localhost`, `127.0.0.0/8`, `::1`, `169.254.0.0/16`,
+`fe80::/10`, `0.0.0.0`): anyone working in the folder can write its remote, so it can't aim kwant at
+the server itself or a cloud metadata address. Such a source shows `no_repo`. LAN hosts (a Gitea on
+`192.168.x`) are fetched.
+
+Right before every fetch or remote read (GitHub's too), kwant looks the host up itself and refuses it
+if any address is loopback, unspecified, `0.0.0.0/8`, link-local (`169.254.0.0/16`, so
+`169.254.169.254`, and `fe80::/10`), broadcast, the cloud metadata addresses outside link-local
+(`100.100.100.200` and `fd00:ec2::254` exactly; `100.64.0.0/10`, Tailscale's, stays allowed), or one
+of these inside an IPv6 address (IPv4-mapped
+or -compatible, NAT64): a name that resolves to the server is refused like the address itself. The
+row reads `error` ("Dev mode can’t use this repo address or branch name."). Private LAN ranges stay
+allowed. Over http(s) git is then pinned to the addresses checked with
+`-c http.curloptResolve=<host>:<port>:<addresses>` (git 2.37+), so DNS can't answer differently
+between the check and the connect; ssh and git:// (and git 2.31-2.36) get the check alone. git never
+follows an HTTP redirect, since it would lead to a host the check didn't see: a remote that redirects
+(say `http://` to `https://`) reads as an error until its URL is the one the host serves. A GitHub
+remote kwant can't fetch falls back to the API, as any failed fetch does.
+
+The address check and the pin don't cover what the server's admin set up for git outside kwant: a
+proxy (`http_proxy`, `https_proxy`, `ALL_PROXY` in kwant's environment, or `http.proxy` in the
+admin's git config) gets the request and looks the host up itself, so it bypasses the pin and the
+check; and an ssh host alias or `ProxyCommand` in kwant's `~/.ssh/config` connects to an address the
+check never saw. Over ssh, git always runs `ssh` (or the admin's `GIT_SSH`/`GIT_SSH_COMMAND`), never a
+command a repo's own config names; a host whose key isn't in kwant's `known_hosts` fails ("The repo’s
+host said no"), so the admin adds it first. DNS can still change between the check and the connect
+over ssh, git:// and git older than 2.37 (the check stands alone there).
+
+**Team folders.** A `local` team folder is read only if its `.git` is its own, checked again on every
+poll because anyone working in the folder can change it. The row reads `error` ("Dev mode can’t use
+this repo address or branch name.") when `.git` is a symlink; when it is a file (a linked worktree)
+whose git dir doesn't point back at this folder or doesn't sit in its main repo's `worktrees/`; when a
+`.git` directory has a `commondir`; when the git dir or its main repo is under `<data>/dev`; or when
+it has `objects/info/alternates` or a symlink among its objects and refs. A real `git worktree add`
+checkout reads as before; a git submodule checkout (whose `.git` file names `.git/modules/…`) is
+refused. Team detection follows the same rules, so a folder whose `.git` points at another repo is
+not detected as a source at all, and a submodule checkout used as a team folder is no longer
+detected from its folder: link the repo on the team instead.
+
+The check and git's own read are separate steps. A process that keeps swapping a team folder's
+`.git` can sometimes get another repo read in between, and the next poll doesn't stop that (in a
+review probe, 65 of 131 reads got the other repo). Only give a team folder to people you would let
+read every repo on this server. A sandboxed local read is planned for 0.7.4.
+
+**Mirror size.** A mirror is a full bare copy of the repo. A fetch may not write any file past 1 GB
+(`RLIMIT_FSIZE`, with what it fetches kept as one pack), so a huge or hostile remote stops at the cap
+rather than after it. The limit is per file, and the pack, its `.idx` and its `.rev` are each
+limited separately, so one fetch can briefly write about 3× the cap before it is stopped. A fetch stopped there, or a mirror over 1 GB on disk after its fetch, is deleted and a `<mirror>.too-big` note is left beside it; the row reads `error` with "This repo
+is too big for Dev mode to read (over 1 GB)." and `poll_code: "too_big"` (a GitHub row falls back to
+the API instead). One answer from git over 16 MB (a commit touching a vast number of files) reads
+`error` with "This repo is too big for Dev mode to read." and the same `poll_code`. The repo
+isn't fetched again for a day, or until it is removed and added again, which deletes the note.
+
+**Tags and merges.** `last_tag` is the nearest tag reachable from the watched branch (`git describe`),
+where 0.7.2 took GitHub's newest tag: a tag on another branch no longer counts. A merge commit's
+files are its diff against its first parent, which is what the pull request changed.
+
+**New columns, and going back to 0.7.2.** `dev_repos` gains `git_branch` and `git_url` (additive,
+both `NULL` on GitHub rows). A git row keeps `branch = ''` and its real branch in `git_branch`, so
+0.7.2, which ignores the new columns, never polls it (an empty branch waits for reconcile), and its
+reconcile drops the row as one no GitHub source points at. Its cards stay, and 0.7.2 shows them like
+any other repo's. Coming back to 0.7.3 adds the row again; its first poll back-fills the newest
+merges, and a commit that already has a card never gets a second. GitHub rows are unchanged, so 0.7.2
+keeps polling them from their `last_seen_sha`. The mirrors under `<data>/dev/` are left on disk by
+0.7.2 and reused by 0.7.3. 0.7.2 ignores the `<mirror>.too-big` notes and the `poll_code` field;
+back on 0.7.3 a note younger than a day still holds its repo back.
+
`GET /api/dev/cards/:id` returns one card of any kind, in the same shape as the lists, or 404. The
desk reads a release notes draft here once its `dev_card` event says it is ready, since no list
returns those. A card in an archived space is refused like that space's lists.
@@ -372,7 +462,8 @@ included, and must appear nowhere but the vault (logs, errors, events, cards, th
prompts, other files under the data folder).
Test seams, for the test server only: `KWANT_DEV_POLL_SECS` (5–86400, default 300) and
-`KWANT_DEV_CALL_CAP` (0–1000, default 30), read once at the first use. The daily cap counts per UTC
+`KWANT_DEV_CALL_CAP` (0–1000, default 30) and `KWANT_DEV_MIRROR_CAP_BYTES` (1 B to 1 TB, default
+1 GB, so QA can make a small repo too big), read once at the first use. The daily cap counts per UTC
day. Tests move Dev mode's clock in-process with `server::dev::set_clock_skew`
(`tests/dev_seams_test.rs`). There are table tests for each
floor kind in `src/mcp/prod_floor.rs`. The backup checks and the Allow refusal are tested in
diff --git a/src/db/dev_mode.rs b/src/db/dev_mode.rs
index 556ab019..5602eebe 100644
--- a/src/db/dev_mode.rs
+++ b/src/db/dev_mode.rs
@@ -21,6 +21,10 @@ pub const MAX_REPOS: usize = 10;
pub const BY_TEAM: &str = "team";
pub const BY_HAND: &str = "hand";
pub const BY_MIGRATION: &str = "migrated";
+/// `dev_repos.provider` of a repo read with git alone (any-git.md G1): a non-GitHub host or a
+/// team folder. Its branch is kept in `git_branch` and `branch` stays `''`, so 0.7.2 (which polls
+/// only rows with a branch, through GitHub) leaves it alone.
+pub const GIT: &str = "git";
/// Card kinds and statuses, as stored.
pub const LANDED: &str = "landed";
@@ -158,6 +162,9 @@ pub struct DevRepoRow {
pub poll_error: Option<String>,
pub added_by: String,
pub added_at: DateTime<Utc>,
+ /// A [`GIT`] row's fetch URL (userinfo stripped) or team folder: kwant's own, never returned.
+ #[sqlx(default)]
+ pub git_url: Option<String>,
}
impl DevRepoRow {
@@ -169,8 +176,19 @@ impl DevRepoRow {
BY_HAND
}
}
+
+ /// Read with git alone (no GitHub connection behind it).
+ pub fn is_git(&self) -> bool {
+ self.provider == GIT
+ }
}
+/// `dev_repos` columns as kwant reads them: a [`GIT`] row's branch is its `git_branch`.
+const REPO_COLS: &str = "space_id, key, team, provider, repo, host, CASE WHEN provider = 'git' THEN COALESCE(git_branch, '') ELSE branch END AS branch, deploy_hint, last_seen_sha, polled_at, poll_error, added_by, added_at, git_url";
+
+/// The branch a row watches, in SQL (see [`REPO_COLS`]).
+const ROW_BRANCH: &str = "(CASE WHEN provider = 'git' THEN COALESCE(git_branch, '') ELSE branch END)";
+
/// What adding a repo row did.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RepoAdd {
@@ -293,6 +311,13 @@ impl Database {
sqlx::query("ALTER TABLE dev_cards ADD COLUMN rev INTEGER NOT NULL DEFAULT 0").execute(&self.pool).await?;
}
sqlx::query(CARDS_071_GUARD).execute(&self.pool).await?;
+ // 0.7.3: repos read with git alone (any-git.md G1). Additive; 0.7.2 never names them
+ for column in ["git_branch", "git_url"] {
+ let has: Option<(String,)> = sqlx::query_as("SELECT name FROM pragma_table_info('dev_repos') WHERE name = ?").bind(column).fetch_optional(&self.pool).await?;
+ if has.is_none() {
+ sqlx::query(&format!("ALTER TABLE dev_repos ADD COLUMN {column} TEXT")).execute(&self.pool).await?;
+ }
+ }
for sql in CARD_INDEXES {
sqlx::query(sql).execute(&self.pool).await?;
}
@@ -415,11 +440,11 @@ impl Database {
/// A space's watched repos, oldest first.
pub async fn dev_repos(&self, space_id: &str) -> Result<Vec<DevRepoRow>, DbError> {
- Ok(sqlx::query_as("SELECT * FROM dev_repos WHERE space_id = ? ORDER BY added_at, key").bind(space_id).fetch_all(&self.pool).await?)
+ Ok(sqlx::query_as(&format!("SELECT {REPO_COLS} FROM dev_repos WHERE space_id = ? ORDER BY added_at, key")).bind(space_id).fetch_all(&self.pool).await?)
}
pub async fn dev_repo(&self, space_id: &str, key: &str) -> Result<Option<DevRepoRow>, DbError> {
- Ok(sqlx::query_as("SELECT * FROM dev_repos WHERE space_id = ? AND key = ?").bind(space_id).bind(key).fetch_optional(&self.pool).await?)
+ Ok(sqlx::query_as(&format!("SELECT {REPO_COLS} FROM dev_repos WHERE space_id = ? AND key = ?")).bind(space_id).bind(key).fetch_optional(&self.pool).await?)
}
/// Adds a watched repo, unless the space watches [`MAX_REPOS`] already (T4). A row with the
@@ -436,6 +461,30 @@ impl Database {
branch: &str,
deploy_hint: Option<&str>,
added_by: &str,
+ ) -> Result<RepoAdd, DbError> {
+ self.add_repo_row(space_id, key, team, repo, host, branch, deploy_hint, added_by, None).await
+ }
+
+ /// [`Self::add_dev_repo`] for a repo read with git alone ([`GIT`]): `url` is what git fetches
+ /// from (userinfo stripped by the caller) or the team folder, `branch` may be `''` (the
+ /// poller takes the default branch).
+ #[allow(clippy::too_many_arguments)]
+ pub async fn add_dev_repo_git(&self, space_id: &str, key: &str, team: Option<&str>, repo: &str, host: Option<&str>, branch: &str, url: &str, added_by: &str) -> Result<RepoAdd, DbError> {
+ self.add_repo_row(space_id, key, team, repo, host, branch, None, added_by, Some(url)).await
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ async fn add_repo_row(
+ &self,
+ space_id: &str,
+ key: &str,
+ team: Option<&str>,
+ repo: &str,
+ host: Option<&str>,
+ branch: &str,
+ deploy_hint: Option<&str>,
+ added_by: &str,
+ git_url: Option<&str>,
) -> Result<RepoAdd, DbError> {
let _writes = self.dev_on.writes.lock().await;
// Reads, then writes: holds the write lock from BEGIN, or a poller's write in between
@@ -461,18 +510,26 @@ impl Database {
tx.rollback().await?;
return Ok(RepoAdd::TooMany);
}
+ // A git row keeps its branch in git_branch; `branch` stays '' for 0.7.2's poller
+ let (provider, gh_branch, git_branch) = match git_url {
+ Some(_) => (GIT, "", Some(branch)),
+ None => ("github", branch, None),
+ };
sqlx::query(
- "INSERT INTO dev_repos (space_id, key, team, repo, host, branch, deploy_hint, added_by, added_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ "INSERT INTO dev_repos (space_id, key, team, provider, repo, host, branch, deploy_hint, added_by, added_at, git_branch, git_url) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
)
.bind(space_id)
.bind(key)
.bind(team)
+ .bind(provider)
.bind(repo)
.bind(host)
- .bind(branch)
+ .bind(gh_branch)
.bind(deploy_hint)
.bind(added_by)
.bind(Utc::now())
+ .bind(git_branch)
+ .bind(git_url)
.execute(&mut *tx)
.await?;
tx.commit().await?;
@@ -483,12 +540,15 @@ impl Database {
/// cleared), the same one keeps them. False: no such row.
pub async fn set_dev_repo_branch(&self, space_id: &str, key: &str, branch: &str) -> Result<bool, DbError> {
let done = sqlx::query(
- "UPDATE dev_repos SET
- last_seen_sha = CASE WHEN branch = ?3 THEN last_seen_sha ELSE NULL END,
- polled_at = CASE WHEN branch = ?3 THEN polled_at ELSE NULL END,
- poll_error = CASE WHEN branch = ?3 THEN poll_error ELSE NULL END,
- branch = ?3
- WHERE space_id = ?1 AND key = ?2",
+ &format!(
+ "UPDATE dev_repos SET
+ last_seen_sha = CASE WHEN {ROW_BRANCH} = ?3 THEN last_seen_sha ELSE NULL END,
+ polled_at = CASE WHEN {ROW_BRANCH} = ?3 THEN polled_at ELSE NULL END,
+ poll_error = CASE WHEN {ROW_BRANCH} = ?3 THEN poll_error ELSE NULL END,
+ branch = CASE WHEN provider = 'git' THEN '' ELSE ?3 END,
+ git_branch = CASE WHEN provider = 'git' THEN ?3 ELSE git_branch END
+ WHERE space_id = ?1 AND key = ?2"
+ ),
)
.bind(space_id)
.bind(key)
diff --git a/src/server/dev/git.rs b/src/server/dev/git.rs
new file mode 100644
index 00000000..11fa0f5f
--- /dev/null
+++ b/src/server/dev/git.rs
@@ -0,0 +1,2058 @@
+//! Git itself (any-git.md G1, G2): Dev mode reads a watched repo's history with git, from a bare
+//! mirror kwant keeps per repo under `<data>/dev/<space>/` or straight from a team folder's own
+//! `.git` (never its working tree). Any host git can fetch from works: GitHub, GitLab, Gitea, a
+//! plain git server, a folder.
+//!
+//! Every call is the same safe run ([`run`]):
+//! - git runs as kwant's own user, so the person's SSH keys and credential helpers work;
+//! - a connection's token goes in as an `http.<origin>/.extraHeader` through
+//! `GIT_CONFIG_COUNT`/`GIT_CONFIG_KEY_n`/`GIT_CONFIG_VALUE_n`: never in argv, on disk or in a log;
+//! - no prompt (`GIT_TERMINAL_PROMPT=0`, no askpass, its own session so ssh can't open a tty),
+//! no hooks, no fsmonitor, no pager, no external diff or textconv, no signature checks;
+//! - only the https, http, ssh and git protocols (file only for a team folder), and no redirect
+//! while a token is set;
+//! - before git reaches a remote, its host is looked up and refused if any address is this machine
+//! or link-local ([`check_remote`]); over http(s) git is pinned to the addresses checked
+//! (`http.curloptResolve`), so DNS can't answer differently between the check and the connect;
+//! - `nice 10`, a timeout that kills its whole process group, and capped output;
+//! - a mirror over [`MIRROR_CAP`] on disk is deleted after the fetch that grew it, and fetched again
+//! at most once a day;
+//! - stderr is only sorted into a [`GitError`], never logged or returned, so a URL in it goes
+//! nowhere.
+
+use super::facts::FileDiff;
+use super::source::{Commit, Person};
+use chrono::{DateTime, Utc};
+use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
+use std::path::{Path, PathBuf};
+use std::process::Stdio;
+use std::sync::{Arc, Mutex, OnceLock};
+use std::time::{Duration, Instant};
+use tokio::io::{AsyncRead, AsyncReadExt};
+use zeroize::Zeroizing;
+
+/// The oldest git kwant runs: `GIT_CONFIG_COUNT` came in 2.31.
+pub const MIN_VERSION: (u32, u32) = (2, 31);
+/// What the desk says to do when the server has no usable git.
+pub const INSTALL_HINT: &str = "Install git 2.31 or newer on the server.";
+/// How long one fetch may take (a first fetch of a big repo is the slow one).
+pub const FETCH_TIMEOUT: Duration = Duration::from_secs(300);
+/// How long one ls-remote may take.
+pub const REMOTE_TIMEOUT: Duration = Duration::from_secs(30);
+/// How long one local read may take.
+pub const READ_TIMEOUT: Duration = Duration::from_secs(20);
+/// Most stdout one call returns; a bigger answer is [`GitError::TooBig`].
+pub const MAX_OUT: usize = 16 << 20;
+/// Most stderr kept to sort an error by.
+const MAX_ERR: usize = 8 << 10;
+/// Biggest file [`Repo::file_at`] reads.
+pub const MAX_FILE: usize = 1 << 20;
+/// Most commits one [`Repo::commits_since`] lists, as GitHub's list.
+pub const MAX_COMMITS: usize = crate::zombie::github::MAX_COMMITS;
+/// Most files one diff lists, as GitHub's PR files.
+pub const MAX_FILES: usize = crate::zombie::github::MAX_PR_FILES;
+/// The most disk one repo's mirror may use (1 GB): one over it is deleted after the fetch.
+pub const MIRROR_CAP: u64 = 1 << 30;
+/// How long a mirror that was too big waits before it is fetched again (unless its repo is
+/// removed and added again, which starts afresh).
+pub const TOO_BIG_RETRY: Duration = Duration::from_secs(24 * 60 * 60);
+/// How long looking a remote's host up may take.
+const LOOKUP_TIMEOUT: Duration = Duration::from_secs(10);
+/// The first git with `http.curloptResolve` (2.37), which pins a checked address.
+const PIN_VERSION: (u32, u32) = (2, 37);
+
+/// Why git didn't answer. Each says the same fixed words whatever git printed.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum GitError {
+ /// No git on the server, or one older than [`MIN_VERSION`].
+ NoGit,
+ /// The host refused: no key, no credentials, a bad token, an unknown host key.
+ Auth,
+ /// No such repo, branch or commit.
+ NotFound,
+ /// The host couldn't be reached.
+ Unreachable,
+ Timeout,
+ TooBig,
+ /// The repo's mirror passed [`MIRROR_CAP`] and was deleted: it is fetched again after
+ /// [`TOO_BIG_RETRY`], or when the repo is removed and added again.
+ RepoTooBig,
+ /// kwant refused the input before running git (a URL or ref it won't pass on).
+ Refused,
+ Failed,
+}
+
+impl std::fmt::Display for GitError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str(match self {
+ // Wording from Mira's copy-073.md; the desk matches RepoTooBig by `poll_code`.
+ GitError::NoGit => "Needs git 2.31 or newer on the server.",
+ GitError::Auth => "The repo’s host said no. Check the server’s SSH key or git login for this repo.",
+ GitError::NotFound => "Couldn’t find this repo or branch.",
+ GitError::Unreachable => "Couldn’t reach the repo’s host.",
+ GitError::Timeout => "The repo’s host took too long to answer.",
+ GitError::TooBig => "This repo is too big for Dev mode to read.",
+ GitError::RepoTooBig => "This repo is too big for Dev mode to read (over 1 GB).",
+ GitError::Refused => "Dev mode can’t use this repo address or branch name.",
+ GitError::Failed => "Couldn’t read this repo.",
+ })
+ }
+}
+
+impl std::error::Error for GitError {}
+
+impl GitError {
+ /// The `poll_code` for a row whose `poll_error` is `message`: `too_big` for either too-big
+ /// error (a mirror over the cap, or one answer from git over [`MAX_OUT`]), so the desk never
+ /// matches strings; `None` for the rest.
+ pub fn poll_code(message: &str) -> Option<&'static str> {
+ [GitError::RepoTooBig, GitError::TooBig].iter().any(|e| e.to_string() == message).then_some("too_big")
+ }
+}
+
+/// Sorts git's stderr. The text itself goes no further.
+fn classify(stderr: &[u8]) -> GitError {
+ let e = String::from_utf8_lossy(stderr).to_lowercase();
+ let any = |words: &[&str]| words.iter().any(|w| e.contains(w));
+ if any(&[
+ "permission denied",
+ "authentication failed",
+ "could not read username",
+ "could not read password",
+ "terminal prompts disabled",
+ "host key verification failed",
+ "the requested url returned error: 401",
+ "the requested url returned error: 403",
+ "invalid credentials",
+ "access denied",
+ ]) {
+ GitError::Auth
+ } else if any(&["not found", "does not appear to be a git repository", "couldn't find remote ref", "not a valid", "unknown revision", "bad revision", "invalid object name", "not a git repository", "returned error: 404"]) {
+ GitError::NotFound
+ } else if any(&["could not resolve host", "connection refused", "connection timed out", "network is unreachable", "failed to connect", "could not connect", "ssl", "tls", "no route to host", "connection reset"]) {
+ GitError::Unreachable
+ } else {
+ GitError::Failed
+ }
+}
+
+/// An `Authorization` header for one origin, given to git through the environment. Its value is
+/// never printed (`Debug` hides it) and is wiped when dropped.
+pub struct Auth {
+ key: String,
+ value: Zeroizing<String>,
+}
+
+impl std::fmt::Debug for Auth {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("Auth").field("key", &self.key).field("value", &"<hidden>").finish()
+ }
+}
+
+impl Auth {
+ /// `Authorization: <authorization>` for requests to `url`'s origin. `None` unless `url` is
+ /// https (or http to this machine, for tests) and the value is one header line.
+ pub fn header(url: &str, authorization: Zeroizing<String>) -> Option<Self> {
+ let u = url::Url::parse(url).ok()?;
+ let host = u.host_str()?;
+ let ok = u.scheme() == "https" || (u.scheme() == "http" && crate::zombie::imap::is_loopback(host));
+ if !ok || authorization.is_empty() || authorization.chars().any(|c| c.is_control() || !(c.is_ascii_graphic() || c == ' ')) {
+ return None;
+ }
+ let origin = u.origin().ascii_serialization();
+ Some(Auth { key: format!("http.{origin}/.extraheader"), value: Zeroizing::new(format!("Authorization: {}", authorization.as_str())) })
+ }
+}
+
+/// Environment variables git keeps from kwant's own: the person's ssh and config choices. Every
+/// other `GIT_*` is dropped (a `GIT_DIR`, `GIT_CONFIG_PARAMETERS` or `GIT_ASKPASS` from kwant's
+/// environment must not steer these calls).
+const KEEP_ENV: &[&str] = &[
+ "GIT_SSH",
+ "GIT_SSH_COMMAND",
+ "GIT_SSH_VARIANT",
+ "GIT_CONFIG_GLOBAL",
+ "GIT_CONFIG_SYSTEM",
+ "GIT_CONFIG_NOSYSTEM",
+ "GIT_EXEC_PATH",
+ "GIT_SSL_CAINFO",
+ "GIT_SSL_CAPATH",
+];
+
+/// Settings every call gets, whatever the repo's own config says.
+const SAFE_CONFIG: &[&str] = &[
+ "core.fsmonitor=false",
+ "core.hooksPath=/dev/null",
+ "core.askPass=",
+ "core.quotePath=false",
+ "log.showSignature=false",
+ "gc.autoDetach=false",
+ "maintenance.autoDetach=false",
+ "fetch.recurseSubmodules=false",
+ "submodule.recurse=false",
+ "protocol.allow=never",
+ "protocol.https.allow=always",
+ "protocol.http.allow=always",
+ "protocol.ssh.allow=always",
+ "protocol.git.allow=always",
+];
+
+/// The `core.sshCommand` every call gets (G2 review F1): plain `ssh` from `PATH`, or the admin's
+/// `GIT_SSH` program, so a repo's own config can never choose the command. (An empty value would
+/// make git try to run `''` and break every ssh remote; `GIT_SSH_COMMAND` still wins over this.)
+fn ssh_command(git_ssh: Option<&std::ffi::OsStr>) -> String {
+ match git_ssh.and_then(|s| s.to_str()).filter(|s| !s.is_empty()) {
+ // Single-quoted for the shell git runs it with: a `'` inside becomes `'\''`
+ Some(prog) => format!("core.sshCommand='{}'", prog.replace('\'', "'\\''")),
+ None => "core.sshCommand=ssh".to_string(),
+ }
+}
+
+#[derive(Clone, Copy)]
+struct Opts<'a> {
+ timeout: Duration,
+ max_out: usize,
+ auth: Option<&'a Auth>,
+ /// A team folder: the file protocol is allowed (git reads its own objects).
+ file: bool,
+ /// `-c` settings from [`check_remote`] that pin git to the addresses it checked.
+ pin: &'a [String],
+ /// A fetch into a mirror: no file git writes may pass this many bytes (`RLIMIT_FSIZE`), and
+ /// what it fetches is kept as one pack, so a fetch stops at the cap instead of after it (G2
+ /// review F3). Passing it is [`GitError::RepoTooBig`]. The limit is per file: the pack, its
+ /// `.idx` and its `.rev` can each reach it, so one fetch can briefly write about 3× the cap.
+ fsize: Option<u64>,
+}
+
+impl Opts<'static> {
+ fn read() -> Self {
+ Opts { timeout: READ_TIMEOUT, max_out: MAX_OUT, auth: None, file: false, pin: &[], fsize: None }
+ }
+}
+
+/// Runs `git [--git-dir <dir>] <args>` as described in the module docs. Its stdout on success.
+async fn run(bin: &str, git_dir: Option<&Path>, args: &[&str], o: Opts<'_>) -> Result<Vec<u8>, GitError> {
+ let mut cmd = tokio::process::Command::new(bin);
+ if let Some(d) = git_dir {
+ cmd.arg("--git-dir").arg(d);
+ }
+ cmd.arg("--no-pager");
+ for c in SAFE_CONFIG {
+ cmd.arg("-c").arg(c);
+ }
+ cmd.arg("-c").arg(ssh_command(std::env::var_os("GIT_SSH").as_deref()));
+ if o.fsize.is_some() {
+ // One pack file, not loose objects each under the limit on their own
+ cmd.args(["-c", "fetch.unpackLimit=1", "-c", "transfer.unpackLimit=1"]);
+ }
+ if o.file {
+ cmd.args(["-c", "protocol.file.allow=always"]);
+ }
+ // No redirect: it would take git to a host the address check never saw (and, with a token,
+ // the token with it)
+ cmd.args(["-c", "http.followRedirects=false"]);
+ if o.auth.is_some() {
+ // The token goes to this origin only: no helper asked or told
+ cmd.args(["-c", "credential.helper="]);
+ }
+ for c in o.pin {
+ cmd.arg("-c").arg(c);
+ }
+ cmd.args(args);
+ for (k, _) in std::env::vars_os() {
+ if let Some(k) = k.to_str() {
+ if k.starts_with("GIT_") && !KEEP_ENV.contains(&k) {
+ cmd.env_remove(k);
+ }
+ }
+ }
+ cmd.env_remove("SSH_ASKPASS");
+ cmd.env("GIT_TERMINAL_PROMPT", "0")
+ .env("GIT_OPTIONAL_LOCKS", "0")
+ .env("GIT_LITERAL_PATHSPECS", "1")
+ .env("GIT_NO_REPLACE_OBJECTS", "1")
+ .env("GCM_INTERACTIVE", "never")
+ .env("SSH_ASKPASS_REQUIRE", "never")
+ .env("LC_ALL", "C");
+ match o.auth {
+ Some(a) => {
+ cmd.env("GIT_CONFIG_COUNT", "1").env("GIT_CONFIG_KEY_0", &a.key).env("GIT_CONFIG_VALUE_0", a.value.as_str());
+ }
+ None => {
+ cmd.env("GIT_CONFIG_COUNT", "0");
+ }
+ }
+ cmd.current_dir(git_dir.filter(|d| d.is_dir()).unwrap_or(Path::new("/")));
+ cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).kill_on_drop(true);
+ #[cfg(unix)]
+ let fsize = o.fsize;
+ #[cfg(unix)]
+ // SAFETY: setsid(2), nice(2), setrlimit(2) and signal(2) are async-signal-safe and touch no
+ // memory of this process
+ unsafe {
+ cmd.pre_exec(move || {
+ // Its own session: no controlling terminal for ssh to prompt on, and one process
+ // group the timeout can kill whole
+ libc::setsid();
+ libc::nice(10);
+ if let Some(cap) = fsize {
+ // A write past the cap stops git (SIGXFSZ, inherited by index-pack)
+ let lim = libc::rlimit { rlim_cur: cap as libc::rlim_t, rlim_max: cap as libc::rlim_t };
+ if libc::setrlimit(libc::RLIMIT_FSIZE, &lim) != 0 {
+ return Err(std::io::Error::last_os_error());
+ }
+ libc::signal(libc::SIGXFSZ, libc::SIG_DFL);
+ // ...without a core file
+ let none = libc::rlimit { rlim_cur: 0, rlim_max: 0 };
+ libc::setrlimit(libc::RLIMIT_CORE, &none);
+ }
+ Ok(())
+ });
+ }
+ let mut child = cmd.spawn().map_err(|e| if e.kind() == std::io::ErrorKind::NotFound { GitError::NoGit } else { GitError::Failed })?;
+ let mut group = crate::drivers::cli::ProcessGroup::of(&child);
+ let (so, se) = (child.stdout.take(), child.stderr.take());
+ let work = async {
+ let (out, err) = tokio::try_join!(read_capped(so, o.max_out), async { Ok(drain(se, MAX_ERR).await) })?;
+ let status = child.wait().await.map_err(|_| GitError::Failed)?;
+ Ok::<_, GitError>((out, err, status))
+ };
+ let (out, err, status) = tokio::time::timeout(o.timeout, work).await.map_err(|_| GitError::Timeout)??;
+ group.disarm();
+ if status.success() {
+ Ok(out)
+ } else if o.fsize.is_some() && hit_size_limit(&status, &err) {
+ Err(GitError::RepoTooBig)
+ } else {
+ Err(classify(&err))
+ }
+}
+
+/// Whether a size-limited git (or the index-pack it ran) stopped at `RLIMIT_FSIZE`: killed by
+/// SIGXFSZ, or told "File too large" if that signal is ignored.
+fn hit_size_limit(status: &std::process::ExitStatus, stderr: &[u8]) -> bool {
+ #[cfg(unix)]
+ {
+ use std::os::unix::process::ExitStatusExt;
+ if status.signal() == Some(libc::SIGXFSZ) {
+ return true;
+ }
+ }
+ let _ = status;
+ let e = String::from_utf8_lossy(stderr).to_lowercase();
+ e.contains(&format!("died of signal {}", libc::SIGXFSZ)) || e.contains("file too large")
+}
+
+/// Reads all of `r`, or [`GitError::TooBig`] as soon as it passes `cap`.
+async fn read_capped<R: AsyncRead + Unpin>(r: Option<R>, cap: usize) -> Result<Vec<u8>, GitError> {
+ let Some(mut r) = r else { return Ok(Vec::new()) };
+ let mut out = Vec::new();
+ let mut buf = vec![0u8; 64 << 10];
+ loop {
+ let n = r.read(&mut buf).await.map_err(|_| GitError::Failed)?;
+ if n == 0 {
+ return Ok(out);
+ }
+ if out.len() + n > cap {
+ return Err(GitError::TooBig);
+ }
+ out.extend_from_slice(&buf[..n]);
+ }
+}
+
+/// Reads all of `r` (so git never blocks on a full pipe), keeping the first `keep` bytes.
+async fn drain<R: AsyncRead + Unpin>(r: Option<R>, keep: usize) -> Vec<u8> {
+ let Some(mut r) = r else { return Vec::new() };
+ let mut out = Vec::new();
+ let mut buf = [0u8; 4096];
+ while let Ok(n) = r.read(&mut buf).await {
+ if n == 0 {
+ break;
+ }
+ let room = keep.saturating_sub(out.len()).min(n);
+ out.extend_from_slice(&buf[..room]);
+ }
+ out
+}
+
+/// `(major, minor)` of `git --version`.
+async fn version(bin: &str) -> Option<(u32, u32)> {
+ let out = run(bin, None, &["--version"], Opts::read()).await.ok()?;
+ parse_version(&String::from_utf8_lossy(&out))
+}
+
+fn parse_version(s: &str) -> Option<(u32, u32)> {
+ let v = s.trim().strip_prefix("git version ")?;
+ let mut it = v.split(|c: char| !c.is_ascii_digit());
+ Some((it.next()?.parse().ok()?, it.next()?.parse().ok()?))
+}
+
+/// The server's git version, if it has one kwant can use ([`MIN_VERSION`] or newer). A yes is kept;
+/// a no is asked again after a minute, so installing git needs no restart.
+async fn usable_version() -> Option<(u32, u32)> {
+ // The last answer and when it was asked
+ type Seen = Option<(Option<(u32, u32)>, Instant)>;
+ static SEEN: OnceLock<Mutex<Seen>> = OnceLock::new();
+ let seen = SEEN.get_or_init(Default::default);
+ if let Some((v, at)) = *seen.lock().unwrap() {
+ if v.is_some() || at.elapsed() < Duration::from_secs(60) {
+ return v;
+ }
+ }
+ let v = version("git").await.filter(|v| *v >= MIN_VERSION);
+ *seen.lock().unwrap() = Some((v, Instant::now()));
+ v
+}
+
+/// Whether the server has a git kwant can use ([`MIN_VERSION`] or newer).
+pub async fn available() -> bool {
+ usable_version().await.is_some()
+}
+
+// ---------------------------------------------------------------------------------------------
+// Input checks: nothing reaches git's argv unchecked.
+
+/// A full commit id (sha-1 or sha-256), lowercase hex.
+pub fn is_sha(s: &str) -> bool {
+ (s.len() == 40 || s.len() == 64) && s.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
+}
+
+/// A ref name kwant passes to git: a valid branch name (as the routes check) under `refs/`.
+fn ok_ref(r: &str) -> bool {
+ r.strip_prefix("refs/").is_some_and(super::routes::valid_branch)
+}
+
+fn ok_branch(b: &str) -> bool {
+ super::routes::valid_branch(b)
+}
+
+/// A user name kept in an ssh URL (`git@`, `gitlab@`): never a password or a token.
+fn ok_user(u: &str) -> bool {
+ !u.is_empty() && u.len() <= 32 && !u.starts_with('-') && u.chars().all(|c| c.is_ascii_alphanumeric() || "._-".contains(c))
+}
+
+fn ok_host(h: &str) -> bool {
+ h.len() > 1 && h.len() <= 253 && !h.starts_with('-') && !h.starts_with('.') && h.chars().all(|c| c.is_ascii_alphanumeric() || "-.".contains(c))
+}
+
+fn ok_path(p: &str) -> bool {
+ let p = p.trim_matches('/');
+ !p.is_empty()
+ && p.len() <= 400
+ && p.split('/').all(|s| !s.is_empty() && s != "." && s != ".." && !s.starts_with('-') && s.chars().all(|c| c.is_ascii_alphanumeric() || "._-~".contains(c)))
+}
+
+/// [`fetch_url`] for a remote that a team's folder or repo link names, which anyone working in that
+/// folder can write: also `None` for a host on this machine or link-local (`localhost`, `127.0.0.0/8`,
+/// `::1`, `169.254.0.0/16`, `fe80::/10`, `0.0.0.0`), so a folder can't point kwant's fetches at the
+/// server itself or a cloud metadata address. LAN hosts (a self-hosted Gitea on `192.168.x`) stay.
+/// A remote kwant makes itself from a connection the person set up uses [`fetch_url`].
+pub fn remote_url(raw: &str) -> Option<String> {
+ fetch_url(raw).filter(|u| !on_this_machine(u))
+}
+
+fn on_this_machine(url: &str) -> bool {
+ match url::Host::parse(&remote_host(url).0) {
+ Ok(url::Host::Domain(d)) => {
+ let d = d.trim_end_matches('.').to_ascii_lowercase();
+ d == "localhost" || d.ends_with(".localhost")
+ }
+ Ok(url::Host::Ipv4(ip)) => blocked(IpAddr::V4(ip)),
+ Ok(url::Host::Ipv6(ip)) => blocked(IpAddr::V6(ip)),
+ Err(_) => true,
+ }
+}
+
+/// The host of a [`fetch_url`] (`[v6]` keeps its brackets) and its port, if it names one.
+fn remote_host(url: &str) -> (String, Option<u16>) {
+ match url.find("://") {
+ Some(i) => {
+ let rest = &url[i + 3..];
+ let rest = &rest[..rest.find('/').unwrap_or(rest.len())];
+ let rest = rest.rsplit_once('@').map_or(rest, |(_, h)| h);
+ // `host:port` or `[v6]:port`
+ match rest.strip_prefix('[') {
+ Some(r) => {
+ let end = r.find(']').unwrap_or(r.len());
+ (format!("[{}]", &r[..end]), r[end..].strip_prefix("]:").and_then(|p| p.parse().ok()))
+ }
+ None => {
+ let mut it = rest.splitn(2, ':');
+ (it.next().unwrap_or("").to_string(), it.next().and_then(|p| p.parse().ok()))
+ }
+ }
+ }
+ None => {
+ let h = url.split_once(':').map_or(url, |(h, _)| h);
+ (h.rsplit_once('@').map_or(h, |(_, h)| h).to_string(), None)
+ }
+ }
+}
+
+/// Cloud metadata services outside link-local (G2 review F6): Alibaba's `100.100.100.200` and AWS's
+/// IPv6 `fd00:ec2::254`. Only these addresses, not their ranges: `100.64.0.0/10` is Tailscale.
+const METADATA_V4: Ipv4Addr = Ipv4Addr::new(100, 100, 100, 200);
+const METADATA_V6: Ipv6Addr = Ipv6Addr::new(0xfd00, 0xec2, 0, 0, 0, 0, 0, 0x254);
+
+/// An address kwant never lets git connect to: this machine (loopback, unspecified, `0.0.0.0/8`),
+/// link-local (`169.254.0.0/16`, where cloud metadata lives, and `fe80::/10`), broadcast, the cloud
+/// metadata addresses outside link-local ([`METADATA_V4`], [`METADATA_V6`]), or any of these inside
+/// an IPv6 address (IPv4-mapped, IPv4-compatible, NAT64 `64:ff9b::/96`). Private LAN ranges are
+/// allowed: people run Gitea at home.
+pub fn blocked(ip: IpAddr) -> bool {
+ let v4 = |ip: Ipv4Addr| ip.is_loopback() || ip.is_link_local() || ip.is_unspecified() || ip.is_broadcast() || ip.octets()[0] == 0 || ip == METADATA_V4;
+ match ip {
+ IpAddr::V4(ip) => v4(ip),
+ IpAddr::V6(ip) => {
+ let s = ip.segments();
+ let nat64 = s[..6] == [0x64, 0xff9b, 0, 0, 0, 0];
+ let embedded = |ip: Ipv6Addr| {
+ let o = ip.octets();
+ Ipv4Addr::new(o[12], o[13], o[14], o[15])
+ };
+ ip.is_loopback()
+ || ip.is_unspecified()
+ || ip == METADATA_V6
+ || (s[0] & 0xffc0) == 0xfe80
+ || ip.to_ipv4_mapped().is_some_and(v4)
+ || (s[..6] == [0; 6] && v4(embedded(ip)))
+ || (nat64 && v4(embedded(ip)))
+ }
+ }
+}
+
+/// Looks a remote's host up: the seam [`check_remote`] is tested through, with no network.
+#[async_trait::async_trait]
+pub trait Resolver: Send + Sync {
+ async fn lookup(&self, host: &str, port: u16) -> Result<Vec<IpAddr>, GitError>;
+}
+
+/// The system's resolver, with a timeout.
+pub struct SystemResolver;
+
+#[async_trait::async_trait]
+impl Resolver for SystemResolver {
+ async fn lookup(&self, host: &str, port: u16) -> Result<Vec<IpAddr>, GitError> {
+ let found = tokio::time::timeout(LOOKUP_TIMEOUT, tokio::net::lookup_host((host, port))).await.map_err(|_| GitError::Unreachable)?.map_err(|_| GitError::Unreachable)?;
+ Ok(found.map(|a| a.ip()).collect())
+ }
+}
+
+/// Checks a [`fetch_url`] right before git reaches it (any-git.md G2): its host is looked up, and
+/// refused ([`GitError::Refused`]) if it is, or any address it has is, [`blocked`]. Over http(s),
+/// with git [`PIN_VERSION`] or newer, the answer is the `-c http.curloptResolve=<host>:<port>:<addrs>`
+/// that pins git to the addresses checked, so DNS can't change between the check and the connect;
+/// over ssh and git://, or on an older git, the check stands alone.
+pub async fn check_remote(url: &str, resolver: &dyn Resolver, git: Option<(u32, u32)>) -> Result<Vec<String>, GitError> {
+ if fetch_url(url).as_deref() != Some(url) || on_this_machine(url) {
+ return Err(GitError::Refused);
+ }
+ let (host, port) = remote_host(url);
+ let scheme = url.find("://").map(|i| &url[..i]);
+ let port = port.unwrap_or(match scheme {
+ Some("https") => 443,
+ Some("http") => 80,
+ Some("git") => 9418,
+ _ => 22,
+ });
+ let addrs = match url::Host::parse(&host).map_err(|_| GitError::Refused)? {
+ // A literal address needs no lookup and no pin: on_this_machine checked it
+ url::Host::Ipv4(_) | url::Host::Ipv6(_) => return Ok(Vec::new()),
+ url::Host::Domain(d) => resolver.lookup(&d, port).await?,
+ };
+ if addrs.is_empty() {
+ return Err(GitError::Unreachable);
+ }
+ if addrs.iter().any(|a| blocked(*a)) {
+ return Err(GitError::Refused);
+ }
+ if !matches!(scheme, Some("https" | "http")) || git.is_none_or(|v| v < PIN_VERSION) {
+ return Ok(Vec::new());
+ }
+ let list: Vec<String> = addrs.iter().map(|a| if a.is_ipv6() { format!("[{a}]") } else { a.to_string() }).collect();
+ Ok(vec![format!("http.curloptResolve={host}:{port}:{}", list.join(","))])
+}
+
+/// [`check_remote`] with the system's resolver and this server's git.
+async fn checked(url: &str) -> Result<Vec<String>, GitError> {
+ check_remote(url, &SystemResolver, usable_version().await).await
+}
+
+/// What git fetches a remote from, made from a remote URL or repo link as written: its userinfo
+/// stripped first (an ssh user name like `git` is put back; a password or token never is), its
+/// query and fragment dropped. https, http, ssh, git and scp-like `user@host:path` only: a local
+/// path, `file://` or `ext::` is `None`, as is a host, user or path segment that starts with `-`.
+pub fn fetch_url(raw: &str) -> Option<String> {
+ let raw = raw.trim();
+ if raw.is_empty() || raw.len() > 500 || raw.chars().any(|c| c.is_whitespace() || c.is_control()) {
+ return None;
+ }
+ // Never a `.` or `..` segment (the URL parser would fold it away)
+ if raw.split(['/', ':']).any(|seg| seg == "." || seg == "..") {
+ return None;
+ }
+ // The user name (never its password) before anything is stripped, to put back on ssh only:
+ // the userinfo is everything up to the last `@` before any `?` or `#`, as strip_userinfo reads
+ let user = {
+ let rest = raw.find("://").map(|i| &raw[i + 3..]).unwrap_or(raw);
+ let rest = &rest[..rest.find(['?', '#']).unwrap_or(rest.len())];
+ rest.rfind('@').and_then(|at| rest[..at].split(':').next()).filter(|u| ok_user(u)).map(str::to_string)
+ };
+ let s = super::repo::strip_userinfo(raw);
+ if let Some(i) = s.find("://") {
+ let scheme = s[..i].to_ascii_lowercase();
+ let scheme = scheme.strip_prefix("git+").unwrap_or(&scheme).to_string();
+ if !matches!(scheme.as_str(), "https" | "http" | "ssh" | "git") {
+ return None;
+ }
+ let u = url::Url::parse(&format!("{scheme}{}", &s[i..])).ok()?;
+ let host = u.host_str()?.to_ascii_lowercase();
+ if matches!(u.host(), Some(url::Host::Domain(d)) if !ok_host(d)) {
+ return None;
+ }
+ if !ok_path(u.path()) {
+ return None;
+ }
+ let port = u.port().map(|p| format!(":{p}")).unwrap_or_default();
+ let user = match (&*scheme, user) {
+ ("ssh", Some(u)) => format!("{u}@"),
+ _ => String::new(),
+ };
+ Some(format!("{scheme}://{user}{host}{port}{}", u.path()))
+ } else {
+ // scp-like: host:path, with the user name put back
+ let (host, path) = s.split_once(':')?;
+ let host = host.to_ascii_lowercase();
+ if !ok_host(&host) || !ok_path(path) {
+ return None;
+ }
+ Some(match user {
+ Some(u) => format!("{u}@{host}:{path}"),
+ None => format!("{host}:{path}"),
+ })
+ }
+}
+
+/// The web page of a commit on `host` (`base/<sha>`), for the hosts whose pages kwant knows.
+pub fn commit_base(host: &str, repo: &str) -> Option<String> {
+ let h = host.to_ascii_lowercase();
+ let tail = if h == "gitlab.com" || h.starts_with("gitlab.") {
+ "-/commit"
+ } else if h == "bitbucket.org" {
+ "commits"
+ } else if h == "codeberg.org" || h.starts_with("gitea.") || h.starts_with("forgejo.") {
+ "commit"
+ } else {
+ return None;
+ };
+ (ok_host(&h) && ok_path(repo)).then(|| format!("https://{h}/{}/{tail}", repo.trim_matches('/')))
+}
+
+// ---------------------------------------------------------------------------------------------
+// Repos
+
+/// One lock per mirror: a poll and a removal never meet in the same directory.
+fn locks() -> &'static Mutex<std::collections::HashMap<PathBuf, Arc<tokio::sync::Mutex<()>>>> {
+ static L: OnceLock<Mutex<std::collections::HashMap<PathBuf, Arc<tokio::sync::Mutex<()>>>>> = OnceLock::new();
+ L.get_or_init(Default::default)
+}
+
+async fn lock(dir: &Path) -> tokio::sync::OwnedMutexGuard<()> {
+ let m = locks().lock().unwrap().entry(dir.to_path_buf()).or_default().clone();
+ m.lock_owned().await
+}
+
+/// A file name made of `s`: letters, digits, `.`, `_` and `-`, at most 60, never starting with `.`.
+fn safe_name(s: &str) -> String {
+ let n: String = s.chars().map(|c| if c.is_ascii_alphanumeric() || "._-".contains(c) { c } else { '_' }).take(60).collect();
+ let n = n.trim_start_matches('.').to_string();
+ if n.is_empty() {
+ "_".into()
+ } else {
+ n
+ }
+}
+
+/// Where the mirror of watched repo `key` in `space` lives:
+/// `<data>/dev/<space>/<key, made safe>-<8 hex of its sha-256>.git` (the hash keeps two keys that
+/// read the same once made safe apart).
+pub fn mirror_dir(data_dir: &Path, space: &str, key: &str) -> PathBuf {
+ use sha2::Digest;
+ let hash = sha2::Sha256::digest(key.as_bytes());
+ let hex: String = hash.iter().take(4).map(|b| format!("{b:02x}")).collect();
+ data_dir.join("dev").join(safe_name(space)).join(format!("{}-{hex}.git", safe_name(key)))
+}
+
+/// The note left beside a mirror deleted for passing [`MIRROR_CAP`]: `<mirror>.too-big`. Its
+/// age is when that was.
+pub fn too_big_mark(mirror: &Path) -> PathBuf {
+ let mut name = mirror.file_name().unwrap_or_default().to_os_string();
+ name.push(".too-big");
+ mirror.with_file_name(name)
+}
+
+/// What `dir` and everything under it take on disk (links not followed).
+fn disk_use(dir: &Path) -> u64 {
+ let mut total = 0;
+ let mut todo = vec![dir.to_path_buf()];
+ while let Some(d) = todo.pop() {
+ let Ok(list) = std::fs::read_dir(&d) else { continue };
+ for e in list.flatten() {
+ let Ok(m) = e.path().symlink_metadata() else { continue };
+ if m.is_dir() {
+ todo.push(e.path());
+ } else {
+ total += m.len();
+ }
+ }
+ }
+ total
+}
+
+/// The biggest single file under `dir` (links not followed).
+fn largest_file(dir: &Path) -> u64 {
+ let mut most = 0;
+ let mut todo = vec![dir.to_path_buf()];
+ while let Some(d) = todo.pop() {
+ let Ok(list) = std::fs::read_dir(&d) else { continue };
+ for e in list.flatten() {
+ let Ok(m) = e.path().symlink_metadata() else { continue };
+ if m.is_dir() {
+ todo.push(e.path());
+ } else {
+ most = most.max(m.len());
+ }
+ }
+ }
+ most
+}
+
+/// Deletes the mirror of a repo no longer watched (its cards stay), and any note that it was too
+/// big, so adding the repo again fetches it afresh.
+pub async fn remove_mirror(data_dir: &Path, space: &str, key: &str) {
+ let dir = mirror_dir(data_dir, space, key);
+ let _held = lock(&dir).await;
+ let _ = tokio::fs::remove_file(too_big_mark(&dir)).await;
+ if dir.is_dir() {
+ if let Err(e) = tokio::fs::remove_dir_all(&dir).await {
+ tracing::warn!(space = %space, "dev: could not remove a repo mirror: {}", e.kind());
+ }
+ }
+}
+
+/// The git dir of team folder `folder`, only if it is that folder's own (G2 review F2): the folder
+/// is writable by anyone working in it, so its `.git` could otherwise point kwant at another
+/// space's repo or at one of kwant's own mirrors, and its cards would show that repo. Refused
+/// ([`GitError::Refused`]): everything [`own_git_dir`] refuses, and a git dir, or its main repo,
+/// under `<data>/dev` (kwant's mirrors). No `.git` at all is [`GitError::NotFound`].
+pub fn local_git_dir(folder: &Path, data_dir: &Path) -> Result<PathBuf, GitError> {
+ let (git_dir, common) = own_git_dirs(folder)?;
+ if let Ok(mirrors) = std::fs::canonicalize(data_dir.join("dev")) {
+ if git_dir.starts_with(&mirrors) || common.starts_with(&mirrors) {
+ return Err(GitError::Refused);
+ }
+ }
+ Ok(git_dir)
+}
+
+/// The git dir of `folder` if it is that folder's own (G2 delta D1; team detection reads a
+/// folder's remote and branch only through this). Refused ([`GitError::Refused`]):
+/// - a `.git` that is a symlink;
+/// - a `.git` file (a linked worktree) unless the git dir it names points back at this folder's
+/// `.git` (its `gitdir` file, which `git worktree add` writes) and sits in its main repo's
+/// `worktrees/`, so only that repo can have made it (a submodule checkout is refused);
+/// - a `.git` directory with a `commondir` (it would borrow another repo's objects and refs);
+/// - `objects/info/alternates`, and any symlink among the objects and refs git reads.
+///
+/// No `.git` at all is [`GitError::NotFound`].
+pub fn own_git_dir(folder: &Path) -> Result<PathBuf, GitError> {
+ own_git_dirs(folder).map(|(git_dir, _)| git_dir)
+}
+
+/// [`own_git_dir`] and the main repo's git dir (the same dir unless `folder` is a worktree).
+fn own_git_dirs(folder: &Path) -> Result<(PathBuf, PathBuf), GitError> {
+ let folder = std::fs::canonicalize(folder).map_err(|_| GitError::NotFound)?;
+ let dot_git = folder.join(".git");
+ let meta = std::fs::symlink_metadata(&dot_git).map_err(|_| GitError::NotFound)?;
+ let canon = |p: &Path| std::fs::canonicalize(p).map_err(|_| GitError::Refused);
+ let (git_dir, common) = if meta.file_type().is_symlink() {
+ return Err(GitError::Refused);
+ } else if meta.is_dir() {
+ if dot_git.join("commondir").exists() {
+ return Err(GitError::Refused);
+ }
+ (dot_git.clone(), dot_git.clone())
+ } else if meta.is_file() {
+ // `gitdir: <main>/.git/worktrees/<name>`, relative to the folder if not absolute
+ let text = read_small(&dot_git)?;
+ let target = text.trim_end_matches(['\n', '\r']).strip_prefix("gitdir: ").filter(|t| !t.is_empty()).ok_or(GitError::Refused)?;
+ let git_dir = canon(&folder.join(target))?;
+ // git writes `<git dir>/gitdir` = this worktree's `.git` file
+ let back = read_small(&git_dir.join("gitdir"))?;
+ let back = Path::new(back.trim_end_matches(['\n', '\r']));
+ let back = if back.is_absolute() { back.to_path_buf() } else { git_dir.join(back) };
+ if canon(&back)? != dot_git {
+ return Err(GitError::Refused);
+ }
+ let common = read_small(&git_dir.join("commondir"))?;
+ let common = Path::new(common.trim_end_matches(['\n', '\r']));
+ let common = canon(&if common.is_absolute() { common.to_path_buf() } else { git_dir.join(common) })?;
+ if git_dir.parent() != Some(common.join("worktrees").as_path()) {
+ return Err(GitError::Refused);
+ }
+ (git_dir, common)
+ } else {
+ return Err(GitError::Refused);
+ };
+ for d in [&git_dir, &common] {
+ if d.join("objects/info/alternates").symlink_metadata().is_ok() || has_symlink(d) {
+ return Err(GitError::Refused);
+ }
+ }
+ Ok((git_dir, common))
+}
+
+
+/// A small text file (a `.git` file, `gitdir`, `commondir`), refused if it is a symlink or big.
+fn read_small(p: &Path) -> Result<String, GitError> {
+ let m = std::fs::symlink_metadata(p).map_err(|_| GitError::Refused)?;
+ if !m.is_file() || m.len() > 4096 {
+ return Err(GitError::Refused);
+ }
+ std::fs::read_to_string(p).map_err(|_| GitError::Refused)
+}
+
+/// Whether any of the entries git reads its history from in `git_dir` (`HEAD`, `packed-refs`,
+/// `objects/`, `refs/`) is, or holds, a symlink.
+fn has_symlink(git_dir: &Path) -> bool {
+ let mut todo = Vec::new();
+ for name in ["HEAD", "packed-refs", "objects", "refs"] {
+ let p = git_dir.join(name);
+ match p.symlink_metadata() {
+ Ok(m) if m.file_type().is_symlink() => return true,
+ Ok(m) if m.is_dir() => todo.push(p),
+ _ => {}
+ }
+ }
+ while let Some(d) = todo.pop() {
+ let Ok(list) = std::fs::read_dir(&d) else { continue };
+ for e in list.flatten() {
+ match e.file_type() {
+ Ok(t) if t.is_symlink() => return true,
+ Ok(t) if t.is_dir() => todo.push(e.path()),
+ _ => {}
+ }
+ }
+ }
+ false
+}
+
+/// A git repo kwant reads: a bare mirror it keeps, or a team folder's `.git`.
+pub struct Repo {
+ dir: PathBuf,
+ local: bool,
+ _held: Option<tokio::sync::OwnedMutexGuard<()>>,
+}
+
+impl std::fmt::Debug for Repo {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("Repo").field("local", &self.local).finish_non_exhaustive()
+ }
+}
+
+impl Repo {
+ /// The mirror of `key` in `space`, made (empty) if it isn't there yet. Held locked until dropped.
+ pub async fn mirror(data_dir: &Path, space: &str, key: &str) -> Result<Repo, GitError> {
+ let dir = mirror_dir(data_dir, space, key);
+ let held = lock(&dir).await;
+ if !dir.join("HEAD").is_file() {
+ let parent = dir.parent().ok_or(GitError::Failed)?;
+ tokio::fs::create_dir_all(parent).await.map_err(|_| GitError::Failed)?;
+ let _ = tokio::fs::remove_dir_all(&dir).await;
+ let d = dir.to_str().ok_or(GitError::Refused)?;
+ if let Err(e) = run("git", None, &["init", "--bare", "--quiet", "--template=", "--", d], Opts::read()).await {
+ let _ = tokio::fs::remove_dir_all(&dir).await;
+ return Err(e);
+ }
+ }
+ Ok(Repo { dir, local: false, _held: Some(held) })
+ }
+
+ /// A team folder's own git, read in place: `<folder>/.git` (a directory, or a worktree's file),
+ /// once [`local_git_dir`] has checked it's really this folder's. Called on every poll, since
+ /// anyone working in the folder can change it.
+ pub async fn local(folder: &Path, data_dir: &Path) -> Result<Repo, GitError> {
+ let (folder, data_dir) = (folder.to_path_buf(), data_dir.to_path_buf());
+ let dir = tokio::task::spawn_blocking(move || local_git_dir(&folder, &data_dir)).await.map_err(|_| GitError::Failed)??;
+ Ok(Repo { dir, local: true, _held: None })
+ }
+
+ pub fn is_local(&self) -> bool {
+ self.local
+ }
+
+ async fn git(&self, args: &[&str]) -> Result<Vec<u8>, GitError> {
+ run("git", Some(&self.dir), args, Opts { file: self.local, ..Opts::read() }).await
+ }
+
+ async fn text(&self, args: &[&str]) -> Result<String, GitError> {
+ Ok(String::from_utf8_lossy(&self.git(args).await?).into_owned())
+ }
+
+ /// Brings the mirror's `branch` and tags up to date from `url` (pruning deleted tags). A team
+ /// folder isn't fetched: it's read as its team left it.
+ pub async fn fetch(&self, url: &str, branch: &str, auth: Option<&Auth>) -> Result<(), GitError> {
+ if self.local {
+ return Ok(());
+ }
+ if !ok_branch(branch) || fetch_url(url).as_deref() != Some(url) {
+ return Err(GitError::Refused);
+ }
+ self.not_too_big().await?;
+ let pin = checked(url).await?;
+ let heads = format!("+refs/heads/{branch}:refs/heads/{branch}");
+ let args = ["fetch", "--quiet", "--no-tags", "--no-write-fetch-head", "--no-recurse-submodules", "--prune", "--", url, &heads, "+refs/tags/*:refs/tags/*"];
+ self.fetch_capped(&args, Opts { timeout: FETCH_TIMEOUT, max_out: MAX_OUT, auth, file: false, pin: &pin, fsize: None }, crate::server::dev::mirror_cap()).await
+ }
+
+ /// Runs one `git fetch` into this mirror with no file allowed past `cap` bytes, then
+ /// [`Self::cap`]: a fetch stopped at the cap, or a mirror over it, ends as
+ /// [`GitError::RepoTooBig`] with the mirror deleted and its note left.
+ async fn fetch_capped(&self, args: &[&str], o: Opts<'_>, cap: u64) -> Result<(), GitError> {
+ let mut done = run("git", Some(&self.dir), args, Opts { fsize: Some(cap), ..o }).await.map(|_| ());
+ if done.is_err() && done != Err(GitError::RepoTooBig) {
+ // git 2.43 says only "invalid index-pack output" when the limit stops index-pack: a
+ // file left at the cap (within one write) is the sign
+ let dir = self.dir.clone();
+ if tokio::task::spawn_blocking(move || largest_file(&dir)).await.unwrap_or(0) >= cap.saturating_sub(64 << 10) {
+ done = Err(GitError::RepoTooBig);
+ }
+ }
+ self.cap(cap).await?;
+ if done == Err(GitError::RepoTooBig) {
+ // Stopped at the limit, though what it left (if anything) is under the cap
+ self.too_big().await;
+ }
+ done
+ }
+
+ /// [`GitError::RepoTooBig`] while this mirror's note says it passed the cap less than
+ /// [`TOO_BIG_RETRY`] ago; an older note is cleared, so this fetch tries again.
+ async fn not_too_big(&self) -> Result<(), GitError> {
+ let mark = too_big_mark(&self.dir);
+ let Ok(m) = tokio::fs::metadata(&mark).await else { return Ok(()) };
+ let age = m.modified().ok().and_then(|t| t.elapsed().ok()).unwrap_or_default();
+ if age < TOO_BIG_RETRY {
+ return Err(GitError::RepoTooBig);
+ }
+ let _ = tokio::fs::remove_file(&mark).await;
+ Ok(())
+ }
+
+ /// After a fetch: a mirror over `cap` bytes on disk is deleted and a note left beside it, so
+ /// it isn't fetched again for [`TOO_BIG_RETRY`] ([`GitError::RepoTooBig`]).
+ async fn cap(&self, cap: u64) -> Result<(), GitError> {
+ if self.local {
+ return Ok(());
+ }
+ let dir = self.dir.clone();
+ let used = tokio::task::spawn_blocking(move || disk_use(&dir)).await.unwrap_or(0);
+ if used <= cap {
+ return Ok(());
+ }
+ self.too_big().await;
+ Err(GitError::RepoTooBig)
+ }
+
+ /// Deletes this mirror and leaves the note that it was too big.
+ async fn too_big(&self) {
+ if let Err(e) = tokio::fs::remove_dir_all(&self.dir).await {
+ if e.kind() != std::io::ErrorKind::NotFound {
+ tracing::warn!("dev: could not remove a repo mirror over the size cap: {}", e.kind());
+ }
+ }
+ let _ = tokio::fs::write(too_big_mark(&self.dir), b"").await;
+ }
+
+ /// Fetches one ref of `url` (a PR head, `refs/pull/7/head`) into `to` (`refs/kwant/…`); the sha
+ /// it now points at.
+ pub async fn fetch_ref(&self, url: &str, from: &str, to: &str, auth: Option<&Auth>) -> Result<String, GitError> {
+ if self.local || !ok_ref(from) || !to.starts_with("refs/kwant/") || !ok_ref(to) || fetch_url(url).as_deref() != Some(url) {
+ return Err(GitError::Refused);
+ }
+ self.not_too_big().await?;
+ let pin = checked(url).await?;
+ let spec = format!("+{from}:{to}");
+ let args = ["fetch", "--quiet", "--no-tags", "--no-write-fetch-head", "--no-recurse-submodules", "--", url, &spec];
+ self.fetch_capped(&args, Opts { timeout: FETCH_TIMEOUT, max_out: MAX_OUT, auth, file: false, pin: &pin, fsize: None }, crate::server::dev::mirror_cap()).await?;
+ self.resolve(to).await
+ }
+
+ /// Deletes a ref [`Self::fetch_ref`] made.
+ pub async fn drop_ref(&self, name: &str) {
+ if !self.local && name.starts_with("refs/kwant/") && ok_ref(name) {
+ let _ = self.git(&["update-ref", "-d", name]).await;
+ }
+ }
+
+ /// The default branch of `url` (what its `HEAD` points at), or of a team folder.
+ pub async fn default_branch(&self, url: &str, auth: Option<&Auth>) -> Result<String, GitError> {
+ let branch = if self.local {
+ self.text(&["symbolic-ref", "--quiet", "HEAD"]).await?
+ } else {
+ if fetch_url(url).as_deref() != Some(url) {
+ return Err(GitError::Refused);
+ }
+ let pin = checked(url).await?;
+ let out = run("git", Some(&self.dir), &["ls-remote", "--symref", "--", url, "HEAD"], Opts { timeout: REMOTE_TIMEOUT, max_out: 1 << 16, auth, file: false, pin: &pin, fsize: None }).await?;
+ let out = String::from_utf8_lossy(&out).into_owned();
+ out.lines().find_map(|l| l.strip_prefix("ref: ").and_then(|r| r.strip_suffix("\tHEAD")).map(str::to_string)).ok_or(GitError::NotFound)?
+ };
+ branch.trim().strip_prefix("refs/heads/").filter(|b| ok_branch(b)).map(str::to_string).ok_or(GitError::NotFound)
+ }
+
+ /// Whether `url` (or a team folder) has `branch`.
+ pub async fn has_branch(&self, url: &str, branch: &str, auth: Option<&Auth>) -> Result<bool, GitError> {
+ if !ok_branch(branch) {
+ return Ok(false);
+ }
+ let name = format!("refs/heads/{branch}");
+ if self.local {
+ return Ok(self.resolve(&name).await.is_ok());
+ }
+ if fetch_url(url).as_deref() != Some(url) {
+ return Err(GitError::Refused);
+ }
+ let pin = checked(url).await?;
+ let out = run("git", Some(&self.dir), &["ls-remote", "--heads", "--", url, &name], Opts { timeout: REMOTE_TIMEOUT, max_out: 1 << 16, auth, file: false, pin: &pin, fsize: None }).await?;
+ Ok(String::from_utf8_lossy(&out).lines().any(|l| l.split('\t').nth(1) == Some(name.as_str())))
+ }
+
+ /// The commit a ref or sha names.
+ pub async fn resolve(&self, rev: &str) -> Result<String, GitError> {
+ if !(is_sha(rev) || ok_ref(rev)) {
+ return Err(GitError::Refused);
+ }
+ let spec = format!("{rev}^{{commit}}");
+ // `--quiet` prints nothing for a missing ref: that's a not found
+ let sha = match self.text(&["rev-parse", "--verify", "--quiet", "--end-of-options", &spec]).await {
+ Ok(s) => s.trim().to_string(),
+ Err(GitError::Failed) => return Err(GitError::NotFound),
+ Err(e) => return Err(e),
+ };
+ if is_sha(&sha) {
+ Ok(sha)
+ } else {
+ Err(GitError::NotFound)
+ }
+ }
+
+ /// Up to [`MAX_COMMITS`] commits on `branch`'s first-parent line newer than `last_seen`, oldest
+ /// first, and whether `last_seen` was found. With no `last_seen`, or one that's gone (a force
+ /// push), the newest ones, as GitHub's list.
+ pub async fn commits_since(&self, branch: &str, last_seen: Option<&str>) -> Result<(Vec<Commit>, bool), GitError> {
+ if !ok_branch(branch) {
+ return Err(GitError::Refused);
+ }
+ let head = format!("refs/heads/{branch}");
+ self.resolve(&head).await?;
+ let found = match last_seen.filter(|s| is_sha(s)) {
+ Some(s) => self.git(&["merge-base", "--is-ancestor", s, &head]).await.is_ok(),
+ None => false,
+ };
+ let max = format!("--max-count={MAX_COMMITS}");
+ let not = last_seen.map(|s| format!("^{s}")).unwrap_or_default();
+ let mut args = vec!["log", "-z", "--first-parent", &max, LOG_FORMAT, "--end-of-options", &head];
+ if found {
+ args.push(&not);
+ }
+ args.push("--");
+ let out = self.git(&args).await?;
+ let mut list = parse_log(&out);
+ list.reverse();
+ Ok((list, found))
+ }
+
+ /// One commit, with its files against its first parent (or every file, for a root commit).
+ pub async fn commit(&self, sha: &str) -> Result<Commit, GitError> {
+ if !is_sha(sha) {
+ return Err(GitError::Refused);
+ }
+ let out = self.git(&["log", "-z", "-1", LOG_FORMAT, "--end-of-options", sha, "--"]).await?;
+ let mut c = parse_log(&out).into_iter().next().ok_or(GitError::NotFound)?;
+ c.files = self.diff(c.parents.first().map(String::as_str), sha).await?;
+ Ok(c)
+ }
+
+ /// The files changed from `base` to `head` (every file of `head` with no base), as GitHub
+ /// lists a PR's: status, line counts, renames, and each text file's hunks. At most
+ /// [`MAX_FILES`]; when the patches are too big to read whole, the list comes without them.
+ pub async fn diff(&self, base: Option<&str>, head: &str) -> Result<Vec<FileDiff>, GitError> {
+ if !is_sha(head) || base.is_some_and(|b| !is_sha(b)) {
+ return Err(GitError::Refused);
+ }
+ let range: Vec<&str> = match base {
+ Some(b) => vec![b, head],
+ None => vec!["--root", head],
+ };
+ let with = |extra: &[&'static str]| {
+ let mut a: Vec<&str> = vec!["diff-tree", "-r", "-M", "--no-commit-id"];
+ a.extend_from_slice(extra);
+ a.extend_from_slice(&range);
+ a.push("--");
+ a
+ };
+ let raw = self.git(&with(&["-z", "--raw"])).await?;
+ let num = self.git(&with(&["-z", "--numstat"])).await?;
+ let mut files = parse_raw(&raw);
+ let counts = parse_numstat(&num);
+ if counts.len() == files.len() {
+ for (f, (a, d)) in files.iter_mut().zip(counts) {
+ f.additions = a;
+ f.deletions = d;
+ }
+ }
+ // Hunks: one section per file, in the same order; anything else and none are kept
+ if let Ok(p) = self.git(&with(&["-p", "--no-color", "--no-ext-diff", "--no-textconv", "--src-prefix=a/", "--dst-prefix=b/"])).await {
+ let patches = split_patches(&String::from_utf8_lossy(&p));
+ if patches.len() == files.len() {
+ for (f, p) in files.iter_mut().zip(patches) {
+ f.patch = p;
+ }
+ }
+ }
+ files.truncate(MAX_FILES);
+ Ok(files)
+ }
+
+ /// The commit both `a` and `b` grew from.
+ pub async fn merge_base(&self, a: &str, b: &str) -> Result<String, GitError> {
+ if !(is_sha(a) || ok_ref(a)) || !(is_sha(b) || ok_ref(b)) {
+ return Err(GitError::Refused);
+ }
+ let out = self.text(&["merge-base", "--end-of-options", a, b]).await?;
+ let sha = out.trim().to_string();
+ if is_sha(&sha) {
+ Ok(sha)
+ } else {
+ Err(GitError::NotFound)
+ }
+ }
+
+ /// A text file at `sha`. `None` when it isn't a file there, is bigger than [`MAX_FILE`] or
+ /// isn't UTF-8.
+ pub async fn file_at(&self, path: &str, sha: &str) -> Result<Option<String>, GitError> {
+ if !is_sha(sha) || path.is_empty() || path.len() > 4096 || path.starts_with('/') || path.contains('\0') {
+ return Err(GitError::Refused);
+ }
+ let spec = format!("{sha}:{path}");
+ match self.text(&["cat-file", "-t", &spec]).await {
+ Ok(t) if t.trim() == "blob" => {}
+ Ok(_) | Err(GitError::NotFound | GitError::Failed) => return Ok(None),
+ Err(e) => return Err(e),
+ }
+ match run("git", Some(&self.dir), &["cat-file", "blob", &spec], Opts { max_out: MAX_FILE, file: self.local, ..Opts::read() }).await {
+ Ok(bytes) => Ok(String::from_utf8(bytes).ok()),
+ Err(GitError::TooBig | GitError::NotFound) => Ok(None),
+ Err(e) => Err(e),
+ }
+ }
+
+ /// The tag nearest `branch`'s tip (`git describe`), with its commit's date. `None`: no tag.
+ pub async fn latest_tag(&self, branch: &str) -> Result<Option<(String, Option<DateTime<Utc>>)>, GitError> {
+ if !ok_branch(branch) {
+ return Err(GitError::Refused);
+ }
+ let head = format!("refs/heads/{branch}");
+ let name = match self.text(&["describe", "--tags", "--abbrev=0", "--end-of-options", &head]).await {
+ Ok(n) => n.trim().to_string(),
+ Err(_) => return Ok(None),
+ };
+ let tag = format!("refs/tags/{name}");
+ if !ok_ref(&tag) {
+ return Ok(None);
+ }
+ let sha = self.resolve(&tag).await?;
+ let at = self.text(&["log", "-1", "--format=%cI", "--end-of-options", &sha, "--"]).await.ok().and_then(|d| date(d.trim()));
+ Ok(Some((name, at)))
+ }
+
+ /// How many commits on `branch` touched `path` between `since` and `until` (at most 2), by
+ /// commit date as GitHub's `since`/`until`.
+ pub async fn path_commits(&self, branch: &str, path: &str, since: DateTime<Utc>, until: DateTime<Utc>) -> Result<usize, GitError> {
+ if !ok_branch(branch) || path.is_empty() || path.contains('\0') {
+ return Err(GitError::Refused);
+ }
+ let head = format!("refs/heads/{branch}");
+ let (s, u) = (format!("--since={}", since.to_rfc3339()), format!("--until={}", until.to_rfc3339()));
+ let out = self.text(&["log", "--format=%H", "--max-count=2", &s, &u, "--end-of-options", &head, "--", path]).await?;
+ Ok(out.lines().filter(|l| is_sha(l.trim())).count())
+ }
+
+ /// The names at the root of `branch` (files and folders).
+ pub async fn root_names(&self, branch: &str) -> Result<Vec<String>, GitError> {
+ if !ok_branch(branch) {
+ return Err(GitError::Refused);
+ }
+ let head = format!("refs/heads/{branch}");
+ let out = self.git(&["ls-tree", "-z", "--name-only", "--end-of-options", &head]).await?;
+ Ok(out.split(|b| *b == 0).filter(|n| !n.is_empty()).map(|n| String::from_utf8_lossy(n).into_owned()).collect())
+ }
+}
+
+/// One commit per NUL-ended record: sha, parents, author name, email, date, committer name,
+/// email, date and the whole message, split by unit separators.
+const LOG_FORMAT: &str = "--format=%H%x1f%P%x1f%an%x1f%ae%x1f%aI%x1f%cn%x1f%ce%x1f%cI%x1f%B";
+
+fn date(s: &str) -> Option<DateTime<Utc>> {
+ DateTime::parse_from_rfc3339(s).ok().map(|d| d.with_timezone(&Utc))
+}
+
+fn parse_log(out: &[u8]) -> Vec<Commit> {
+ let text = String::from_utf8_lossy(out);
+ text.split('\0')
+ .map(|r| r.trim_start_matches('\n'))
+ .filter(|r| !r.is_empty())
+ .filter_map(|r| {
+ let f: Vec<&str> = r.splitn(9, '\x1f').collect();
+ if f.len() < 9 || !is_sha(f[0]) {
+ return None;
+ }
+ let person = |name: &str, email: &str, at: &str| Person { name: name.to_string(), email: Some(email.to_string()).filter(|e| !e.is_empty()), date: date(at) };
+ Some(Commit {
+ sha: f[0].to_string(),
+ url: None,
+ message: f[8].trim_end().to_string(),
+ author: person(f[2], f[3], f[4]),
+ committer: person(f[5], f[6], f[7]),
+ login: None,
+ parents: f[1].split_whitespace().filter(|p| is_sha(p)).map(str::to_string).collect(),
+ files: Vec::new(),
+ })
+ })
+ .collect()
+}
+
+/// `--raw -z`: `:mode mode sha sha STATUS\0path\0` (two paths for a rename or copy).
+fn parse_raw(out: &[u8]) -> Vec<FileDiff> {
+ let text = String::from_utf8_lossy(out);
+ let mut it = text.split('\0');
+ let mut files = Vec::new();
+ while let Some(meta) = it.next() {
+ let meta = meta.trim_start_matches('\n');
+ if !meta.starts_with(':') {
+ continue;
+ }
+ let code = meta.rsplit(' ').next().and_then(|s| s.chars().next()).unwrap_or('M');
+ let (path, previous) = if matches!(code, 'R' | 'C') {
+ let old = it.next().unwrap_or_default().to_string();
+ (it.next().unwrap_or_default().to_string(), Some(old))
+ } else {
+ (it.next().unwrap_or_default().to_string(), None)
+ };
+ let status = match code {
+ 'A' => "added",
+ 'D' => "removed",
+ 'R' => "renamed",
+ 'C' => "copied",
+ 'T' => "changed",
+ _ => "modified",
+ };
+ files.push(FileDiff { path, status: status.into(), additions: 0, deletions: 0, patch: None, previous_path: previous });
+ }
+ files
+}
+
+/// `--numstat -z`: `add\tdel\tpath\0`, or `add\tdel\t\0old\0new\0` for a rename; `-` for binary.
+fn parse_numstat(out: &[u8]) -> Vec<(u64, u64)> {
+ let text = String::from_utf8_lossy(out);
+ let mut it = text.split('\0');
+ let mut out = Vec::new();
+ while let Some(tok) = it.next() {
+ let tok = tok.trim_start_matches('\n');
+ let mut f = tok.splitn(3, '\t');
+ let (Some(a), Some(d), Some(p)) = (f.next(), f.next(), f.next()) else { continue };
+ if p.is_empty() {
+ it.next();
+ it.next();
+ }
+ out.push((a.parse().unwrap_or(0), d.parse().unwrap_or(0)));
+ }
+ out
+}
+
+/// A `-p` diff split per file: each file's hunks from its first `@@` (GitHub's `patch`), `None`
+/// for a binary file or one with no hunks (a mode change, an empty file).
+fn split_patches(text: &str) -> Vec<Option<String>> {
+ if text.trim().is_empty() {
+ return Vec::new();
+ }
+ let Some(body) = text.strip_prefix("diff --git ") else { return Vec::new() };
+ body.split("\ndiff --git ")
+ .map(|sec| {
+ let hunks = sec.find("\n@@ ").map(|i| &sec[i + 1..])?;
+ if sec[..sec.len() - hunks.len()].contains("\nBinary files ") {
+ return None;
+ }
+ Some(hunks.trim_end_matches('\n').to_string())
+ })
+ .collect()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::process::Command;
+
+ /// Plain git for setting a throwaway repo up (never the code under test).
+ fn sh(dir: &Path, args: &[&str]) -> String {
+ let out = Command::new("git")
+ .arg("-C")
+ .arg(dir)
+ .args(["-c", "user.name=Demo Person", "-c", "[email protected]", "-c", "init.defaultBranch=main", "-c", "commit.gpgsign=false", "-c", "tag.gpgsign=false"])
+ .args(args)
+ .env("GIT_CONFIG_GLOBAL", "/dev/null")
+ .env("GIT_CONFIG_NOSYSTEM", "1")
+ .env("GIT_AUTHOR_DATE", "2026-11-01T10:00:00Z")
+ .env("GIT_COMMITTER_DATE", "2026-11-01T10:00:00Z")
+ .output()
+ .unwrap();
+ assert!(out.status.success(), "git {args:?}: {}", String::from_utf8_lossy(&out.stderr));
+ String::from_utf8_lossy(&out.stdout).trim().to_string()
+ }
+
+ fn write(dir: &Path, path: &str, text: &[u8]) {
+ let p = dir.join(path);
+ std::fs::create_dir_all(p.parent().unwrap()).unwrap();
+ std::fs::write(p, text).unwrap();
+ }
+
+ fn commit_all(dir: &Path, msg: &str) -> String {
+ sh(dir, &["add", "-A"]);
+ sh(dir, &["commit", "-q", "--allow-empty", "-m", msg]);
+ sh(dir, &["rev-parse", "HEAD"])
+ }
+
+ /// A work repo with: a root commit, a feature branch merged with a merge commit, a rename, a
+ /// binary file and a tag.
+ fn upstream(root: &Path) -> (PathBuf, Vec<String>) {
+ let w = root.join("work");
+ std::fs::create_dir_all(&w).unwrap();
+ sh(&w, &["init", "-q"]);
+ write(&w, "README.md", b"hello\n");
+ write(&w, "fly.toml", b"app = 'demo'\n");
+ let c0 = commit_all(&w, "Start");
+ write(&w, "src/a.rs", b"fn a() {}\n");
+ let c1 = commit_all(&w, "Add a\n\nWith a body.");
+ sh(&w, &["tag", "v0.1.0"]);
+ sh(&w, &["checkout", "-q", "-b", "feature"]);
+ write(&w, "src/b.rs", b"fn b() {}\n");
+ let f1 = commit_all(&w, "Add b on a branch");
+ sh(&w, &["checkout", "-q", "main"]);
+ sh(&w, &["merge", "-q", "--no-ff", "-m", "Merge feature", "feature"]);
+ let m = sh(&w, &["rev-parse", "HEAD"]);
+ sh(&w, &["mv", "src/a.rs", "src/renamed.rs"]);
+ write(&w, "logo.bin", &[0, 159, 146, 150, 0, 1, 2]);
+ write(&w, "README.md", b"hello\nworld\n");
+ let c3 = commit_all(&w, "Rename a, add a logo");
+ (w, vec![c0, c1, f1, m, c3])
+ }
+
+ #[tokio::test]
+ async fn a_mirror_reads_first_parent_history_files_tags_and_text() {
+ let tmp = tempfile::tempdir().unwrap();
+ let (w, c) = upstream(tmp.path());
+ let data = tmp.path().join("data");
+ let url = w.to_str().unwrap();
+ let repo = Repo::mirror(&data, "space 1", "local:web").await.unwrap();
+ // A local path is no fetch URL: the mirror is filled the way a test may, by file protocol
+ assert_eq!(repo.fetch(url, "main", None).await, Err(GitError::Refused));
+ run("git", Some(&repo.dir), &["fetch", "--quiet", "--", url, "+refs/heads/main:refs/heads/main", "+refs/tags/*:refs/tags/*"], Opts { file: true, ..Opts::read() }).await.unwrap();
+
+ let (list, found) = repo.commits_since("main", None).await.unwrap();
+ assert!(!found);
+ let shas: Vec<&str> = list.iter().map(|c| c.sha.as_str()).collect();
+ assert_eq!(shas, [&c[0], &c[1], &c[3], &c[4]], "first parent only: the branch commit isn't listed");
+ assert_eq!(list[1].message, "Add a\n\nWith a body.");
+ assert_eq!((list[1].author.name.as_str(), list[1].author.email.as_deref()), ("Demo Person", Some("[email protected]")));
+ assert_eq!(list[1].committer.date.unwrap().to_rfc3339(), "2026-11-01T10:00:00+00:00");
+ assert_eq!(list[2].parents, [c[1].clone(), c[2].clone()], "the merge's parents, first one first");
+
+ let (list, found) = repo.commits_since("main", Some(&c[1])).await.unwrap();
+ assert!(found);
+ assert_eq!(list.iter().map(|c| c.sha.clone()).collect::<Vec<_>>(), [c[3].clone(), c[4].clone()]);
+ let (list, found) = repo.commits_since("main", Some(&c[4])).await.unwrap();
+ assert!(found && list.is_empty(), "nothing new");
+ let gone = "0".repeat(40);
+ let (list, found) = repo.commits_since("main", Some(&gone)).await.unwrap();
+ assert!(!found && list.len() == 4, "a lost last-seen commit: the newest, as GitHub's list");
+ assert_eq!(repo.commits_since("nope", None).await.unwrap_err(), GitError::NotFound);
+ assert_eq!(repo.commits_since("-x", None).await.unwrap_err(), GitError::Refused);
+
+ // The merge against its first parent is what the branch brought
+ let merge = repo.commit(&c[3]).await.unwrap();
+ assert_eq!(merge.files, [FileDiff { path: "src/b.rs".into(), status: "added".into(), additions: 1, deletions: 0, patch: Some("@@ -0,0 +1 @@\n+fn b() {}".into()), previous_path: None }]);
+ let last = repo.commit(&c[4]).await.unwrap();
+ let by = |p: &str| last.files.iter().find(|f| f.path == p).unwrap().clone();
+ assert_eq!(by("src/renamed.rs").status, "renamed");
+ assert_eq!(by("src/renamed.rs").previous_path.as_deref(), Some("src/a.rs"));
+ assert_eq!((by("logo.bin").status.as_str(), by("logo.bin").patch.clone(), by("logo.bin").additions), ("added", None, 0), "binary: no patch");
+ assert_eq!((by("README.md").additions, by("README.md").deletions), (1, 0));
+ assert_eq!(by("README.md").patch.as_deref(), Some("@@ -1 +1,2 @@\n hello\n+world"));
+ let root = repo.commit(&c[0]).await.unwrap();
+ assert_eq!(root.files.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(), ["README.md", "fly.toml"], "a root commit lists every file");
+ assert!(root.files.iter().all(|f| f.status == "added"));
+ // Three-dot: from where the branch grew
+ let mb = repo.merge_base(&c[1], &c[2]).await.unwrap();
+ assert_eq!(mb, c[1]);
+ assert_eq!(repo.diff(Some(&c[0]), &c[4]).await.unwrap().len(), 4);
+
+ assert_eq!(repo.file_at("README.md", &c[4]).await.unwrap().as_deref(), Some("hello\nworld\n"));
+ assert_eq!(repo.file_at("logo.bin", &c[4]).await.unwrap(), None, "not UTF-8");
+ assert_eq!(repo.file_at("src", &c[4]).await.unwrap(), None, "a folder");
+ assert_eq!(repo.file_at("missing.txt", &c[4]).await.unwrap(), None);
+ assert_eq!(repo.file_at("README.md", "main").await.unwrap_err(), GitError::Refused, "a sha only");
+
+ let (tag, at) = repo.latest_tag("main").await.unwrap().unwrap();
+ assert_eq!((tag.as_str(), at.unwrap().to_rfc3339().as_str()), ("v0.1.0", "2026-11-01T10:00:00+00:00"));
+ let mut names = repo.root_names("main").await.unwrap();
+ names.sort();
+ assert_eq!(names, ["README.md", "fly.toml", "logo.bin", "src"]);
+ assert_eq!(super::super::repo::deploy_hint(&names), Some("fly"));
+
+ let day = chrono::Duration::days(1);
+ let t = date("2026-11-01T10:00:00Z").unwrap();
+ assert_eq!(repo.path_commits("main", "README.md", t - day, t + day).await.unwrap(), 2);
+ assert_eq!(repo.path_commits("main", "README.md", t + day, t + day + day).await.unwrap(), 0);
+ assert_eq!(repo.path_commits("main", "src/*", t - day, t + day).await.unwrap(), 0, "a path is literal, never a glob");
+ }
+
+ #[tokio::test]
+ async fn a_team_folder_is_read_in_place_without_touching_its_work() {
+ let tmp = tempfile::tempdir().unwrap();
+ let (w, c) = upstream(tmp.path());
+ write(&w, "README.md", b"uncommitted\n");
+ let status_before = sh(&w, &["status", "--porcelain"]);
+ let index_before = std::fs::read(w.join(".git/index")).unwrap();
+ let repo = Repo::local(&w, &tmp.path().join("data")).await.unwrap();
+ assert!(repo.is_local());
+ assert_eq!(repo.default_branch("", None).await.unwrap(), "main");
+ assert!(repo.has_branch("", "feature", None).await.unwrap());
+ assert!(!repo.has_branch("", "nope", None).await.unwrap());
+ repo.fetch("anything", "main", None).await.unwrap();
+ let (list, _) = repo.commits_since("main", Some(&c[3])).await.unwrap();
+ assert_eq!(list.iter().map(|c| c.sha.clone()).collect::<Vec<_>>(), [c[4].clone()]);
+ assert_eq!(repo.file_at("README.md", &c[4]).await.unwrap().as_deref(), Some("hello\nworld\n"), "the commit's text, not the folder's");
+ assert_eq!(std::fs::read_to_string(w.join("README.md")).unwrap(), "uncommitted\n");
+ assert_eq!(sh(&w, &["status", "--porcelain"]), status_before);
+ assert_eq!(std::fs::read(w.join(".git/index")).unwrap(), index_before, "the index wasn't refreshed");
+ assert_eq!(Repo::local(&tmp.path().join("nothing"), tmp.path()).await.unwrap_err(), GitError::NotFound);
+ }
+
+ #[tokio::test]
+ async fn a_mirror_lives_under_data_dev_and_is_removed_whole() {
+ let tmp = tempfile::tempdir().unwrap();
+ let data = tmp.path();
+ let a = mirror_dir(data, "s1", "gitlab.example.com/group/sub/ops");
+ let b = mirror_dir(data, "s1", "gitlab.example.com/group_sub/ops");
+ assert!(a.starts_with(data.join("dev").join("s1")));
+ assert_ne!(a, b, "two keys that read the same once made safe stay apart");
+ assert_eq!(mirror_dir(data, "../x", "../../etc").parent().unwrap().file_name().unwrap(), "_x", "no way out of the data folder");
+ assert!(mirror_dir(data, "../x", "../../etc").starts_with(data.join("dev")));
+ let repo = Repo::mirror(data, "s1", "gitlab.example.com/group/sub/ops").await.unwrap();
+ assert!(a.join("HEAD").is_file());
+ assert!(!a.join("hooks").exists(), "no template: no sample hooks");
+ drop(repo);
+ remove_mirror(data, "s1", "gitlab.example.com/group/sub/ops").await;
+ assert!(!a.exists());
+ }
+
+ #[test]
+ fn a_folders_remote_never_points_at_this_machine() {
+ for raw in [
+ "http://127.0.0.1:9/o/n.git",
+ "https://127.1/o/n",
+ "http://localhost:3000/o/n",
+ "https://git.localhost/o/n",
+ "ssh://dev@[::1]:2222/o/n",
+ "https://169.254.169.254/latest/meta-data",
+ "http://[fe80::1]/o/n",
+ "http://[::ffff:127.0.0.1]/o/n",
+ "http://0.0.0.0/o/n",
+ "http://2130706433/o/n",
+ "http://LOCALHOST./o/n",
+ ] {
+ assert_eq!(remote_url(raw), None, "{raw}");
+ }
+ for raw in ["https://gitlab.example.com/group/ops.git", "http://192.168.1.20:3000/o/n.git", "[email protected]:o/n", "ssh://git@[2001:db8::1]/o/n"] {
+ assert_eq!(remote_url(raw), fetch_url(raw), "{raw}");
+ assert!(remote_url(raw).is_some(), "{raw}");
+ }
+ }
+
+ #[test]
+ fn fetch_urls_lose_their_userinfo_and_refuse_what_git_must_not_get() {
+ let ok = [
+ ("https://deploy:[email protected]/group/sub/ops.git", "https://gitlab.example.com/group/sub/ops.git"),
+ ("https://x-access-token:a/b@[email protected]/o/n.git", "https://github.com/o/n.git"),
+ ("https://gitlab.com/group/proj?x=1#y", "https://gitlab.com/group/proj"),
+ ("git+https://host.example:8443/o/n", "https://host.example:8443/o/n"),
+ ("ssh://git:[email protected]:2222/o/n.git", "ssh://[email protected]:2222/o/n.git"),
+ ("[email protected]:group/proj.git", "[email protected]:group/proj.git"),
+ ("gitea.example.org:o/n", "gitea.example.org:o/n"),
+ ("git://git.example.org/o/n", "git://git.example.org/o/n"),
+ ("http://127.0.0.1:9/o/n.git", "http://127.0.0.1:9/o/n.git"),
+ ("oauth2:[email protected]:group/proj", "[email protected]:group/proj"),
+ ("ssh://dev@[::1]:2222/o/n", "ssh://dev@[::1]:2222/o/n"),
+ ];
+ for (raw, want) in ok {
+ assert_eq!(fetch_url(raw).as_deref(), Some(want), "{raw}");
+ }
+ // A token as an ssh user name is never put back (made here so no token shape sits in the source)
+ let tok = format!("{}{}", ["gh", "p_"].concat(), "a".repeat(40));
+ assert_eq!(fetch_url(&format!("ssh://{tok}@host.example/o/n")).as_deref(), Some("ssh://host.example/o/n"));
+ for raw in [
+ "/srv/repos/app",
+ "./app",
+ "file:///srv/app",
+ "ext::sh -c touch% /tmp/pwned",
+ "fd::17",
+ "https://-oProxyCommand=x/o/n",
+ "ssh://-oProxyCommand=x/o/n",
+ "-oProxyCommand=x:o/n",
+ "git@host:-o/n",
+ "https://host.example/o/../n",
+ "https://host.example/",
+ "https://host .example/o/n",
+ "https://host.example/o\n/n",
+ "ssh://host.example/o/./n",
+ "",
+ ] {
+ assert_eq!(fetch_url(raw), None, "{raw}");
+ }
+ }
+
+ #[test]
+ fn commit_pages_are_known_for_some_hosts() {
+ assert_eq!(commit_base("gitlab.com", "group/sub/p").as_deref(), Some("https://gitlab.com/group/sub/p/-/commit"));
+ assert_eq!(commit_base("gitlab.example.com", "g/p").as_deref(), Some("https://gitlab.example.com/g/p/-/commit"));
+ assert_eq!(commit_base("codeberg.org", "o/n").as_deref(), Some("https://codeberg.org/o/n/commit"));
+ assert_eq!(commit_base("bitbucket.org", "o/n").as_deref(), Some("https://bitbucket.org/o/n/commits"));
+ assert_eq!(commit_base("git.example.org", "o/n"), None);
+ }
+
+ #[test]
+ fn errors_are_sorted_and_say_fixed_words() {
+ assert_eq!(classify(b"fatal: could not read Username for 'https://gitlab.example.com': terminal prompts disabled"), GitError::Auth);
+ assert_eq!(classify(b"git@host: Permission denied (publickey)."), GitError::Auth);
+ assert_eq!(classify(b"remote: Repository not found.\nfatal: repository 'https://h/o/n.git/' not found"), GitError::NotFound);
+ assert_eq!(classify(b"fatal: couldn't find remote ref refs/heads/nope"), GitError::NotFound);
+ assert_eq!(classify(b"fatal: unable to access 'https://x/': Could not resolve host: x"), GitError::Unreachable);
+ assert_eq!(classify(b"something else"), GitError::Failed);
+ for e in [GitError::Auth, GitError::NotFound, GitError::Unreachable, GitError::Failed] {
+ assert!(!e.to_string().contains("http"), "no URL in the words: {e}");
+ }
+ assert!(GitError::NoGit.to_string().contains("git 2.31 or newer on the server") && INSTALL_HINT.contains("git 2.31 or newer on the server"));
+ assert_eq!(parse_version("git version 2.43.0\n"), Some((2, 43)));
+ assert_eq!(parse_version("git version 2.30.9.windows.1"), Some((2, 30)));
+ assert!(parse_version("git version 2.30.9").unwrap() < MIN_VERSION);
+ }
+
+ #[tokio::test]
+ async fn no_git_says_so() {
+ assert_eq!(run("/nonexistent/kwant-no-git", None, &["--version"], Opts::read()).await, Err(GitError::NoGit));
+ assert_eq!(version("/nonexistent/kwant-no-git").await, None);
+ assert!(available().await, "the test machine has git {MIN_VERSION:?} or newer");
+ }
+
+ #[tokio::test]
+ async fn a_slow_git_is_killed_with_its_children() {
+ let tmp = tempfile::tempdir().unwrap();
+ let fake = tmp.path().join("git");
+ let pid_file = tmp.path().join("child.pid");
+ std::fs::write(&fake, format!("#!/bin/sh\nsleep 30 &\necho $! > {}\nwait\n", pid_file.display())).unwrap();
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
+ }
+ let t = Instant::now();
+ let r = run(fake.to_str().unwrap(), None, &["x"], Opts { timeout: Duration::from_millis(500), ..Opts::read() }).await;
+ assert_eq!(r, Err(GitError::Timeout));
+ assert!(t.elapsed() < Duration::from_secs(5));
+ tokio::time::sleep(Duration::from_millis(200)).await;
+ let pid: i32 = std::fs::read_to_string(&pid_file).unwrap().trim().parse().unwrap();
+ // SAFETY: signal 0 only asks whether the process exists
+ let alive = unsafe { libc::kill(pid, 0) } == 0;
+ assert!(!alive, "the grandchild was killed with the group");
+ }
+
+ #[tokio::test]
+ async fn the_token_reaches_git_by_environment_only() {
+ let tmp = tempfile::tempdir().unwrap();
+ let fake = tmp.path().join("git");
+ let seen = tmp.path().join("seen");
+ // Records its argv and the config git would read from the environment
+ std::fs::write(
+ &fake,
+ format!(
+ "#!/bin/sh\nprintf '%s\\n' \"$@\" > {0}.argv\nenv | grep -E '^(GIT_|SSH_ASKPASS|GCM_)' | sort > {0}.env\n",
+ seen.display()
+ ),
+ )
+ .unwrap();
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
+ }
+ let token = format!("{}{}", ["gh", "s_"].concat(), "c4n4ry".repeat(6));
+ let header = Zeroizing::new(format!("Basic {token}"));
+ let auth = Auth::header("https://github.com/o/n.git", header).unwrap();
+ assert!(!format!("{auth:?}").contains(&token), "Debug hides it");
+ run(fake.to_str().unwrap(), Some(tmp.path()), &["fetch", "--", "https://github.com/o/n.git"], Opts { auth: Some(&auth), ..Opts::read() }).await.unwrap();
+ let argv = std::fs::read_to_string(seen.with_extension("argv")).unwrap();
+ let env = std::fs::read_to_string(seen.with_extension("env")).unwrap();
+ assert!(!argv.contains(&token), "argv: {argv}");
+ assert!(argv.contains("credential.helper=") && argv.contains("http.followRedirects=false"));
+ assert!(argv.contains("protocol.allow=never") && !argv.contains("protocol.file.allow"));
+ assert!(env.contains("GIT_CONFIG_COUNT=1\n"));
+ assert!(env.contains("GIT_CONFIG_KEY_0=http.https://github.com/.extraheader\n"));
+ assert!(env.contains(&format!("GIT_CONFIG_VALUE_0=Authorization: Basic {token}\n")));
+ assert!(env.contains("GIT_TERMINAL_PROMPT=0\n"));
+ let ours = ["GIT_CONFIG_COUNT", "GIT_CONFIG_KEY_0", "GIT_CONFIG_VALUE_0", "GIT_TERMINAL_PROMPT", "GIT_OPTIONAL_LOCKS", "GIT_LITERAL_PATHSPECS", "GIT_NO_REPLACE_OBJECTS", "GCM_INTERACTIVE", "SSH_ASKPASS_REQUIRE"];
+ for name in env.lines().filter_map(|l| l.split('=').next()) {
+ assert!(ours.contains(&name) || KEEP_ENV.contains(&name), "only kwant's own or the person's ssh/config choices reach git: {name}");
+ }
+
+ assert!(Auth::header("http://github.com/o/n.git", Zeroizing::new("Basic x".into())).is_none(), "never over plain http");
+ assert!(Auth::header("ssh://[email protected]/o/n.git", Zeroizing::new("Basic x".into())).is_none());
+ assert!(Auth::header("https://github.com/o/n.git", Zeroizing::new("Basic x\r\nX-Evil: 1".into())).is_none(), "one header line");
+ assert!(Auth::header("http://127.0.0.1:9/o/n.git", Zeroizing::new("Basic x".into())).is_some(), "a test server on this machine");
+ }
+
+ /// A resolver with fixed answers that remembers what it was asked (no network).
+ struct Fake {
+ answers: std::collections::HashMap<&'static str, Vec<IpAddr>>,
+ asked: Mutex<Vec<(String, u16)>>,
+ }
+
+ #[async_trait::async_trait]
+ impl Resolver for Fake {
+ async fn lookup(&self, host: &str, port: u16) -> Result<Vec<IpAddr>, GitError> {
+ self.asked.lock().unwrap().push((host.to_string(), port));
+ match host {
+ "down.example" => Err(GitError::Unreachable),
+ _ => Ok(self.answers.get(host).cloned().unwrap_or_default()),
+ }
+ }
+ }
+
+ fn ip(s: &str) -> IpAddr {
+ s.parse().unwrap()
+ }
+
+ #[tokio::test]
+ async fn a_remote_is_looked_up_refused_on_this_machine_and_pinned_to_what_was_checked() {
+ let fake = Fake {
+ answers: [
+ ("gitea.home.example", vec![ip("192.168.1.20")]),
+ ("two.example", vec![ip("203.0.113.7"), ip("2001:db8::5")]),
+ ("rebind.example", vec![ip("127.0.0.1")]),
+ ("meta.example", vec![ip("169.254.169.254")]),
+ ("v6local.example", vec![ip("fe80::1")]),
+ ("v6loop.example", vec![ip("::1")]),
+ ("mapped.example", vec![ip("::ffff:127.0.0.1")]),
+ ("mapped-meta.example", vec![ip("::ffff:169.254.169.254")]),
+ ("nat64.example", vec![ip("64:ff9b::7f00:1")]),
+ ("zero.example", vec![ip("0.0.0.0")]),
+ ("mixed.example", vec![ip("203.0.113.7"), ip("127.0.0.2")]),
+ ]
+ .into_iter()
+ .collect(),
+ asked: Mutex::new(Vec::new()),
+ };
+ let new = Some((2, 43));
+ let pin = |s: &str| Ok(vec![format!("http.curloptResolve={s}")]);
+
+ // A LAN host is allowed (people run Gitea at home) and pinned to the address checked
+ assert_eq!(check_remote("https://gitea.home.example/o/n.git", &fake, new).await, pin("gitea.home.example:443:192.168.1.20"));
+ assert_eq!(check_remote("http://gitea.home.example:3000/o/n.git", &fake, new).await, pin("gitea.home.example:3000:192.168.1.20"));
+ assert_eq!(check_remote("https://two.example/o/n.git", &fake, new).await, pin("two.example:443:203.0.113.7,[2001:db8::5]"), "every address checked, v6 in brackets");
+ // An older git (before 2.37) can't pin: the check stands alone
+ assert_eq!(check_remote("https://gitea.home.example/o/n.git", &fake, Some((2, 36))).await, Ok(vec![]));
+ // ssh and git:// are checked, never pinned
+ assert_eq!(check_remote("ssh://[email protected]/o/n.git", &fake, new).await, Ok(vec![]));
+ assert_eq!(check_remote("[email protected]:o/n.git", &fake, new).await, Ok(vec![]));
+ assert_eq!(check_remote("git://gitea.home.example/o/n.git", &fake, new).await, Ok(vec![]));
+ assert_eq!(
+ fake.asked.lock().unwrap().clone(),
+ [("gitea.home.example", 443), ("gitea.home.example", 3000), ("two.example", 443), ("gitea.home.example", 443), ("gitea.home.example", 22), ("gitea.home.example", 22), ("gitea.home.example", 9418)]
+ .map(|(h, p)| (h.to_string(), p))
+ );
+
+ // A name that resolves to this machine or link-local is refused, over every protocol
+ for host in ["rebind.example", "meta.example", "v6local.example", "v6loop.example", "mapped.example", "mapped-meta.example", "nat64.example", "zero.example", "mixed.example"] {
+ for url in [format!("https://{host}/o/n.git"), format!("ssh://git@{host}/o/n.git"), format!("git@{host}:o/n.git"), format!("git://{host}/o/n.git")] {
+ assert_eq!(check_remote(&url, &fake, new).await, Err(GitError::Refused), "{url}");
+ }
+ }
+ // A literal address or localhost is decided without a lookup
+ fake.asked.lock().unwrap().clear();
+ for url in ["https://127.0.0.1/o/n.git", "https://[::1]/o/n.git", "https://169.254.169.254/o/n.git", "https://[::ffff:169.254.169.254]/o/n.git", "https://localhost/o/n.git", "ssh://[email protected]/o/n.git"] {
+ assert_eq!(check_remote(url, &fake, new).await, Err(GitError::Refused), "{url}");
+ }
+ assert_eq!(check_remote("https://192.168.1.9:8443/o/n.git", &fake, new).await, Ok(vec![]), "a LAN address: nothing to pin");
+ assert!(fake.asked.lock().unwrap().is_empty());
+ // No answer is unreachable; an address kwant won't pass on is refused before any lookup
+ assert_eq!(check_remote("https://nowhere.example/o/n.git", &fake, new).await, Err(GitError::Unreachable));
+ assert_eq!(check_remote("https://down.example/o/n.git", &fake, new).await, Err(GitError::Unreachable));
+ assert_eq!(check_remote("file:///etc/o.git", &fake, new).await, Err(GitError::Refused));
+ assert_eq!(check_remote("https://u:[email protected]/o/n.git", &fake, new).await, Err(GitError::Refused), "only a stripped fetch URL");
+ }
+
+ #[test]
+ fn blocked_addresses_are_this_machine_and_link_local_never_the_lan() {
+ for a in ["127.0.0.1", "127.9.9.9", "0.0.0.0", "0.1.2.3", "169.254.169.254", "169.254.0.1", "255.255.255.255", "::1", "::", "fe80::1", "febf::1", "::ffff:127.0.0.1", "::ffff:169.254.169.254", "::127.0.0.1", "64:ff9b::a9fe:a9fe"] {
+ assert!(blocked(ip(a)), "{a}");
+ }
+ for a in ["10.0.0.1", "172.16.0.1", "192.168.1.20", "100.64.0.1", "203.0.113.7", "fd00::1", "2001:db8::5", "::ffff:192.168.1.20", "fec0::1"] {
+ assert!(!blocked(ip(a)), "{a}");
+ }
+ }
+
+ /// The pin is what git connects to: a name that can't resolve (`.invalid`) reaches a listener
+ /// on this machine only through `http.curloptResolve`. (The check never lets kwant pin to
+ /// loopback; `run` is called directly to see real git honour the setting.)
+ #[tokio::test]
+ async fn real_git_connects_where_it_was_pinned() {
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ let port = listener.local_addr().unwrap().port();
+ let seen = std::thread::spawn(move || {
+ use std::io::{Read, Write};
+ let (mut c, _) = listener.accept().unwrap();
+ c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
+ let mut buf = [0u8; 4096];
+ let n = c.read(&mut buf).unwrap_or(0);
+ let _ = c.write_all(b"HTTP/1.0 404 Not Found\r\nContent-Length: 0\r\n\r\n");
+ String::from_utf8_lossy(&buf[..n]).to_string()
+ });
+ let tmp = tempfile::tempdir().unwrap();
+ let pin = [format!("http.curloptResolve=pinned.invalid:{port}:127.0.0.1")];
+ let url = format!("http://pinned.invalid:{port}/o/n.git");
+ let r = run("git", Some(tmp.path()), &["ls-remote", "--", &url], Opts { timeout: REMOTE_TIMEOUT, pin: &pin, ..Opts::read() }).await;
+ assert_eq!(r, Err(GitError::NotFound));
+ let request = seen.join().unwrap();
+ assert!(request.starts_with("GET /o/n.git/info/refs"), "{request}");
+ assert!(request.to_ascii_lowercase().contains(&format!("host: pinned.invalid:{port}")), "{request}");
+ }
+
+ #[tokio::test]
+ async fn a_fetch_checks_its_remote_first() {
+ let tmp = tempfile::tempdir().unwrap();
+ let repo = Repo::mirror(tmp.path(), "s1", "localhost/o/n").await.unwrap();
+ for url in ["https://localhost/o/n.git", "https://127.0.0.1/o/n.git", "http://[::1]:8080/o/n.git"] {
+ assert_eq!(repo.fetch(url, "main", None).await, Err(GitError::Refused), "{url}");
+ assert_eq!(repo.fetch_ref(url, "refs/pull/1/head", "refs/kwant/pr-1", None).await, Err(GitError::Refused), "{url}");
+ assert_eq!(repo.default_branch(url, None).await, Err(GitError::Refused), "{url}");
+ assert_eq!(repo.has_branch(url, "main", None).await, Err(GitError::Refused), "{url}");
+ }
+ }
+
+ #[tokio::test]
+ async fn a_mirror_over_the_cap_is_deleted_and_fetched_again_after_a_day_or_when_added_again() {
+ let tmp = tempfile::tempdir().unwrap();
+ let (w, _) = upstream(tmp.path());
+ let data = tmp.path().join("data");
+ let key = "gitlab.example.com/group/big";
+ let dir = mirror_dir(&data, "s1", key);
+ let repo = Repo::mirror(&data, "s1", key).await.unwrap();
+ run("git", Some(&repo.dir), &["fetch", "--quiet", "--", w.to_str().unwrap(), "+refs/heads/main:refs/heads/main"], Opts { file: true, ..Opts::read() }).await.unwrap();
+ assert_eq!(repo.cap(MIRROR_CAP).await, Ok(()), "a small repo stays");
+ assert!(dir.join("HEAD").is_file());
+ // A tiny cap (the test hook): the mirror goes and a note says why
+ assert_eq!(repo.cap(1000).await, Err(GitError::RepoTooBig));
+ assert!(!dir.exists(), "the mirror is deleted");
+ assert!(too_big_mark(&dir).is_file());
+ assert_eq!(GitError::RepoTooBig.to_string(), "This repo is too big for Dev mode to read (over 1 GB).");
+ drop(repo);
+
+ // The next polls don't fetch it again: refused before git or a lookup runs
+ let repo = Repo::mirror(&data, "s1", key).await.unwrap();
+ assert_eq!(repo.fetch("https://gitlab.example.com/group/big.git", "main", None).await, Err(GitError::RepoTooBig));
+ assert_eq!(repo.fetch_ref("https://gitlab.example.com/group/big.git", "refs/pull/1/head", "refs/kwant/pr-1", None).await, Err(GitError::RepoTooBig));
+ // A day on, it is tried again
+ let day_ago = std::time::SystemTime::now() - TOO_BIG_RETRY - Duration::from_secs(60);
+ std::fs::File::options().write(true).open(too_big_mark(&dir)).unwrap().set_modified(day_ago).unwrap();
+ assert_eq!(repo.not_too_big().await, Ok(()));
+ assert!(!too_big_mark(&dir).exists(), "the old note is cleared");
+ drop(repo);
+
+ // Removing the repo (and adding it again) starts afresh
+ std::fs::write(too_big_mark(&dir), b"").unwrap();
+ remove_mirror(&data, "s1", key).await;
+ assert!(!too_big_mark(&dir).exists() && !dir.exists());
+ let repo = Repo::mirror(&data, "s1", key).await.unwrap();
+ assert_eq!(repo.not_too_big().await, Ok(()));
+
+ // A team folder is never capped: kwant didn't copy it
+ let local = Repo::local(&w, &data).await.unwrap();
+ assert_eq!(local.cap(1).await, Ok(()));
+ assert!(w.join(".git/HEAD").is_file());
+ }
+
+ #[test]
+ fn a_password_in_a_remote_is_never_kept() {
+ // http(s) and git:// lose their userinfo whole; ssh keeps a user name only
+ assert_eq!(fetch_url("https://u:[email protected]/x.git").as_deref(), Some("https://host.example/x.git"));
+ assert_eq!(fetch_url("ssh://u:[email protected]/x.git").as_deref(), Some("ssh://[email protected]/x.git"));
+ assert_eq!(fetch_url("http://u:[email protected]:8080/x.git").as_deref(), Some("http://host.example:8080/x.git"));
+ assert_eq!(fetch_url("git://u:[email protected]/x.git").as_deref(), Some("git://host.example/x.git"));
+ assert_eq!(fetch_url("https://[email protected]/x.git").as_deref(), Some("https://host.example/x.git"));
+ assert_eq!(fetch_url("u:[email protected]:x.git").as_deref(), Some("[email protected]:x.git"));
+ let secret = "s3cr3t-c4n4ry";
+ for raw in [format!("https://u:{secret}@host.example/x.git"), format!("ssh://u:{secret}@host.example/x.git"), format!("u:{secret}@host.example:x.git")] {
+ for got in [fetch_url(&raw), remote_url(&raw)] {
+ let got = got.unwrap_or_default();
+ assert!(!got.contains(secret) && !got.contains(":p@"), "{raw} -> {got}");
+ }
+ }
+ }
+
+ #[test]
+ fn diff_output_parses_like_githubs_files() {
+ let raw = b":100644 100644 aaa bbb M\0src/a.rs\0:000000 100644 000 ccc A\0new.txt\0:100644 100644 ddd eee R087\0old.rs\0new.rs\0";
+ let files = parse_raw(raw);
+ assert_eq!(files.iter().map(|f| (f.path.as_str(), f.status.as_str(), f.previous_path.as_deref())).collect::<Vec<_>>(), [("src/a.rs", "modified", None), ("new.txt", "added", None), ("new.rs", "renamed", Some("old.rs"))]);
+ assert_eq!(parse_numstat(b"3\t1\tsrc/a.rs\0-\t-\tnew.txt\x002\t0\t\0old.rs\0new.rs\0"), [(3, 1), (0, 0), (2, 0)]);
+ let p = "diff --git a/x b/x\nindex 1..2 100644\n--- a/x\n+++ b/x\n@@ -1 +1 @@\n-a\n+b\ndiff --git a/y b/y\nBinary files a/y and b/y differ\ndiff --git a/z b/z\nold mode 100644\nnew mode 100755\n";
+ assert_eq!(split_patches(p), [Some("@@ -1 +1 @@\n-a\n+b".to_string()), None, None]);
+ assert!(split_patches("").is_empty());
+ }
+
+ // -----------------------------------------------------------------------------------------
+ // G2 review (Lin, at 6dd0243): one test per probe.
+
+ fn exe(path: &Path, text: &str) {
+ std::fs::write(path, text).unwrap();
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap();
+ }
+ }
+
+ /// F1 (probe P1): an ssh remote runs `ssh`, never an empty command, whatever the repo's own
+ /// config says. A fake `ssh` first on PATH logs what git asked it for.
+ #[tokio::test]
+ async fn ssh_remotes_run_ssh_and_never_the_repos_own_command() {
+ let tmp = tempfile::tempdir().unwrap();
+ let bin = tmp.path().join("bin");
+ std::fs::create_dir_all(&bin).unwrap();
+ let log = tmp.path().join("ssh.log");
+ exe(&bin.join("ssh"), &format!("#!/bin/sh\necho \"$@\" >> '{}'\nexit 1\n", log.display()));
+ // git itself, with the fake ssh first on its PATH
+ let wrap = tmp.path().join("git-with-fake-ssh");
+ exe(&wrap, &format!("#!/bin/sh\nPATH='{}':\"$PATH\"\nexport PATH\nexec git \"$@\"\n", bin.display()));
+ // A mirror whose config names another command: `-c` must beat it
+ let data = tmp.path().join("data");
+ let repo = Repo::mirror(&data, "s1", "gitea.example.org/o/n").await.unwrap();
+ let canary = tmp.path().join("canary");
+ sh(&repo.dir, &["config", "core.sshCommand", &format!("touch '{}'", canary.display())]);
+ let w = wrap.to_str().unwrap();
+ for url in ["ssh://[email protected]/o/n.git", "[email protected]:o/n.git"] {
+ let r = run(w, Some(&repo.dir), &["ls-remote", "--", url], Opts { timeout: REMOTE_TIMEOUT, ..Opts::read() }).await;
+ assert!(r.is_err(), "the fake ssh says no");
+ }
+ let seen = std::fs::read_to_string(&log).unwrap_or_default();
+ assert!(seen.contains("[email protected] git-upload-pack '/o/n.git'"), "ssh:// ran ssh: {seen:?}");
+ assert!(seen.contains("[email protected] git-upload-pack 'o/n.git'"), "scp-style ran ssh: {seen:?}");
+ assert!(!canary.exists(), "the repo's own sshCommand never ran");
+ // The admin's GIT_SSH program is kept, quoted for the shell
+ assert_eq!(ssh_command(None), "core.sshCommand=ssh");
+ assert_eq!(ssh_command(Some(std::ffi::OsStr::new(""))), "core.sshCommand=ssh");
+ assert_eq!(ssh_command(Some(std::ffi::OsStr::new("/opt/my ssh/plink"))), "core.sshCommand='/opt/my ssh/plink'");
+ assert_eq!(ssh_command(Some(std::ffi::OsStr::new("/x/it's"))), "core.sshCommand='/x/it'\\''s'");
+ }
+
+ /// A team folder at `root/<name>` with one commit of its own.
+ fn team_folder(root: &Path, name: &str) -> PathBuf {
+ let f = root.join(name);
+ std::fs::create_dir_all(&f).unwrap();
+ sh(&f, &["init", "-q"]);
+ write(&f, "mine.txt", b"ours\n");
+ commit_all(&f, "Our own work");
+ f
+ }
+
+ /// F2 (probe P3, setup 1): a `.git` file naming another repo's git dir (another team's, or a
+ /// kwant mirror fetched with another space's token) is refused, not read.
+ #[tokio::test]
+ async fn a_git_file_naming_another_repo_is_refused() {
+ let tmp = tempfile::tempdir().unwrap();
+ let (victim, _) = upstream(tmp.path());
+ let data = tmp.path().join("data");
+ let mirror = Repo::mirror(&data, "space-b", "github.com/b/private").await.unwrap();
+ let mirror_dir = mirror.dir.clone();
+ drop(mirror);
+ let a = tmp.path().join("team-a");
+ std::fs::create_dir_all(&a).unwrap();
+ for target in [victim.join(".git"), mirror_dir] {
+ std::fs::write(a.join(".git"), format!("gitdir: {}\n", target.display())).unwrap();
+ assert_eq!(Repo::local(&a, &data).await.unwrap_err(), GitError::Refused, "{}", target.display());
+ }
+ // Relative works the same
+ std::fs::write(a.join(".git"), "gitdir: ../work/.git\n").unwrap();
+ assert_eq!(Repo::local(&a, &data).await.unwrap_err(), GitError::Refused);
+ }
+
+ /// F2 (probe P3, setup 2): a `.git` symlink is refused.
+ #[tokio::test]
+ async fn a_git_symlink_is_refused() {
+ let tmp = tempfile::tempdir().unwrap();
+ let (victim, _) = upstream(tmp.path());
+ let b = tmp.path().join("team-b");
+ std::fs::create_dir_all(&b).unwrap();
+ std::os::unix::fs::symlink(victim.join(".git"), b.join(".git")).unwrap();
+ assert_eq!(Repo::local(&b, &tmp.path().join("data")).await.unwrap_err(), GitError::Refused);
+ }
+
+ /// F2 (probe P3, setup 3): a repo borrowing another's objects through
+ /// `objects/info/alternates` is refused.
+ #[tokio::test]
+ async fn alternates_are_refused() {
+ let tmp = tempfile::tempdir().unwrap();
+ let (victim, _) = upstream(tmp.path());
+ let c = team_folder(tmp.path(), "team-c");
+ let data = tmp.path().join("data");
+ assert!(Repo::local(&c, &data).await.is_ok(), "its own repo reads");
+ std::fs::write(c.join(".git/objects/info/alternates"), format!("{}\n", victim.join(".git/objects").display())).unwrap();
+ assert_eq!(Repo::local(&c, &data).await.unwrap_err(), GitError::Refused);
+ }
+
+ /// F2: the same reach by other routes: a `.git` directory with a `commondir`, or with its
+ /// objects or refs a symlink to another repo's.
+ #[tokio::test]
+ async fn a_git_dir_borrowing_another_repos_objects_or_refs_is_refused() {
+ let tmp = tempfile::tempdir().unwrap();
+ let (victim, _) = upstream(tmp.path());
+ let data = tmp.path().join("data");
+ let d = team_folder(tmp.path(), "team-d");
+ std::fs::write(d.join(".git/commondir"), format!("{}\n", victim.join(".git").display())).unwrap();
+ assert_eq!(Repo::local(&d, &data).await.unwrap_err(), GitError::Refused, "commondir");
+ for (name, what) in [("team-e", "objects"), ("team-f", "refs"), ("team-g", "objects/pack")] {
+ let f = team_folder(tmp.path(), name);
+ std::fs::remove_dir_all(f.join(".git").join(what)).unwrap();
+ std::os::unix::fs::symlink(victim.join(".git").join(what), f.join(".git").join(what)).unwrap();
+ assert_eq!(Repo::local(&f, &data).await.unwrap_err(), GitError::Refused, "{what}");
+ }
+ }
+
+ /// F2: a folder under kwant's own mirrors (`<data>/dev`) is never read as a team's.
+ #[tokio::test]
+ async fn kwants_own_mirrors_are_never_read_as_a_team_folder() {
+ let tmp = tempfile::tempdir().unwrap();
+ let data = tmp.path().join("data");
+ let inside = team_folder(&data.join("dev/space-b"), "checkout");
+ assert_eq!(Repo::local(&inside, &data).await.unwrap_err(), GitError::Refused);
+ }
+
+ /// F2: a real linked worktree (`git worktree add`) still reads; a hand-made one that names
+ /// another repo as its main repo doesn't (only that repo can make a worktree of itself).
+ #[tokio::test]
+ async fn a_real_worktree_still_reads_and_a_forged_one_does_not() {
+ let tmp = tempfile::tempdir().unwrap();
+ let (main, c) = upstream(tmp.path());
+ let data = tmp.path().join("data");
+ let wt = tmp.path().join("wt");
+ sh(&main, &["worktree", "add", "-q", "-b", "wt-branch", wt.to_str().unwrap()]);
+ let repo = Repo::local(&wt, &data).await.expect("a real worktree reads");
+ assert_eq!(repo.resolve("refs/heads/main").await.unwrap(), c[4]);
+
+ // Forged: a git dir in the team's own folder that points back at it, with the victim as
+ // its main repo
+ let (victim, _) = upstream(&tmp.path().join("v"));
+ let f = tmp.path().join("team-h");
+ let gd = f.join("fake");
+ std::fs::create_dir_all(&gd).unwrap();
+ std::fs::write(gd.join("gitdir"), format!("{}\n", f.join(".git").display())).unwrap();
+ std::fs::write(gd.join("commondir"), format!("{}\n", victim.join(".git").display())).unwrap();
+ std::fs::write(gd.join("HEAD"), "ref: refs/heads/main\n").unwrap();
+ std::fs::write(f.join(".git"), format!("gitdir: {}\n", gd.display())).unwrap();
+ assert_eq!(Repo::local(&f, &data).await.unwrap_err(), GitError::Refused);
+ }
+
+ /// Bytes that don't compress, so a pack of them is as big as they are.
+ fn noise(n: usize) -> Vec<u8> {
+ let mut x: u64 = 0x9e37_79b9_7f4a_7c15;
+ (0..n)
+ .map(|_| {
+ x ^= x << 13;
+ x ^= x >> 7;
+ x ^= x << 17;
+ x as u8
+ })
+ .collect()
+ }
+
+ /// F3 (probe P7): a fetch stops at the cap, not after it, and ends as too big: the mirror
+ /// deleted, its note left, no ref written. (A tiny cap stands in for 1 GB; the source is a
+ /// local repo with a 3 MB blob, so there's no network.)
+ #[tokio::test]
+ async fn a_fetch_stops_at_the_cap_and_ends_as_too_big() {
+ let tmp = tempfile::tempdir().unwrap();
+ let src = team_folder(tmp.path(), "big");
+ write(&src, "noise.bin", &noise(3 << 20));
+ commit_all(&src, "Three megabytes");
+ let data = tmp.path().join("data");
+ let key = "gitea.example.org/o/big";
+ let dir = mirror_dir(&data, "s1", key);
+ let cap: u64 = 500_000;
+ let from = src.to_str().unwrap();
+ let args = ["fetch", "--quiet", "--no-tags", "--no-write-fetch-head", "--", from, "+refs/heads/main:refs/heads/main"];
+
+ // The limit itself: git is stopped with no file past the cap and no ref
+ let repo = Repo::mirror(&data, "s1", key).await.unwrap();
+ let r = run("git", Some(&repo.dir), &args, Opts { timeout: FETCH_TIMEOUT, file: true, fsize: Some(cap), ..Opts::read() }).await;
+ assert!(r.is_err(), "stopped");
+ assert!(largest_file(&dir) <= cap, "a file passed the cap: {}", largest_file(&dir));
+ assert!(largest_file(&dir) > cap / 2, "it was the limit that stopped it");
+ assert_eq!(repo.resolve("refs/heads/main").await, Err(GitError::NotFound), "no ref written");
+
+ // A mirror's fetch: too big, the mirror deleted and the note left
+ assert_eq!(repo.fetch_capped(&args, Opts { timeout: FETCH_TIMEOUT, file: true, ..Opts::read() }, cap).await, Err(GitError::RepoTooBig));
+ assert!(!dir.exists(), "the mirror is deleted");
+ assert!(too_big_mark(&dir).is_file(), "the note is left");
+ assert_eq!(GitError::poll_code(&GitError::RepoTooBig.to_string()), Some("too_big"));
+ drop(repo);
+
+ // Under the cap it fetches as before
+ std::fs::remove_file(too_big_mark(&dir)).unwrap();
+ let repo = Repo::mirror(&data, "s1", key).await.unwrap();
+ assert_eq!(repo.fetch_capped(&args, Opts { timeout: FETCH_TIMEOUT, file: true, ..Opts::read() }, MIRROR_CAP).await, Ok(()));
+ assert!(repo.resolve("refs/heads/main").await.is_ok());
+ }
+
+ /// F6: cloud metadata addresses outside link-local are refused (exactly, not their ranges).
+ #[test]
+ fn cloud_metadata_outside_link_local_is_refused() {
+ for a in ["100.100.100.200", "fd00:ec2::254", "::ffff:100.100.100.200", "64:ff9b::6464:64c8"] {
+ assert!(blocked(ip(a)), "{a}");
+ }
+ for a in ["100.100.100.201", "100.64.0.1", "100.127.255.254", "fd00:ec2::253", "fd00::254"] {
+ assert!(!blocked(ip(a)), "{a}");
+ }
+ }
+
+ /// Both too-big errors give the desk `poll_code: "too_big"`; no other error does.
+ #[test]
+ fn both_too_big_errors_have_the_too_big_poll_code() {
+ assert_eq!(GitError::poll_code(&GitError::TooBig.to_string()), Some("too_big"));
+ assert_eq!(GitError::poll_code(&GitError::RepoTooBig.to_string()), Some("too_big"));
+ for e in [GitError::NoGit, GitError::Auth, GitError::NotFound, GitError::Unreachable, GitError::Timeout, GitError::Refused, GitError::Failed] {
+ assert_eq!(GitError::poll_code(&e.to_string()), None, "{e:?}");
+ }
+ assert_eq!(GitError::poll_code("anything else"), None);
+ }
+}
diff --git a/src/server/dev/mod.rs b/src/server/dev/mod.rs
index 3b047e19..cc561e40 100644
--- a/src/server/dev/mod.rs
+++ b/src/server/dev/mod.rs
@@ -4,11 +4,12 @@
//! `generate` turns them into cards. The production floor lives in `crate::mcp::prod_floor`.
//!
//! Lin owns `facts`, `routes`, `poller`, `post`, `repo`, `backup` and `floor`; Vega owns `generate`, `landed`,
-//! `review`, `risk`, `tamper` and `notes`; Juno owns `scan`.
+//! `review`, `risk`, `tamper`, `notes` and `source`; Juno owns `scan`.
pub mod backup;
pub mod facts;
pub mod floor;
+pub mod git;
pub mod generate;
pub mod landed;
pub mod notes;
@@ -19,6 +20,7 @@ pub mod review;
pub mod risk;
pub mod routes;
pub mod scan;
+pub mod source;
pub mod tamper;
pub use generate::generate;
@@ -56,6 +58,13 @@ pub fn call_cap() -> i64 {
*CAP.get_or_init(|| env_num("KWANT_DEV_CALL_CAP", 0, 1000).map_or(CALLS_CAP, |v| v as i64))
}
+/// The most disk one repo's git mirror may use: `KWANT_DEV_MIRROR_CAP_BYTES` (1 B–1 TB, so a test
+/// can use a tiny cap), else [`git::MIRROR_CAP`] (1 GB).
+pub fn mirror_cap() -> u64 {
+ static CAP: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
+ *CAP.get_or_init(|| env_num("KWANT_DEV_MIRROR_CAP_BYTES", 1, 1 << 40).unwrap_or(git::MIRROR_CAP))
+}
+
/// Where the secrets scan downloads gitleaks from: `KWANT_DEV_GITLEAKS_URL` (an http(s) base; the
/// pinned checksums still apply), else GitHub's release page.
pub fn scan_gitleaks_base() -> Option<&'static str> {
diff --git a/src/server/dev/poller.rs b/src/server/dev/poller.rs
index 9396c9fd..3c69e643 100644
--- a/src/server/dev/poller.rs
+++ b/src/server/dev/poller.rs
@@ -12,7 +12,9 @@ use crate::db::dev_mode::{DevCardRow, DevRepoRow, LANDED, PENDING, REVIEW, STALE
use crate::db::models::Kwant;
use crate::db::spaces::SpaceId;
use crate::server::AppState;
-use crate::zombie::github::{EtagCache, GhCheck, GhCommit, GhError, GhFile, GhPull, GithubSource};
+use super::git::{self, Auth, GitError, Repo};
+use super::source::{Change, Commit, Forge, GithubForge, History};
+use crate::zombie::github::{EtagCache, GhError};
use chrono::{DateTime, Duration, Utc};
use std::collections::{HashMap, HashSet};
use std::sync::{Mutex, OnceLock};
@@ -191,59 +193,119 @@ pub async fn poll_logged(state: &AppState, row: DevRepoRow) {
}
/// One poll of one watched repo. Merges are recorded as `last_seen_sha` one by one, so a failure
-/// part way keeps the ones done.
+/// part way keeps the ones done. History comes from git ([`History`]: kwant's mirror of the repo,
+/// or a team folder's own `.git`) and, on GitHub, from the API when git can't answer; pull
+/// requests and checks come from the repo's [`Forge`] (GitHub only, until G4).
pub async fn poll(state: &AppState, mode: &DevRepoRow) -> Result<(), GhError> {
+ if mode.repo.trim().is_empty() {
+ return Ok(());
+ }
+ if mode.is_git() {
+ return poll_git(state, mode).await;
+ }
// A row whose branch isn't known yet (added while off): reconcile fills it at switch-on
- if mode.repo.trim().is_empty() || mode.branch.trim().is_empty() {
+ if mode.branch.trim().is_empty() {
return Ok(());
}
- let space = SpaceId::new(&mode.space_id);
let (client, _) = repo::client_for(state, &mode.repo).await?;
+ let mut git_repo = None;
+ let (mut url, mut auth) = (String::new(), None);
+ if git::available().await {
+ if let Ok((u, header)) = client.dev_git_remote(&mode.repo) {
+ if let Some(a) = Auth::header(&u, header) {
+ git_repo = Repo::mirror(&state.config.data_dir, &mode.space_id, &mode.key).await.ok();
+ (url, auth) = (u, Some(a));
+ }
+ }
+ }
+ let commit_base = Some(format!("{}/{}/commit", client.dev_web(), mode.repo.trim_matches('/')));
+ let mut h = History::new(git_repo, url, auth, Some((&client, mode.repo.as_str())), &mode.branch, commit_base);
+ h.fetch().await?;
+ let forge = GithubForge { client: &client, repo: &mode.repo };
+ read(state, mode, &h, Some(&forge)).await
+}
+
+/// A repo GitHub's API can't read (GitLab, Gitea, a bare git server, a team folder with no
+/// remote): git only, so only landed cards, without PRs or checks.
+async fn poll_git(state: &AppState, mode: &DevRepoRow) -> Result<(), GhError> {
+ if !git::available().await {
+ return Err(GitError::NoGit.into());
+ }
+ let from = mode.git_url.as_deref().unwrap_or_default();
+ let (g, url) = if from.starts_with('/') {
+ (Repo::local(std::path::Path::new(from), &state.config.data_dir).await?, String::new())
+ } else {
+ let url = git::remote_url(from).filter(|u| u == from).ok_or(GitError::Refused)?;
+ (Repo::mirror(&state.config.data_dir, &mode.space_id, &mode.key).await?, url)
+ };
+ let mut mode = mode.clone();
+ if mode.branch.trim().is_empty() {
+ mode.branch = g.default_branch(&url, None).await?;
+ state.db.set_dev_repo_branch(&mode.space_id, &mode.key, &mode.branch).await.map_err(|e| GhError::Other(e.to_string()))?;
+ }
+ let base = mode.host.as_deref().and_then(|h| git::commit_base(h, &mode.repo));
+ let mut h = History::new(Some(g), url, None, None, &mode.branch, base);
+ h.fetch().await?;
+ if mode.deploy_hint.is_none() {
+ if let Some(hint) = h.root_names().await.as_deref().and_then(repo::deploy_hint) {
+ let _ = state.db.set_dev_repo_hint(&mode.space_id, &mode.key, Some(hint)).await;
+ }
+ }
+ read(state, &mode, &h, None).await
+}
+
+/// Reads what landed, the open changes and the CI that was still running, and makes their cards:
+/// the poll's body over any [`History`] and, when the host has one, its [`Forge`] (the seam a GitLab
+/// or Gitea forge plugs into, any-git.md G4). With no forge, only landed cards.
+pub async fn read(state: &AppState, mode: &DevRepoRow, h: &History<'_>, forge: Option<&dyn Forge>) -> Result<(), GhError> {
+ let space = SpaceId::new(&mode.space_id);
let kwants = state.db.list_kwants(&space).await.unwrap_or_default();
let cache = etags();
// The newest tag, for release notes
- if let Ok(tag) = client.dev_latest_tag(&mode.repo, cache).await {
- update_tag(&client, mode, tag).await;
- }
+ update_tag(h, mode).await;
// What landed
- let (commits, found) = client.dev_commits_since(&mode.repo, &mode.branch, mode.last_seen_sha.as_deref(), cache).await?;
+ let (commits, found) = h.commits_since(mode.last_seen_sha.as_deref(), cache).await?;
let mut last = None;
+ let mut skipped: Option<String> = None;
for c in window(commits, mode.last_seen_sha.is_none(), found) {
- landed(state, &client, mode, &kwants, &c).await?;
+ // A rebase-merge's earlier commits are skipped; the PR's card shows what they all changed
+ let base = skipped.take();
+ if !landed(state, h, forge, mode, &kwants, &c, base.as_deref()).await? {
+ skipped = base.or_else(|| c.parents.first().cloned());
+ }
last = Some(c.sha.clone());
}
state.db.dev_repo_polled(&mode.space_id, &mode.key, last.as_deref(), None).await.map_err(|e| GhError::Other(e.to_string()))?;
+ let Some(forge) = forge else { return Ok(()) };
// Open PRs
- let pulls = client.dev_open_pulls(&mode.repo, &mode.branch, cache).await?;
- reviews(state, &client, mode, &kwants, &pulls).await?;
+ let pulls = forge.open_changes(&mode.branch, cache).await?;
+ reviews(state, h, forge, mode, &kwants, &pulls).await?;
// CI that was still running
- recheck_ci(state, &client, mode).await;
+ recheck_ci(state, forge, mode).await;
Ok(())
}
-async fn update_tag(client: &GithubSource, mode: &DevRepoRow, tag: Option<(String, Option<String>)>) {
+async fn update_tag(h: &History<'_>, mode: &DevRepoRow) {
let key = tag_key(&mode.space_id, &mode.key);
- let Some((name, sha)) = tag else {
- shared().lock().unwrap().tags.remove(&key);
- return;
- };
- if shared().lock().unwrap().tags.get(&key).is_some_and(|(t, at)| *t == name && at.is_some()) {
- return;
+ let known = shared().lock().unwrap().tags.get(&key).cloned();
+ match h.latest_tag(known.as_ref(), etags()).await {
+ Ok(Some(t)) => {
+ shared().lock().unwrap().tags.insert(key, t);
+ }
+ Ok(None) => {
+ shared().lock().unwrap().tags.remove(&key);
+ }
+ Err(_) => {}
}
- let at = match sha {
- Some(s) => client.dev_commit(&mode.repo, &s).await.ok().and_then(|c| c.commit.committer.date.or(c.commit.author.date)),
- None => None,
- };
- shared().lock().unwrap().tags.insert(key, (name, at));
}
/// Which of the new commits (oldest first) become cards: the newest [`BACKFILL`] on a space's
/// first poll, else up to [`MAX_NEW`] (the newest, when there were more or `last_seen` was lost).
-pub fn window(commits: Vec<GhCommit>, first: bool, _found: bool) -> Vec<GhCommit> {
+pub fn window(commits: Vec<Commit>, first: bool, _found: bool) -> Vec<Commit> {
let keep = if first { BACKFILL } else { MAX_NEW };
let skip = commits.len().saturating_sub(keep);
commits.into_iter().skip(skip).collect()
@@ -252,9 +314,9 @@ pub fn window(commits: Vec<GhCommit>, first: bool, _found: bool) -> Vec<GhCommit
/// The merged PR a commit on the branch is the merge (or squash) commit of. `Err(())` when the
/// commit is one of several a rebase-merge put on the branch and isn't the last: the PR's card
/// is made from its merge commit, so this one is skipped.
-pub(crate) fn merged_pr<'a>(pulls: &'a [GhPull], sha: &str, branch: &str) -> Result<Option<&'a GhPull>, ()> {
- let merged: Vec<&GhPull> = pulls.iter().filter(|p| p.merged_at.is_some() && p.base.branch == branch).collect();
- if let Some(p) = merged.iter().find(|p| p.merge_commit_sha.as_deref() == Some(sha)) {
+pub(crate) fn merged_pr<'a>(pulls: &'a [Change], sha: &str, branch: &str) -> Result<Option<&'a Change>, ()> {
+ let merged: Vec<&Change> = pulls.iter().filter(|p| p.merged_at.is_some() && p.base_branch == branch).collect();
+ if let Some(p) = merged.iter().find(|p| p.merge_sha.as_deref() == Some(sha)) {
return Ok(Some(p));
}
if merged.is_empty() {
@@ -264,26 +326,45 @@ pub(crate) fn merged_pr<'a>(pulls: &'a [GhPull], sha: &str, branch: &str) -> Res
}
}
-async fn landed(state: &AppState, client: &GithubSource, mode: &DevRepoRow, kwants: &[Kwant], c: &GhCommit) -> Result<(), GhError> {
+/// Makes the landed card of commit `c`. False when `c` is one of a rebase-merge's earlier commits
+/// and was skipped; `base` is then where the next card's files start (the commit before the first
+/// skipped one), so the PR's card shows all it changed.
+async fn landed(state: &AppState, h: &History<'_>, forge: Option<&dyn Forge>, mode: &DevRepoRow, kwants: &[Kwant], c: &Commit, base: Option<&str>) -> Result<bool, GhError> {
if state.db.dev_cards_of_ref_in(&mode.space_id, &mode.key, LANDED, &c.sha).await.map(|v| !v.is_empty()).unwrap_or(false) {
- return Ok(());
+ return Ok(true);
}
- let pulls = client.dev_pulls_for_commit(&mode.repo, &c.sha).await.unwrap_or_default();
- let Ok(pr) = merged_pr(&pulls, &c.sha, &mode.branch) else { return Ok(()) };
- let full = client.dev_commit(&mode.repo, &c.sha).await?;
- let files = match pr {
- Some(p) => client.dev_pull_files(&mode.repo, p.number).await?,
- None => full.files.clone(),
+ let pulls = match forge {
+ Some(f) => f.changes_for_commit(&c.sha).await.unwrap_or_default(),
+ None => Vec::new(),
};
- let checks = client.dev_check_runs(&mode.repo, &c.sha, etags()).await.unwrap_or_default();
- let until = pr.and_then(|p| p.merged_at).or(full.commit.committer.date).unwrap_or_else(Utc::now) - Duration::seconds(1);
- let first = first_edits(client, mode, &files, until).await;
+ let Ok(pr) = merged_pr(&pulls, &c.sha, &mode.branch) else { return Ok(false) };
+ let mut full = h.commit(&c.sha).await?;
+ let files = match (h.has_git(), pr, forge) {
+ (true, _, _) => match base {
+ Some(b) => h.landed_files(Some(b), &c.sha).await.unwrap_or_else(|| full.files.clone()),
+ None => full.files.clone(),
+ },
+ (false, Some(p), Some(f)) => f.change_files(p.number).await?,
+ _ => full.files.clone(),
+ };
+ // Git knows no forge accounts: a direct push asks the forge who wrote it
+ if full.login.is_none() && pr.is_none() && h.has_git() {
+ if let Some(f) = forge {
+ full.login = f.commit_login(&c.sha).await;
+ }
+ }
+ let checks = match forge {
+ Some(f) => f.checks(&c.sha, etags()).await.unwrap_or_default(),
+ None => Vec::new(),
+ };
+ let until = pr.and_then(|p| p.merged_at).or(full.committer.date).unwrap_or_else(Utc::now) - Duration::seconds(1);
+ let first = first_edits(h, &files, until).await;
let facts = landed_facts(mode, &full, pr, files, checks, kwants, first);
insert(state, mode, LANDED, &c.sha, &c.sha, &facts).await;
- Ok(())
+ Ok(true)
}
-async fn reviews(state: &AppState, client: &GithubSource, mode: &DevRepoRow, kwants: &[Kwant], pulls: &[GhPull]) -> Result<(), GhError> {
+async fn reviews(state: &AppState, h: &History<'_>, forge: &dyn Forge, mode: &DevRepoRow, kwants: &[Kwant], pulls: &[Change]) -> Result<(), GhError> {
let mut open = HashSet::new();
let mut read = 0;
for p in pulls {
@@ -295,26 +376,30 @@ async fn reviews(state: &AppState, client: &GithubSource, mode: &DevRepoRow, kwa
continue;
}
let have = state.db.dev_cards_of_ref_in(&mode.space_id, &mode.key, REVIEW, &ref_).await.unwrap_or_default();
- if have.iter().any(|c| c.head_sha == p.head.sha) {
- stale(state, mode, &ref_, Some(&p.head.sha)).await;
+ if have.iter().any(|c| c.head_sha == p.head_sha) {
+ stale(state, mode, &ref_, Some(&p.head_sha)).await;
continue;
}
if read >= MAX_REVIEWS {
continue;
}
read += 1;
- let mut files = client.dev_pull_files(&mode.repo, p.number).await?;
- let head = client.dev_commit(&mode.repo, &p.head.sha).await.ok();
- let checks = client.dev_check_runs(&mode.repo, &p.head.sha, etags()).await.unwrap_or_default();
- let first = first_edits(client, mode, &files, Utc::now()).await;
+ let head_ref = forge.change_head_ref(p.number);
+ let mut files: Vec<FileDiff> = match h.change_files(head_ref.as_deref(), p.number, &p.head_sha, &p.base_branch).await {
+ Some(f) => f,
+ None => forge.change_files(p.number).await?,
+ };
+ let head = h.commit(&p.head_sha).await.ok();
+ let checks: Vec<Check> = forge.checks(&p.head_sha, etags()).await.unwrap_or_default();
+ let first = first_edits(h, &files, Utc::now()).await;
// The whole diff is scanned before the 60k cut, and secret lines are hidden before
// anything is stored or shown (Juno, plan §3.4)
let capped = files.len() >= crate::zombie::github::MAX_PR_FILES;
- let security = super::scan::for_review(&state.config.data_dir, client, &mode.repo, &p.head.sha, &mut files, capped).await;
+ let security = super::scan::for_review(&state.config.data_dir, h, &p.head_sha, &mut files, capped).await;
let mut facts = review_facts(mode, p, head.as_ref(), files, checks, kwants, first);
facts.security = Some(security);
- insert(state, mode, REVIEW, &ref_, &p.head.sha, &facts).await;
- stale(state, mode, &ref_, Some(&p.head.sha)).await;
+ insert(state, mode, REVIEW, &ref_, &p.head_sha, &facts).await;
+ stale(state, mode, &ref_, Some(&p.head_sha)).await;
}
// A PR of this repo that closed or merged: its review cards go stale
if let Ok(cards) = state.db.dev_cards_in(&mode.space_id, Some(&mode.key), REVIEW, None, 200).await {
@@ -349,7 +434,7 @@ async fn insert(state: &AppState, mode: &DevRepoRow, kind: &str, ref_: &str, hea
/// Landed and review cards made in the last [`CI_RECHECK_HOURS`] whose CI was pending: read the
/// checks again, and when they changed, store them and run `generate` again.
-async fn recheck_ci(state: &AppState, client: &GithubSource, mode: &DevRepoRow) {
+async fn recheck_ci(state: &AppState, forge: &dyn Forge, mode: &DevRepoRow) {
let since = Utc::now() - Duration::hours(CI_RECHECK_HOURS);
let mut rows: Vec<DevCardRow> = Vec::new();
for kind in [LANDED, REVIEW] {
@@ -365,7 +450,7 @@ async fn recheck_ci(state: &AppState, client: &GithubSource, mode: &DevRepoRow)
continue;
}
done += 1;
- let Ok(checks) = client.dev_check_runs(&mode.repo, &row.head_sha, etags()).await else { continue };
+ let Ok(checks) = forge.checks(&row.head_sha, etags()).await else { continue };
let checks = to_checks(checks);
if checks == facts.checks {
continue;
@@ -383,21 +468,21 @@ async fn recheck_ci(state: &AppState, client: &GithubSource, mode: &DevRepoRow)
/// The changed files (not new ones) nobody committed to in the last [`FIRST_EDIT_DAYS`] before
/// `until`, reading at most [`FIRST_EDIT_FILES`] histories.
-async fn first_edits(client: &GithubSource, mode: &DevRepoRow, files: &[GhFile], until: DateTime<Utc>) -> Vec<String> {
+async fn first_edits(h: &History<'_>, files: &[FileDiff], until: DateTime<Utc>) -> Vec<String> {
let since = until - Duration::days(FIRST_EDIT_DAYS);
let mut out = Vec::new();
for f in files.iter().filter(|f| f.status != "added").take(FIRST_EDIT_FILES) {
- let path = f.previous_filename.as_deref().unwrap_or(&f.filename);
- if let Ok(0) = client.dev_path_commits(&mode.repo, &mode.branch, path, since, until).await {
- out.push(f.filename.clone());
+ let path = f.previous_path.as_deref().unwrap_or(&f.path);
+ if let Ok(0) = h.path_commits(path, since, until).await {
+ out.push(f.path.clone());
}
}
out
}
-/// GitHub's files with their patches, cut so the patches add up to at most [`DIFF_CHARS`]: a
+/// The changed files with their patches, cut so the patches add up to at most [`DIFF_CHARS`]: a
/// patch that doesn't fit is dropped whole, and `cut` says how many files weren't read.
-pub fn cut_diffs(files: Vec<GhFile>) -> (Vec<FileDiff>, Option<String>) {
+pub fn cut_diffs(files: Vec<FileDiff>) -> (Vec<FileDiff>, Option<String>) {
let mut left = DIFF_CHARS;
let mut unread = 0;
let out = files
@@ -414,7 +499,7 @@ pub fn cut_diffs(files: Vec<GhFile>) -> (Vec<FileDiff>, Option<String>) {
}
None => None,
};
- FileDiff { path: f.filename, status: f.status, additions: f.additions, deletions: f.deletions, patch, previous_path: f.previous_filename }
+ FileDiff { patch, ..f }
})
.collect();
let cut = (unread > 0).then(|| format!("diff cut, {unread} {} not read", if unread == 1 { "file" } else { "files" }));
@@ -452,8 +537,9 @@ fn https(u: Option<&str>) -> Option<String> {
u.filter(|u| u.starts_with("https://")).map(str::to_string)
}
-fn to_checks(cs: Vec<GhCheck>) -> Vec<Check> {
- let mut v: Vec<Check> = cs.into_iter().map(|c| Check { name: c.name, status: c.status, conclusion: c.conclusion, url: https(c.html_url.as_deref()) }).collect();
+/// The checks with only https links, sorted by name so a re-read compares equal.
+fn to_checks(cs: Vec<Check>) -> Vec<Check> {
+ let mut v: Vec<Check> = cs.into_iter().map(|c| Check { url: https(c.url.as_deref()), ..c }).collect();
v.sort_by(|a, b| a.name.cmp(&b.name));
v
}
@@ -464,16 +550,16 @@ fn ci_link(checks: &[Check]) -> Option<String> {
checks.iter().find(bad).or(checks.first()).and_then(|c| c.url.clone())
}
-fn author_of(commit: Option<&GhCommit>, pr: Option<&GhPull>, kwants: &[Kwant]) -> Author {
- let login = pr.and_then(|p| p.user.as_ref()).or(commit.and_then(|c| c.author.as_ref())).map(|u| u.login.clone());
- let name = commit.map(|c| c.commit.author.name.clone()).filter(|n| !n.trim().is_empty()).or_else(|| login.clone()).unwrap_or_default();
- let email = commit.and_then(|c| c.commit.author.email.clone());
+fn author_of(commit: Option<&Commit>, pr: Option<&Change>, kwants: &[Kwant]) -> Author {
+ let login = pr.and_then(|p| p.author.clone()).or(commit.and_then(|c| c.login.clone()));
+ let name = commit.map(|c| c.author.name.clone()).filter(|n| !n.trim().is_empty()).or_else(|| login.clone()).unwrap_or_default();
+ let email = commit.and_then(|c| c.author.email.clone());
let bot = match_bot(&name, email.as_deref(), kwants);
Author { login, name, email, bot }
}
-pub fn landed_facts(mode: &DevRepoRow, c: &GhCommit, pr: Option<&GhPull>, files: Vec<GhFile>, checks: Vec<GhCheck>, kwants: &[Kwant], first: Vec<String>) -> DevFacts {
- let (msg_title, msg_body) = split_message(&c.commit.message);
+pub fn landed_facts(mode: &DevRepoRow, c: &Commit, pr: Option<&Change>, files: Vec<FileDiff>, checks: Vec<Check>, kwants: &[Kwant], first: Vec<String>) -> DevFacts {
+ let (msg_title, msg_body) = split_message(&c.message);
let (files, cut) = cut_diffs(files);
let checks = to_checks(checks);
DevFacts {
@@ -484,24 +570,24 @@ pub fn landed_facts(mode: &DevRepoRow, c: &GhCommit, pr: Option<&GhPull>, files:
body: pr.and_then(|p| p.body.clone()).unwrap_or(msg_body),
head_sha: c.sha.clone(),
base_branch: mode.branch.clone(),
- merged_at: pr.and_then(|p| p.merged_at).or(c.commit.committer.date),
- merged_by: pr.and_then(|p| p.merged_by.as_ref()).map(|u| u.login.clone()),
+ merged_at: pr.and_then(|p| p.merged_at).or(c.committer.date),
+ merged_by: pr.and_then(|p| p.merged_by.clone()),
author: author_of(Some(c), pr, kwants),
files,
cut,
ci: CiState::of(&checks),
- links: Links { pr: https(pr.and_then(|p| p.html_url.as_deref())), commit: https(c.html_url.as_deref()), ci: ci_link(&checks) },
+ links: Links { pr: https(pr.and_then(|p| p.url.as_deref())), commit: https(c.url.as_deref()), ci: ci_link(&checks) },
security: None,
checks,
task: None,
first_edit_files: first,
draft: false,
head_branch: None,
- pr_head_sha: pr.map(|p| p.head.sha.clone()),
+ pr_head_sha: pr.map(|p| p.head_sha.clone()),
}
}
-pub fn review_facts(mode: &DevRepoRow, p: &GhPull, head: Option<&GhCommit>, files: Vec<GhFile>, checks: Vec<GhCheck>, kwants: &[Kwant], first: Vec<String>) -> DevFacts {
+pub fn review_facts(mode: &DevRepoRow, p: &Change, head: Option<&Commit>, files: Vec<FileDiff>, checks: Vec<Check>, kwants: &[Kwant], first: Vec<String>) -> DevFacts {
let (files, cut) = cut_diffs(files);
let checks = to_checks(checks);
DevFacts {
@@ -510,21 +596,21 @@ pub fn review_facts(mode: &DevRepoRow, p: &GhPull, head: Option<&GhCommit>, file
pr: Some(p.number),
title: p.title.trim().to_string(),
body: p.body.clone().unwrap_or_default(),
- head_sha: p.head.sha.clone(),
- base_branch: p.base.branch.clone(),
+ head_sha: p.head_sha.clone(),
+ base_branch: p.base_branch.clone(),
merged_at: None,
merged_by: None,
author: author_of(head, Some(p), kwants),
files,
cut,
ci: CiState::of(&checks),
- links: Links { pr: https(p.html_url.as_deref()), commit: https(head.and_then(|c| c.html_url.as_deref())), ci: ci_link(&checks) },
+ links: Links { pr: https(p.url.as_deref()), commit: https(head.and_then(|c| c.url.as_deref())), ci: ci_link(&checks) },
security: None,
checks,
task: None,
first_edit_files: first,
draft: p.draft,
- head_branch: Some(p.head.branch.clone()),
+ head_branch: Some(p.head_branch.clone()),
pr_head_sha: None,
}
}
@@ -534,8 +620,8 @@ mod tests {
use super::*;
use serde_json::json;
- fn file(name: &str, patch_len: Option<usize>) -> GhFile {
- serde_json::from_value(json!({"filename": name, "status": "modified", "additions": 3, "deletions": 1, "patch": patch_len.map(|n| "x".repeat(n))})).unwrap()
+ fn file(name: &str, patch_len: Option<usize>) -> FileDiff {
+ FileDiff { path: name.into(), status: "modified".into(), additions: 3, deletions: 1, patch: patch_len.map(|n| "x".repeat(n)), previous_path: None }
}
fn kwant(id: &str, name: &str) -> Kwant {
@@ -547,24 +633,27 @@ mod tests {
.unwrap()
}
- fn pull(n: u64, merge: Option<&str>, merged: bool, base: &str) -> GhPull {
- serde_json::from_value(json!({
+ /// Built from GitHub's JSON, so the conversion is under test too.
+ fn pull(n: u64, merge: Option<&str>, merged: bool, base: &str) -> Change {
+ serde_json::from_value::<crate::zombie::github::GhPull>(json!({
"number": n, "title": format!("PR {n}"), "state": if merged { "closed" } else { "open" }, "draft": false,
"head": {"ref": "feature", "sha": "h1"}, "base": {"ref": base, "sha": "b1"},
"merged_at": if merged { json!("2026-11-05T01:00:00Z") } else { json!(null) },
"merge_commit_sha": merge,
}))
.unwrap()
+ .into()
}
- fn commit(sha: &str) -> GhCommit {
- serde_json::from_value(json!({
+ fn commit(sha: &str) -> Commit {
+ serde_json::from_value::<crate::zombie::github::GhCommit>(json!({
"sha": sha, "html_url": format!("https://github.com/demo-org/app/commit/{sha}"),
"commit": {"message": "Fix the thing\n\nLonger words.", "author": {"name": "Lin (kwant bot)", "email": "[email protected]", "date": "2026-11-05T01:00:00Z"},
"committer": {"name": "GitHub", "email": "[email protected]", "date": "2026-11-05T01:00:00Z"}},
"parents": []
}))
.unwrap()
+ .into()
}
#[test]
@@ -598,7 +687,7 @@ mod tests {
#[test]
fn the_first_poll_backfills_five_and_later_ones_twenty() {
- let cs: Vec<GhCommit> = (0..30).map(|i| commit(&format!("c{i:02}"))).collect();
+ let cs: Vec<Commit> = (0..30).map(|i| commit(&format!("c{i:02}"))).collect();
let w = window(cs.clone(), true, false);
assert_eq!(w.iter().map(|c| c.sha.as_str()).collect::<Vec<_>>(), ["c25", "c26", "c27", "c28", "c29"]);
let w = window(cs.clone(), false, true);
@@ -632,16 +721,17 @@ mod tests {
polled_at: None,
poll_error: None,
added_by: "team".into(),
+ git_url: None,
added_at: Utc::now(),
};
let c = commit("m1");
let mut p = pull(7, Some("m1"), true, "main");
- p.html_url = Some("javascript:alert(1)".into());
- let checks: Vec<GhCheck> = serde_json::from_value(json!([
+ p.url = Some("javascript:alert(1)".into());
+ let checks: Vec<Check> = crate::server::dev::source::all(serde_json::from_value::<Vec<crate::zombie::github::GhCheck>>(json!([
{"name": "rust", "status": "completed", "conclusion": "failure", "html_url": "https://github.com/demo-org/app/actions/runs/1"},
{"name": "frontend", "status": "completed", "conclusion": "success", "html_url": "https://github.com/demo-org/app/actions/runs/2"}
]))
- .unwrap();
+ .unwrap());
let f = landed_facts(&mode, &c, Some(&p), vec![file("src/a.rs", Some(10))], checks, &[kwant("k1", "Lin")], vec!["src/a.rs".into()]);
assert_eq!(f.pr, Some(7));
assert_eq!(f.title, "PR 7");
diff --git a/src/server/dev/repo.rs b/src/server/dev/repo.rs
index 6ee0e5d4..78b8a794 100644
--- a/src/server/dev/repo.rs
+++ b/src/server/dev/repo.rs
@@ -3,6 +3,7 @@
//! with its teams (team-repos.md T3, T4). Repos are read through the Loose ends GitHub connection
//! (its vault token and Enterprise `api_base`). kwant writes nothing to GitHub.
+use super::git;
use crate::db::dev_mode::{DevRepoRow, RepoAdd, BY_HAND, BY_MIGRATION, BY_TEAM, MAX_REPOS};
use crate::db::spaces::SpaceId;
use crate::server::AppState;
@@ -220,6 +221,11 @@ pub struct Source {
/// What dedupes sources: `host/repo` lowercased, or the folder for a `local` one.
#[serde(skip)]
key: String,
+ /// What git reads it from (any-git.md G1): the link's or remote's URL without its userinfo
+ /// ([`git::fetch_url`]), or the folder itself (an absolute path) for a `local` source.
+ /// `None` when git couldn't read it. Never sent to the browser.
+ #[serde(skip)]
+ pub fetch: Option<String>,
}
impl Source {
@@ -245,6 +251,12 @@ impl Source {
}
}
+ /// The key of its watched row: [`Self::key`] for a remote, [`Self::api_key`] for a `local`
+ /// source (so no folder path is stored as a key or shown).
+ pub fn row_key(&self) -> String {
+ self.api_key()
+ }
+
/// What [`check`] takes for this source: `host/owner/name`.
pub fn check_input(&self) -> String {
match &self.host {
@@ -369,7 +381,10 @@ async fn git(dir: &std::path::Path, args: &[&str]) -> Option<String> {
/// What a team folder's git says: its remote's URL (`origin`, else the first remote; `None` when
/// it has none) and its default branch. `None` when the folder isn't a git checkout.
pub async fn read_folder(dir: &std::path::Path) -> Option<(Option<String>, Option<String>)> {
- if !dir.join(".git").exists() {
+ // Only the folder's own repo: a `.git` symlink or `gitdir:` file naming another repo would
+ // show that repo's remote and branch here (G2 delta D1)
+ let d = dir.to_path_buf();
+ if !matches!(tokio::task::spawn_blocking(move || git::own_git_dir(&d)).await, Ok(Ok(_))) {
return None;
}
// A folder git can't open (dubious ownership, a broken .git) counts as no checkout
@@ -413,25 +428,29 @@ pub async fn detect_teams(teams: &[TeamRef<'_>], space_dir: &std::path::Path, gh
let read = read_folder(&folder).await;
let branch = read.as_ref().and_then(|(_, b)| b.clone());
let found = if let Some((host, repo)) = link.and_then(|l| source_repo(l, gh_hosts, true)) {
- Some((Some(host), repo, "repo"))
+ Some((Some(host), repo, "repo", link.and_then(git::remote_url)))
} else if let Some((url, _)) = &read {
- match url.as_deref().and_then(|u| source_repo(u, gh_hosts, false)) {
- Some((host, repo)) => Some((Some(host), repo, "folder")),
+ match url.as_deref().and_then(|u| source_repo(u, gh_hosts, false).map(|hr| (hr, u))) {
+ Some(((host, repo), u)) => Some((Some(host), repo, "folder", git::remote_url(u))),
// A checkout with no remote, or one that isn't a URL (another folder)
- None => folder.file_name().map(|n| (None, n.to_string_lossy().to_string(), "local")),
+ None => folder.file_name().map(|n| (None, n.to_string_lossy().to_string(), "local", None)),
}
} else {
None
};
- let Some((host, repo, from)) = found else { continue };
+ let Some((host, repo, from, mut fetch)) = found else { continue };
let key = match &host {
Some(h) => format!("{h}/{repo}").to_lowercase(),
- None => format!("local:{}", std::fs::canonicalize(&folder).unwrap_or(folder.clone()).display()),
+ None => {
+ let real = std::fs::canonicalize(&folder).unwrap_or(folder.clone());
+ fetch = real.to_str().filter(|p| p.starts_with('/')).map(str::to_string);
+ format!("local:{}", real.display())
+ }
};
if out.iter().any(|s| s.key == key) {
continue;
}
- out.push(Source { team: t.name.to_string(), team_id: t.id.to_string(), repo, host, from, branch, key });
+ out.push(Source { team: t.name.to_string(), team_id: t.id.to_string(), repo, host, from, branch, key, fetch });
}
out
}
@@ -482,9 +501,12 @@ pub struct Reconciled {
/// one GitHub doesn't answer for is added with the folder's branch (the poller says why);
/// - while on, a row with no branch yet (added while off) gets the repo's default branch.
///
+/// - while on and git is on the server, each other source (GitLab, Gitea, a bare git server, a
+/// `local` folder) with no row gets a git row ([`crate::db::dev_mode::GIT`], any-git.md G1): the
+/// poller reads it with git alone and makes landed cards. Without git it gets none (`no_git`).
+///
/// Existing rows are never checked again here: the poller reports their errors. Off, nothing is
-/// fetched (D12). A space with no Dev mode row is left alone. Non-GitHub and `local` sources never
-/// get a row: they show as `other_host`.
+/// fetched (D12). A space with no Dev mode row is left alone. A removed row's git mirror is deleted.
pub async fn reconcile(state: &AppState, space: &SpaceId) -> Reconciled {
let _one = reconcile_lock().lock().await;
reconciled().lock().unwrap().insert(space.as_str().to_string(), std::time::Instant::now());
@@ -523,11 +545,12 @@ pub async fn reconcile(state: &AppState, space: &SpaceId) -> Reconciled {
rows = db.dev_repos(sp).await.unwrap_or(rows);
for r in &rows {
- let source = gh.iter().find(|s| s.key == r.key);
+ let source = if r.is_git() { sources.iter().find(|s| !s.on_github(&hosts) && s.row_key() == r.key) } else { gh.iter().copied().find(|s| s.key == r.key) };
match (r.added_by.as_str(), source) {
// A team row whose team no longer points at it
(BY_TEAM, None) => {
if matches!(db.delete_dev_repo(sp, &r.key).await, Ok(true)) {
+ git::remove_mirror(&state.config.data_dir, sp, &r.key).await;
tracing::info!(space = %space, repo = %r.repo, "dev: stopped watching a repo no team points at");
out.removed.push(r.key.clone());
}
@@ -552,8 +575,9 @@ pub async fn reconcile(state: &AppState, space: &SpaceId) -> Reconciled {
// Rows added while off have no branch yet. One the check can't read keeps no branch (the
// poller skips it) and records why, so the desk shows an error, not watching (QA g); the next
- // reconcile checks again, and setting the branch clears the error.
- for r in rows.iter().filter(|r| r.branch.trim().is_empty()) {
+ // reconcile checks again, and setting the branch clears the error. A git row's branch is read
+ // by the poller, which records its own errors.
+ for r in rows.iter().filter(|r| r.branch.trim().is_empty() && !r.is_git()) {
let why = match check(state, space, &r.check_input()).await {
Ok(found) if found.state == "found" => {
let branch = found.branch.clone().unwrap_or_else(|| "main".into());
@@ -609,6 +633,31 @@ pub async fn reconcile(state: &AppState, space: &SpaceId) -> Reconciled {
}
rows = db.dev_repos(sp).await.unwrap_or(rows);
}
+ // Repos GitHub's API can't read: git reads them
+ if git::available().await {
+ for s in sources.iter().filter(|s| !s.on_github(&hosts)) {
+ let key = s.row_key();
+ let Some(url) = s.fetch.as_deref() else { continue };
+ if rows.iter().any(|r| r.key == key) {
+ continue;
+ }
+ if rows.len() >= MAX_REPOS {
+ out.too_many.push(key);
+ continue;
+ }
+ let branch = s.branch.as_deref().unwrap_or("");
+ match db.add_dev_repo_git(sp, &key, Some(&s.team_id), &s.repo, s.host.as_deref(), branch, url, BY_TEAM).await {
+ Ok(RepoAdd::Added) => {
+ tracing::info!(space = %space, repo = %s.repo, "dev: watching a team's repo with git");
+ out.added.push(key);
+ }
+ Ok(RepoAdd::Kept) => {}
+ Ok(RepoAdd::TooMany) => out.too_many.push(key),
+ Err(e) => tracing::warn!(space = %space, "dev: could not add a repo: {e}"),
+ }
+ rows = db.dev_repos(sp).await.unwrap_or(rows);
+ }
+ }
if !out.added.is_empty() {
super::poller::poll_soon(state, sp);
}
@@ -653,25 +702,31 @@ impl CheckInput for DevRepoRow {
}
/// The desk's line (plan any-git.md S4), from whether Dev mode is on, the watched repo (`""`:
-/// none), the detected sources and whether a GitHub connection exists:
-/// - `watching`: a repo is watched (or, while off, would be: a GitHub source and a connection);
+/// none), the detected sources, whether a GitHub connection exists and whether git is on the
+/// server ([`git::available`]):
+/// - `watching`: a repo is watched (or, while off, would be: a GitHub source and a connection, or
+/// any other source git reads);
/// - `no_repo`: no team points at a git repo;
/// - `not_connected`: a GitHub source that no connection reads;
-/// - `other_host`: only non-GitHub or `local` sources, read from 0.7.2.
-pub fn status(on: bool, watched: &str, sources: &[Source], gh_hosts: &[String], connected: bool) -> &'static str {
+/// - `no_git`: only non-GitHub or `local` sources, and no git on the server to read them
+/// ([`git::INSTALL_HINT`]). 0.7.2's `other_host` is retired: git reads those hosts now.
+pub fn status(on: bool, watched: &str, sources: &[Source], gh_hosts: &[String], connected: bool, git: bool) -> &'static str {
+ let github = sources.iter().any(|s| s.on_github(gh_hosts));
+ let other = sources.iter().any(|s| !s.on_github(gh_hosts) && s.fetch.is_some());
if !watched.is_empty() {
"watching"
} else if sources.is_empty() {
"no_repo"
- } else if sources.iter().any(|s| s.on_github(gh_hosts)) {
+ } else if (github && !on && connected) || (other && git) {
+ "watching"
+ } else if github {
// On with no repo means switching on found none a connection reads
- if !on && connected {
- "watching"
- } else {
- "not_connected"
- }
+ "not_connected"
+ } else if git {
+ // Sources git can't fetch from (an unknown URL scheme)
+ "no_repo"
} else {
- "other_host"
+ "no_git"
}
}
@@ -906,20 +961,94 @@ mod tests {
assert_eq!(got.len(), 1);
}
+ /// Another team's private checkout (G2 delta D1): its remote carries a token and its branch a
+ /// name only that team should see.
+ fn victim(root: &std::path::Path) -> std::path::PathBuf {
+ let t = fake_token();
+ checkout(root, "victim", "b-private-branch", &[("origin", &format!("https://bob:{t}@git.example.org/b/private.git"))])
+ }
+
+ /// What a team's folder detection must never show: the other repo, its branch or its token.
+ fn shows_nothing_of(got: &[Source], what: &str) {
+ let out = format!("{got:?}");
+ assert!(got.is_empty(), "{what}: detected {out}");
+ for leak in ["private", "b-private-branch", "git.example.org", &fake_token()] {
+ assert!(!out.contains(leak), "{what}: {leak} leaked");
+ }
+ }
+
+ #[tokio::test]
+ async fn a_team_folder_whose_git_is_a_symlink_to_another_repo_is_not_detected() {
+ let tmp = tempfile::tempdir().unwrap();
+ let root = tmp.path();
+ let v = victim(root);
+ let a = root.join("team-a");
+ std::fs::create_dir_all(&a).unwrap();
+ std::os::unix::fs::symlink(v.join(".git"), a.join(".git")).unwrap();
+ let a = a.to_string_lossy();
+ shows_nothing_of(&detect_teams(&[team("A", Some(&a), None)], root, &gh()).await, ".git symlink");
+ assert!(read_folder(std::path::Path::new(&*a)).await.is_none());
+ }
+
+ #[tokio::test]
+ async fn a_team_folder_whose_git_file_names_another_repo_is_not_detected() {
+ let tmp = tempfile::tempdir().unwrap();
+ let root = tmp.path();
+ let v = victim(root);
+ let a = root.join("team-a");
+ let r = root.join("team-r");
+ for (dir, target) in [(&a, v.join(".git").to_string_lossy().to_string()), (&r, "../victim/.git".to_string())] {
+ std::fs::create_dir_all(dir).unwrap();
+ std::fs::write(dir.join(".git"), format!("gitdir: {target}\n")).unwrap();
+ }
+ let (a, r) = (a.to_string_lossy(), r.to_string_lossy());
+ shows_nothing_of(&detect_teams(&[team("A", Some(&a), None)], root, &gh()).await, "gitdir: absolute");
+ shows_nothing_of(&detect_teams(&[team("R", Some(&r), None)], root, &gh()).await, "gitdir: relative");
+ }
+
+ #[tokio::test]
+ async fn a_real_worktree_is_still_detected_and_one_borrowing_its_gitdir_is_not() {
+ let tmp = tempfile::tempdir().unwrap();
+ let root = tmp.path();
+ let main = checkout(root, "main", "main", &[("origin", "https://git.example.org/team/app.git")]);
+ sh_git(&main, &["-c", "user.name=t", "-c", "[email protected]", "commit", "-q", "--allow-empty", "-m", "first"]);
+ let wt = root.join("wt");
+ sh_git(&main, &["worktree", "add", "-q", "-b", "feature", wt.to_str().unwrap()]);
+ assert!(wt.join(".git").is_file(), "git wrote a .git file");
+ // Same `gitdir:` line as the real worktree, but the git dir points back at `wt`, not here
+ let forged = root.join("forged");
+ std::fs::create_dir_all(&forged).unwrap();
+ std::fs::copy(wt.join(".git"), forged.join(".git")).unwrap();
+ let (w, f) = (wt.to_string_lossy(), forged.to_string_lossy());
+ // The forged team comes first: had it been detected, it would take the repo from `wt`
+ let got = detect_teams(&[team("Forged", Some(&f), None), team("Wt", Some(&w), None)], root, &gh()).await;
+ assert_eq!(brief(&got), vec![("Wt".into(), "team/app".into(), Some("git.example.org".into()), "folder", Some("feature".into()))]);
+ // An ordinary checkout still reads as before
+ let m = main.to_string_lossy();
+ assert_eq!(brief(&detect_teams(&[team("Main", Some(&m), None)], root, &gh()).await), vec![("Main".into(), "team/app".into(), Some("git.example.org".into()), "folder", Some("main".into()))]);
+ }
+
#[test]
fn the_status_says_what_the_desk_shows() {
- let src = |host: Option<&str>| Source { team: "T".into(), team_id: "t".into(), repo: "o/r".into(), host: host.map(str::to_string), from: "folder", branch: None, key: String::new() };
+ let src = |host: Option<&str>| Source { team: "T".into(), team_id: "t".into(), repo: "o/r".into(), host: host.map(str::to_string), from: "folder", branch: None, key: String::new(), fetch: Some("https://x.example/o/r".into()) };
let github = [src(Some("github.com"))];
let gitlab = [src(Some("gitlab.com")), src(None)];
- assert_eq!(status(true, "o/r", &github, &gh(), false), "watching");
- assert_eq!(status(true, "", &[], &gh(), false), "no_repo");
- assert_eq!(status(false, "", &[], &gh(), true), "no_repo");
- assert_eq!(status(true, "", &github, &gh(), true), "not_connected", "on with no repo: no connection read it");
- assert_eq!(status(false, "", &github, &gh(), false), "not_connected");
- assert_eq!(status(false, "", &github, &gh(), true), "watching", "off: turning on would watch it");
- assert_eq!(status(true, "", &gitlab, &gh(), true), "other_host");
+ assert_eq!(status(true, "o/r", &github, &gh(), false, true), "watching");
+ assert_eq!(status(true, "", &[], &gh(), false, true), "no_repo");
+ assert_eq!(status(false, "", &[], &gh(), true, true), "no_repo");
+ assert_eq!(status(true, "", &github, &gh(), true, true), "not_connected", "on with no repo: no connection read it");
+ assert_eq!(status(false, "", &github, &gh(), false, true), "not_connected");
+ assert_eq!(status(false, "", &github, &gh(), true, true), "watching", "off: turning on would watch it");
+ assert_eq!(status(true, "", &gitlab, &gh(), true, true), "watching", "git reads other hosts");
+ assert_eq!(status(true, "", &gitlab, &gh(), true, false), "no_git");
+ assert_eq!(status(false, "", &gitlab, &gh(), false, true), "watching", "off: turning on would watch it");
+ let mixed = [src(Some("github.com")), src(Some("gitlab.com"))];
+ assert_eq!(status(true, "", &mixed, &gh(), false, false), "not_connected");
+ assert_eq!(status(true, "", &mixed, &gh(), false, true), "watching");
+ let unread = [Source { fetch: None, ..src(Some("gitlab.com")) }];
+ assert_eq!(status(true, "", &unread, &gh(), false, true), "no_repo", "nothing git can fetch");
// A GitHub Enterprise host is GitHub
let ghe = vec!["github.com".to_string(), "gitlab.com".to_string()];
- assert_eq!(status(true, "", &gitlab, &ghe, false), "not_connected");
+ assert_eq!(status(true, "", &gitlab, &ghe, false, false), "not_connected");
}
}
diff --git a/src/server/dev/review.rs b/src/server/dev/review.rs
index 89d3bf7a..a13e7db2 100644
--- a/src/server/dev/review.rs
+++ b/src/server/dev/review.rs
@@ -426,7 +426,6 @@ mod tests {
#[tokio::test]
async fn j_f_a_secret_or_a_missing_package_from_the_scan_forces_high() {
use super::super::scan::{self, testkit::*, Config, State};
- use crate::zombie::github::GhFile;
let _l = port_lock().await;
let (archive, a, b) = fake_release(&fake_gitleaks(""));
let mock = serve(move |r| {
@@ -452,7 +451,7 @@ mod tests {
gitleaks_timeout: std::time::Duration::from_secs(20),
registries: scan::packages::Registries::all_at(&mock.base),
};
- let gh = |path: &str, patch: String| GhFile { filename: path.into(), status: "added".into(), additions: 1, deletions: 0, patch: Some(patch), previous_filename: None };
+ let gh = |path: &str, patch: String| FileDiff { path: path.into(), status: "added".into(), additions: 1, deletions: 0, patch: Some(patch), previous_path: None };
let base = review_facts(290);
let (_, quiet) = card::<Stub>(&base, None, None).await;
assert_eq!(quiet["risk"]["level"], "low", "the fixture alone is Low");
diff --git a/src/server/dev/routes.rs b/src/server/dev/routes.rs
index 8854ae8d..64435fb5 100644
--- a/src/server/dev/routes.rs
+++ b/src/server/dev/routes.rs
@@ -66,7 +66,7 @@ struct Entry<'a> {
/// team order (with its row, if any), then hand rows not tied to a source (oldest first), then team
/// rows no team points at any more.
fn entries<'a>(rows: &'a [DevRepoRow], sources: &'a [repo::Source]) -> Vec<Entry<'a>> {
- let mut out: Vec<Entry> = sources.iter().map(|s| Entry { source: Some(s), row: rows.iter().find(|r| s.host.is_some() && r.key == s.key()) }).collect();
+ let mut out: Vec<Entry> = sources.iter().map(|s| Entry { source: Some(s), row: rows.iter().find(|r| r.key == s.row_key()) }).collect();
let tied = |r: &DevRepoRow| out_has(sources, r);
out.extend(rows.iter().filter(|r| r.added_by != BY_TEAM && !tied(r)).map(|r| Entry { source: None, row: Some(r) }));
out.extend(rows.iter().filter(|r| r.added_by == BY_TEAM && !tied(r)).map(|r| Entry { source: None, row: Some(r) }));
@@ -74,7 +74,7 @@ fn entries<'a>(rows: &'a [DevRepoRow], sources: &'a [repo::Source]) -> Vec<Entry
}
fn out_has(sources: &[repo::Source], r: &DevRepoRow) -> bool {
- sources.iter().any(|s| s.host.is_some() && s.key() == r.key)
+ sources.iter().any(|s| s.row_key() == r.key)
}
/// The space's rows in the API's order: the first is the one the deprecated top-level fields,
@@ -100,16 +100,21 @@ pub async fn mode_json(state: &AppState, space: &SpaceId) -> Result<Value, Respo
// Only while off does a source with no row hang on a connection existing
let ask = !on && list.iter().any(|e| e.row.is_none() && e.source.is_some_and(|s| s.on_github(&hosts)));
let connected = ask && repo::clients(state).await.is_ok();
- // A row whose poll failed because no connection reads GitHub any more (deleted, or the vault
- // locked) needs the connection, not a retry: it reads not_connected (QA h)
- let lost = rows.iter().any(|r| r.poll_error.is_some()) && repo::clients(state).await.is_err();
+ // A GitHub row whose poll failed because no connection reads GitHub any more (deleted, or the
+ // vault locked) needs the connection, not a retry: it reads not_connected (QA h). A git row
+ // never needs one.
+ let lost = rows.iter().any(|r| r.poll_error.is_some() && !r.is_git()) && repo::clients(state).await.is_err();
+ let git = super::git::available().await;
let mut repos = Vec::new();
for e in &list {
let status = match (e.row, e.source) {
- (Some(r), _) if r.poll_error.is_some() && lost => "not_connected",
+ (Some(r), _) if r.poll_error.is_some() && lost && !r.is_git() => "not_connected",
(Some(r), _) if r.poll_error.is_some() => "error",
(Some(_), _) => "watching",
- (None, Some(s)) if !s.on_github(&hosts) => "other_host",
+ // Git reads every other host (any-git.md G1); a row comes at switch-on
+ (None, Some(s)) if !s.on_github(&hosts) && !git => "no_git",
+ (None, Some(s)) if !s.on_github(&hosts) && s.fetch.is_none() => "no_repo",
+ (None, Some(s)) if !s.on_github(&hosts) && (!on || rows.len() < crate::db::dev_mode::MAX_REPOS) => "watching",
(None, _) if rows.len() >= crate::db::dev_mode::MAX_REPOS => "too_many",
(None, _) if !on && connected => "watching",
(None, _) => "not_connected",
@@ -119,6 +124,12 @@ pub async fn mode_json(state: &AppState, space: &SpaceId) -> Result<Value, Respo
(None, Some(s)) => (s.api_key(), s.repo.clone(), s.host.clone()),
(None, None) => continue,
};
+ // How it's read: the API and git (`github`, GitHub Enterprise too), or git alone (`git`)
+ let provider = match (e.row, e.source) {
+ (Some(r), _) if r.is_git() => "git",
+ (None, Some(s)) if !s.on_github(&hosts) => "git",
+ _ => "github",
+ };
let team_id = match (e.source, e.row) {
(Some(s), _) => Some(s.team_id.clone()),
(None, Some(r)) => r.team.clone(),
@@ -136,9 +147,12 @@ pub async fn mode_json(state: &AppState, space: &SpaceId) -> Result<Value, Respo
"team": team_name(team_id.as_deref()),
"team_id": team_id,
"from": from,
+ "provider": provider,
"branch": e.row.map(|r| &r.branch).filter(|b| !b.is_empty()),
"status": status,
"poll_error": e.row.and_then(|r| r.poll_error.clone()),
+ // A code for the one error the desk words differently; null for the rest
+ "poll_code": e.row.and_then(|r| r.poll_error.as_deref()).and_then(super::git::GitError::poll_code),
"polled_at": e.row.and_then(|r| r.polled_at),
"last_tag": e.row.and_then(|r| poller::last_tag(space.as_str(), &r.key)),
"added_by": e.row.map(|r| r.added_by_shown()),
@@ -167,8 +181,11 @@ pub async fn mode_json(state: &AppState, space: &SpaceId) -> Result<Value, Respo
} else if any_unread {
"not_connected"
} else {
- repo::status(on, "", &sources, &hosts, connected)
+ repo::status(on, "", &sources, &hosts, connected, git)
});
+ if v["status"] == "no_git" {
+ v["install_hint"] = json!(super::git::INSTALL_HINT);
+ }
v["sources"] = json!(sources);
v["new_reviews"] = json!(new_reviews(state, row.as_ref()).await);
// Where a review would be posted, and as whom (post-to-github.md P7 and its amendment)
@@ -298,6 +315,34 @@ async fn branch_exists(state: &AppState, repo_name: &str, branch: &str) -> Resul
}
}
+/// [`branch_exists`] for a watched row: a git row asks git (its folder, or its remote), a GitHub
+/// row asks GitHub.
+#[allow(clippy::result_large_err)]
+async fn row_branch_exists(state: &AppState, row: &DevRepoRow, branch: &str) -> Result<(), Response> {
+ use super::git::{self, Repo};
+ if !row.is_git() {
+ return branch_exists(state, &row.repo, branch).await;
+ }
+ let from = row.git_url.as_deref().unwrap_or_default();
+ let found = if from.starts_with('/') {
+ match Repo::local(std::path::Path::new(from), &state.config.data_dir).await {
+ Ok(g) => g.has_branch("", branch, None).await,
+ Err(e) => Err(e),
+ }
+ } else {
+ match Repo::mirror(&state.config.data_dir, &row.space_id, &row.key).await {
+ Ok(g) => g.has_branch(from, branch, None).await,
+ Err(e) => Err(e),
+ }
+ };
+ match found {
+ Ok(true) => Ok(()),
+ Ok(false) => Err(coded(StatusCode::BAD_REQUEST, "no_branch", format!("{} has no branch {branch}", row.repo))),
+ Err(git::GitError::NoGit) => Err(coded(StatusCode::BAD_GATEWAY, "no_git", git::INSTALL_HINT)),
+ Err(e) => Err(coded(StatusCode::BAD_GATEWAY, "git", e.to_string())),
+ }
+}
+
pub async fn put_mode(State(state): State<AppState>, headers: HeaderMap, Path(id): Path<String>, Json(body): Json<PutBody>) -> Response {
let space = match guard(&state, &headers, &id).await {
Ok(s) => s,
@@ -403,7 +448,7 @@ pub async fn put_mode(State(state): State<AppState>, headers: HeaderMap, Path(id
Ok(Some(r)) => {
if let Some(b) = asked_branch.filter(|b| *b != r.branch) {
if on {
- if let Err(resp) = branch_exists(&state, &r.repo, b).await {
+ if let Err(resp) = row_branch_exists(&state, &r, b).await {
return resp;
}
}
@@ -449,7 +494,7 @@ pub async fn put_mode(State(state): State<AppState>, headers: HeaderMap, Path(id
if let (Some(b), Some(first)) = (asked_branch, ordered_rows(&rows_before, &sources).first()) {
if b != first.branch {
if on {
- if let Err(resp) = branch_exists(&state, &first.repo, b).await {
+ if let Err(resp) = row_branch_exists(&state, first, b).await {
return resp;
}
}
@@ -464,7 +509,7 @@ pub async fn put_mode(State(state): State<AppState>, headers: HeaderMap, Path(id
let rows = state.db.dev_repos(sp).await.unwrap_or_default();
if let Some(r) = rows.iter().find(|r| r.team.as_deref() == Some(team_id.as_str()) && r.branch != b) {
if on {
- if let Err(resp) = branch_exists(&state, &r.repo, b).await {
+ if let Err(resp) = row_branch_exists(&state, r, b).await {
return resp;
}
}
@@ -627,7 +672,9 @@ pub async fn landed(State(state): State<AppState>, headers: HeaderMap, Path(id):
Err(e) => return internal(e),
};
let reviews = open_reviews(&state, &space, only.as_deref()).await.unwrap_or_default();
- let rollup = rollup(&recent, &reviews, mode.as_ref().and_then(|m| m.seen_at), Utc::now());
+ // Repos read with git alone have no CI to read
+ let no_ci: Vec<String> = state.db.dev_repos(space.as_str()).await.unwrap_or_default().into_iter().filter(|r| r.is_git()).map(|r| r.key).collect();
+ let rollup = rollup(&recent, &reviews, &no_ci, mode.as_ref().and_then(|m| m.seen_at), Utc::now());
// The repo asked for, else the first watched one (deprecated, like the top-level `repo`)
let tag_repo = match &only {
Some(k) => Some(k.clone()),
@@ -647,9 +694,10 @@ pub async fn landed(State(state): State<AppState>, headers: HeaderMap, Path(id):
/// - `count`: landed cards since then.
/// - `needs_you`: those with failed tests or a high risk, plus open reviews that are high risk or
/// have an open critical or high finding.
-/// - `main_green`: CI on the newest landed card (`null` when it has no checks or is pending).
+/// - `main_green`: CI on the newest landed card from a repo with CI (`null` when it has no checks or
+/// is pending, or when every landed card is from a repo in `no_ci`, read with git alone).
/// - `areas`: cards since then by `area`, newest area first, with the newest card's headline.
-pub fn rollup(landed: &[DevCardRow], reviews: &[DevCardRow], since: Option<DateTime<Utc>>, now: DateTime<Utc>) -> Value {
+pub fn rollup(landed: &[DevCardRow], reviews: &[DevCardRow], no_ci: &[String], since: Option<DateTime<Utc>>, now: DateTime<Utc>) -> Value {
let fresh: Vec<&DevCardRow> = landed.iter().filter(|r| since.is_none_or(|s| r.created_at > s)).collect();
let card = |r: &DevCardRow| r.card.as_deref().and_then(|c| serde_json::from_str::<Value>(c).ok()).unwrap_or(Value::Null);
let mut needs = 0usize;
@@ -666,7 +714,7 @@ pub fn rollup(landed: &[DevCardRow], reviews: &[DevCardRow], since: Option<DateT
needs += 1;
}
}
- let main_green = landed.first().and_then(|r| serde_json::from_str::<DevFacts>(&r.facts).ok()).and_then(|f| match f.ci {
+ let main_green = landed.iter().find(|r| !no_ci.contains(&r.repo)).and_then(|r| serde_json::from_str::<DevFacts>(&r.facts).ok()).and_then(|f| match f.ci {
CiState::Green => Some(true),
CiState::Red => Some(false),
_ => None,
@@ -1143,16 +1191,32 @@ mod tests {
row(REVIEW, Some(json!({"risk": {"level": "low"}, "findings": [{"state": "open", "severity": "high"}]})), facts("none"), h(1)),
row(REVIEW, Some(json!({"risk": {"level": "low"}, "findings": [{"state": "dismissed", "severity": "critical"}]})), facts("none"), h(1)),
];
- let v = rollup(&landed, &reviews, Some(h(24)), now);
+ let v = rollup(&landed, &reviews, &[], Some(h(24)), now);
assert_eq!(v["count"], 3);
assert_eq!(v["needs_you"], 3, "high risk, failed tests, a review with an open high finding");
assert_eq!(v["main_green"], true);
assert_eq!(v["areas"][0], json!({"area": "Sidebar", "count": 2, "first_headline": "B"}));
assert_eq!(v["areas"][1], json!({"area": "Other", "count": 1, "first_headline": null}));
- let all = rollup(&landed, &[], None, now);
+ let all = rollup(&landed, &[], &[], None, now);
assert_eq!(all["count"], 4);
assert_eq!(all["since"], Value::Null);
- assert_eq!(rollup(&[], &[], None, now)["main_green"], Value::Null);
+ assert_eq!(rollup(&[], &[], &[], None, now)["main_green"], Value::Null);
+ }
+
+ #[test]
+ fn main_green_never_comes_from_a_repo_read_with_git_alone() {
+ let now = Utc::now();
+ let h = |n: i64| now - chrono::Duration::hours(n);
+ let mut git_card = row(LANDED, None, facts("green"), h(1));
+ git_card.repo = "gitlab.example.com/group/ops".into();
+ let mut red = row(LANDED, None, facts("red"), h(2));
+ red.repo = "o/web".into();
+ let no_ci = ["gitlab.example.com/group/ops".to_string()];
+ // A git-only repo's card is skipped, even when it is the newest...
+ assert_eq!(rollup(&[git_card.clone(), red], &[], &no_ci, None, now)["main_green"], false);
+ // ...and with only git-only cards there's no CI to read
+ assert_eq!(rollup(&[git_card.clone()], &[], &no_ci, None, now)["main_green"], Value::Null);
+ assert_eq!(rollup(&[git_card], &[], &[], None, now)["main_green"], true, "without the list it's an ordinary card");
}
fn body(action: &str, reason: Option<&str>) -> FindingBody {
diff --git a/src/server/dev/scan/mod.rs b/src/server/dev/scan/mod.rs
index fea07216..5c7c7dc2 100644
--- a/src/server/dev/scan/mod.rs
+++ b/src/server/dev/scan/mod.rs
@@ -307,21 +307,20 @@ const MAX_FETCHED: usize = 20;
/// at `head_sha`, runs [`scan`], and hides the flagged lines in `files`' patches in place.
pub async fn for_review(
data_dir: &std::path::Path,
- client: &crate::zombie::github::GithubSource,
- repo: &str,
+ history: &crate::server::dev::source::History<'_>,
head_sha: &str,
- files: &mut [crate::zombie::github::GhFile],
+ files: &mut [FileDiff],
capped: bool,
) -> Security {
let mut contents = BTreeMap::new();
let wanted = files
.iter()
.filter(|f| f.status != "removed")
- .filter(|f| packages::manifest_kind(&f.filename).is_some() || (f.patch.is_none() && gitleaks::needs_text(&diff_of(f))))
+ .filter(|f| packages::manifest_kind(&f.path).is_some() || (f.patch.is_none() && gitleaks::needs_text(f)))
.take(MAX_FETCHED);
for f in wanted {
- if let Ok(Some(text)) = client.dev_file_at(repo, &f.filename, head_sha).await {
- contents.insert(f.filename.clone(), text);
+ if let Ok(Some(text)) = history.file_at(&f.path, head_sha).await {
+ contents.insert(f.path.clone(), text);
}
}
let capped = capped.then(|| format!("the PR has more than {} files; the rest weren't read", files.len()));
@@ -331,31 +330,20 @@ pub async fn for_review(
/// [`scan`], then the flagged added lines replaced in `files`' patches.
pub async fn scan_and_hide(
cfg: &Config,
- files: &mut [crate::zombie::github::GhFile],
+ files: &mut [FileDiff],
contents: BTreeMap<String, String>,
files_capped: Option<String>,
) -> Security {
- let input = Input { files: files.iter().map(diff_of).collect(), contents, files_capped };
+ let input = Input { files: files.to_vec(), contents, files_capped };
let out = scan(cfg, &input).await;
for f in files.iter_mut() {
- if let (Some(ranges), Some(p)) = (out.hide.get(&f.filename), f.patch.as_mut()) {
+ if let (Some(ranges), Some(p)) = (out.hide.get(&f.path), f.patch.as_mut()) {
*p = hide_lines(p, ranges);
}
}
out.security
}
-fn diff_of(f: &crate::zombie::github::GhFile) -> FileDiff {
- FileDiff {
- path: f.filename.clone(),
- status: f.status.clone(),
- additions: f.additions,
- deletions: f.deletions,
- patch: f.patch.clone(),
- previous_path: f.previous_filename.clone(),
- }
-}
-
#[cfg(test)]
pub(crate) mod testkit;
diff --git a/src/server/dev/scan/tests.rs b/src/server/dev/scan/tests.rs
index 55904728..ad2c320f 100644
--- a/src/server/dev/scan/tests.rs
+++ b/src/server/dev/scan/tests.rs
@@ -6,21 +6,15 @@ use super::gitleaks::{self, Source, Target, PINS};
use super::packages::{self, Eco, Registries};
use super::testkit::*;
use super::*;
-use crate::zombie::github::GhFile;
use chrono::{Duration as Days, TimeZone, Utc};
use serde_json::json;
use std::collections::{BTreeMap, BTreeSet};
use std::time::Duration;
-fn gh(path: &str, status: &str, patch: Option<&str>) -> GhFile {
+fn diff(path: &str, status: &str, patch: Option<&str>) -> FileDiff {
let adds = patch.map_or(0, |p| p.lines().filter(|l| l.starts_with('+')).count() as u64);
let dels = patch.map_or(0, |p| p.lines().filter(|l| l.starts_with('-')).count() as u64);
- GhFile { filename: path.into(), status: status.into(), additions: adds, deletions: dels, patch: patch.map(Into::into), previous_filename: None }
-}
-
-fn diff(path: &str, status: &str, patch: Option<&str>) -> FileDiff {
- let g = gh(path, status, patch);
- FileDiff { path: g.filename, status: g.status, additions: g.additions, deletions: g.deletions, patch: g.patch, previous_path: None }
+ FileDiff { path: path.into(), status: status.into(), additions: adds, deletions: dels, patch: patch.map(Into::into), previous_path: None }
}
/// A Config whose gitleaks comes from the mock, cached in `dir`, and whose registries all fail
@@ -216,7 +210,7 @@ async fn j_s2_the_value_is_hidden_from_facts_card_findings_and_fix_it_text() {
let (_mock, c) = fake(dir.path(), "").await;
let value = secret(424242);
let patch = format!("@@ -1,2 +1,4 @@\n use x;\n+// demo config for example.com\n+const KEY: &str = \"{value}\";\n fn f() {{}}");
- let mut files = vec![gh("src/config.rs", "modified", Some(&patch)), gh("README.md", "modified", Some("@@ -1 +1,2 @@\n # demo\n+More text."))];
+ let mut files = vec![diff("src/config.rs", "modified", Some(&patch)), diff("README.md", "modified", Some("@@ -1 +1,2 @@\n # demo\n+More text."))];
let sec = scan_and_hide(&c, &mut files, BTreeMap::new(), None).await;
assert_eq!(sec.secrets.state, State::Hit);
// The stored patch keeps its shape, with the line replaced
@@ -319,7 +313,7 @@ async fn j_s4_files_cut_from_the_models_60k_are_still_scanned() {
let big_patch = added_patch(&big.iter().map(String::as_str).collect::<Vec<_>>());
assert!(big_patch.len() > super::super::facts::DIFF_CHARS);
let late = added_patch(&["fn demo() {}", &format!("let k = \"{}\";", secret(7))]);
- let mut files = vec![gh("src/a_small.rs", "added", Some("@@ -0,0 +1 @@\n+fn a() {}")), gh("src/b_big.rs", "added", Some(&big_patch)), gh("src/c_late.rs", "added", Some(&late))];
+ let mut files = vec![diff("src/a_small.rs", "added", Some("@@ -0,0 +1 @@\n+fn a() {}")), diff("src/b_big.rs", "added", Some(&big_patch)), diff("src/c_late.rs", "added", Some(&late))];
let sec = scan_and_hide(&c, &mut files, BTreeMap::new(), None).await;
let (diffs, cut) = crate::server::dev::poller::cut_diffs(files);
assert!(cut.is_some() && diffs[1].patch.is_none(), "the big file is cut for the model");
@@ -771,7 +765,7 @@ async fn f_a_real_gitleaks_finds_and_hides_keys_in_paths_its_allowlist_skips() {
("docs/gitleaks.toml.md", format!("aws_access_key_id = \"{aws}\""), aws.clone()),
("package-lock.json", format!(" \"resolved\": \"https://demo:{ghp}@npm.pkg.github.com/demo/-/demo-1.0.0.tgz\","), ghp.clone()),
];
- let mut files: Vec<GhFile> = cases.iter().map(|(p, line, _)| gh(p, "added", Some(&added_patch(&["// demo", line])))).collect();
+ let mut files: Vec<FileDiff> = cases.iter().map(|(p, line, _)| diff(p, "added", Some(&added_patch(&["// demo", line])))).collect();
let sec = scan_and_hide(&c, &mut files, BTreeMap::new(), None).await;
assert_eq!(sec.secrets.state, State::Hit, "{:?}", sec.secrets);
assert!(sec.secrets.count >= 4, "{:?}", sec.secrets);
diff --git a/src/server/dev/source.rs b/src/server/dev/source.rs
new file mode 100644
index 00000000..cda74749
--- /dev/null
+++ b/src/server/dev/source.rs
@@ -0,0 +1,364 @@
+//! Host-neutral history types (any-git.md G3). The poller, `landed`, `review` and the scan read
+//! these, never a host's own shapes: a commit is a [`Commit`], a pull or merge request is a
+//! [`Change`], a changed file is a [`FileDiff`] and a CI run is a [`Check`]. Each host converts at
+//! its own boundary (GitHub's REST shapes below; git itself in `git`), so a card made from a plain
+//! git repo and one made from GitHub's API carry the same facts.
+
+use super::facts::{Check, FileDiff};
+use super::git::{Auth, GitError, Repo};
+use crate::zombie::github::{EtagCache, GhCheck, GhCommit, GhError, GhFile, GhGitPerson, GhPull, GithubSource};
+use chrono::{DateTime, Utc};
+
+/// A git author or committer.
+#[derive(Debug, Clone, PartialEq, Default)]
+pub struct Person {
+ pub name: String,
+ pub email: Option<String>,
+ pub date: Option<DateTime<Utc>>,
+}
+
+/// One commit. `files` is filled only on a single-commit read.
+#[derive(Debug, Clone, PartialEq, Default)]
+pub struct Commit {
+ pub sha: String,
+ /// The commit's web page, when the host has one.
+ pub url: Option<String>,
+ pub message: String,
+ pub author: Person,
+ pub committer: Person,
+ /// The host account that wrote it, when the host knows one (GitHub matches the email).
+ pub login: Option<String>,
+ pub parents: Vec<String>,
+ pub files: Vec<FileDiff>,
+}
+
+/// A pull request or merge request.
+#[derive(Debug, Clone, PartialEq, Default)]
+pub struct Change {
+ pub number: u64,
+ pub title: String,
+ pub body: Option<String>,
+ pub draft: bool,
+ pub url: Option<String>,
+ /// Who opened it.
+ pub author: Option<String>,
+ pub head_branch: String,
+ pub head_sha: String,
+ pub base_branch: String,
+ pub merged_at: Option<DateTime<Utc>>,
+ /// The commit its merge (or squash) put on the base branch.
+ pub merge_sha: Option<String>,
+ pub merged_by: Option<String>,
+ pub updated_at: Option<DateTime<Utc>>,
+}
+
+impl From<GhGitPerson> for Person {
+ fn from(p: GhGitPerson) -> Self {
+ Person { name: p.name, email: p.email, date: p.date }
+ }
+}
+
+impl From<GhFile> for FileDiff {
+ fn from(f: GhFile) -> Self {
+ FileDiff { path: f.filename, status: f.status, additions: f.additions, deletions: f.deletions, patch: f.patch, previous_path: f.previous_filename }
+ }
+}
+
+impl From<GhCheck> for Check {
+ /// The link as GitHub sent it; the poller keeps only https ones.
+ fn from(c: GhCheck) -> Self {
+ Check { name: c.name, status: c.status, conclusion: c.conclusion, url: c.html_url }
+ }
+}
+
+impl From<GhCommit> for Commit {
+ fn from(c: GhCommit) -> Self {
+ Commit {
+ sha: c.sha,
+ url: c.html_url,
+ message: c.commit.message,
+ author: c.commit.author.into(),
+ committer: c.commit.committer.into(),
+ login: c.author.map(|u| u.login),
+ parents: c.parents.iter().filter_map(|p| p["sha"].as_str().map(str::to_string)).collect(),
+ files: c.files.into_iter().map(Into::into).collect(),
+ }
+ }
+}
+
+impl From<GhPull> for Change {
+ fn from(p: GhPull) -> Self {
+ Change {
+ number: p.number,
+ title: p.title,
+ body: p.body,
+ draft: p.draft,
+ url: p.html_url,
+ author: p.user.map(|u| u.login),
+ head_branch: p.head.branch,
+ head_sha: p.head.sha,
+ base_branch: p.base.branch,
+ merged_at: p.merged_at,
+ merge_sha: p.merge_commit_sha,
+ merged_by: p.merged_by.map(|u| u.login),
+ updated_at: p.updated_at,
+ }
+ }
+}
+
+/// Converts a list at the host boundary.
+pub fn all<A, B: From<A>>(v: Vec<A>) -> Vec<B> {
+ v.into_iter().map(B::from).collect()
+}
+
+impl From<GitError> for GhError {
+ /// git's fixed words, as a poll error the desk shows.
+ fn from(e: GitError) -> Self {
+ GhError::Other(e.to_string())
+ }
+}
+
+/// Where a watched repo's history comes from (any-git.md G1): git first (a mirror kwant keeps, or
+/// a team folder's own `.git`), GitHub's API when git can't answer. Commits, diffs, files, tags,
+/// path history and root names all come through here; what only a forge knows (pull requests,
+/// checks) comes through [`Forge`].
+pub struct History<'a> {
+ git: Option<Repo>,
+ /// What the mirror fetches from (empty for a team folder), and the header that goes with it.
+ url: String,
+ auth: Option<Auth>,
+ api: Option<(&'a GithubSource, &'a str)>,
+ branch: String,
+ /// `<base>/<sha>` is a commit's web page.
+ commit_base: Option<String>,
+}
+
+impl<'a> History<'a> {
+ pub fn new(git: Option<Repo>, url: String, auth: Option<Auth>, api: Option<(&'a GithubSource, &'a str)>, branch: &str, commit_base: Option<String>) -> Self {
+ History { git, url, auth, api, branch: branch.to_string(), commit_base }
+ }
+
+ pub fn has_git(&self) -> bool {
+ self.git.is_some()
+ }
+
+ /// Brings the mirror up to date. When that fails and the API can answer, git is set aside for
+ /// this poll; without an API, the error is the poll's.
+ pub async fn fetch(&mut self) -> Result<(), GhError> {
+ let Some(g) = &self.git else { return Ok(()) };
+ match g.fetch(&self.url, &self.branch, self.auth.as_ref()).await {
+ Ok(()) => Ok(()),
+ Err(_) if self.api.is_some() => {
+ self.git = None;
+ Ok(())
+ }
+ Err(e) => Err(e.into()),
+ }
+ }
+
+ fn no_source() -> GhError {
+ GitError::Failed.into()
+ }
+
+ fn with_url(&self, mut c: Commit) -> Commit {
+ if c.url.is_none() {
+ c.url = self.commit_base.as_ref().map(|b| format!("{b}/{}", c.sha));
+ }
+ c
+ }
+
+ /// The tag nearest the branch tip and when its commit was made. `known` is what the last poll
+ /// saw: the API isn't asked for a date it already gave.
+ pub async fn latest_tag(&self, known: Option<&(String, Option<DateTime<Utc>>)>, cache: &EtagCache) -> Result<Option<(String, Option<DateTime<Utc>>)>, GhError> {
+ if let Some(g) = &self.git {
+ if let Ok(t) = g.latest_tag(&self.branch).await {
+ return Ok(t);
+ }
+ }
+ let (client, repo) = self.api.ok_or_else(Self::no_source)?;
+ let Some((name, sha)) = client.dev_latest_tag(repo, cache).await? else { return Ok(None) };
+ if let Some(k) = known.filter(|(n, at)| *n == name && at.is_some()) {
+ return Ok(Some(k.clone()));
+ }
+ let at = match sha {
+ Some(s) => client.dev_commit(repo, &s).await.ok().map(Commit::from).and_then(|c| c.committer.date.or(c.author.date)),
+ None => None,
+ };
+ Ok(Some((name, at)))
+ }
+
+ /// Commits on the branch newer than `last_seen`, oldest first, and whether `last_seen` was
+ /// found (see [`Repo::commits_since`]).
+ pub async fn commits_since(&self, last_seen: Option<&str>, cache: &EtagCache) -> Result<(Vec<Commit>, bool), GhError> {
+ if let Some(g) = &self.git {
+ match g.commits_since(&self.branch, last_seen).await {
+ Ok((list, found)) => return Ok((list.into_iter().map(|c| self.with_url(c)).collect(), found)),
+ Err(e) if self.api.is_none() => return Err(e.into()),
+ Err(_) => {}
+ }
+ }
+ let (client, repo) = self.api.ok_or_else(Self::no_source)?;
+ let (list, found) = client.dev_commits_since(repo, &self.branch, last_seen, cache).await?;
+ Ok((all(list), found))
+ }
+
+ /// One commit with its files against its first parent.
+ pub async fn commit(&self, sha: &str) -> Result<Commit, GhError> {
+ if let Some(g) = &self.git {
+ match g.commit(sha).await {
+ Ok(c) => return Ok(self.with_url(c)),
+ Err(e) if self.api.is_none() => return Err(e.into()),
+ Err(_) => {}
+ }
+ }
+ let (client, repo) = self.api.ok_or_else(Self::no_source)?;
+ Ok(client.dev_commit(repo, sha).await?.into())
+ }
+
+ /// What landed with `head`: the files from `base` (the commit before the merge, or before the
+ /// first commit of a rebase-merge) to `head`. `None` when git can't say (the caller asks the
+ /// forge for the PR's files instead).
+ pub async fn landed_files(&self, base: Option<&str>, head: &str) -> Option<Vec<FileDiff>> {
+ self.git.as_ref()?.diff(base, head).await.ok()
+ }
+
+ /// An open change's files, from where it grew off `base_branch` to its head, read from the
+ /// forge's head ref (`head_ref`, fetched into the mirror). `None` when git can't say.
+ pub async fn change_files(&self, head_ref: Option<&str>, number: u64, head_sha: &str, base_branch: &str) -> Option<Vec<FileDiff>> {
+ let g = self.git.as_ref()?;
+ let local = format!("refs/kwant/pull/{number}");
+ if g.resolve(head_sha).await.is_err() {
+ g.fetch_ref(&self.url, head_ref?, &local, self.auth.as_ref()).await.ok()?;
+ }
+ let got = async {
+ if g.resolve(head_sha).await.ok()? != head_sha {
+ return None;
+ }
+ let base = g.merge_base(&format!("refs/heads/{base_branch}"), head_sha).await.ok()?;
+ g.diff(Some(&base), head_sha).await.ok()
+ }
+ .await;
+ g.drop_ref(&local).await;
+ got
+ }
+
+ /// A text file at `sha` (see [`Repo::file_at`]).
+ pub async fn file_at(&self, path: &str, sha: &str) -> Result<Option<String>, GhError> {
+ if let Some(g) = &self.git {
+ match g.file_at(path, sha).await {
+ Ok(t) => return Ok(t),
+ Err(e) if self.api.is_none() => return Err(e.into()),
+ Err(_) => {}
+ }
+ }
+ let (client, repo) = self.api.ok_or_else(Self::no_source)?;
+ client.dev_file_at(repo, path, sha).await
+ }
+
+ /// How many commits on the branch touched `path` in the window (at most 2).
+ pub async fn path_commits(&self, path: &str, since: DateTime<Utc>, until: DateTime<Utc>) -> Result<usize, GhError> {
+ if let Some(g) = &self.git {
+ match g.path_commits(&self.branch, path, since, until).await {
+ Ok(n) => return Ok(n),
+ Err(e) if self.api.is_none() => return Err(e.into()),
+ Err(_) => {}
+ }
+ }
+ let (client, repo) = self.api.ok_or_else(Self::no_source)?;
+ client.dev_path_commits(repo, &self.branch, path, since, until).await
+ }
+
+ /// The names at the branch's root (for the deploy hint); git only.
+ pub async fn root_names(&self) -> Option<Vec<String>> {
+ self.git.as_ref()?.root_names(&self.branch).await.ok()
+ }
+}
+
+/// What only a forge knows about a repo: its pull or merge requests and CI checks (any-git.md
+/// G4 seam). GitHub's API implements it ([`GithubForge`]); a plain git repo has none, so its
+/// commits get landed cards without a PR, checks or review cards. GitLab and Gitea forges plug in
+/// here (Juno, G4-G5) without touching the poller.
+#[async_trait::async_trait]
+pub trait Forge: Send + Sync {
+ /// The changes `sha` belongs to (merged ones carry the merge sha).
+ async fn changes_for_commit(&self, sha: &str) -> Result<Vec<Change>, GhError>;
+ /// The open changes into `base`.
+ async fn open_changes(&self, base: &str, cache: &EtagCache) -> Result<Vec<Change>, GhError>;
+ /// The CI checks on `sha`.
+ async fn checks(&self, sha: &str, cache: &EtagCache) -> Result<Vec<Check>, GhError>;
+ /// A change's files as the forge lists them (when git can't read them).
+ async fn change_files(&self, number: u64) -> Result<Vec<FileDiff>, GhError>;
+ /// The ref git fetches a change's head from (`refs/pull/7/head`, `refs/merge-requests/7/head`).
+ fn change_head_ref(&self, number: u64) -> Option<String>;
+ /// The forge account that wrote `sha`, when the forge matches it (a direct push has no change
+ /// to name its author).
+ async fn commit_login(&self, sha: &str) -> Option<String>;
+}
+
+/// [`Forge`] over GitHub's REST API.
+pub struct GithubForge<'a> {
+ pub client: &'a GithubSource,
+ pub repo: &'a str,
+}
+
+#[async_trait::async_trait]
+impl Forge for GithubForge<'_> {
+ async fn changes_for_commit(&self, sha: &str) -> Result<Vec<Change>, GhError> {
+ Ok(all(self.client.dev_pulls_for_commit(self.repo, sha).await?))
+ }
+ async fn open_changes(&self, base: &str, cache: &EtagCache) -> Result<Vec<Change>, GhError> {
+ Ok(all(self.client.dev_open_pulls(self.repo, base, cache).await?))
+ }
+ async fn checks(&self, sha: &str, cache: &EtagCache) -> Result<Vec<Check>, GhError> {
+ Ok(all(self.client.dev_check_runs(self.repo, sha, cache).await?))
+ }
+ async fn change_files(&self, number: u64) -> Result<Vec<FileDiff>, GhError> {
+ Ok(all(self.client.dev_pull_files(self.repo, number).await?))
+ }
+ fn change_head_ref(&self, number: u64) -> Option<String> {
+ Some(format!("refs/pull/{number}/head"))
+ }
+ async fn commit_login(&self, sha: &str) -> Option<String> {
+ self.client.dev_commit(self.repo, sha).await.ok().and_then(|c| c.author.map(|u| u.login))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ #[test]
+ fn github_shapes_convert_without_losing_a_field() {
+ let c: GhCommit = serde_json::from_value(json!({
+ "sha": "m1", "html_url": "https://github.com/demo-org/app/commit/m1",
+ "commit": {"message": "Fix\n\nWhy", "author": {"name": "Lin", "email": "[email protected]", "date": "2026-11-05T01:00:00Z"},
+ "committer": {"name": "GitHub", "date": "2026-11-05T02:00:00Z"}},
+ "author": {"login": "lin-bot"}, "parents": [{"sha": "p1"}, {"sha": "p2"}],
+ "files": [{"filename": "b.rs", "status": "renamed", "additions": 2, "deletions": 1, "patch": "@@ x", "previous_filename": "a.rs"}]
+ }))
+ .unwrap();
+ let n = Commit::from(c);
+ assert_eq!(n.sha, "m1");
+ assert_eq!(n.url.as_deref(), Some("https://github.com/demo-org/app/commit/m1"));
+ assert_eq!((n.author.name.as_str(), n.author.email.as_deref()), ("Lin", Some("[email protected]")));
+ assert_eq!(n.committer.date.unwrap().to_rfc3339(), "2026-11-05T02:00:00+00:00");
+ assert_eq!(n.login.as_deref(), Some("lin-bot"));
+ assert_eq!(n.parents, ["p1", "p2"]);
+ assert_eq!(n.files[0], FileDiff { path: "b.rs".into(), status: "renamed".into(), additions: 2, deletions: 1, patch: Some("@@ x".into()), previous_path: Some("a.rs".into()) });
+
+ let p: GhPull = serde_json::from_value(json!({
+ "number": 7, "title": "T", "body": "B", "draft": true, "html_url": "https://github.com/demo-org/app/pull/7",
+ "user": {"login": "oleks"}, "head": {"ref": "feat", "sha": "h1"}, "base": {"ref": "main", "sha": "b1"},
+ "merged_at": "2026-11-05T01:00:00Z", "merge_commit_sha": "m1", "merged_by": {"login": "ada"}
+ }))
+ .unwrap();
+ let ch = Change::from(p);
+ assert_eq!((ch.number, ch.title.as_str(), ch.body.as_deref(), ch.draft), (7, "T", Some("B"), true));
+ assert_eq!((ch.head_branch.as_str(), ch.head_sha.as_str(), ch.base_branch.as_str()), ("feat", "h1", "main"));
+ assert_eq!((ch.author.as_deref(), ch.merged_by.as_deref(), ch.merge_sha.as_deref()), (Some("oleks"), Some("ada"), Some("m1")));
+
+ let k: GhCheck = serde_json::from_value(json!({"name": "rust", "status": "completed", "conclusion": "success", "html_url": "https://x"})).unwrap();
+ assert_eq!(Check::from(k), Check { name: "rust".into(), status: "completed".into(), conclusion: Some("success".into()), url: Some("https://x".into()) });
+ }
+}
diff --git a/src/zombie/github.rs b/src/zombie/github.rs
index a817e169..bf2c98f3 100644
--- a/src/zombie/github.rs
+++ b/src/zombie/github.rs
@@ -414,6 +414,31 @@ impl GithubSource {
serde_json::from_value(self.get_dev(path, cache).await?).map_err(|_| GhError::Other("GitHub sent an answer kwant could not read".into()))
}
+ /// The web origin of this connection's GitHub: `https://github.com` for api.github.com, the
+ /// Enterprise host's own origin otherwise.
+ pub fn dev_web(&self) -> String {
+ let Ok(u) = url::Url::parse(self.cfg.api_base.trim()) else { return String::new() };
+ if u.host_str().is_some_and(|h| h.eq_ignore_ascii_case("api.github.com")) {
+ "https://github.com".into()
+ } else {
+ u.origin().ascii_serialization()
+ }
+ }
+
+ /// What git fetches `repo` from (`<web>/owner/name.git`) and the `Authorization` value that
+ /// carries this connection's token to it (any-git.md G2). The value goes to git through its
+ /// environment only (`dev::git::Auth`), never into argv, a file or a log.
+ pub fn dev_git_remote(&self, repo: &str) -> Result<(String, Zeroizing<String>), GhError> {
+ use base64::Engine;
+ let web = self.dev_web();
+ if web.is_empty() || web == "null" {
+ return Err(GhError::Other("this GitHub connection has no web address".into()));
+ }
+ let url = format!("{web}/{}.git", repo_path(repo)?);
+ let pair = Zeroizing::new(format!("x-access-token:{}", self.token.as_str()));
+ Ok((url, Zeroizing::new(format!("Basic {}", base64::engine::general_purpose::STANDARD.encode(pair.as_bytes())))))
+ }
+
/// The repo and its default branch.
pub async fn dev_repo(&self, repo: &str) -> Result<GhRepo, GhError> {
self.get_as(&format!("/repos/{}", repo_path(repo)?), None).await
diff --git a/tests/dev_any_git_test.rs b/tests/dev_any_git_test.rs
new file mode 100644
index 00000000..f705c2f0
--- /dev/null
+++ b/tests/dev_any_git_test.rs
@@ -0,0 +1,436 @@
+//! Dev mode reads any git repo (plan dev-mode/plan/any-git.md G1-G3): a team folder that is a plain
+//! git checkout with no remote and no forge gets a watched row and landed cards, read with git in
+//! place, without touching the folder's working tree, index or refs.
+//!
+//! The folder is a throwaway `git init` in a temp dir with commits, a branch, a merge and a tag.
+//! Nothing here touches the network or any remote.
+
+mod common;
+
+use common::*;
+use kwnt::db::dev_mode::{GIT, LANDED};
+use kwnt::db::models::NewTeam;
+use kwnt::db::spaces::SpaceId;
+use kwnt::server::dev::facts::DevFacts;
+use kwnt::server::dev::{git, poller};
+use serde_json::{json, Value};
+use std::path::Path;
+
+fn git(dir: &Path, args: &[&str]) -> String {
+ let out = std::process::Command::new("git")
+ .arg("-C")
+ .arg(dir)
+ .args(["-c", "user.name=Lin (kwant bot)", "-c", "[email protected]", "-c", "commit.gpgsign=false", "-c", "tag.gpgsign=false"])
+ .args(args)
+ .env("GIT_TERMINAL_PROMPT", "0")
+ .env("GIT_CONFIG_NOSYSTEM", "1")
+ .output()
+ .unwrap();
+ assert!(out.status.success(), "git {args:?}: {}", String::from_utf8_lossy(&out.stderr));
+ String::from_utf8_lossy(&out.stdout).trim().to_string()
+}
+
+fn commit(dir: &Path, file: &str, text: &str, message: &str) -> String {
+ std::fs::write(dir.join(file), text).unwrap();
+ git(dir, &["add", "--", file]);
+ git(dir, &["commit", "-q", "-m", message]);
+ git(dir, &["rev-parse", "HEAD"])
+}
+
+/// Everything about the folder a read could change: its files, index, HEAD and every ref.
+fn snapshot(dir: &Path) -> (String, Vec<u8>, String, String) {
+ let index = std::fs::read(dir.join(".git/index")).unwrap();
+ let refs = git(dir, &["for-each-ref", "--format=%(refname) %(objectname)"]);
+ (git(dir, &["status", "--porcelain", "--ignored"]), index, git(dir, &["rev-parse", "HEAD"]), refs)
+}
+
+async fn landed(env: &Env, key: &str) -> Vec<DevFacts> {
+ let space = SpaceId::default_space();
+ let mut rows = env.state.db.dev_cards_in(space.as_str(), Some(key), LANDED, None, 50).await.unwrap();
+ rows.sort_by(|a, b| a.created_at.cmp(&b.created_at).then(a.id.cmp(&b.id)));
+ rows.iter().map(|r| serde_json::from_str(&r.facts).unwrap()).collect()
+}
+
+#[tokio::test]
+async fn a_plain_git_folder_gets_landed_cards_read_in_place() {
+ let env = setup().await;
+ let space = SpaceId::default_space();
+ let folder = env.tmp.path().join("folders/plain");
+ std::fs::create_dir_all(&folder).unwrap();
+ git(&folder, &["init", "-q", "-b", "main"]);
+ let root = commit(&folder, "README.md", "# Plain\n", "Start the repo");
+ let second = commit(&folder, "app.rs", "fn main() {}\n", "Add the app\n\nIt does nothing yet.");
+ git(&folder, &["tag", "v0.1.0"]);
+ let third = commit(&folder, "app.rs", "fn main() {\n println!(\"hi\");\n}\n", "Say hi");
+ // Something the team is in the middle of: kwant must leave it as it is
+ std::fs::write(folder.join("wip.txt"), "not committed\n").unwrap();
+ std::fs::write(folder.join("README.md"), "# Plain\n\nEdited, not staged.\n").unwrap();
+ let before = snapshot(&folder);
+
+ let t = NewTeam {
+ name: "Plain".into(),
+ description: None,
+ icon: None,
+ lead_kwant_id: env.a.clone(),
+ member_kwants: vec![env.a.clone()],
+ workspace_path: Some(folder.to_string_lossy().to_string()),
+ repo_url: None,
+ };
+ env.state.db.create_team(&space, &t).await.unwrap();
+ let uri = format!("/api/spaces/{}/dev_mode", space.as_str());
+
+ // Off: turning on would watch it
+ let (s, v) = call(&env.app, "GET", &uri, None).await;
+ assert_eq!(s.as_u16(), 200, "{v}");
+ assert_eq!((v["status"].clone(), v["sources"].clone()), (json!("watching"), json!([{"team": "Plain", "repo": "plain", "host": null, "from": "local"}])), "{v}");
+
+ // On: the team's folder gets a git row, keyed by the team, never by its path
+ let (s, v) = call(&env.app, "PUT", &uri, Some(json!({"on": true}))).await;
+ assert_eq!(s.as_u16(), 200, "{v}");
+ assert_eq!(v["status"], "watching", "{v}");
+ assert_eq!((v["repos"][0]["key"].clone(), v["repos"][0]["provider"].clone()), (json!("local:plain"), json!("git")), "{v}");
+ assert_eq!((v["repos"][0]["status"].clone(), v["repos"][0]["from"].clone(), v["repos"][0]["branch"].clone()), (json!("watching"), json!("local"), json!("main")), "{v}");
+ let path = std::fs::canonicalize(&folder).unwrap().to_string_lossy().to_string();
+ assert!(!v.to_string().contains(&path), "the folder path reached a reply: {v}");
+ let rows = env.state.db.dev_repos(space.as_str()).await.unwrap();
+ assert_eq!(rows.len(), 1);
+ let row = &rows[0];
+ assert_eq!((row.provider.as_str(), row.repo.as_str(), row.host.as_deref(), row.branch.as_str()), (GIT, "plain", None, "main"));
+ assert_eq!(row.git_url.as_deref(), Some(path.as_str()));
+
+ // The first poll backfills what's on the branch, oldest first, from git alone
+ poller::poll_space(&env.state, space.as_str()).await;
+ let row = env.state.db.dev_repo(space.as_str(), "local:plain").await.unwrap().unwrap();
+ assert_eq!(row.poll_error, None);
+ assert_eq!(row.last_seen_sha.as_deref(), Some(third.as_str()));
+ assert_eq!(poller::last_tag(space.as_str(), "local:plain").as_deref(), Some("v0.1.0"));
+ let cards = landed(&env, "local:plain").await;
+ assert_eq!(cards.iter().map(|c| c.head_sha.as_str()).collect::<Vec<_>>(), [root.as_str(), second.as_str(), third.as_str()]);
+ let add = &cards[1];
+ assert_eq!((add.title.as_str(), add.body.as_str(), add.pr, add.repo.as_str(), add.base_branch.as_str()), ("Add the app", "It does nothing yet.", None, "plain", "main"));
+ assert_eq!(add.author.name, "Lin (kwant bot)");
+ assert_eq!(add.author.email.as_deref(), Some("[email protected]"));
+ assert!(add.merged_at.is_some(), "the commit's date");
+ assert_eq!(add.files.len(), 1);
+ assert_eq!((add.files[0].path.as_str(), add.files[0].status.as_str(), add.files[0].additions), ("app.rs", "added", 1));
+ assert!(add.files[0].patch.as_deref().is_some_and(|p| p.contains("+fn main() {}")), "{:?}", add.files[0].patch);
+ assert!(add.checks.is_empty() && add.links.pr.is_none() && add.links.commit.is_none(), "no forge, no host: no PR, CI or web link");
+ let hi = &cards[2];
+ assert_eq!((hi.files[0].status.as_str(), hi.files[0].additions, hi.files[0].deletions), ("modified", 3, 1));
+ assert_eq!(cards[0].files[0].path, "README.md", "the root commit's files");
+
+ // A feature branch merged with a merge commit: one card, with the branch's changes
+ git(&folder, &["stash", "-q", "--include-untracked"]);
+ git(&folder, &["checkout", "-q", "-b", "feature"]);
+ commit(&folder, "lib.rs", "pub fn x() {}\n", "Add lib");
+ commit(&folder, "lib.rs", "pub fn x() -> u8 { 1 }\n", "Return one");
+ git(&folder, &["checkout", "-q", "main"]);
+ git(&folder, &["merge", "-q", "--no-ff", "-m", "Merge feature", "feature"]);
+ let merge = git(&folder, &["rev-parse", "HEAD"]);
+ git(&folder, &["stash", "pop", "-q"]);
+ let before = (before.0, snapshot(&folder).1, merge.clone(), snapshot(&folder).3);
+ poller::poll_space(&env.state, space.as_str()).await;
+ let cards = landed(&env, "local:plain").await;
+ assert_eq!(cards.len(), 4, "only the merge is new on the branch's first-parent line");
+ let m = &cards[3];
+ assert_eq!((m.head_sha.as_str(), m.title.as_str()), (merge.as_str(), "Merge feature"));
+ assert_eq!(m.files.iter().map(|f| (f.path.as_str(), f.status.as_str())).collect::<Vec<_>>(), [("lib.rs", "added")]);
+ assert!(m.files[0].patch.as_deref().is_some_and(|p| p.contains("+pub fn x() -> u8 { 1 }")));
+
+ // Nothing new: nothing announced twice
+ poller::poll_space(&env.state, space.as_str()).await;
+ assert_eq!(landed(&env, "local:plain").await.len(), 4);
+
+ // The desk's rollup: four landed, and no "main is green" from a repo with no CI to read
+ let (s, v) = call(&env.app, "GET", &format!("/api/spaces/{}/dev/landed", space.as_str()), None).await;
+ assert_eq!(s.as_u16(), 200, "{v}");
+ assert_eq!((v["rollup"]["count"].clone(), v["rollup"]["main_green"].clone()), (json!(4), Value::Null), "{v}");
+
+ // The folder is as the team left it: files, index, HEAD, refs (no kwant refs)
+ let after = snapshot(&folder);
+ assert_eq!(after, before);
+ assert!(!after.3.contains("refs/kwant"), "{}", after.3);
+ // ...and kwant made no mirror for it
+ assert!(!env.tmp.path().join("data/dev").exists() || std::fs::read_dir(env.tmp.path().join("data/dev")).unwrap().flatten().all(|d| std::fs::read_dir(d.path()).map(|mut r| r.next().is_none()).unwrap_or(true)));
+
+ // A git row whose read failed shows its error, never not_connected: it needs no GitHub
+ // connection (this space has none), so connecting one couldn't fix it
+ assert!(env.state.db.set_dev_repo_error(space.as_str(), "local:plain", "git could not read the repo").await.unwrap());
+ let (_, v) = call(&env.app, "GET", &uri, None).await;
+ assert_eq!((v["status"].clone(), v["repos"][0]["status"].clone()), (json!("watching"), json!("error")), "{v}");
+ // ...and the next good read clears it
+ poller::poll_space(&env.state, space.as_str()).await;
+ let (_, v) = call(&env.app, "GET", &uri, None).await;
+ assert_eq!(v["repos"][0]["status"], "watching", "{v}");
+
+ // The team stops pointing at a git folder: its row goes, its cards stay
+ let teams = env.state.db.list_teams(&space).await.unwrap();
+ env.state.db.delete_team(&teams.iter().find(|t| t.name == "Plain").unwrap().id).await.unwrap();
+ // (the team route does this in the background)
+ kwnt::server::dev::repo::reconcile(&env.state, &space).await;
+ let (_, v) = call(&env.app, "GET", &uri, None).await;
+ assert_eq!((v["status"].clone(), v["repos"].clone()), (json!("no_repo"), Value::Array(vec![])), "{v}");
+ assert_eq!(landed(&env, "local:plain").await.len(), 4);
+ assert_eq!(snapshot(&folder), before, "dropping the row leaves the folder alone too");
+}
+
+/// The forge seam (any-git.md G4): a host with a forge gets its PRs, logins and checks from it and
+/// everything git can read from git. A fake forge over a temp repo stands in for GitHub here (the
+/// mock GitHub can't serve git), so this is the path every GitHub row takes in 0.7.3.
+#[tokio::test]
+async fn with_a_forge_prs_and_checks_come_from_it_and_files_from_git() {
+ use kwnt::db::dev_mode::{BY_HAND, REVIEW};
+ use kwnt::server::dev::facts::{Check, FileDiff};
+ use kwnt::server::dev::git::Repo;
+ use kwnt::server::dev::source::{Change, Forge, History};
+ use kwnt::zombie::github::{EtagCache, GhError};
+ use std::sync::Mutex;
+
+ struct Fake {
+ merged: Change,
+ open: Change,
+ asked_files: Mutex<Vec<u64>>,
+ }
+ #[async_trait::async_trait]
+ impl Forge for Fake {
+ async fn changes_for_commit(&self, sha: &str) -> Result<Vec<Change>, GhError> {
+ Ok(if self.merged.merge_sha.as_deref() == Some(sha) { vec![self.merged.clone()] } else { vec![] })
+ }
+ async fn open_changes(&self, _base: &str, _cache: &EtagCache) -> Result<Vec<Change>, GhError> {
+ Ok(vec![self.open.clone()])
+ }
+ async fn checks(&self, _sha: &str, _cache: &EtagCache) -> Result<Vec<Check>, GhError> {
+ Ok(vec![Check { name: "ci".into(), status: "completed".into(), conclusion: Some("success".into()), url: Some("https://github.com/demo-org/app/actions/runs/1".into()) }])
+ }
+ async fn change_files(&self, number: u64) -> Result<Vec<FileDiff>, GhError> {
+ self.asked_files.lock().unwrap().push(number);
+ Ok(vec![])
+ }
+ fn change_head_ref(&self, number: u64) -> Option<String> {
+ Some(format!("refs/pull/{number}/head"))
+ }
+ async fn commit_login(&self, _sha: &str) -> Option<String> {
+ Some("demo-person".into())
+ }
+ }
+
+ let env = setup().await;
+ let space = SpaceId::default_space();
+ let dir = env.tmp.path().join("app");
+ std::fs::create_dir_all(&dir).unwrap();
+ git(&dir, &["init", "-q", "-b", "main"]);
+ commit(&dir, "README.md", "# App\n", "Start");
+ let pushed = commit(&dir, "app.rs", "fn main() {}\n", "Push straight to main");
+ git(&dir, &["checkout", "-q", "-b", "feature"]);
+ let head = commit(&dir, "lib.rs", "pub fn x() {}\n", "Add lib");
+ git(&dir, &["checkout", "-q", "main"]);
+ git(&dir, &["merge", "-q", "--no-ff", "-m", "Merge pull request #7 from demo-org/feature", "feature"]);
+ let merge = git(&dir, &["rev-parse", "HEAD"]);
+ git(&dir, &["checkout", "-q", "-b", "next"]);
+ let open_head = commit(&dir, "next.rs", "pub fn next() {}\n", "Next thing");
+ git(&dir, &["checkout", "-q", "main"]);
+
+ let at = chrono::Utc::now();
+ let change = |n: u64, title: &str, head_branch: &str, head_sha: &str| Change {
+ number: n,
+ title: title.into(),
+ url: Some(format!("https://github.com/demo-org/app/pull/{n}")),
+ author: Some("demo-person".into()),
+ head_branch: head_branch.into(),
+ head_sha: head_sha.into(),
+ base_branch: "main".into(),
+ ..Default::default()
+ };
+ let fake = Fake {
+ merged: Change { merged_at: Some(at), merge_sha: Some(merge.clone()), ..change(7, "Add the lib", "feature", &head) },
+ open: change(8, "Next thing", "next", &open_head),
+ asked_files: Mutex::new(vec![]),
+ };
+ env.state.db.add_dev_repo(space.as_str(), "github.com/demo-org/app", None, "demo-org/app", Some("github.com"), "main", None, BY_HAND).await.unwrap();
+ let row = env.state.db.dev_repo(space.as_str(), "github.com/demo-org/app").await.unwrap().unwrap();
+ let h = History::new(Some(Repo::local(&dir, &env.state.config.data_dir).await.unwrap()), dir.to_string_lossy().to_string(), None, None, "main", Some("https://github.com/demo-org/app/commit".into()));
+ poller::read(&env.state, &row, &h, Some(&fake)).await.unwrap();
+
+ let cards = landed(&env, "github.com/demo-org/app").await;
+ let by = |sha: &str| cards.iter().find(|c| c.head_sha == sha).unwrap_or_else(|| panic!("no card for {sha}: {cards:?}"));
+ let m = by(&merge);
+ assert_eq!((m.pr, m.title.as_str()), (Some(7), "Add the lib"), "the PR names the merge");
+ assert_eq!(m.files.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(), ["lib.rs"], "files from git");
+ assert_eq!(m.checks.len(), 1, "checks from the forge");
+ assert_eq!(m.links.pr.as_deref(), Some("https://github.com/demo-org/app/pull/7"));
+ assert_eq!(m.links.commit, Some(format!("https://github.com/demo-org/app/commit/{merge}")));
+ let p = by(&pushed);
+ assert_eq!((p.pr, p.title.as_str(), p.author.login.as_deref()), (None, "Push straight to main", Some("demo-person")), "a direct push asks the forge who wrote it");
+ assert_eq!(p.files.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(), ["app.rs"]);
+
+ // The open PR's review card: its files from git too (the head is in the repo), never the forge's list
+ let reviews = env.state.db.dev_cards_in(space.as_str(), Some("github.com/demo-org/app"), REVIEW, None, 10).await.unwrap();
+ assert_eq!(reviews.len(), 1);
+ let r: DevFacts = serde_json::from_str(&reviews[0].facts).unwrap();
+ assert_eq!((r.pr, r.head_sha.as_str()), (Some(8), open_head.as_str()));
+ assert_eq!(r.files.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(), ["next.rs"]);
+ assert!(fake.asked_files.lock().unwrap().is_empty(), "git read every diff");
+ // ...and the repo read in place has no kwant refs
+ assert!(!git(&dir, &["for-each-ref"]).contains("refs/kwant"));
+}
+
+/// A team folder at `folders/<name>` on `main` whose `origin` is `remote`.
+async fn remote_team(env: &Env, name: &str, remote: &str) -> std::path::PathBuf {
+ let folder = env.tmp.path().join("folders").join(name.to_lowercase());
+ std::fs::create_dir_all(&folder).unwrap();
+ git(&folder, &["init", "-q", "-b", "main"]);
+ git(&folder, &["remote", "add", "origin", remote]);
+ let t = NewTeam {
+ name: name.into(),
+ description: None,
+ icon: None,
+ lead_kwant_id: env.a.clone(),
+ member_kwants: vec![env.a.clone()],
+ workspace_path: Some(folder.to_string_lossy().to_string()),
+ repo_url: None,
+ };
+ env.state.db.create_team(&SpaceId::default_space(), &t).await.unwrap();
+ folder
+}
+
+/// Every file under `dir` whose bytes contain `needle`.
+fn files_with(dir: &Path, needle: &[u8], out: &mut Vec<String>) {
+ for e in std::fs::read_dir(dir).into_iter().flatten().flatten() {
+ let p = e.path();
+ if p.is_dir() {
+ files_with(&p, needle, out);
+ } else if std::fs::read(&p).is_ok_and(|b| b.windows(needle.len()).any(|w| w == needle)) {
+ out.push(p.display().to_string());
+ }
+ }
+}
+
+/// any-git.md G2: a remote's password never reaches the database, a reply or the data folder.
+/// http(s) and git:// lose their userinfo whole; ssh keeps a user name (not a credential), never a
+/// password. Nothing is fetched here (the poller isn't running).
+#[tokio::test]
+async fn a_remotes_password_is_never_stored() {
+ let env = setup().await;
+ let space = SpaceId::default_space();
+ let secret = "s3cr3t-c4n4ry-pw";
+ remote_team(&env, "Web", &format!("https://deploy:{secret}@gitlab.example.com/group/web.git")).await;
+ remote_team(&env, "Ops", &format!("ssh://deploy:{secret}@gitea.example.org/group/ops.git")).await;
+ let uri = format!("/api/spaces/{}/dev_mode", space.as_str());
+ let (s, on) = call(&env.app, "PUT", &uri, Some(json!({"on": true}))).await;
+ assert_eq!(s.as_u16(), 200, "{on}");
+ let (_, v) = call(&env.app, "GET", &uri, None).await;
+
+ let mut rows = env.state.db.dev_repos(space.as_str()).await.unwrap();
+ rows.sort_by(|a, b| a.key.cmp(&b.key));
+ let urls: Vec<_> = rows.iter().map(|r| (r.key.as_str(), r.git_url.as_deref())).collect();
+ assert_eq!(urls, [("gitea.example.org/group/ops", Some("ssh://[email protected]/group/ops.git")), ("gitlab.example.com/group/web", Some("https://gitlab.example.com/group/web.git"))]);
+ for r in [on, v] {
+ assert!(!r.to_string().contains(secret), "{r}");
+ }
+ let mut leaked = Vec::new();
+ files_with(&env.tmp.path().join("data"), secret.as_bytes(), &mut leaked);
+ assert!(leaked.is_empty(), "the password was stored in {leaked:?}");
+}
+
+/// any-git.md G1: a mirror over the size cap (1 GB) was deleted after its fetch and left a note.
+/// Until a day has passed the repo isn't fetched again, and the row reads `error` with the reason;
+/// removing the repo (and adding it again) starts afresh. The cap itself is tested in git.rs with a
+/// tiny cap; nothing here touches the network (the note stops the poll before any lookup).
+#[tokio::test]
+async fn a_repo_too_big_to_copy_reads_as_an_error_until_it_is_added_again() {
+ let env = setup().await;
+ let space = SpaceId::default_space();
+ remote_team(&env, "Big", "https://gitlab.example.com/group/big.git").await;
+ let uri = format!("/api/spaces/{}/dev_mode", space.as_str());
+ let (s, v) = call(&env.app, "PUT", &uri, Some(json!({"on": true}))).await;
+ assert_eq!((s.as_u16(), v["repos"][0]["key"].clone(), v["repos"][0]["branch"].clone()), (200, json!("gitlab.example.com/group/big"), json!("main")), "{v}");
+
+ // The last fetch passed the cap: the mirror went and a note was left beside it
+ let dir = git::mirror_dir(&env.state.config.data_dir, space.as_str(), "gitlab.example.com/group/big");
+ std::fs::create_dir_all(dir.parent().unwrap()).unwrap();
+ std::fs::write(git::too_big_mark(&dir), b"").unwrap();
+
+ poller::poll_space(&env.state, space.as_str()).await;
+ let (_, v) = call(&env.app, "GET", &uri, None).await;
+ assert_eq!((v["repos"][0]["status"].clone(), v["repos"][0]["poll_error"].clone()), (json!("error"), json!("This repo is too big for Dev mode to read (over 1 GB).")), "{v}");
+ assert_eq!(v["repos"][0]["poll_code"], json!("too_big"), "{v}");
+ assert_eq!(v["status"], "watching", "{v}");
+ assert!(landed(&env, "gitlab.example.com/group/big").await.is_empty());
+ assert!(git::too_big_mark(&dir).is_file(), "the note stays for its day");
+
+ // The team stops pointing at it: the row and the note go, so adding it again fetches afresh
+ let teams = env.state.db.list_teams(&space).await.unwrap();
+ env.state.db.delete_team(&teams.iter().find(|t| t.name == "Big").unwrap().id).await.unwrap();
+ kwnt::server::dev::repo::reconcile(&env.state, &space).await;
+ assert!(!git::too_big_mark(&dir).exists() && !dir.exists());
+}
+
+/// G2 review F2: the folder check runs on every poll, not only when the repo was added. A team
+/// folder that read fine is pointed at another team's repo (its `.git` swapped for a symlink): the
+/// next poll reads `error` and makes no card from the other repo's commits; put back, it reads
+/// again.
+#[tokio::test]
+async fn a_team_folder_pointed_at_another_repo_reads_as_an_error_on_the_next_poll() {
+ let env = setup().await;
+ let space = SpaceId::default_space();
+ let folder = env.tmp.path().join("folders/ours");
+ std::fs::create_dir_all(&folder).unwrap();
+ git(&folder, &["init", "-q", "-b", "main"]);
+ let ours = commit(&folder, "README.md", "# Ours\n", "Our start");
+ let victim = env.tmp.path().join("elsewhere/theirs");
+ std::fs::create_dir_all(&victim).unwrap();
+ git(&victim, &["init", "-q", "-b", "main"]);
+ let theirs = commit(&victim, "s.txt", "SECRET-OTHER-TEAM\n", "other team secret");
+ let t = NewTeam {
+ name: "Ours".into(),
+ description: None,
+ icon: None,
+ lead_kwant_id: env.a.clone(),
+ member_kwants: vec![env.a.clone()],
+ workspace_path: Some(folder.to_string_lossy().to_string()),
+ repo_url: None,
+ };
+ env.state.db.create_team(&space, &t).await.unwrap();
+ let uri = format!("/api/spaces/{}/dev_mode", space.as_str());
+ let (s, v) = call(&env.app, "PUT", &uri, Some(json!({"on": true}))).await;
+ assert_eq!(s.as_u16(), 200, "{v}");
+ let key = v["repos"][0]["key"].as_str().unwrap().to_string();
+ poller::poll_space(&env.state, space.as_str()).await;
+ assert_eq!(landed(&env, &key).await.iter().map(|c| c.head_sha.clone()).collect::<Vec<_>>(), std::slice::from_ref(&ours));
+
+ // Someone working in the folder points its .git at the other repo
+ std::fs::rename(folder.join(".git"), env.tmp.path().join("ours.git")).unwrap();
+ std::os::unix::fs::symlink(victim.join(".git"), folder.join(".git")).unwrap();
+ poller::poll_space(&env.state, space.as_str()).await;
+ let row = env.state.db.dev_repo(space.as_str(), &key).await.unwrap().unwrap();
+ assert_eq!(row.poll_error.as_deref(), Some(git::GitError::Refused.to_string().as_str()));
+ let cards = landed(&env, &key).await;
+ assert!(cards.iter().all(|c| c.head_sha != theirs && !c.title.contains("other team")), "{cards:?}");
+ let (_, v) = call(&env.app, "GET", &uri, None).await;
+ assert_eq!(v["repos"][0]["status"], "error", "{v}");
+ assert!(!v.to_string().contains("SECRET") && !v.to_string().contains("other team"), "{v}");
+
+ // Put back, it reads again
+ std::fs::remove_file(folder.join(".git")).unwrap();
+ std::fs::rename(env.tmp.path().join("ours.git"), folder.join(".git")).unwrap();
+ poller::poll_space(&env.state, space.as_str()).await;
+ assert_eq!(env.state.db.dev_repo(space.as_str(), &key).await.unwrap().unwrap().poll_error, None);
+}
+
+/// The second too-big error (one answer from git over the output cap, `GitError::TooBig`) can
+/// still happen, so its row gets `poll_code: "too_big"` too, as the 1 GB one does.
+#[tokio::test]
+async fn both_too_big_errors_read_as_poll_code_too_big() {
+ let env = setup().await;
+ let space = SpaceId::default_space();
+ remote_team(&env, "Wide", "https://gitlab.example.com/group/wide.git").await;
+ let uri = format!("/api/spaces/{}/dev_mode", space.as_str());
+ let (s, v) = call(&env.app, "PUT", &uri, Some(json!({"on": true}))).await;
+ assert_eq!(s.as_u16(), 200, "{v}");
+ let key = "gitlab.example.com/group/wide";
+ for (e, code) in [(git::GitError::TooBig, json!("too_big")), (git::GitError::RepoTooBig, json!("too_big")), (git::GitError::Unreachable, Value::Null)] {
+ assert!(env.state.db.set_dev_repo_error(space.as_str(), key, &e.to_string()).await.unwrap());
+ let (_, v) = call(&env.app, "GET", &uri, None).await;
+ assert_eq!((v["repos"][0]["status"].clone(), v["repos"][0]["poll_code"].clone()), (json!("error"), code), "{e:?}: {v}");
+ }
+}
diff --git a/tests/dev_autodetect_test.rs b/tests/dev_autodetect_test.rs
index ea30f9db..d4347334 100644
--- a/tests/dev_autodetect_test.rs
+++ b/tests/dev_autodetect_test.rs
@@ -164,7 +164,13 @@ async fn with_no_connection_it_still_turns_on_and_no_token_leaks() {
let (s, v) = call(&env.app, "GET", &uri(), None).await;
assert_eq!(s.as_u16(), 200, "{v}");
- assert_eq!(v["status"], "not_connected", "{v}");
+ // Ops is on a host git reads, so turning on would watch it; Web waits for a connection
+ assert_eq!(v["status"], "watching", "{v}");
+ let by_host = |v: &Value, h: &str| v["repos"].as_array().unwrap().iter().find(|r| r["host"] == h).map(|r| r["status"].clone());
+ assert_eq!((by_host(&v, "github.com"), by_host(&v, "gitlab.example.com")), (Some(json!("not_connected")), Some(json!("watching"))), "{v}");
+ // The desk reads the kind from `provider`, never from the host
+ let provider = |v: &Value, h: &str| v["repos"].as_array().unwrap().iter().find(|r| r["host"] == h).map(|r| r["provider"].clone());
+ assert_eq!((provider(&v, "github.com"), provider(&v, "gitlab.example.com")), (Some(json!("github")), Some(json!("git"))), "{v}");
assert_eq!(v["repo"], REPO, "the folder's repo is the prefill");
assert_eq!(
v["sources"],
@@ -177,28 +183,34 @@ async fn with_no_connection_it_still_turns_on_and_no_token_leaks() {
let (s, v) = call(&env.app, "PUT", &uri(), Some(json!({"on": true}))).await;
assert_eq!(s.as_u16(), 200, "no connection is not a 409: {v}");
- assert_eq!((v["on"].clone(), v["repo"].clone(), v["status"].clone()), (json!(true), Value::Null, json!("not_connected")), "{v}");
- assert_eq!(v["branch"], "main", "the floor still learns the folder's branch");
+ // Ops gets a git row (the poller isn't running here, so nothing is fetched); Web still can't be read
+ assert_eq!((v["on"].clone(), v["repo"].clone(), v["branch"].clone(), v["status"].clone()), (json!(true), json!("group/sub/ops"), json!("trunk"), json!("watching")), "{v}");
+ assert_eq!(by_host(&v, "github.com"), Some(json!("not_connected")), "{v}");
+ assert_eq!((provider(&v, "github.com"), provider(&v, "gitlab.example.com")), (Some(json!("github")), Some(json!("git"))), "with a row too: {v}");
+ let mode = env.state.db.dev_mode(SpaceId::default_space().as_str()).await.unwrap().unwrap();
+ assert_eq!(mode.branch, "main", "the floor still learns the folder's branch");
+ let ops_row = env.state.db.dev_repo(SpaceId::default_space().as_str(), "gitlab.example.com/group/sub/ops").await.unwrap().expect("a git row for Ops");
+ assert_eq!((ops_row.provider.as_str(), ops_row.git_url.as_deref()), ("git", Some("https://gitlab.example.com/group/sub/ops.git")), "stored with no userinfo");
replies.push(v);
// A repo asked for by name that nothing reads: on anyway, with the check saying why
let (s, v) = call(&env.app, "PUT", &uri(), Some(json!({"on": true, "repo": format!("https://u:{token}@github.com/{REPO}")}))).await;
assert_eq!(s.as_u16(), 200, "{v}");
- assert_eq!((v["on"].clone(), v["repo"].clone(), v["check"]["state"].clone(), v["check"]["repo"].clone()), (json!(true), Value::Null, json!("not_connected"), json!(REPO)), "the token is dropped and the repo still read: {v}");
+ assert_eq!((v["on"].clone(), v["repo"].clone(), v["check"]["state"].clone(), v["check"]["repo"].clone()), (json!(true), json!("group/sub/ops"), json!("not_connected"), json!(REPO)), "the token is dropped and the repo still read: {v}");
replies.push(v);
// ...and one with no connection problem but no such repo name says not_found (Pixel's two reasons)
let (s, v) = call(&env.app, "PUT", &uri(), Some(json!({"on": true, "repo": "not a repo"}))).await;
- assert_eq!((s.as_u16(), v["on"].clone(), v["repo"].clone(), v["check"]["state"].clone()), (200, json!(true), Value::Null, json!("not_found")), "{v}");
+ assert_eq!((s.as_u16(), v["on"].clone(), v["repo"].clone(), v["check"]["state"].clone()), (200, json!(true), json!("group/sub/ops"), json!("not_found")), "{v}");
replies.push(v);
let (_, v) = call(&env.app, "POST", &format!("{}/check", uri()), Some(json!({}))).await;
assert_eq!((v["state"].clone(), v["repo"].clone()), (json!("not_connected"), json!(REPO)), "the check reads the folder's repo: {v}");
replies.push(v);
- // A space whose only remotes are on other hosts says so
+ // A space whose only remote is on another host watches it with git (other_host is retired)
let teams = env.state.db.list_teams(&SpaceId::default_space()).await.unwrap();
env.state.db.delete_team(&teams.iter().find(|t| t.name == "Web").unwrap().id).await.unwrap();
let (_, v) = call(&env.app, "GET", &uri(), None).await;
- assert_eq!((v["status"].clone(), v["sources"][0]["host"].clone()), (json!("other_host"), json!("gitlab.example.com")), "{v}");
+ assert_eq!((v["status"].clone(), v["sources"][0]["host"].clone()), (json!("watching"), json!("gitlab.example.com")), "{v}");
replies.push(v);
let folder = folders.to_string_lossy().to_string();
@@ -393,7 +405,8 @@ async fn connecting_github_while_on_binds_the_detected_repo_without_off_and_on()
team_in(&env, &off, "Idle", Some(&web)).await;
// On before any connection: no repo. (The mock's host only counts as GitHub once a connection
- // names it, so here it reads other_host; on github.com it is not_connected.)
+ // names it, and git never fetches a folder's remote on this machine, so here it reads no_repo;
+ // on github.com it is not_connected.)
let u = uri_of(&space);
let (s, v) = call(&env.app, "PUT", &u, Some(json!({"on": true}))).await;
assert_eq!((s.as_u16(), v["on"].clone(), v["repo"].clone()), (200, json!(true), Value::Null), "{v}");
diff --git a/tests/dev_github_test.rs b/tests/dev_github_test.rs
index 14bbbdd5..6b01c575 100644
--- a/tests/dev_github_test.rs
+++ b/tests/dev_github_test.rs
@@ -129,7 +129,7 @@ async fn a_lost_base_commit_falls_back_to_the_newest() {
let (commits, found) = c.dev_commits_since(REPO, "main", Some(&sha(1)), &EtagCache::default()).await.unwrap();
assert!(!found);
assert_eq!(commits.iter().map(|c| c.sha.clone()).collect::<Vec<_>>(), [sha(2), sha(3), sha(4)], "oldest first");
- assert_eq!(poller::window(commits, false, found).len(), 3, "at most MAX_NEW of them");
+ assert_eq!(poller::window(kwnt::server::dev::source::all(commits), false, found).len(), 3, "at most MAX_NEW of them");
assert_eq!(c.dev_commit(REPO, &sha(1)).await.unwrap_err(), GhError::NotFound);
let (commits, found) = c.dev_commits_since(REPO, "main", Some(&sha(3)), &EtagCache::default()).await.unwrap();
diff --git a/tests/dev_seams_test.rs b/tests/dev_seams_test.rs
index 96716693..7738e733 100644
--- a/tests/dev_seams_test.rs
+++ b/tests/dev_seams_test.rs
@@ -1,5 +1,5 @@
//! Dev mode's test seams (QA plan §2.2), in their own binary because both are process-wide:
-//! `KWANT_DEV_POLL_SECS` / `KWANT_DEV_CALL_CAP` are read once, and the clock skew moves
+//! `KWANT_DEV_POLL_SECS` / `KWANT_DEV_CALL_CAP` / `KWANT_DEV_MIRROR_CAP_BYTES` are read once, and the clock skew moves
//! `kwnt::server::dev::now()` for everything in the process.
use chrono::{Duration, Utc};
@@ -49,8 +49,10 @@ async fn the_env_seams_set_the_poll_and_the_cap() {
// Read once per process: set before the first read, as a test server would at launch
std::env::set_var("KWANT_DEV_POLL_SECS", "7");
std::env::set_var("KWANT_DEV_CALL_CAP", "2");
+ std::env::set_var("KWANT_DEV_MIRROR_CAP_BYTES", "4096");
assert_eq!(dev::poll_every(), std::time::Duration::from_secs(7));
assert_eq!(dev::call_cap(), 2);
+ assert_eq!(dev::mirror_cap(), 4096, "a tiny git mirror cap, for QA (the default is 1 GB)");
let tmp = tempfile::tempdir().unwrap();
let db = Database::init(tmp.path()).await.unwrap();