GITv

Move installation-specific values into /etc/gitv/gitv.conf

Browse files

The hostname, the forced-command path written by add-key, and the web account's default name were hard-coded for one server. The host now comes from GITV_HOST, then the config file, then the machine's hostname; the command defaults to /usr/local/bin/gitv. Unknown keys and bad values are errors that stop both binaries at startup, and over SSH the details go to the operator log only. A first gitv-web setup now names the account admin, and setup --force keeps the existing account's name. deploy/gitv.conf holds this server's settings, and tests run against git.example.test with no config file. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Author
Um9i vulgarmessiah@gmail.com
Date
22 Nov 2026, 16:07
Commit
ce526ea46651
Parent
a58a982

17 files changed +320−49

@@ -15,7 +15,7 @@ futures-util = { version = "0.3.34", default-features = false, features = ["std"
getrandom = "0.4.3"
hmac = "0.13.0"
html-escape = "0.3.1"
nix = { version = "0.32.0", features = ["user", "fs", "dir", "resource"] }
nix = { version = "0.32.0", features = ["user", "fs", "dir", "resource", "hostname"] }
pulldown-cmark = { version = "0.13.6", default-features = false, features = ["html"] }
qrcode = { version = "0.15.0", default-features = false }
rpassword = "7.5.5"
+15−3
@@ -40,7 +40,7 @@ The browser follows the system's light or dark setting. Its stylesheet (`assets/
The browser asks for a username, a password and a code from an authenticator app (TOTP, as used by Google Authenticator, 1Password, Aegis and others). Create the account once on the server, as the user the browser runs as (or as root, which hands the file to the `gitv-web` account):
```sh
gitv-web setup # account Um9i; --user NAME for another; --force to replace it
gitv-web setup # account admin; --user NAME for another; --force to replace it (keeping its name)
```
It prints a generated password (20 random characters, shown only this once), the authenticator secret, and a QR code to scan. Then sign in at the browser's address.
@@ -59,7 +59,7 @@ Set `GITV_REPOS` (and optionally `GITV_KEYS`) to point at a local tree. When `GI
```sh
cargo build
export GITV_REPOS=$PWD/dev/repos GITV_KEYS=$PWD/dev/authorized_keys
export GITV_REPOS=$PWD/dev/repos GITV_KEYS=$PWD/dev/authorized_keys GITV_HOST=localhost
mkdir -p dev/repos
./target/debug/gitv create um9i demo
export GITV_WEB_AUTH=$PWD/dev/web-login
@@ -83,13 +83,25 @@ 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`.
## Configuration
Settings that differ between installations live in `/etc/gitv/gitv.conf` (`deploy/gitv.conf` is this server's copy; `$GITV_CONFIG` points elsewhere):
```sh
host = git.um9i.dev # in clone addresses and help; default: $GITV_HOST, then the machine's hostname
command = /usr/local/bin/gitv # what add-key writes into each key's forced command (this is the default)
```
It must be readable by the `git` and `gitv-web` accounts (mode 0644). Both binaries check it at startup and refuse to run with an unknown setting or a bad value. Over SSH, a key holder is told only that the server is misconfigured, and the details go to the operator log. `gitv-web serve` prints the host it uses and where that came from.
## Production configuration
The deployment files are the source copies for the Fedora host. Caddy uses
`deploy/Caddyfile` at `/etc/caddy/Caddyfile`. The web service runs with
`deploy/gitv-web.service` at `/etc/systemd/system/gitv-web.service`, alongside
Fedora's distribution-provided systemd defaults. OpenSSH uses
`deploy/sshd-gitv.conf` at `/etc/ssh/sshd_config.d/90-gitv.conf`. The trash purge runs from
`deploy/sshd-gitv.conf` at `/etc/ssh/sshd_config.d/90-gitv.conf`. GITV's own settings are
`deploy/gitv.conf` at `/etc/gitv/gitv.conf`. The trash purge runs from
`deploy/gitv-purge.service` and `deploy/gitv-purge.timer` in `/etc/systemd/system`, enabled with
`systemctl enable --now gitv-purge.timer`.
+8−0
@@ -0,0 +1,8 @@
# 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.
# The name people reach this server by, in clone addresses and help.
host = git.um9i.dev
# Where gitv is installed: what `gitv add-key` writes into each key's forced command.
command = /usr/local/bin/gitv
@@ -4,7 +4,7 @@
//! The account lives in one small file (see [`auth_path`]), readable only by its owner:
//!
//! ```text
//! user=Um9i
//! user=admin
//! password=$argon2id$v=19$m=19456,t=2,p=1$...
//! totp=JBSWY3DPEHPK3PXP...
//! ```
@@ -25,8 +25,8 @@ use sha1::Sha1;
use sha2::{Digest, Sha256};
use subtle::ConstantTimeEq;
/// The account name `gitv-web setup` uses unless told otherwise.
pub const DEFAULT_USER: &str = "Um9i";
/// The account name a first `gitv-web setup` uses unless told otherwise.
pub const DEFAULT_USER: &str = "admin";
/// How authenticator apps label the account.
pub const ISSUER: &str = "GITv";
/// Shortest password accepted, in characters.
@@ -521,7 +521,7 @@ mod tests {
fn account() -> Credentials {
Credentials {
user: DEFAULT_USER.into(),
user: "Um9i".into(),
password_hash: hash_password("correct horse battery").unwrap(),
totp_secret: RFC_SECRET.to_vec(),
}
@@ -568,11 +568,14 @@ pub async fn change_password(
/// # Errors
/// [`AuthError::AlreadySetUp`] if the account exists and `force` isn't set, or any error from
/// creating and saving it.
pub fn setup(user: &str, force: bool) -> Result<(), AuthError> {
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);
// 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)?;
let path = auth_path();
// 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()?;
@@ -64,9 +64,9 @@ enum Action {
},
/// Create the web account: a generated password and an authenticator (2FA) secret
Setup {
/// The account name
#[arg(long, default_value = gitv::auth::DEFAULT_USER)]
user: String,
/// The account name [default: the current account's with --force, otherwise admin]
#[arg(long)]
user: Option<String>,
/// Replace an existing account, signing every session out
#[arg(long)]
force: bool,
@@ -187,7 +187,7 @@ async fn blocking(visitor: Visitor, f: impl FnOnce() -> View + Send + 'static) -
fn main() -> std::process::ExitCode {
let outcome = match Cli::parse().action {
Action::Serve { port } => serve(port),
Action::Setup { user, force } => login::setup(&user, force).map_err(|e| e.to_string()),
Action::Setup { user, force } => login::setup(user.as_deref(), force).map_err(|e| e.to_string()),
Action::Password => login::change_password_at_terminal(),
};
match outcome {
@@ -200,6 +200,7 @@ fn main() -> std::process::ExitCode {
}
fn serve(port: u16) -> Result<(), String> {
let config = gitv::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.
@@ -268,7 +269,12 @@ fn serve(port: u16) -> Result<(), String> {
.map_err(|e| format!("can't listen on port {port}: {e}"))?;
// Print the bound address (not the requested port), so `--port 0` works for tests.
let address = listener.local_addr().map_err(|e| e.to_string())?;
println!("gitv-web listening on http://{address} (repos: {})", repos_root().display());
println!(
"gitv-web listening on http://{address} (repos: {}; host {} from {})",
repos_root().display(),
config.host,
config.host_source
);
// Connection details let sign-in throttle each client separately.
let app = app.into_make_service_with_connect_info::<std::net::SocketAddr>();
axum::serve(listener, app).await.map_err(|e| e.to_string())
@@ -7,7 +7,7 @@ use std::os::fd::{AsFd, OwnedFd};
use std::sync::Arc;
use std::time::{Instant, SystemTime, UNIX_EPOCH};
use gitv::{HOST, RepoDir, entries, open_dir_at, open_owner, open_root, repo_in, try_subdirs};
use gitv::{RepoDir, config, entries, open_dir_at, open_owner, open_root, repo_in, try_subdirs};
use super::Repo;
use crate::cache::cached;
@@ -137,8 +137,15 @@ pub(crate) fn view_index(signed_in: bool) -> View {
})
.collect();
View::Html(
templates::Repositories { title: "Repositories", signed_in, count, rows, branch: icon("branch"), host: HOST }
.to_string(),
templates::Repositories {
title: "Repositories",
signed_in,
count,
rows,
branch: icon("branch"),
host: config::host(),
}
.to_string(),
)
}
@@ -12,7 +12,7 @@ use std::fmt::Write as _;
use std::os::unix::ffi::OsStrExt;
use std::time::Instant;
use gitv::{HOST, RepoDir, render, repo_dir};
use gitv::{RepoDir, config, render, repo_dir};
use html_escape::{encode_double_quoted_attribute as attr, encode_text as esc};
use crate::html::{ago, icon, layout, subject_or_placeholder};
@@ -61,9 +61,9 @@ impl Repo {
pub(crate) fn clone_address(&self) -> (&'static str, String) {
if self.reader.dir.is_public() {
("HTTPS", format!("https://{HOST}/{}/{}", self.owner, self.name))
("HTTPS", format!("https://{}/{}/{}", config::host(), self.owner, self.name))
} else {
("SSH", format!("git@{HOST}:{}/{}.git", self.owner, self.name))
("SSH", format!("git@{}:{}/{}.git", config::host(), self.owner, self.name))
}
}
@@ -3,7 +3,7 @@
use std::ffi::OsStr;
use std::sync::Arc;
use gitv::{HOST, render};
use gitv::{config, render};
use html_escape::encode_text as esc;
use super::{Entry, PAGE, Repo, SHOW_LIMIT, entry};
@@ -22,7 +22,8 @@ pub(crate) fn view_tree(repo: &Repo, q: &Q) -> Option<View> {
let body = repo.masthead("tree", &reference, None)
+ &format!(
r#"<div class="panel empty"><h2>This repository is empty</h2><p>Push a branch to get started.</p>
<code>git push git@{HOST}:{}/{}.git main</code></div>"#,
<code>git push git@{}:{}/{}.git main</code></div>"#,
config::host(),
esc(&repo.owner),
esc(&repo.name)
);
@@ -10,7 +10,7 @@ use std::process::{Command, ExitCode, Stdio};
use base64::Engine;
use clap::{Parser, Subcommand};
use gitv::{
HOST, NAME_RULE, RepoDir, chown_tree, entries, git, git_command, git_in, keys_path, kind_at, open_dir_at,
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,
};
use nix::errno::Errno;
@@ -22,12 +22,18 @@ use std::os::fd::{AsFd, OwnedFd};
use std::os::unix::ffi::OsStrExt;
use std::time::{SystemTime, UNIX_EPOCH};
const HELP: &str = "Commands for your key, run as: ssh git@git.um9i.dev <command>
/// What `help` prints.
fn help() -> String {
let host = config::host();
format!(
"Commands for your key, run as: ssh git@{host} <command>
list list your repositories
create <name> create an empty repository
visibility <name> public|private set web access
delete <name> --yes move a repository to the trash (the operator can restore it for 30 days)
Pushing to a repository that does not exist yet creates it.";
Pushing to a repository that does not exist yet creates it."
)
}
#[derive(Parser)]
#[command(about = "Private Git hosting over OpenSSH and Git's native pack protocol")]
@@ -383,7 +389,7 @@ fn restore(owner: &str, entry: &str, as_name: Option<&str>) -> Result<(), String
e => e.to_string(),
},
)?;
println!("restored git@{HOST}:{owner}/{name}.git");
println!("restored git@{}:{owner}/{name}.git", config::host());
Ok(())
}
@@ -447,7 +453,7 @@ fn add_key(owner: &str, file: &Path) -> Result<(), String> {
return Err("key already registered".into());
}
let separator = if old.is_empty() || old.ends_with('\n') { "" } else { "\n" };
let line = format!("{separator}restrict,command=\"/usr/local/bin/gitv serve {owner}\" ssh-ed25519 {token}\n");
let line = format!("{separator}restrict,command=\"{} serve {owner}\" ssh-ed25519 {token}\n", config::command());
let temporary = directory.join(format!(".authorized_keys.{}", std::process::id()));
let mut out = fs::File::create(&temporary).map_err(|e| e.to_string())?;
out.write_all(format!("{old}{line}").as_bytes()).map_err(|e| e.to_string())?;
@@ -509,10 +515,11 @@ fn visibility(owner: &str, name: &str, visibility: &str) -> Result<(), String> {
/// Handle one SSH request from a key registered to owner.
fn serve(owner: &str, command: &str) -> Result<u8, String> {
let args = shlex::split(command).ok_or("unreadable command; run: ssh git@git.um9i.dev help")?;
let args =
shlex::split(command).ok_or_else(|| format!("unreadable command; run: ssh git@{} help", config::host()))?;
let args: Vec<&str> = args.iter().map(String::as_str).collect();
match args.as_slice() {
[] | ["help"] => println!("{HELP}"),
[] | ["help"] => println!("{}", help()),
[program @ ("git-upload-pack" | "git-receive-pack"), path] => return serve_git(owner, program, path),
["visibility", name, value] => visibility(owner, name, value)?,
["list"] => {
@@ -526,7 +533,7 @@ fn serve(owner: &str, command: &str) -> Result<u8, String> {
.collect();
names.sort();
for name in names {
println!("git@{HOST}:{owner}/{name}.git");
println!("git@{}:{owner}/{name}.git", config::host());
}
}
["create", name] => {
@@ -534,7 +541,7 @@ fn serve(owner: &str, command: &str) -> Result<u8, String> {
// to the operator's log.
let name = check_name(name)?;
match create(owner, name) {
Ok(_) => println!("git@{HOST}:{owner}/{name}.git"),
Ok(_) => println!("git@{}:{owner}/{name}.git", config::host()),
Err(CreateError::Exists { .. }) => return Err("repository already exists".into()),
Err(error) => {
log_operator(&format!("ssh create of {owner}/{name}.git failed: {}", error.detail()));
@@ -555,7 +562,7 @@ fn serve(owner: &str, command: &str) -> Result<u8, String> {
"moved {owner}/{name}.git to the trash; the server's operator can restore it for {TRASH_DAYS} days"
);
}
_ => return Err("unknown command; run: ssh git@git.um9i.dev help".into()),
_ => return Err(format!("unknown command; run: ssh git@{} help", config::host())),
}
Ok(0)
}
@@ -742,6 +749,14 @@ fn fix_head(repo: &RepoDir) -> Result<(), String> {
fn run() -> Result<u8, String> {
let cli = Cli::parse();
if let Err(error) = config::load() {
if matches!(cli.action, Action::Serve { .. }) {
// A key holder needn't see the server's paths; the operator does.
log_operator(&format!("bad configuration: {error}"));
return Err("the server is misconfigured; its operator can see why".into());
}
return Err(error);
}
if let Action::Serve { owner } = &cli.action {
return serve(owner, &std::env::var("SSH_ORIGINAL_COMMAND").unwrap_or_default());
}
@@ -753,7 +768,7 @@ fn run() -> Result<u8, String> {
Action::Create { owner, name } => {
// An administrator sees everything.
let created = create(&owner, &name).map_err(|e| e.detail())?;
println!("git@{HOST}:{owner}/{name}.git");
println!("git@{}:{owner}/{name}.git", config::host());
if let Some(leftover) = created.leftover {
eprintln!("gitv: created {owner}/{name}.git, but {leftover}");
}
+158−0
@@ -0,0 +1,158 @@
//! Settings that differ between installations, read once from `/etc/gitv/gitv.conf`
//! (`$GITV_CONFIG` to use another file):
//!
//! ```text
//! # The name people reach this server by, in clone addresses and help.
//! host = git.example.com
//! # Where gitv is installed: what each key's forced command runs.
//! command = /usr/local/bin/gitv
//! ```
//!
//! Both are optional. `host` defaults to `$GITV_HOST`, then the machine's hostname; `command`
//! defaults to `/usr/local/bin/gitv`. A missing file means all defaults; an unknown key or a bad
//! value is an error, so a typo can't silently change nothing. Each binary calls [`load`] at
//! startup, so a problem stops it with a clear message before it serves anything.
use std::path::{Path, PathBuf};
use std::sync::LazyLock;
pub struct Config {
/// The server's public hostname, lowercase.
pub host: String,
/// The absolute path of the `gitv` binary, for forced commands.
pub command: String,
/// Where `host` came from, for startup messages.
pub host_source: &'static str,
}
static CONFIG: LazyLock<Result<Config, String>> =
LazyLock::new(|| read(&config_path(), std::env::var("GITV_HOST").ok()));
/// Where the configuration file is: `$GITV_CONFIG`, or `/etc/gitv/gitv.conf`.
pub fn config_path() -> PathBuf {
std::env::var_os("GITV_CONFIG").map_or_else(|| PathBuf::from("/etc/gitv/gitv.conf"), PathBuf::from)
}
/// Read and check the configuration.
///
/// # Errors
/// A message naming the file and the problem.
pub fn load() -> Result<&'static Config, String> {
CONFIG.as_ref().map_err(Clone::clone)
}
/// The server's public hostname. Binaries [`load`] the configuration first; should it be
/// broken anyway, `localhost` stands in rather than a wrong real name.
pub fn host() -> &'static str {
CONFIG.as_ref().map_or("localhost", |c| c.host.as_str())
}
/// The command each key's forced command runs.
pub fn command() -> &'static str {
CONFIG.as_ref().map_or("/usr/local/bin/gitv", |c| c.command.as_str())
}
fn read(path: &Path, host_override: Option<String>) -> Result<Config, String> {
let text = match std::fs::read_to_string(path) {
Ok(text) => text,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
Err(e) => return Err(format!("couldn't read {}: {e}", path.display())),
};
parse(&text, host_override).map_err(|e| format!("{}: {e}", path.display()))
}
fn parse(text: &str, host_override: Option<String>) -> Result<Config, String> {
let (mut host, mut command) = (None, None);
for (number, line) in text.lines().enumerate() {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
let (key, value) =
line.split_once('=').ok_or_else(|| format!("line {}: expected `key = value`", number + 1))?;
let value = value.trim().to_string();
match key.trim() {
"host" => host = Some(value),
"command" => command = Some(value),
other => return Err(format!("line {}: unknown setting `{other}` (known: host, command)", number + 1)),
}
}
// Every value given is checked, even one GITV_HOST overrides: a broken file is still broken.
let checked = |host: String, source: &'static str| {
let host = host.to_ascii_lowercase();
if valid_host(&host) { Ok((host, source)) } else { Err(format!("`{host}` (from {source}) isn't a hostname")) }
};
let from_file = host.map(|host| checked(host, "the configuration file")).transpose()?;
let (host, host_source) = match (host_override, from_file) {
(Some(host), _) => checked(host, "GITV_HOST")?,
(None, Some(found)) => found,
(None, None) => {
let name = nix::unistd::gethostname().map_err(|e| format!("no host set and no hostname: {e}"))?;
checked(name.to_string_lossy().into_owned(), "the machine's hostname")?
}
};
let command = command.unwrap_or_else(|| "/usr/local/bin/gitv".into());
// It goes inside command="..." in authorized_keys, so nothing that could end or escape that.
if !command.starts_with('/') || command.bytes().any(|b| b.is_ascii_whitespace() || b"\"\\'".contains(&b)) {
return Err(format!("command `{command}` must be an absolute path without spaces or quotes"));
}
Ok(Config { host, command, host_source })
}
/// A DNS name: dot-separated labels of letters, digits and inner hyphens, 253 characters at most.
fn valid_host(host: &str) -> bool {
host.len() <= 253
&& host.split('.').all(|label| {
(1..=63).contains(&label.len())
&& label.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
&& !label.starts_with('-')
&& !label.ends_with('-')
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn settings_come_from_the_file_with_the_environment_first() {
let file = "# comment\nhost = Git.Example.COM\n\ncommand = /opt/gitv/bin/gitv\n";
let config = parse(file, None).unwrap();
assert_eq!((config.host.as_str(), config.command.as_str()), ("git.example.com", "/opt/gitv/bin/gitv"));
assert_eq!(config.host_source, "the configuration file");
let config = parse(file, Some("other.example".into())).unwrap();
assert_eq!((config.host.as_str(), config.host_source), ("other.example", "GITV_HOST"));
}
#[test]
fn defaults_fill_in_what_is_missing() {
let config = parse("", None).unwrap();
assert_eq!(config.command, "/usr/local/bin/gitv");
assert_eq!(config.host_source, "the machine's hostname");
assert!(valid_host(&config.host));
}
#[test]
fn mistakes_are_refused_with_the_line() {
for (text, expected) in [
("hots = x.example", "line 1: unknown setting `hots`"),
("\nhost", "line 2: expected `key = value`"),
("host = git.example.com/repos", "isn't a hostname"),
("host = -bad.example", "isn't a hostname"),
("host = a..b", "isn't a hostname"),
("command = gitv", "must be an absolute path"),
("command = /usr/bin/gitv\" evil", "must be an absolute path"),
] {
let error = parse(text, Some("ok.example".into())).err().unwrap_or_default();
assert!(error.contains(expected), "{text:?}: {error}");
}
}
#[test]
fn a_missing_file_means_defaults_and_an_unreadable_one_is_an_error() {
let missing = std::env::temp_dir().join(format!("gitv-no-config-{}", std::process::id()));
assert!(read(&missing, Some("x.example".into())).is_ok());
let error = read(&std::env::temp_dir(), None).err().unwrap_or_default();
assert!(error.contains("couldn't read"), "{error}");
}
}
@@ -1,6 +1,7 @@
//! 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};
@@ -20,8 +21,6 @@ use nix::fcntl::{AtFlags, OFlag, open, openat};
use nix::sys::stat::{Mode, SFlag, fstatat};
use nix::unistd::{Gid, Uid, UnlinkatFlags, fchown, fchownat, unlinkat};
pub const HOST: &str = "git.um9i.dev";
/// Where bare repositories live: `<root>/<owner>/<name>.git`. `GITV_REPOS` overrides it for local runs.
pub fn repos_root() -> PathBuf {
std::env::var_os("GITV_REPOS").map_or_else(|| PathBuf::from("/srv/gitv/repos"), PathBuf::from)
@@ -7,7 +7,7 @@
{% if signed_in %}
<h2>No repositories yet</h2>
<p>Create your first repository by pushing a branch over SSH.</p>
<code>git push git@{{ host }}:um9i/my-project.git main</code>
<code>git push git@{{ host }}:&lt;owner&gt;/my-project.git main</code>
{% else %}
<h2>No public repositories yet</h2>
<a class="button" href="/login">Sign in to view private repositories</a>
@@ -487,10 +487,18 @@ mod setup {
}
#[test]
fn uses_um9i_by_default() {
fn names_the_first_account_admin_and_keeps_the_name_when_replacing_it() {
let dir = scratch("auth-setup-user");
let account = common::Account::create(&dir);
assert_eq!(gitv::auth::Credentials::load(&account.file).unwrap().user(), "Um9i");
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();
assert!(out.status.success(), "{}", stderr(&out));
gitv::auth::Credentials::load(&file).unwrap().user().to_string()
};
assert_eq!(setup(&[]), "admin");
assert_eq!(setup(&["--force", "--user", "Um9i"]), "Um9i");
assert_eq!(setup(&["--force"]), "Um9i", "a replaced account keeps its name");
}
#[test]
@@ -13,6 +13,10 @@ 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 {
@@ -65,7 +69,7 @@ impl Host {
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='{}' exec '{GITV}' serve \"$owner\"\n",
"#!/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()
);
@@ -94,6 +98,8 @@ impl Host {
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())
@@ -105,6 +111,8 @@ impl 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())
@@ -143,7 +151,8 @@ impl Account {
/// Run `gitv-web setup` for a new account in `dir`.
pub fn create(dir: &Path) -> Account {
let file = dir.join("login");
let out = Command::new(GITV_WEB).arg("setup").env("GITV_WEB_AUTH", &file).output().unwrap();
let out =
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| {
@@ -240,6 +249,8 @@ impl Server {
let log = account.file.with_file_name(format!("server-{}-{number}.log", std::process::id()));
let mut child = command
.args(["serve", "--port", "0"])
.env("GITV_HOST", TEST_HOST)
.env("GITV_CONFIG", NO_CONFIG)
.env("GITV_REPOS", repos)
.env("GITV_WEB_AUTH", &account.file)
.stdout(Stdio::piped())
@@ -42,12 +42,15 @@ fn create_list_and_delete() {
let host = Host::new("ssh-crud");
let out = host.ssh("ada", "create notes");
assert!(out.status.success(), "{}", stderr(&out));
assert_eq!(stdout(&out).trim(), "git@git.um9i.dev:ada/notes.git");
assert_eq!(stdout(&out).trim(), "git@git.example.test:ada/notes.git");
assert!(host.repo("ada", "notes").join("HEAD").is_file());
assert!(!host.ssh("ada", "create notes").status.success(), "duplicates are refused");
host.ssh("ada", "create alpha");
assert_eq!(stdout(&host.ssh("ada", "list")), "git@git.um9i.dev:ada/alpha.git\ngit@git.um9i.dev:ada/notes.git\n");
assert_eq!(
stdout(&host.ssh("ada", "list")),
"git@git.example.test:ada/alpha.git\ngit@git.example.test:ada/notes.git\n"
);
assert_eq!(stdout(&host.ssh("bob", "list")), "", "owners only see their own repositories");
let out = host.ssh("ada", "delete notes");
@@ -62,7 +65,7 @@ fn create_list_and_delete() {
assert_eq!(trash(&host, "ada").len(), 1, "the repository waits in the trash");
assert!(host.logged().contains("ada/notes.git moved to the trash"), "{}", host.logged());
assert!(!host.ssh("ada", "delete notes --yes").status.success(), "a missing repository can't be deleted");
assert_eq!(stdout(&host.ssh("ada", "list")), "git@git.um9i.dev:ada/alpha.git\n", "the trash isn't listed");
assert_eq!(stdout(&host.ssh("ada", "list")), "git@git.example.test:ada/alpha.git\n", "the trash isn't listed");
}
/// The names in an owner's trash.
@@ -155,7 +158,7 @@ fn admin_create_and_delete() {
let host = Host::new("admin-crud");
let out = host.admin(&["create", "ada", "tools"]);
assert!(out.status.success(), "{}", stderr(&out));
assert_eq!(stdout(&out).trim(), "git@git.um9i.dev:ada/tools.git");
assert_eq!(stdout(&out).trim(), "git@git.example.test:ada/tools.git");
assert_eq!(git(&host.repo("ada", "tools"), &["symbolic-ref", "HEAD"]), "refs/heads/main");
let out = host.admin(&["delete", "ada", "tools"]);
@@ -231,6 +234,46 @@ fn overwritten_and_deleted_branches_stay_recoverable() {
assert_eq!(git(&repo, &["cat-file", "-t", &first]), "commit", "the deleted branch's commit is still there");
}
#[test]
fn the_configuration_file_sets_the_host_and_the_forced_command() {
let host = Host::new("ssh-config");
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)
.args(args)
.env("GITV_CONFIG", &config)
.env("GITV_REPOS", &host.repos)
.env("GITV_KEYS", &host.keys)
.output()
.unwrap()
};
let out = admin(&["create", "ada", "tools"]);
assert!(out.status.success(), "{}", stderr(&out));
assert_eq!(stdout(&out).trim(), "git@code.example.org:ada/tools.git");
let key = host.dir.join("ada.pub");
fs::write(&key, ed25519_key(3)).unwrap();
assert!(admin(&["add-key", "ada", key.to_str().unwrap()]).status.success());
assert!(fs::read_to_string(&host.keys).unwrap().starts_with("restrict,command=\"/opt/gitv/bin/gitv serve ada\""));
// A mistake stops every command, and a key holder isn't shown the server's paths.
fs::write(&config, "hostname = code.example.org\n").unwrap();
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)
.args(["serve", "ada"])
.env("SSH_ORIGINAL_COMMAND", "list")
.env("GITV_CONFIG", &config)
.env("GITV_REPOS", &host.repos)
.env("GITV_LOG", host.log())
.output()
.unwrap();
assert!(!out.status.success());
assert!(stderr(&out).contains("misconfigured") && !stderr(&out).contains("gitv.conf"), "{}", stderr(&out));
assert!(host.logged().contains("unknown setting `hostname`"), "{}", host.logged());
}
#[test]
fn admin_add_key() {
let host = Host::new("admin-keys");
@@ -337,7 +337,7 @@ fn tree_lists_folders_first_and_renders_the_readme() {
assert!(html.contains("Commits<span class=\"n\">5</span>"), "commit count on main, side included");
assert!(html.contains("Tags<span class=\"n\">3</span>"));
assert!(html.contains("Add a submodule and a big file"), "latest commit in the header");
assert!(html.contains("git@git.um9i.dev:ada/site.git"), "clone address");
assert!(html.contains("git@git.example.test:ada/site.git"), "clone address");
// README rendering: Markdown, safe links and escaped HTML.
assert!(html.contains("<article class=\"markdown\"><h1 id=\"md-fixture-onclickalert1-main-skip\">Fixture {onclick=alert(1) #main .skip}</h1>"), "{html}");
@@ -594,7 +594,7 @@ fn empty_repository_explains_how_to_start() {
assert_eq!(page.status, 200);
let html = page.text();
assert!(html.contains("This repository is empty"));
assert!(html.contains("git push git@git.um9i.dev:ada/empty.git main"));
assert!(html.contains("git push git@git.example.test:ada/empty.git main"));
let tags = s.get("/ada/empty/tags").text();
assert!(tags.contains("No tags yet"));
}
@@ -828,7 +828,7 @@ fn public_web_clone_and_visibility_changes() {
assert!(!index.contains("/ada/secret/tree"));
assert!(server.get("/").text().contains("/ada/secret/tree"));
let page = server.get_signed_out("/ada/sharing/tree").text();
assert!(page.contains("https://git.um9i.dev/ada/sharing"));
assert!(page.contains("https://git.example.test/ada/sharing"));
assert_eq!(server.get_signed_out("/ada/sharing/raw?path=hello").text(), "public content");
git(&work, &["clone", &url, "copy"]);
let copy = work.join("copy");