Split into a workspace: gitv-core, gitv and gitv-web
Browse filesOne package held both programs, so building the SSH tool compiled the web server's whole stack (syntect with its oniguruma C library, axum, tokio, argon2, askama). The repository is now a workspace: - crates/gitv-core: configuration, names, directory handles, bounded git - crates/gitv: the SSH command handler and admin CLI (28 crates in its dependency tree) - crates/gitv-web: the browser, its auth and rendering library, its templates and assets (136 crates) Dependency versions live once in the workspace manifest. Integration tests moved with their crates; helpers both use are in testing/host.rs, and the web tests find the gitv binary beside their own executable, so the workspace is tested from its root. CI checks the whole workspace. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Author
- Um9i vulgarmessiah@gmail.com
- Date
- 22 Nov 2026, 16:26
- Commit
- 1e37b1fb3244
- Parent
- 9d62c18
63 files changed +370−226
| @@ -24,10 +24,11 @@ jobs: | ||
| with: | ||
| components: rustfmt, clippy | ||
| - uses: Swatinem/rust-cache@v2 | ||
| - run: cargo fmt --check | ||
| - run: cargo clippy --all-targets --locked -- -D warnings | ||
| - run: cargo fmt --all --check | ||
| - run: cargo clippy --workspace --all-targets --locked -- -D warnings | ||
| # The integration tests drive real git, rsync, flock and mountpoint, all on the runner. | ||
| - run: cargo test --locked | ||
| # The whole workspace at once: the web tests use the gitv binary too. | ||
| - run: cargo test --workspace --locked | ||
| audit: | ||
| name: Dependency advisories | ||
| @@ -440,6 +440,24 @@ dependencies = [ | ||
| [[package]] | ||
| name = "gitv" | ||
| version = "0.1.0" | ||
| dependencies = [ | ||
| "base64", | ||
| "clap", | ||
| "gitv-core", | ||
| "nix", | ||
| "shlex", | ||
| ] | ||
| [[package]] | ||
| name = "gitv-core" | ||
| version = "0.1.0" | ||
| dependencies = [ | ||
| "nix", | ||
| ] | ||
| [[package]] | ||
| name = "gitv-web" | ||
| version = "0.1.0" | ||
| dependencies = [ | ||
| "argon2", | ||
| "askama", | ||
| @@ -450,6 +468,7 @@ dependencies = [ | ||
| "flate2", | ||
| "futures-util", | ||
| "getrandom", | ||
| "gitv-core", | ||
| "hmac", | ||
| "html-escape", | ||
| "nix", | ||
| @@ -459,7 +478,6 @@ dependencies = [ | ||
| "serde", | ||
| "sha1", | ||
| "sha2", | ||
| "shlex", | ||
| "subtle", | ||
| "syntect", | ||
| "thiserror", | ||
| @@ -1,9 +1,15 @@ | ||
| [package] | ||
| name = "gitv" | ||
| [workspace] | ||
| resolver = "3" | ||
| members = ["crates/gitv-core", "crates/gitv", "crates/gitv-web"] | ||
| [workspace.package] | ||
| version = "0.1.0" | ||
| edition = "2024" | ||
| [dependencies] | ||
| # One version of each dependency for the whole workspace; each crate names only what it uses, | ||
| # so building the SSH tool never compiles the web server's dependencies. | ||
| [workspace.dependencies] | ||
| gitv-core = { path = "crates/gitv-core" } | ||
| argon2 = "0.6.0" | ||
| askama = { version = "0.16.1", default-features = false, features = ["derive", "std"] } | ||
| axum = "0.8.9" | ||
| @@ -2,8 +2,8 @@ | ||
| Git hosting with SSH pushes, public and private repository browsing, and read-only HTTPS cloning for public repositories. | ||
| - `gitv`: the SSH forced-command handler (`serve`) and the root admin CLI (`create`, `visibility`, `delete`, `add-key`) | ||
| - `gitv-web`: the read-only browser (repositories, tree, blob, raw, log, commit, tags), with Markdown rendering and syntax highlighting (`src/render.rs`) | ||
| - `gitv`: the SSH forced-command handler (`serve`) and the root admin CLI (`create`, `visibility`, `delete`, `add-key`, `trash`, `restore`, `purge`) | ||
| - `gitv-web`: the read-only browser (repositories, tree, blob, raw, log, commit, tags), with Markdown rendering and syntax highlighting (`crates/gitv-web/src/render.rs`) | ||
| **Who can read what.** Over SSH each key reaches only its owner's repositories. The web browser has one account, and whoever signs in to it can read every repository on the server. It binds to localhost only; put it behind an HTTPS reverse proxy. | ||
| @@ -33,7 +33,7 @@ gitv purge # remove entries deleted 30+ days ag | ||
| History overwritten by a push can be recovered for the same 30 days. Every push records a reflog entry for each ref it changes, and keeps unreachable objects as long as those entries; for example, `git -C <repo> rev-parse main@{1}` finds where `main` pointed before a force-push. Git drops a branch's reflog when the branch is deleted, so each push also appends its ref changes to `gitv-push.log` in the repository (`<unix time> <old> <new> <ref>`, `-` for none). To bring back a deleted branch, find its last commit there and run `git -C <repo> branch <name> <commit>`. | ||
| The browser follows the system's light or dark setting. Its stylesheet (`assets/style.css`) and the Red Hat Display, Text and Mono fonts (`assets/fonts`, SIL Open Font License) are built into the `gitv-web` binary, so the server needs no font packages. | ||
| The browser follows the system's light or dark setting. Its stylesheet (`crates/gitv-web/assets/style.css`) and the Red Hat Display, Text and Mono fonts (`crates/gitv-web/assets/fonts`, SIL Open Font License) are built into the `gitv-web` binary, so the server needs no font packages. | ||
| ## Web sign-in | ||
| @@ -53,6 +53,16 @@ It prints a generated password (20 random characters, shown only this once), the | ||
| Until the account exists, pages requiring sign-in show setup instructions. Public repositories can already be browsed and cloned. | ||
| ## Layout | ||
| The repository is a Cargo workspace of three crates: | ||
| - `crates/gitv-core`: what both programs share: configuration, name rules, working through directory handles, and running git with a deadline and an output cap | ||
| - `crates/gitv`: the SSH command handler and administrator CLI | ||
| - `crates/gitv-web`: the web browser and HTTPS clone service, with its templates and assets | ||
| `gitv` depends only on `gitv-core` and a few small crates, so building it (`cargo build -p gitv`) never compiles the web server's dependencies. | ||
| ## Run locally | ||
| Set `GITV_REPOS` (and optionally `GITV_KEYS`) to point at a local tree. When `GITV_REPOS` is set, admin commands run without root. | ||
| @@ -81,7 +91,7 @@ git clone um9i@local:um9i/myrepo.git | ||
| cargo test | ||
| ``` | ||
| `tests/ssh.rs` runs `gitv serve` the way a key does over SSH, pushing and cloning real repositories through a stand-in for ssh. `tests/web.rs` builds a fixture repository and checks every page of a running `gitv-web` over HTTP, signed in, including escaping and the requests it must refuse. `tests/auth.rs` covers signing in, two-factor codes, lockout, sessions and changing the password. Neither needs an SSH server or network access; both write only to `target/tmp`. | ||
| Run them from the workspace root, so both binaries are built: the web tests use `gitv` to set up their repositories. `crates/gitv/tests/ssh.rs` runs `gitv serve` the way a key does over SSH, pushing and cloning real repositories through a stand-in for ssh, and `crates/gitv/tests/backup.rs` runs the backup and restore scripts. `crates/gitv-web/tests/web.rs` builds a fixture repository and checks every page of a running `gitv-web` over HTTP, signed in, including escaping and the requests it must refuse. `crates/gitv-web/tests/auth.rs` covers signing in, two-factor codes, lockout, sessions and changing the password. None needs an SSH server or network access; all write only to `target/tmp`. Helpers both packages use are in `testing/host.rs`. | ||
| `.github/workflows/ci.yml` runs the same checks on every push and pull request (`cargo fmt --check`, clippy with warnings as errors, `cargo test`), plus `cargo audit` against the RustSec advisory database, also weekly so new advisories surface without a push. | ||
| @@ -0,0 +1,9 @@ | ||
| [package] | ||
| name = "gitv-core" | ||
| description = "Shared pieces of GITv: configuration, name rules, directory handles and bounded git commands" | ||
| version.workspace = true | ||
| edition.workspace = true | ||
| publish = false | ||
| [dependencies] | ||
| nix.workspace = true | ||
No content changes.
| @@ -1,8 +1,6 @@ | ||
| //! Shared pieces of GITv: configuration, name rules and read-only git access. | ||
| pub mod auth; | ||
| pub mod config; | ||
| pub mod render; | ||
| use std::ffi::{OsStr, OsString}; | ||
| use std::io::Read; | ||
| @@ -0,0 +1,34 @@ | ||
| [package] | ||
| name = "gitv-web" | ||
| description = "GITv's repository browser and read-only HTTPS clone service" | ||
| version.workspace = true | ||
| edition.workspace = true | ||
| publish = false | ||
| [dependencies] | ||
| gitv-core.workspace = true | ||
| argon2.workspace = true | ||
| askama.workspace = true | ||
| axum.workspace = true | ||
| clap.workspace = true | ||
| data-encoding.workspace = true | ||
| flate2.workspace = true | ||
| futures-util.workspace = true | ||
| getrandom.workspace = true | ||
| hmac.workspace = true | ||
| html-escape.workspace = true | ||
| nix.workspace = true | ||
| pulldown-cmark.workspace = true | ||
| qrcode.workspace = true | ||
| rpassword.workspace = true | ||
| serde.workspace = true | ||
| sha1.workspace = true | ||
| sha2.workspace = true | ||
| subtle.workspace = true | ||
| syntect.workspace = true | ||
| thiserror.workspace = true | ||
| tokio.workspace = true | ||
| [dev-dependencies] | ||
| # The shared test helpers build SSH keys for their fixtures. | ||
| base64.workspace = true | ||
No content changes.
No content changes.
No content changes.
No content changes.
No content changes.
| @@ -274,7 +274,7 @@ fn write_atomically(path: &Path, contents: &[u8], owner: Owner, mode: Publish) - | ||
| return written; | ||
| } | ||
| // Published only once the rename survives a crash. | ||
| crate::sync_directory_of(path).map_err(write_error) | ||
| gitv_core::sync_directory_of(path).map_err(write_error) | ||
| } | ||
| /// Where the account file lives: `$GITV_WEB_AUTH`, or `/var/lib/gitv-web/login`. | ||
No content changes.
No content changes.
| @@ -24,7 +24,7 @@ impl Output { | ||
| pub async fn prefix(&mut self, len: usize) -> io::Result<Bytes> { | ||
| let mut bytes = vec![0; len]; | ||
| tokio::time::timeout(gitv::GIT_TIMEOUT, self.stdout.read_exact(&mut bytes)).await??; | ||
| tokio::time::timeout(gitv_core::GIT_TIMEOUT, self.stdout.read_exact(&mut bytes)).await??; | ||
| Ok(bytes.into()) | ||
| } | ||
No content changes.
| @@ -0,0 +1,5 @@ | ||
| //! The parts of gitv-web its tests use directly: sign-in credentials and Markdown and code | ||
| //! rendering. The server itself is the `gitv-web` binary. | ||
| pub mod auth; | ||
| pub mod render; | ||
| @@ -2,7 +2,7 @@ | ||
| //! | ||
| //! Every page except the sign-in page and the static assets it needs sits behind | ||
| //! [`require_login`]. Sessions live in memory (a restart signs everyone out) and remember the | ||
| //! account's [fingerprint](gitv::auth::Credentials::fingerprint), so changing the password, here | ||
| //! account's [fingerprint](gitv_web::auth::Credentials::fingerprint), so changing the password, here | ||
| //! or with `gitv-web password`, ends every other session. | ||
| use std::collections::HashMap; | ||
| @@ -18,10 +18,10 @@ use axum::http::{HeaderMap, HeaderValue, StatusCode, header}; | ||
| use axum::middleware::Next; | ||
| use axum::response::{IntoResponse, Response}; | ||
| use data_encoding::BASE64URL_NOPAD; | ||
| use gitv::auth::{ | ||
| use gitv_core::percent_decode; | ||
| use gitv_web::auth::{ | ||
| AuthError, Credentials, MIN_PASSWORD, auth_path, check_new_password, generate_password, random_bytes, | ||
| }; | ||
| use gitv::percent_decode; | ||
| use serde::Deserialize; | ||
| use sha2::{Digest, Sha256}; | ||
| use subtle::ConstantTimeEq; | ||
| @@ -213,7 +213,7 @@ impl Login { | ||
| code: &str, | ||
| ) -> Checked { | ||
| let code_ok = password_ok | ||
| && match gitv::auth::consume_code(&self.path, credentials, code, unix_now()) { | ||
| && match gitv_web::auth::consume_code(&self.path, credentials, code, unix_now()) { | ||
| Ok(accepted) => accepted, | ||
| Err(error) => { | ||
| eprintln!("gitv-web: checking an authenticator code: {error}"); | ||
| @@ -518,7 +518,8 @@ pub async fn change_password( | ||
| // Saved only if the account is still the one just checked: an operator's reset in the | ||
| // meantime wins, rather than being overwritten by a change authorized against the old one. | ||
| let (path, authorized, new) = (login.path.clone(), credentials.fingerprint(), form.new); | ||
| let saved = tokio::task::spawn_blocking(move || gitv::auth::change_password(&path, authorized, &new, None)).await; | ||
| let saved = | ||
| tokio::task::spawn_blocking(move || gitv_web::auth::change_password(&path, authorized, &new, None)).await; | ||
| let fingerprint = match saved { | ||
| Ok(Ok(fingerprint)) => fingerprint, | ||
| Ok(Err(AuthError::Changed)) => { | ||
| @@ -560,15 +561,15 @@ pub fn setup(user: Option<&str>, force: bool) -> Result<(), AuthError> { | ||
| let path = auth_path(); | ||
| // Replacing an account keeps its name unless told otherwise. | ||
| let existing = if force { Credentials::load(&path).ok().map(|c| c.user().to_string()) } else { None }; | ||
| let user = user.or(existing.as_deref()).unwrap_or(gitv::auth::DEFAULT_USER); | ||
| let user = user.or(existing.as_deref()).unwrap_or(gitv_web::auth::DEFAULT_USER); | ||
| // A bad name is refused before anything is made, so --force can't swap a working account | ||
| // for one that won't load. | ||
| gitv::auth::check_user(user)?; | ||
| gitv_web::auth::check_user(user)?; | ||
| // Run as root, everything is made for the service account, which must read the account | ||
| // and take its lock to save password changes. | ||
| let owner = gitv::auth::service_owner()?; | ||
| let owner = gitv_web::auth::service_owner()?; | ||
| prepare_directory(&path, owner)?; | ||
| let _lock = gitv::auth::lock_for_writing(&path, owner)?; | ||
| let _lock = gitv_web::auth::lock_for_writing(&path, owner)?; | ||
| if path.exists() && !force { | ||
| return Err(AuthError::AlreadySetUp(path)); | ||
| } | ||
| @@ -607,14 +608,14 @@ pub fn change_password_at_terminal() -> Result<(), String> { | ||
| return Err("the passwords differ; nothing changed".into()); | ||
| } | ||
| // Typing took a while: apply the change only to the account that was loaded before it. | ||
| let owner = gitv::auth::service_owner().map_err(|e| e.to_string())?; | ||
| gitv::auth::change_password(&path, credentials.fingerprint(), &first, owner).map_err(|e| e.to_string())?; | ||
| let owner = gitv_web::auth::service_owner().map_err(|e| e.to_string())?; | ||
| gitv_web::auth::change_password(&path, credentials.fingerprint(), &first, owner).map_err(|e| e.to_string())?; | ||
| println!("Password changed for {}. Every session has been signed out.", credentials.user()); | ||
| Ok(()) | ||
| } | ||
| /// Create the account file's directory if needed, private to its owner and given to `owner`. | ||
| fn prepare_directory(path: &Path, owner: gitv::auth::Owner) -> Result<(), AuthError> { | ||
| fn prepare_directory(path: &Path, owner: gitv_web::auth::Owner) -> Result<(), AuthError> { | ||
| let directory = path.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new(".")); | ||
| let write_error = |source| AuthError::Write { path: directory.to_owned(), source }; | ||
| // Only hand over a leaf we created or the dedicated service directory. An override | ||
| @@ -22,7 +22,8 @@ use axum::response::{IntoResponse, Redirect, Response}; | ||
| use axum::routing::{get, post}; | ||
| use axum::{Extension, Router}; | ||
| use clap::{Parser, Subcommand}; | ||
| use gitv::{render, repos_root}; | ||
| use gitv_core::repos_root; | ||
| use gitv_web::render; | ||
| use crate::html::view_missing; | ||
| use crate::urls::{encode, lossy, parse_query}; | ||
| @@ -30,10 +31,10 @@ use crate::views::{route, view_index}; | ||
| use capacity::{Pool, Visitor}; | ||
| use throttle::Client; | ||
| const STYLESHEET: &str = include_str!("../../../assets/style.css"); | ||
| const FONT_DISPLAY: &[u8] = include_bytes!("../../../assets/fonts/display.woff2"); | ||
| const FONT_TEXT: &[u8] = include_bytes!("../../../assets/fonts/text.woff2"); | ||
| const FONT_MONO: &[u8] = include_bytes!("../../../assets/fonts/mono.woff2"); | ||
| const STYLESHEET: &str = include_str!("../assets/style.css"); | ||
| const FONT_DISPLAY: &[u8] = include_bytes!("../assets/fonts/display.woff2"); | ||
| const FONT_TEXT: &[u8] = include_bytes!("../assets/fonts/text.woff2"); | ||
| const FONT_MONO: &[u8] = include_bytes!("../assets/fonts/mono.woff2"); | ||
| const FAVICON: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect width="32" height="32" rx="8" fill="#0f6b5f"/><g fill="none" stroke="#fff" stroke-width="2.6" stroke-linecap="round"><circle cx="11" cy="9" r="2.6"/><circle cx="11" cy="23" r="2.6"/><circle cx="22" cy="12" r="2.6"/><path d="M11 11.6v8.8M22 14.6c0 4-3.4 5-11 6"/></g></svg>"##; | ||
| /// The stylesheet's URL carries a hash of its contents, so browsers can cache it for good and | ||
| @@ -175,7 +176,7 @@ async fn blocking(visitor: Visitor, f: impl FnOnce() -> View + Send + 'static) - | ||
| let _permit = permit; | ||
| let started = Instant::now(); | ||
| let view = f(); | ||
| if started.elapsed() >= gitv::GIT_TIMEOUT { View::Busy } else { view } | ||
| if started.elapsed() >= gitv_core::GIT_TIMEOUT { View::Busy } else { view } | ||
| }; | ||
| let view = tokio::task::spawn_blocking(work).await.unwrap_or_else(|error| { | ||
| eprintln!("gitv-web: a page failed to render: {error}"); | ||
| @@ -200,7 +201,7 @@ fn main() -> std::process::ExitCode { | ||
| } | ||
| fn serve(port: u16) -> Result<(), String> { | ||
| let config = gitv::config::load()?; | ||
| let config = gitv_core::config::load()?; | ||
| let runtime = tokio::runtime::Builder::new_multi_thread().enable_all().build().map_err(|e| e.to_string())?; | ||
| runtime.block_on(async { | ||
| // Load the syntax definitions now rather than on the first visitor's request. | ||
| @@ -98,7 +98,7 @@ pub fn resolve_link(dir: &[u8], target: &str) -> Target { | ||
| dir.split(|b| *b == b'/').filter(|p| !p.is_empty()).map(<[u8]>::to_vec).collect() | ||
| }; | ||
| for raw in path.split('/') { | ||
| let part = crate::percent_decode(raw); | ||
| let part = gitv_core::percent_decode(raw); | ||
| match part.as_slice() { | ||
| b"" | b"." => {} | ||
| b".." => { | ||
| @@ -2,7 +2,7 @@ | ||
| use std::{sync::Arc, time::Duration}; | ||
| use gitv::{RepoDir, git, git_with_input}; | ||
| use gitv_core::{RepoDir, git, git_with_input}; | ||
| use crate::cache::cached; | ||
| use crate::urls::{encode, join, lossy}; | ||
| @@ -294,7 +294,7 @@ impl Reader { | ||
| ]; | ||
| // Output past the cap is cut off; what came before it is still exact, and anything not | ||
| // found in it is looked up on its own. | ||
| let (bytes, _) = gitv::git_capped_for(&self.dir, &args, RECENT_BYTES, Duration::from_secs(1)).ok()?; | ||
| let (bytes, _) = gitv_core::git_capped_for(&self.dir, &args, RECENT_BYTES, Duration::from_secs(1)).ok()?; | ||
| Some(recent_changes(&bytes, dir, names)) | ||
| } | ||
| @@ -395,7 +395,7 @@ mod tests { | ||
| use std::io::Write as _; | ||
| let dir = std::env::temp_dir().join(format!("gitv-web-crowded-{}", std::process::id())); | ||
| let _ = std::fs::remove_dir_all(&dir); | ||
| assert!(gitv::git_base().args(["init", "-q", "--bare"]).arg(&dir).status().unwrap().success()); | ||
| assert!(gitv_core::git_base().args(["init", "-q", "--bare"]).arg(&dir).status().unwrap().success()); | ||
| let mut stream = String::new(); | ||
| for i in 0..3000 { | ||
| let data = format!("blob {i}\n"); | ||
| @@ -410,7 +410,7 @@ mod tests { | ||
| ); | ||
| } | ||
| stream += "tag v1\nfrom refs/heads/main\ntagger A <a@example.com> 1800000000 +0000\ndata 3\nv1\n"; | ||
| let mut import = gitv::git_base() | ||
| let mut import = gitv_core::git_base() | ||
| .arg("--git-dir") | ||
| .arg(&dir) | ||
| .args(["fast-import", "--quiet"]) | ||
| @@ -466,7 +466,7 @@ mod tests { | ||
| use std::io::Write as _; | ||
| let dir = std::env::temp_dir().join(format!("gitv-web-walk-{}", std::process::id())); | ||
| let _ = std::fs::remove_dir_all(&dir); | ||
| assert!(gitv::git_base().args(["init", "-q", "--bare"]).arg(&dir).status().unwrap().success()); | ||
| assert!(gitv_core::git_base().args(["init", "-q", "--bare"]).arg(&dir).status().unwrap().success()); | ||
| // old.txt is written once, then busy.txt changes in each of 30 later commits. | ||
| let mut stream = String::from( | ||
| "commit refs/heads/main\ncommitter A <a@example.com> 1700000000 +0000\ndata 6\nfirst\nM 644 inline old.txt\ndata 4\nold\n\n", | ||
| @@ -481,7 +481,7 @@ mod tests { | ||
| content.len() | ||
| ); | ||
| } | ||
| let mut import = gitv::git_base() | ||
| let mut import = gitv_core::git_base() | ||
| .arg("--git-dir") | ||
| .arg(&dir) | ||
| .args(["fast-import", "--quiet"]) | ||
| @@ -8,7 +8,7 @@ use axum::{ | ||
| http::{HeaderMap, StatusCode, header}, | ||
| response::{IntoResponse, Response}, | ||
| }; | ||
| use gitv::{git_command, repo_dir}; | ||
| use gitv_core::{git_command, repo_dir}; | ||
| use std::sync::LazyLock; | ||
| use std::{process::Stdio, time::Duration}; | ||
| use tokio::process::Command; | ||
No content changes.
No content changes.
| @@ -6,7 +6,7 @@ use std::ffi::OsString; | ||
| use std::fmt::Write as _; | ||
| use std::os::unix::ffi::OsStringExt; | ||
| use gitv::percent_decode; | ||
| use gitv_core::percent_decode; | ||
| // --------------------------------------------------------------------------------------------- | ||
| // Query strings and paths | ||
| @@ -2,7 +2,7 @@ | ||
| use std::sync::Arc; | ||
| use gitv::render; | ||
| use gitv_web::render; | ||
| use super::tree::render_file; | ||
| use super::{RAW_LIMIT, Repo, SHOW_LIMIT, entry}; | ||
| @@ -37,7 +37,7 @@ pub(crate) fn view_blob(repo: &Repo, q: &Q, raw: bool) -> Option<View> { | ||
| .to_string(), | ||
| )); | ||
| } | ||
| let mut command = gitv::git_command(&repo.reader.dir); | ||
| let mut command = gitv_core::git_command(&repo.reader.dir); | ||
| command.args(["cat-file", "blob", &item.oid]); | ||
| return Some(View::Raw(Box::new(command), item.size, file_name(&path).to_vec())); | ||
| } | ||
| @@ -1,6 +1,6 @@ | ||
| //! One commit and its changes. | ||
| use gitv::git_capped; | ||
| use gitv_core::git_capped; | ||
| use super::{DIFF_LIMIT, Repo}; | ||
| use crate::cache::cached; | ||
| @@ -7,7 +7,7 @@ use std::os::fd::{AsFd, OwnedFd}; | ||
| use std::sync::Arc; | ||
| use std::time::{Instant, SystemTime, UNIX_EPOCH}; | ||
| use gitv::{RepoDir, config, entries, open_dir_at, open_owner, open_root, repo_in, try_subdirs}; | ||
| use gitv_core::{RepoDir, config, entries, open_dir_at, open_owner, open_root, repo_in, try_subdirs}; | ||
| use super::Repo; | ||
| use crate::cache::cached; | ||
| @@ -89,7 +89,7 @@ pub(crate) struct Row { | ||
| } | ||
| pub(crate) fn view_index(signed_in: bool) -> View { | ||
| let deadline = Instant::now() + gitv::GIT_TIMEOUT; | ||
| let deadline = Instant::now() + gitv_core::GIT_TIMEOUT; | ||
| let mut rows = Vec::new(); | ||
| let root = open_root(); | ||
| for owner in root.as_ref().map(sorted_names).unwrap_or_default() { | ||
No content changes.
| @@ -12,7 +12,8 @@ use std::fmt::Write as _; | ||
| use std::os::unix::ffi::OsStrExt; | ||
| use std::time::Instant; | ||
| use gitv::{RepoDir, config, render, repo_dir}; | ||
| use gitv_core::{RepoDir, config, repo_dir}; | ||
| use gitv_web::render; | ||
| use crate::html::{ago, icon, subject_or_placeholder}; | ||
| use crate::repository::Reader; | ||
| @@ -47,7 +48,7 @@ impl Repo { | ||
| /// every git command then runs inside that open directory. | ||
| pub(crate) fn open(owner: &str, name: &str) -> Option<Repo> { | ||
| let mut dir = repo_dir(owner, name)?; | ||
| dir.limit_until(Instant::now() + gitv::GIT_TIMEOUT); | ||
| dir.limit_until(Instant::now() + gitv_core::GIT_TIMEOUT); | ||
| Some(Repo::from_dir(owner, name, dir)) | ||
| } | ||
No content changes.
| @@ -3,7 +3,8 @@ | ||
| use std::ffi::OsStr; | ||
| use std::sync::Arc; | ||
| use gitv::{config, render}; | ||
| use gitv_core::config; | ||
| use gitv_web::render; | ||
| use super::{Entry, PAGE, Repo, SHOW_LIMIT, entry}; | ||
| use crate::cache::cached; | ||
No content changes.
No content changes.
No content changes.
No content changes.
No content changes.
No content changes.
No content changes.
No content changes.
No content changes.
No content changes.
No content changes.
No content changes.
No content changes.
No content changes.
No content changes.
No content changes.
No content changes.
| @@ -327,7 +327,7 @@ mod changing_the_password { | ||
| assert_eq!(change(&s, &csrf(&s), &old, new, new, &s.account.code(1)).status, 200); | ||
| // Codes used so far: the sign-in's (step 0) and the change's (step +1). | ||
| assert_eq!(sign_in(&s, "Um9i", &old, &s.account.code(1), "/").status, 401); | ||
| let loaded = gitv::auth::Credentials::load(&s.account.file).unwrap(); | ||
| let loaded = gitv_web::auth::Credentials::load(&s.account.file).unwrap(); | ||
| assert!(loaded.verify_password(new) && !loaded.verify_password(&old)); | ||
| } | ||
| @@ -356,7 +356,7 @@ mod changing_the_password { | ||
| let response = | ||
| change(&s, &csrf(&s), "not it", "a brand new password", "a brand new password", &s.account.code(1)); | ||
| assert_eq!(response.status, 401); | ||
| assert!(gitv::auth::Credentials::load(&s.account.file).unwrap().verify_password(&s.account.password)); | ||
| assert!(gitv_web::auth::Credentials::load(&s.account.file).unwrap().verify_password(&s.account.password)); | ||
| } | ||
| #[test] | ||
| @@ -409,7 +409,7 @@ mod changing_the_password { | ||
| let s = Server::start(repos()); | ||
| assert_eq!(s.get("/account").status, 200); | ||
| // What `gitv-web password` does: rewrite the account file with a new password. | ||
| let mut credentials = gitv::auth::Credentials::load(&s.account.file).unwrap(); | ||
| let mut credentials = gitv_web::auth::Credentials::load(&s.account.file).unwrap(); | ||
| credentials.set_password("changed on the server").unwrap(); | ||
| credentials.save(&s.account.file, None).unwrap(); | ||
| assert_eq!(s.get("/account").status, 303); | ||
| @@ -421,10 +421,11 @@ mod setup { | ||
| #[test] | ||
| fn root_setup_refuses_an_unwritable_custom_directory_before_publication() { | ||
| let Some(_) = gitv::auth::service_owner().unwrap() else { return }; | ||
| let Some(_) = gitv_web::auth::service_owner().unwrap() else { return }; | ||
| let dir = scratch("auth-setup-root-owned"); | ||
| std::fs::set_permissions(&dir, std::os::unix::fs::PermissionsExt::from_mode(0o755)).unwrap(); | ||
| let out = Command::new(common::GITV_WEB).arg("setup").env("GITV_WEB_AUTH", dir.join("login")).output().unwrap(); | ||
| let out = | ||
| Command::new(&*common::GITV_WEB).arg("setup").env("GITV_WEB_AUTH", dir.join("login")).output().unwrap(); | ||
| assert!(!out.status.success()); | ||
| assert!(stderr(&out).contains("write and search access")); | ||
| assert_eq!(std::fs::read_dir(dir).unwrap().count(), 0); | ||
| @@ -434,7 +435,8 @@ mod setup { | ||
| fn refuses_to_replace_an_account_without_force() { | ||
| let dir = scratch("auth-setup-twice"); | ||
| common::Account::create(&dir); | ||
| let out = Command::new(common::GITV_WEB).arg("setup").env("GITV_WEB_AUTH", dir.join("login")).output().unwrap(); | ||
| let out = | ||
| Command::new(&*common::GITV_WEB).arg("setup").env("GITV_WEB_AUTH", dir.join("login")).output().unwrap(); | ||
| assert!(!out.status.success()); | ||
| assert!(stderr(&out).contains("already set up"), "{}", stderr(&out)); | ||
| } | ||
| @@ -447,20 +449,20 @@ mod setup { | ||
| let runs: Vec<_> = (0..4) | ||
| .map(|_| { | ||
| scope.spawn(|| { | ||
| Command::new(common::GITV_WEB).arg("setup").env("GITV_WEB_AUTH", &file).output().unwrap() | ||
| Command::new(&*common::GITV_WEB).arg("setup").env("GITV_WEB_AUTH", &file).output().unwrap() | ||
| }) | ||
| }) | ||
| .collect(); | ||
| runs.into_iter().map(|r| r.join().unwrap().status.success()).collect() | ||
| }); | ||
| assert_eq!(results.iter().filter(|ok| **ok).count(), 1, "{results:?}"); | ||
| assert!(gitv::auth::Credentials::load(&file).is_ok()); | ||
| assert!(gitv_web::auth::Credentials::load(&file).is_ok()); | ||
| } | ||
| #[test] | ||
| fn with_force_replaces_it_and_signs_everyone_out() { | ||
| let s = Server::start(repos()); | ||
| let out = Command::new(common::GITV_WEB) | ||
| let out = Command::new(&*common::GITV_WEB) | ||
| .args(["setup", "--force"]) | ||
| .env("GITV_WEB_AUTH", &s.account.file) | ||
| .output() | ||
| @@ -474,7 +476,7 @@ mod setup { | ||
| let dir = scratch("auth-setup-bad-user"); | ||
| let account = common::Account::create(&dir); | ||
| for user in ["", "two words", "line\nbreak"] { | ||
| let out = Command::new(common::GITV_WEB) | ||
| let out = Command::new(&*common::GITV_WEB) | ||
| .args(["setup", "--force", "--user", user]) | ||
| .env("GITV_WEB_AUTH", &account.file) | ||
| .output() | ||
| @@ -482,7 +484,7 @@ mod setup { | ||
| assert!(!out.status.success(), "{user:?} was accepted"); | ||
| assert!(stderr(&out).contains("user name"), "{}", stderr(&out)); | ||
| } | ||
| let kept = gitv::auth::Credentials::load(&account.file).unwrap(); | ||
| let kept = gitv_web::auth::Credentials::load(&account.file).unwrap(); | ||
| assert!(kept.verify_password(&account.password), "a refused setup replaced the account"); | ||
| } | ||
| @@ -492,9 +494,9 @@ mod setup { | ||
| let file = dir.join("login"); | ||
| let setup = |args: &[&str]| { | ||
| let out = | ||
| Command::new(common::GITV_WEB).arg("setup").args(args).env("GITV_WEB_AUTH", &file).output().unwrap(); | ||
| Command::new(&*common::GITV_WEB).arg("setup").args(args).env("GITV_WEB_AUTH", &file).output().unwrap(); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| gitv::auth::Credentials::load(&file).unwrap().user().to_string() | ||
| gitv_web::auth::Credentials::load(&file).unwrap().user().to_string() | ||
| }; | ||
| assert_eq!(setup(&[]), "admin"); | ||
| assert_eq!(setup(&["--force", "--user", "Um9i"]), "Um9i"); | ||
| @@ -0,0 +1,10 @@ | ||
| //! Helpers for the web tests: the shared ones, and a server and HTTP client of their own. | ||
| #![allow(dead_code, unused_imports)] | ||
| #[path = "../../../../testing/host.rs"] | ||
| mod host; | ||
| mod web; | ||
| pub use host::*; | ||
| pub use web::*; | ||
| @@ -1,143 +1,14 @@ | ||
| //! Shared helpers for the integration tests: isolated git, a stand-in for ssh that runs | ||
| //! `gitv serve`, and a minimal HTTP client. | ||
| #![allow(dead_code)] | ||
| //! The web tests' own helpers: a running `gitv-web` with its own account, and a minimal HTTP | ||
| //! client. | ||
| use std::collections::HashMap; | ||
| use std::fs; | ||
| use std::io::{BufRead, BufReader, Read, Write}; | ||
| use std::net::TcpStream; | ||
| use std::os::unix::fs::PermissionsExt; | ||
| use std::path::{Path, PathBuf}; | ||
| use std::process::{Child, Command, Output, Stdio}; | ||
| pub const GITV: &str = env!("CARGO_BIN_EXE_gitv"); | ||
| pub const GITV_WEB: &str = env!("CARGO_BIN_EXE_gitv-web"); | ||
| /// The hostname every test installation is configured with. | ||
| pub const TEST_HOST: &str = "git.example.test"; | ||
| /// A configuration file that doesn't exist, so the machine's own /etc/gitv/gitv.conf never applies. | ||
| pub const NO_CONFIG: &str = "/nonexistent/gitv.conf"; | ||
| /// A fresh, empty directory under Cargo's per-target temporary directory. | ||
| pub fn scratch(name: &str) -> PathBuf { | ||
| let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join(name); | ||
| let _ = fs::remove_dir_all(&dir); | ||
| fs::create_dir_all(&dir).unwrap(); | ||
| dir | ||
| } | ||
| /// Git with no user or system config and a fixed identity and clock, so runs are repeatable. | ||
| pub fn git_cmd(dir: &Path) -> Command { | ||
| let mut command = Command::new("git"); | ||
| command | ||
| .current_dir(dir) | ||
| .env("HOME", dir) | ||
| .env("GIT_CONFIG_NOSYSTEM", "1") | ||
| .env("GIT_CONFIG_GLOBAL", "/dev/null") | ||
| .env("GIT_AUTHOR_NAME", "Ada Lovelace") | ||
| .env("GIT_AUTHOR_EMAIL", "ada@example.com") | ||
| .env("GIT_COMMITTER_NAME", "Ada Lovelace") | ||
| .env("GIT_COMMITTER_EMAIL", "ada@example.com") | ||
| .env("GIT_AUTHOR_DATE", "2026-01-02T03:04:05Z") | ||
| .env("GIT_COMMITTER_DATE", "2026-01-02T03:04:05Z") | ||
| .env("GIT_SSH_VARIANT", "simple") | ||
| .stdin(Stdio::null()); | ||
| command | ||
| } | ||
| use std::process::{Child, Command, Stdio}; | ||
| /// Run git in `dir`, panic with its output on failure, and return trimmed stdout. | ||
| pub fn git(dir: &Path, args: &[&str]) -> String { | ||
| let output = git_cmd(dir).args(args).output().unwrap(); | ||
| assert!(output.status.success(), "git {args:?} failed: {}", String::from_utf8_lossy(&output.stderr)); | ||
| String::from_utf8_lossy(&output.stdout).trim().to_string() | ||
| } | ||
| /// A GITv installation in a scratch directory: repositories, a keys file, and a fake `ssh` | ||
| /// that hands git's command to `gitv serve` as an owner's key would. | ||
| pub struct Host { | ||
| pub dir: PathBuf, | ||
| pub repos: PathBuf, | ||
| pub keys: PathBuf, | ||
| } | ||
| impl Host { | ||
| pub fn new(name: &str) -> Host { | ||
| let dir = scratch(name); | ||
| let repos = dir.join("repos"); | ||
| fs::create_dir_all(&repos).unwrap(); | ||
| let keys = dir.join("authorized_keys"); | ||
| let host = Host { dir, repos, keys }; | ||
| // With GIT_SSH_VARIANT=simple git runs: <ssh> <owner>@host <command>. | ||
| let script = format!( | ||
| "#!/bin/sh\nowner=${{1%%@*}}\nSSH_ORIGINAL_COMMAND=\"$2\" GITV_REPOS='{}' GITV_LOG='{}' GITV_HOST={TEST_HOST} GITV_CONFIG={NO_CONFIG} exec '{GITV}' serve \"$owner\"\n", | ||
| host.repos.display(), | ||
| host.log().display() | ||
| ); | ||
| let ssh = host.ssh_script(); | ||
| fs::write(&ssh, script).unwrap(); | ||
| fs::set_permissions(&ssh, fs::Permissions::from_mode(0o755)).unwrap(); | ||
| host | ||
| } | ||
| /// Where `gitv` writes its operator log in tests. | ||
| pub fn log(&self) -> PathBuf { | ||
| self.dir.join("operator.log") | ||
| } | ||
| /// The operator log so far, empty if nothing was logged. | ||
| pub fn logged(&self) -> String { | ||
| fs::read_to_string(self.log()).unwrap_or_default() | ||
| } | ||
| pub fn ssh_script(&self) -> PathBuf { | ||
| self.dir.join("fake-ssh") | ||
| } | ||
| /// `ssh git@host <command>` as `owner`'s key. | ||
| pub fn ssh(&self, owner: &str, command: &str) -> Output { | ||
| Command::new(GITV) | ||
| .args(["serve", owner]) | ||
| .env("SSH_ORIGINAL_COMMAND", command) | ||
| .env("GITV_HOST", TEST_HOST) | ||
| .env("GITV_CONFIG", NO_CONFIG) | ||
| .env("GITV_REPOS", &self.repos) | ||
| .env("GITV_LOG", self.log()) | ||
| .stdin(Stdio::null()) | ||
| .output() | ||
| .unwrap() | ||
| } | ||
| /// `gitv <args>` as the administrator, pointed at this host. | ||
| pub fn admin(&self, args: &[&str]) -> Output { | ||
| Command::new(GITV) | ||
| .args(args) | ||
| .env("GITV_HOST", TEST_HOST) | ||
| .env("GITV_CONFIG", NO_CONFIG) | ||
| .env("GITV_REPOS", &self.repos) | ||
| .env("GITV_KEYS", &self.keys) | ||
| .env("GITV_LOG", self.log()) | ||
| .stdin(Stdio::null()) | ||
| .output() | ||
| .unwrap() | ||
| } | ||
| /// Git in `dir`, with remotes reached through this host's fake ssh. | ||
| pub fn git(&self, dir: &Path, args: &[&str]) -> Output { | ||
| git_cmd(dir).env("GIT_SSH_COMMAND", self.ssh_script()).args(args).output().unwrap() | ||
| } | ||
| pub fn repo(&self, owner: &str, name: &str) -> PathBuf { | ||
| self.repos.join(owner).join(format!("{name}.git")) | ||
| } | ||
| } | ||
| pub fn stdout(output: &Output) -> String { | ||
| String::from_utf8_lossy(&output.stdout).into_owned() | ||
| } | ||
| pub fn stderr(output: &Output) -> String { | ||
| String::from_utf8_lossy(&output.stderr).into_owned() | ||
| } | ||
| use super::{GITV_WEB, NO_CONFIG, TEST_HOST, scratch, stderr, stdout}; | ||
| /// A web account made by `gitv-web setup`: where it's stored, and what it printed. | ||
| #[derive(Clone)] | ||
| @@ -152,7 +23,7 @@ impl Account { | ||
| pub fn create(dir: &Path) -> Account { | ||
| let file = dir.join("login"); | ||
| let out = | ||
| Command::new(GITV_WEB).args(["setup", "--user", "Um9i"]).env("GITV_WEB_AUTH", &file).output().unwrap(); | ||
| Command::new(&*GITV_WEB).args(["setup", "--user", "Um9i"]).env("GITV_WEB_AUTH", &file).output().unwrap(); | ||
| assert!(out.status.success(), "setup failed: {}", stderr(&out)); | ||
| let printed = stdout(&out); | ||
| let field = |label: &str| { | ||
| @@ -170,8 +41,8 @@ impl Account { | ||
| /// The authenticator code `offset` steps from now. | ||
| pub fn code(&self, offset: i64) -> String { | ||
| let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs(); | ||
| let step = gitv::auth::totp_step(now).saturating_add_signed(offset); | ||
| format!("{:06}", gitv::auth::totp_code(&self.secret, step)) | ||
| let step = gitv_web::auth::totp_step(now).saturating_add_signed(offset); | ||
| format!("{:06}", gitv_web::auth::totp_code(&self.secret, step)) | ||
| } | ||
| } | ||
| @@ -233,7 +104,7 @@ impl Server { | ||
| } | ||
| fn launch(repos: &Path, limit: Option<u64>, account: Account) -> Server { | ||
| let mut command = Command::new(GITV_WEB); | ||
| let mut command = Command::new(&*GITV_WEB); | ||
| if let Some(limit) = limit { | ||
| use std::os::unix::process::CommandExt; | ||
| // SAFETY: setrlimit is async-signal-safe and the closure does nothing else. | ||
| @@ -402,13 +273,3 @@ fn dechunk(mut data: &[u8]) -> Vec<u8> { | ||
| } | ||
| out | ||
| } | ||
| /// A syntactically valid OpenSSH Ed25519 public key built from `seed`. | ||
| pub fn ed25519_key(seed: u8) -> String { | ||
| use base64::Engine; | ||
| let mut blob = 11u32.to_be_bytes().to_vec(); | ||
| blob.extend_from_slice(b"ssh-ed25519"); | ||
| blob.extend_from_slice(&32u32.to_be_bytes()); | ||
| blob.extend_from_slice(&[seed; 32]); | ||
| format!("ssh-ed25519 {} test@example\n", base64::engine::general_purpose::STANDARD.encode(blob)) | ||
| } | ||
No content changes.
| @@ -0,0 +1,13 @@ | ||
| [package] | ||
| name = "gitv" | ||
| description = "GITv's SSH command handler and administrator CLI" | ||
| version.workspace = true | ||
| edition.workspace = true | ||
| publish = false | ||
| [dependencies] | ||
| gitv-core.workspace = true | ||
| base64.workspace = true | ||
| clap.workspace = true | ||
| nix.workspace = true | ||
| shlex.workspace = true | ||
| @@ -9,7 +9,7 @@ use std::process::{Command, ExitCode, Stdio}; | ||
| use base64::Engine; | ||
| use clap::{Parser, Subcommand}; | ||
| use gitv::{ | ||
| use gitv_core::{ | ||
| NAME_RULE, RepoDir, chown_tree, config, entries, git, git_command, git_in, keys_path, kind_at, open_dir_at, | ||
| open_owner, open_root, remove_tree_at, repo_dir, repo_in, repos_root, valid_name, | ||
| }; | ||
| @@ -350,7 +350,7 @@ fn trash_entries() -> Result<Vec<(String, String, Option<u64>)>, String> { | ||
| Err(Errno::ENOENT) => continue, | ||
| Err(e) => return Err(format!("cannot open {owner}/{TRASH}: {e}")), | ||
| }; | ||
| let names = gitv::try_entries(&trash).map_err(|e| format!("cannot list {owner}/{TRASH}: {e}"))?; | ||
| let names = gitv_core::try_entries(&trash).map_err(|e| format!("cannot list {owner}/{TRASH}: {e}"))?; | ||
| for entry in names { | ||
| let entry = entry.to_string_lossy().into_owned(); | ||
| let stamp = parse_trash_entry(&entry).map(|(_, stamp)| stamp); | ||
| @@ -476,7 +476,8 @@ fn add_key(owner: &str, file: &Path) -> Result<(), String> { | ||
| return Err(e.to_string()); | ||
| } | ||
| // The key counts as added only once the rename itself survives a crash. | ||
| gitv::sync_directory_of(&keys).map_err(|e| format!("added the key, but couldn't sync {}: {e}", directory.display())) | ||
| gitv_core::sync_directory_of(&keys) | ||
| .map_err(|e| format!("added the key, but couldn't sync {}: {e}", directory.display())) | ||
| } | ||
| /// The decoded Ed25519 key in an authorized_keys line, wherever it sits: after options, and | ||
| @@ -777,7 +778,7 @@ fn run() -> Result<u8, String> { | ||
| return serve(owner, &std::env::var("SSH_ORIGINAL_COMMAND").unwrap_or_default()); | ||
| } | ||
| // Locally (GITV_REPOS set) administration runs as yourself. | ||
| if !is_root() && !gitv::is_local() { | ||
| if !is_root() && !gitv_core::is_local() { | ||
| return Err("run repository and key administration as root".into()); | ||
| } | ||
| match cli.action { | ||
| @@ -843,7 +844,7 @@ mod tests { | ||
| #[test] | ||
| fn private_commands_keep_their_errors_for_the_operator() { | ||
| let mut command = gitv::git_base(); | ||
| let mut command = gitv_core::git_base(); | ||
| command.args(["init", "--no-such-option"]); | ||
| let error = run_privately(command, "git init").unwrap_err(); | ||
| assert!(error.starts_with("git init failed (exit status: 129): "), "{error}"); | ||
| @@ -10,8 +10,8 @@ use std::time::Duration; | ||
| use common::{Host, git, scratch, stderr}; | ||
| const BACKUP: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/deploy/gitv-backup"); | ||
| const RESTORE: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/deploy/gitv-restore"); | ||
| const BACKUP: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../../deploy/gitv-backup"); | ||
| const RESTORE: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../../deploy/gitv-restore"); | ||
| /// A host with a web sign-in folder, and somewhere for its backups. | ||
| struct Setup { | ||
| @@ -154,7 +154,7 @@ fn a_backup_waits_for_a_push_in_progress() { | ||
| let work = work("backup-lock-work"); | ||
| setup.push(&work, "project"); | ||
| // Hold the lock as a push does; the backup gives up after its (one second) wait. | ||
| let repo = gitv::RepoDir::at(&setup.host.repo("ada", "project")).unwrap(); | ||
| let repo = gitv_core::RepoDir::at(&setup.host.repo("ada", "project")).unwrap(); | ||
| let held = repo.lock(false).unwrap(); | ||
| let out = setup.backup(); | ||
| assert!(!out.status.success()); | ||
| @@ -0,0 +1,8 @@ | ||
| //! Helpers for the SSH and backup tests, shared with the web tests. | ||
| #![allow(dead_code, unused_imports)] | ||
| #[path = "../../../../testing/host.rs"] | ||
| mod host; | ||
| pub use host::*; | ||
| @@ -240,7 +240,7 @@ fn the_configuration_file_sets_the_host_and_the_forced_command() { | ||
| let config = host.dir.join("gitv.conf"); | ||
| fs::write(&config, "# this server\nhost = Code.Example.org\ncommand = /opt/gitv/bin/gitv\n").unwrap(); | ||
| let admin = |args: &[&str]| { | ||
| std::process::Command::new(common::GITV) | ||
| std::process::Command::new(&*common::GITV) | ||
| .args(args) | ||
| .env("GITV_CONFIG", &config) | ||
| .env("GITV_REPOS", &host.repos) | ||
| @@ -261,7 +261,7 @@ fn the_configuration_file_sets_the_host_and_the_forced_command() { | ||
| let out = admin(&["create", "ada", "other"]); | ||
| assert!(!out.status.success()); | ||
| assert!(stderr(&out).contains("unknown setting `hostname`"), "{}", stderr(&out)); | ||
| let out = std::process::Command::new(common::GITV) | ||
| let out = std::process::Command::new(&*common::GITV) | ||
| .args(["serve", "ada"]) | ||
| .env("SSH_ORIGINAL_COMMAND", "list") | ||
| .env("GITV_CONFIG", &config) | ||
| @@ -320,7 +320,7 @@ fn admin_needs_root_outside_a_local_tree() { | ||
| if nix::unistd::geteuid().is_root() { | ||
| return; | ||
| } | ||
| let out = std::process::Command::new(common::GITV) | ||
| let out = std::process::Command::new(&*common::GITV) | ||
| .args(["create", "ada", "tools"]) | ||
| .env_remove("GITV_REPOS") | ||
| .output() | ||
| @@ -405,7 +405,7 @@ fn a_failed_key_write_leaves_no_temporary_file() { | ||
| let host = Host::new("admin-keys-cleanup"); | ||
| let key = host.dir.join("ada.pub"); | ||
| fs::write(&key, ed25519_key(4)).unwrap(); | ||
| let mut command = std::process::Command::new(common::GITV); | ||
| let mut command = std::process::Command::new(&*common::GITV); | ||
| command | ||
| .args(["add-key", "ada", key.to_str().unwrap()]) | ||
| .env("GITV_HOST", common::TEST_HOST) | ||
| @@ -463,7 +463,7 @@ fn add_key_respects_existing_lines() { | ||
| #[test] | ||
| fn the_readme_fake_ssh_script_works() { | ||
| let host = Host::new("ssh-script"); | ||
| let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("scripts/fake-ssh"); | ||
| let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../scripts/fake-ssh"); | ||
| let dir = work("ssh-script-work", "main"); | ||
| let out = common::git_cmd(&dir) | ||
| .env("GIT_SSH_COMMAND", &script) | ||
| @@ -1,5 +1,5 @@ | ||
| # GITv settings, installed at /etc/gitv/gitv.conf (readable by the git and gitv-web accounts). | ||
| # Both gitv (over SSH) and gitv-web read it at startup; see src/config.rs. | ||
| # Both gitv (over SSH) and gitv-web read it at startup; see crates/gitv-core/src/config.rs. | ||
| # The name people reach this server by, in clone addresses and help. | ||
| host = git.um9i.dev | ||
| @@ -9,4 +9,4 @@ | ||
| set -eu | ||
| root=$(cd "$(dirname "$0")/.." && pwd) | ||
| owner=${1%%@*} | ||
| SSH_ORIGINAL_COMMAND=$2 GITV_REPOS=${GITV_REPOS:-$root/dev/repos} exec "$root/target/debug/gitv" serve "$owner" | ||
| SSH_ORIGINAL_COMMAND=$2 GITV_REPOS=${GITV_REPOS:-$root/dev/repos} exec "${CARGO_TARGET_DIR:-$root/target}/debug/gitv" serve "$owner" | ||
| @@ -0,0 +1,164 @@ | ||
| //! Helpers shared by both packages' integration tests: isolated git, scratch folders, and a | ||
| //! stand-in for ssh that runs `gitv serve`. Each package's `tests/common/mod.rs` includes this | ||
| //! file; the web tests add their own server and HTTP client. | ||
| #![allow(dead_code)] | ||
| use std::fs; | ||
| use std::os::unix::fs::PermissionsExt; | ||
| use std::path::{Path, PathBuf}; | ||
| use std::process::{Command, Output, Stdio}; | ||
| use std::sync::LazyLock; | ||
| /// The `gitv` binary. A test can only be told where its own package's binaries are, so the | ||
| /// web tests find it beside their own executable, where a workspace build puts it. | ||
| pub static GITV: LazyLock<String> = LazyLock::new(|| binary(option_env!("CARGO_BIN_EXE_gitv"), "gitv")); | ||
| /// The `gitv-web` binary, found the same way. | ||
| pub static GITV_WEB: LazyLock<String> = LazyLock::new(|| binary(option_env!("CARGO_BIN_EXE_gitv-web"), "gitv-web")); | ||
| fn binary(own: Option<&str>, name: &str) -> String { | ||
| if let Some(path) = own { | ||
| return path.to_string(); | ||
| } | ||
| // Test executables live in target/<profile>/deps; binaries one level up. | ||
| let exe = std::env::current_exe().unwrap(); | ||
| let path = exe.parent().and_then(Path::parent).unwrap().join(name); | ||
| assert!(path.is_file(), "{} isn't built; run the tests from the workspace root with `cargo test`", path.display()); | ||
| path.to_string_lossy().into_owned() | ||
| } | ||
| /// The hostname every test installation is configured with. | ||
| pub const TEST_HOST: &str = "git.example.test"; | ||
| /// A configuration file that doesn't exist, so the machine's own /etc/gitv/gitv.conf never applies. | ||
| pub const NO_CONFIG: &str = "/nonexistent/gitv.conf"; | ||
| /// A fresh, empty directory under Cargo's per-target temporary directory. | ||
| pub fn scratch(name: &str) -> PathBuf { | ||
| let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join(name); | ||
| let _ = fs::remove_dir_all(&dir); | ||
| fs::create_dir_all(&dir).unwrap(); | ||
| dir | ||
| } | ||
| /// Git with no user or system config and a fixed identity and clock, so runs are repeatable. | ||
| pub fn git_cmd(dir: &Path) -> Command { | ||
| let mut command = Command::new("git"); | ||
| command | ||
| .current_dir(dir) | ||
| .env("HOME", dir) | ||
| .env("GIT_CONFIG_NOSYSTEM", "1") | ||
| .env("GIT_CONFIG_GLOBAL", "/dev/null") | ||
| .env("GIT_AUTHOR_NAME", "Ada Lovelace") | ||
| .env("GIT_AUTHOR_EMAIL", "ada@example.com") | ||
| .env("GIT_COMMITTER_NAME", "Ada Lovelace") | ||
| .env("GIT_COMMITTER_EMAIL", "ada@example.com") | ||
| .env("GIT_AUTHOR_DATE", "2026-01-02T03:04:05Z") | ||
| .env("GIT_COMMITTER_DATE", "2026-01-02T03:04:05Z") | ||
| .env("GIT_SSH_VARIANT", "simple") | ||
| .stdin(Stdio::null()); | ||
| command | ||
| } | ||
| /// Run git in `dir`, panic with its output on failure, and return trimmed stdout. | ||
| pub fn git(dir: &Path, args: &[&str]) -> String { | ||
| let output = git_cmd(dir).args(args).output().unwrap(); | ||
| assert!(output.status.success(), "git {args:?} failed: {}", String::from_utf8_lossy(&output.stderr)); | ||
| String::from_utf8_lossy(&output.stdout).trim().to_string() | ||
| } | ||
| /// A GITv installation in a scratch directory: repositories, a keys file, and a fake `ssh` | ||
| /// that hands git's command to `gitv serve` as an owner's key would. | ||
| pub struct Host { | ||
| pub dir: PathBuf, | ||
| pub repos: PathBuf, | ||
| pub keys: PathBuf, | ||
| } | ||
| impl Host { | ||
| pub fn new(name: &str) -> Host { | ||
| let dir = scratch(name); | ||
| let repos = dir.join("repos"); | ||
| fs::create_dir_all(&repos).unwrap(); | ||
| let keys = dir.join("authorized_keys"); | ||
| let host = Host { dir, repos, keys }; | ||
| // With GIT_SSH_VARIANT=simple git runs: <ssh> <owner>@host <command>. | ||
| let script = format!( | ||
| "#!/bin/sh\nowner=${{1%%@*}}\nSSH_ORIGINAL_COMMAND=\"$2\" GITV_REPOS='{}' GITV_LOG='{}' GITV_HOST={TEST_HOST} GITV_CONFIG={NO_CONFIG} exec '{}' serve \"$owner\"\n", | ||
| host.repos.display(), | ||
| host.log().display(), | ||
| *GITV | ||
| ); | ||
| let ssh = host.ssh_script(); | ||
| fs::write(&ssh, script).unwrap(); | ||
| fs::set_permissions(&ssh, fs::Permissions::from_mode(0o755)).unwrap(); | ||
| host | ||
| } | ||
| /// Where `gitv` writes its operator log in tests. | ||
| pub fn log(&self) -> PathBuf { | ||
| self.dir.join("operator.log") | ||
| } | ||
| /// The operator log so far, empty if nothing was logged. | ||
| pub fn logged(&self) -> String { | ||
| fs::read_to_string(self.log()).unwrap_or_default() | ||
| } | ||
| pub fn ssh_script(&self) -> PathBuf { | ||
| self.dir.join("fake-ssh") | ||
| } | ||
| /// `ssh git@host <command>` as `owner`'s key. | ||
| pub fn ssh(&self, owner: &str, command: &str) -> Output { | ||
| Command::new(&*GITV) | ||
| .args(["serve", owner]) | ||
| .env("SSH_ORIGINAL_COMMAND", command) | ||
| .env("GITV_HOST", TEST_HOST) | ||
| .env("GITV_CONFIG", NO_CONFIG) | ||
| .env("GITV_REPOS", &self.repos) | ||
| .env("GITV_LOG", self.log()) | ||
| .stdin(Stdio::null()) | ||
| .output() | ||
| .unwrap() | ||
| } | ||
| /// `gitv <args>` as the administrator, pointed at this host. | ||
| pub fn admin(&self, args: &[&str]) -> Output { | ||
| Command::new(&*GITV) | ||
| .args(args) | ||
| .env("GITV_HOST", TEST_HOST) | ||
| .env("GITV_CONFIG", NO_CONFIG) | ||
| .env("GITV_REPOS", &self.repos) | ||
| .env("GITV_KEYS", &self.keys) | ||
| .env("GITV_LOG", self.log()) | ||
| .stdin(Stdio::null()) | ||
| .output() | ||
| .unwrap() | ||
| } | ||
| /// Git in `dir`, with remotes reached through this host's fake ssh. | ||
| pub fn git(&self, dir: &Path, args: &[&str]) -> Output { | ||
| git_cmd(dir).env("GIT_SSH_COMMAND", self.ssh_script()).args(args).output().unwrap() | ||
| } | ||
| pub fn repo(&self, owner: &str, name: &str) -> PathBuf { | ||
| self.repos.join(owner).join(format!("{name}.git")) | ||
| } | ||
| } | ||
| pub fn stdout(output: &Output) -> String { | ||
| String::from_utf8_lossy(&output.stdout).into_owned() | ||
| } | ||
| pub fn stderr(output: &Output) -> String { | ||
| String::from_utf8_lossy(&output.stderr).into_owned() | ||
| } | ||
| /// A syntactically valid OpenSSH Ed25519 public key built from `seed`. | ||
| pub fn ed25519_key(seed: u8) -> String { | ||
| use base64::Engine; | ||
| let mut blob = 11u32.to_be_bytes().to_vec(); | ||
| blob.extend_from_slice(b"ssh-ed25519"); | ||
| blob.extend_from_slice(&32u32.to_be_bytes()); | ||
| blob.extend_from_slice(&[seed; 32]); | ||
| format!("ssh-ed25519 {} test@example\n", base64::engine::general_purpose::STANDARD.encode(blob)) | ||
| } | ||