GITv

Fix review findings: symlinks, cache isolation, keys, refs and names

Browse files

Security and correctness: - Refuse symlinked owner and repository directories over SSH and on the web, and change ownership with lchown so links are never followed. - Key rendered-Markdown and diff caches by repository, so a README shared by two repositories no longer links into the wrong one. - add-key prepares the owner directory before publishing the key, finds duplicates by the decoded key wherever it sits in a line, and starts a new line when the file lacks a final newline. - A push that loses the race to create a repository uses the winner's, and failed creations clean up their staging directory. - Resolve branches and tags by their exact full ref, so any name git allows opens, while revision syntax is still refused. - Keep file paths as raw bytes from URL to git, and name diff files from NUL-delimited name-status output, so non-UTF-8, quoted and " b/" names link correctly. - Read at most 2 MiB of a commit's patch; larger commits list their files instead of returning 404. - The git watchdog can always kill: waiting polls with brief locks. - Don't cache failed git reads; show "(no message)" for empty subjects; prefer README.md over a plain README; fix cache size accounting. Speed: one git call per repository on the index, cached file facts so repeat views read no blob, cached diffs and latest-commit lookups, at most 16 concurrent renders, and LTO for release builds. Also: a tracked, relocatable scripts/fake-ssh for the README example, a note on the web browser's trust model, rustfmt settings with the tree formatted, and regression tests for every finding (59 tests). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Author
Um9i vulgarmessiah@gmail.com
Date
22 Nov 2026, 11:34
Commit
e03ba7417d8c
Parent
c7a42be

10 files changed +1205−368

@@ -12,4 +12,8 @@ nix = { version = "0.32.0", features = ["user", "fs"] }
pulldown-cmark = { version = "0.13.6", default-features = false, features = ["html"] }
shlex = "2.0.1"
syntect = { version = "5.3.0", default-features = false, features = ["default-syntaxes", "html", "regex-onig"] }
tokio = { version = "1.54.1", features = ["rt-multi-thread", "macros", "net"] }
tokio = { version = "1.54.1", features = ["rt-multi-thread", "macros", "net", "sync"] }
[profile.release]
lto = "thin"
codegen-units = 1
+8−2
@@ -5,6 +5,10 @@ Private Git hosting over OpenSSH, plus a read-only web browser.
- `gitv`: the SSH forced-command handler (`serve`) and the root admin CLI (`create`, `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`)
**Who can read what.** Over SSH each key reaches only its owner's repositories. The web browser has no per-owner access control: it shows every repository on the server to anyone who can reach it. It binds to localhost only, and is meant for one trusted audience behind the reverse proxy's login. Don't expose it more widely, or give web logins to people who shouldn't read every owner's code.
**Storage.** Repositories live in `/srv/gitv/repos/<owner>/<name>.git`. Owner and repository directories must be real directories: GITv refuses symlinks at either level rather than follow them out of the tree.
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.
## Run locally
@@ -19,10 +23,12 @@ mkdir -p dev/repos
./target/debug/gitv-web serve --port 8080 # http://127.0.0.1:8080
```
`dev/fake-ssh` stands in for ssh, so you can push and clone through `gitv serve` without an SSH server:
`scripts/fake-ssh` stands in for ssh, so you can push and clone through `gitv serve` without an SSH server. The user part of the URL picks the owner whose key it acts as:
```sh
GIT_SSH_COMMAND=$PWD/dev/fake-ssh git push git@x:um9i/myrepo.git main
export GIT_SSH_VARIANT=simple GIT_SSH_COMMAND=$PWD/scripts/fake-ssh
git push um9i@local:um9i/myrepo.git main
git clone um9i@local:um9i/myrepo.git
```
## Tests
+2−0
@@ -0,0 +1,2 @@
max_width = 120
use_small_heuristics = "Max"
+12−0
@@ -0,0 +1,12 @@
#!/bin/sh
# Stands in for ssh when trying GITv locally: hands git's command to `gitv serve` as the key of
# the owner named in the URL's user part. Use it with GIT_SSH_VARIANT=simple, which makes git
# run: fake-ssh <owner>@<host> '<git command>'.
#
# GIT_SSH_VARIANT=simple GIT_SSH_COMMAND=scripts/fake-ssh git push um9i@local:um9i/demo.git main
#
# Repositories go to $GITV_REPOS, or dev/repos in this checkout.
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"
@@ -1,20 +1,26 @@
//! Read-only web browser for GITv repositories, served on localhost behind Caddy.
//!
//! Every repository on the server is visible to anyone who can reach this service: it is meant
//! for one trusted audience behind the proxy's login, not for per-owner access like SSH.
use std::borrow::Cow;
use std::cell::OnceCell;
use std::cmp::Reverse;
use std::collections::HashMap;
use std::ffi::{OsStr, OsString};
use std::fmt::Write as _;
use std::os::unix::ffi::{OsStrExt, OsStringExt};
use std::path::PathBuf;
use std::sync::{Arc, LazyLock, Mutex};
use std::time::{SystemTime, UNIX_EPOCH};
use axum::extract::{Path, Query};
use axum::extract::{Path, RawQuery};
use axum::http::{StatusCode, header};
use axum::response::{IntoResponse, Redirect, Response};
use axum::{Router, routing::get};
use clap::{Parser, Subcommand};
use gitv::render;
use gitv::{HOST, git, repos_root, valid_name};
use gitv::{HOST, git, git_capped, repo_dir, repos_root};
use html_escape::{encode_double_quoted_attribute as attr, encode_text as esc};
const STYLESHEET: &str = include_str!("../../assets/style.css");
@@ -40,10 +46,15 @@ const PAGE: usize = 50;
const RAW_LIMIT: usize = 50 << 20;
/// Largest file shown on a page; bigger files offer Raw instead.
const SHOW_LIMIT: usize = 1 << 20;
/// Largest patch shown on a commit page; only this much is ever read.
const DIFF_LIMIT: usize = 2 << 20;
/// Rendered HTML and commit counts keyed by immutable object ids, so repeat views skip the
/// expensive work. Emptied whenever it outgrows its budget.
// ---------------------------------------------------------------------------------------------
// Cache
/// Rendered HTML and git answers keyed by immutable object ids, so repeat views skip the
/// expensive work. Keys for anything that contains links include the repository, since the
/// same content in two repositories links differently. Emptied whenever it outgrows its budget.
#[derive(Default)]
struct Cache {
entries: HashMap<String, Arc<str>>,
@@ -53,23 +64,31 @@ struct Cache {
static CACHE: LazyLock<Mutex<Cache>> = LazyLock::new(Default::default);
const CACHE_BUDGET: usize = 32 << 20;
fn cached(key: String, make: impl FnOnce() -> String) -> Arc<str> {
/// The cached value for `key`, or `make`'s. A failure (`None`) is never cached, so a git
/// command that timed out is retried next time instead of leaving a blank forever.
fn cached(key: String, make: impl FnOnce() -> Option<String>) -> Option<Arc<str>> {
if let Some(hit) = CACHE.lock().ok().and_then(|c| c.entries.get(&key).cloned()) {
return hit;
return Some(hit);
}
let value: Arc<str> = make().into();
let value: Arc<str> = make()?.into();
if let Ok(mut cache) = CACHE.lock() {
let cost = key.len() + value.len();
if cache.bytes + cost > CACHE_BUDGET {
let key_len = key.len();
if cache.bytes + key_len + value.len() > CACHE_BUDGET {
cache.entries.clear();
cache.bytes = 0;
}
cache.bytes += cost;
cache.entries.insert(key, Arc::clone(&value));
// Two requests can render the same key at once; count only the entry that stays.
if let Some(old) = cache.entries.insert(key, Arc::clone(&value)) {
cache.bytes -= key_len + old.len();
}
cache.bytes += key_len + value.len();
}
value
Some(value)
}
// ---------------------------------------------------------------------------------------------
// Responses
#[derive(Parser)]
#[command(about = "Read-only web browser for GITv repositories")]
struct Cli {
@@ -86,19 +105,19 @@ enum Action {
},
}
type Q = HashMap<String, String>;
enum View {
Html(String),
/// Bytes, content type, and a download name for files the browser shouldn't display.
Raw(Vec<u8>, &'static str, Option<String>),
Raw(Vec<u8>, &'static str, Option<Vec<u8>>),
Redirect(String),
Missing,
}
const SECURITY: [(header::HeaderName, &str); 4] = [
(header::CONTENT_SECURITY_POLICY,
"default-src 'none'; style-src 'self'; font-src 'self'; img-src 'self'; base-uri 'none'; frame-ancestors 'none'"),
(
header::CONTENT_SECURITY_POLICY,
"default-src 'none'; style-src 'self'; font-src 'self'; img-src 'self'; base-uri 'none'; frame-ancestors 'none'",
),
(header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
(header::REFERRER_POLICY, "no-referrer"),
(header::CACHE_CONTROL, "no-store"),
@@ -111,8 +130,8 @@ impl IntoResponse for View {
View::Html(body) => (SECURITY, html, body).into_response(),
View::Raw(data, kind, download) => {
let mut response = (SECURITY, [(header::CONTENT_TYPE, kind)], data).into_response();
if let Some(value) = download
.and_then(|name| format!("attachment; filename*=UTF-8''{}", encode(&name)).parse().ok())
if let Some(value) =
download.and_then(|name| format!("attachment; filename*=UTF-8''{}", encode(&name)).parse().ok())
{
response.headers_mut().insert(header::CONTENT_DISPOSITION, value);
}
@@ -129,20 +148,120 @@ fn static_file(kind: &'static str, data: &'static [u8]) -> Response {
}
fn stylesheet() -> Response {
let headers = [(header::CONTENT_TYPE, "text/css; charset=utf-8"), (header::CACHE_CONTROL, "max-age=31536000, immutable")];
let headers =
[(header::CONTENT_TYPE, "text/css; charset=utf-8"), (header::CACHE_CONTROL, "max-age=31536000, immutable")];
(headers, STYLESHEET).into_response()
}
// ---------------------------------------------------------------------------------------------
// Helpers
// Query strings and paths
//
// File paths are bytes, not text: git allows any bytes but `/` and NUL in a name, so a path
// is decoded from the URL, checked and handed to git without ever passing through UTF-8.
/// Query parameters with their values percent-decoded to raw bytes. The first of a repeated
/// key wins.
type Q = HashMap<String, Vec<u8>>;
fn parse_query(raw: Option<&str>) -> Q {
let mut query = Q::new();
for pair in raw.unwrap_or("").split('&').filter(|p| !p.is_empty()) {
let (key, value) = pair.split_once('=').unwrap_or((pair, ""));
if let Ok(key) = String::from_utf8(percent_decode(key)) {
query.entry(key).or_insert_with(|| percent_decode(value));
}
}
query
}
fn percent_decode(text: &str) -> Vec<u8> {
let bytes = text.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
let hex = |b: u8| (b as char).to_digit(16);
match bytes[i] {
b'+' => out.push(b' '),
b'%' if i + 2 < bytes.len() => match (hex(bytes[i + 1]), hex(bytes[i + 2])) {
(Some(high), Some(low)) => {
out.push((high * 16 + low) as u8);
i += 2;
}
_ => out.push(b'%'),
},
byte => out.push(byte),
}
i += 1;
}
out
}
/// A text parameter; one that isn't valid UTF-8 counts as absent.
fn param(q: &Q, key: &str) -> Option<String> {
q.get(key).and_then(|v| String::from_utf8(v.clone()).ok())
}
fn encode(value: &[u8]) -> String {
let mut out = String::with_capacity(value.len());
for &b in value {
match b {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' => out.push(b as char),
_ => {
let _ = write!(out, "%{b:02X}");
}
}
}
out
}
/// A repository-relative path with no `.`, `..`, empty or absolute parts and no NUL.
fn clean_path(value: &[u8]) -> Option<Vec<u8>> {
let parts: Vec<&[u8]> = value.split(|b| *b == b'/').filter(|p| !p.is_empty()).collect();
if parts.iter().any(|p| *p == b"." || *p == b".." || p.contains(&0)) {
return None;
}
Some(parts.join(&b'/'))
}
fn parent_of(path: &[u8]) -> &[u8] {
path.iter().rposition(|b| *b == b'/').map_or(&[], |i| &path[..i])
}
fn file_name(path: &[u8]) -> &[u8] {
path.iter().rposition(|b| *b == b'/').map_or(path, |i| &path[i + 1..])
}
fn join(dir: &[u8], name: &[u8]) -> Vec<u8> {
if dir.is_empty() { name.to_vec() } else { [dir, b"/", name].concat() }
}
/// Bytes for display. Names that aren't UTF-8 show replacement characters, but links keep
/// the real bytes.
fn lossy(bytes: &[u8]) -> Cow<'_, str> {
String::from_utf8_lossy(bytes)
}
/// `<commit>:<path>` for git, path bytes intact.
fn spec(commit: &str, path: &[u8]) -> OsString {
let mut spec = format!("{commit}:").into_bytes();
spec.extend_from_slice(path);
OsString::from_vec(spec)
}
// ---------------------------------------------------------------------------------------------
// Formatting
fn icon(name: &str) -> String {
let path = match name {
"dir" => r#"<path d="M2 4.5c0-.6.4-1 1-1h3.2l1.4 1.5H13c.6 0 1 .4 1 1v6.5c0 .6-.4 1-1 1H3c-.6 0-1-.4-1-1z"/>"#,
"file" => r#"<path d="M4 1.8h5.3L12.5 5v9.2H4z"/><path d="M9 1.8v3.5h3.5"/>"#,
"branch" => r#"<circle cx="4.5" cy="3.5" r="1.6"/><circle cx="4.5" cy="12.5" r="1.6"/><circle cx="11.5" cy="5" r="1.6"/><path d="M4.5 5.1v5.8M11.5 6.6c0 2.6-2.2 3.3-7 4.3"/>"#,
"branch" => {
r#"<circle cx="4.5" cy="3.5" r="1.6"/><circle cx="4.5" cy="12.5" r="1.6"/><circle cx="11.5" cy="5" r="1.6"/><path d="M4.5 5.1v5.8M11.5 6.6c0 2.6-2.2 3.3-7 4.3"/>"#
}
"tag" => r#"<path d="M2 2.5h5.3l6.2 6.2-4.8 4.8-6.7-6.7z"/><circle cx="5" cy="5.5" r="1"/>"#,
"book" => r#"<path d="M2.5 3h4c.8 0 1.5.7 1.5 1.5V13c0-.6-.5-1-1-1h-4.5zM13.5 3h-4c-.8 0-1.5.7-1.5 1.5V13c0-.6.5-1 1-1h4.5z"/>"#,
"book" => {
r#"<path d="M2.5 3h4c.8 0 1.5.7 1.5 1.5V13c0-.6-.5-1-1-1h-4.5zM13.5 3h-4c-.8 0-1.5.7-1.5 1.5V13c0-.6.5-1 1-1h4.5z"/>"#
}
"code" => r#"<path d="M5.5 4.5 2 8l3.5 3.5M10.5 4.5 14 8l-3.5 3.5"/>"#,
"commits" => r#"<circle cx="8" cy="8" r="2.4"/><path d="M1.5 8h4.1M10.4 8h4.1"/>"#,
"chevron" => r#"<path d="M4.5 6.5 8 10l3.5-3.5"/>"#,
@@ -153,33 +272,6 @@ fn icon(name: &str) -> String {
format!(r#"<svg class="ic" viewBox="0 0 16 16" aria-hidden="true">{path}</svg>"#)
}
fn encode(value: &str) -> String {
value
.bytes()
.map(|b| match b {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' => (b as char).to_string(),
_ => format!("%{b:02X}"),
})
.collect()
}
/// A repository-relative path with no `..`, empty or absolute parts.
fn clean_path(value: &str) -> Option<String> {
let parts: Vec<&str> = value.split('/').filter(|p| !p.is_empty()).collect();
if parts.iter().any(|p| *p == "." || *p == ".." || p.contains('\0')) {
return None;
}
Some(parts.join("/"))
}
fn parent_of(path: &str) -> &str {
path.rsplit_once('/').map_or("", |(p, _)| p)
}
fn file_name(path: &str) -> &str {
path.rsplit('/').next().unwrap_or(path)
}
/// "3 hours ago" for recent times, the calendar date (as git printed it) after a month.
fn ago(stamp: &str, date: &str) -> String {
let Ok(then) = stamp.parse::<u64>() else { return date.to_string() };
@@ -195,6 +287,11 @@ fn ago(stamp: &str, date: &str) -> String {
}
}
/// A commit subject for display; an empty one would leave an invisible link.
fn subject_or_placeholder(subject: &str) -> &str {
if subject.trim().is_empty() { "(no message)" } else { subject }
}
fn plural(count: usize, one: &str, many: &str) -> String {
format!("{count} {}", if count == 1 { one } else { many })
}
@@ -224,9 +321,12 @@ fn page(title: &str, body: &str) -> String {
}
fn view_missing() -> String {
page("Not found", r#"<section class="notfound"><h1 class="title">Nothing here</h1>
page(
"Not found",
r#"<section class="notfound"><h1 class="title">Nothing here</h1>
<p class="count">That repository, branch, file or commit doesn’t exist, or the link is malformed.</p>
<a class="button" href="/">Back to repositories</a></section>"#)
<a class="button" href="/">Back to repositories</a></section>"#,
)
}
// ---------------------------------------------------------------------------------------------
@@ -250,37 +350,54 @@ struct Head {
}
impl Repo {
/// A repository whose owner and repository directories are real directories, never
/// symlinks that could lead outside the tree.
fn open(owner: &str, name: &str) -> Option<Repo> {
if !(valid_name(owner) && valid_name(name)) {
return None;
}
let path = repos_root().join(owner).join(format!("{name}.git"));
path.join("HEAD").is_file().then(|| Repo {
Some(Repo {
path: repo_dir(owner, name)?,
owner: owner.into(),
name: name.into(),
path,
heads: OnceCell::new(),
tags: OnceCell::new(),
})
}
fn git(&self, args: &[&str]) -> Option<String> {
git(&self.path, args).ok().map(|out| String::from_utf8_lossy(&out).into_owned())
fn git_bytes<S: AsRef<OsStr>>(&self, args: &[S]) -> Option<Vec<u8>> {
git(&self.path, args).ok()
}
fn git<S: AsRef<OsStr>>(&self, args: &[S]) -> Option<String> {
self.git_bytes(args).map(|out| String::from_utf8_lossy(&out).into_owned())
}
fn url(&self, view: &str, query: &[(&str, &str)]) -> String {
let query: Vec<String> =
query.iter().filter(|(_, v)| !v.is_empty()).map(|(k, v)| format!("{k}={}", encode(v))).collect();
query.iter().filter(|(_, v)| !v.is_empty()).map(|(k, v)| format!("{k}={}", encode(v.as_bytes()))).collect();
let base = format!("/{}/{}/{view}", self.owner, self.name);
if query.is_empty() { base } else { format!("{base}?{}", query.join("&")) }
}
/// A tree, blob or raw link for a path, which may not be UTF-8.
fn url_at(&self, view: &str, reference: &str, path: &[u8], extra: &str) -> String {
let mut url = self.url(view, &[("ref", reference)]);
if !path.is_empty() {
url.push(if url.contains('?') { '&' } else { '?' });
let _ = write!(url, "path={}", encode(path));
}
if !extra.is_empty() {
url.push(if url.contains('?') { '&' } else { '?' });
url.push_str(extra);
}
url
}
/// The branch HEAD names, or when that branch doesn't exist, main, master or the first branch.
fn default_ref(&self) -> String {
let head = self.git(&["symbolic-ref", "--short", "HEAD"]).map(|s| s.trim().to_string());
let head = self.git(&["symbolic-ref", "HEAD"]);
let head = head.as_deref().map(str::trim).and_then(|h| h.strip_prefix("refs/heads/"));
let heads = self.heads();
if let Some(head) = head.filter(|h| heads.contains(h)) {
return head;
if let Some(head) = head.filter(|h| heads.iter().any(|b| b == h)) {
return head.to_string();
}
["main", "master"]
.into_iter()
@@ -290,8 +407,10 @@ impl Repo {
.unwrap_or_else(|| "HEAD".into())
}
/// Names under a namespace exactly as git stores them (not `refname:short`, which can
/// add `heads/` or `tags/` to tell apart a branch and tag of the same name).
fn list_refs(&self, namespace: &str) -> Vec<String> {
self.git(&["for-each-ref", "--format=%(refname:short)", namespace])
self.git(&["for-each-ref", "--format=%(refname:lstrip=2)", namespace])
.map(|s| s.lines().map(str::to_string).collect())
.unwrap_or_default()
}
@@ -304,69 +423,99 @@ impl Repo {
self.tags.get_or_init(|| self.list_refs("refs/tags"))
}
/// The commit a ref names, rejecting anything that could read as an option or range.
/// The commit a reference names. Branches and tags are looked up by their exact full ref,
/// so any name git allows works and none is read as revision syntax; anything else must be
/// a (possibly abbreviated) commit id.
fn resolve(&self, reference: &str) -> Option<String> {
let ok = (1..=200).contains(&reference.len())
&& !reference.starts_with('-')
&& !reference.contains("..")
&& reference.bytes().all(|b| b.is_ascii_alphanumeric() || b"._/-".contains(&b));
if !ok {
let full = if self.heads().iter().any(|h| h == reference) {
format!("refs/heads/{reference}")
} else if self.tags().iter().any(|t| t == reference) {
format!("refs/tags/{reference}")
} else if reference == "HEAD"
|| (4..=64).contains(&reference.len()) && reference.bytes().all(|b| b.is_ascii_hexdigit())
{
reference.to_string()
} else {
return None;
}
let spec = format!("{reference}^{{commit}}");
};
let spec = format!("{full}^{{commit}}");
self.git(&["rev-parse", "--verify", "--quiet", "--end-of-options", &spec]).map(|s| s.trim().into())
}
/// The newest commit on `rev` that touched `path` (the whole tree when empty).
fn latest(&self, rev: &str, path: &str) -> Option<Head> {
let mut args = vec!["log", "-1", "--format=%H%x1f%s%x1f%an%x1f%ct%x1f%cs", rev, "--"];
if !path.is_empty() {
args.push(path);
}
let out = self.git(&args)?;
/// The newest commit on `rev` that touched `path` (the whole tree when empty). Walking
/// history for a path can be slow, so answers for a fixed commit are cached.
fn latest(&self, rev: &str, path: &[u8]) -> Option<Head> {
let lookup = || {
let mut args: Vec<&OsStr> =
["log", "-1", "--format=%H%x1f%s%x1f%an%x1f%ct%x1f%cs", rev, "--"].map(OsStr::new).to_vec();
if !path.is_empty() {
args.push(OsStr::from_bytes(path));
}
self.git(&args).filter(|out| !out.trim().is_empty())
};
let is_oid = rev.len() >= 40 && rev.bytes().all(|b| b.is_ascii_hexdigit());
let out = if is_oid {
cached(format!("latest:{}:{rev}:{}", self.path.display(), encode(path)), lookup)?.to_string()
} else {
lookup()?
};
let f: Vec<&str> = out.trim_end().split('\x1f').collect();
let [oid, subject, author, stamp, date] = <[&str; 5]>::try_from(f).ok()?;
Some(Head { oid: oid.into(), subject: subject.into(), author: author.into(), stamp: stamp.into(), date: date.into() })
Some(Head {
oid: oid.into(),
subject: subject.into(),
author: author.into(),
stamp: stamp.into(),
date: date.into(),
})
}
/// Commits reachable from `commit`. A commit's history never changes, so the count is cached.
fn commit_count(&self, commit: &str) -> usize {
let key = format!("count:{}:{commit}", self.path.display());
let count = cached(key, || {
self.git(&["rev-list", "--count", commit, "--"]).map(|s| s.trim().to_string()).unwrap_or_default()
});
count.parse().unwrap_or(0)
cached(key, || self.git(&["rev-list", "--count", commit, "--"]).map(|s| s.trim().to_string()))
.and_then(|count| count.parse().ok())
.unwrap_or(0)
}
/// Tag names grouped by the commit they point at, for labelling history.
fn tags_by_commit(&self) -> HashMap<String, Vec<String>> {
let mut found: HashMap<String, Vec<String>> = HashMap::new();
let out = self.git(&["for-each-ref", "--format=%(refname:short) %(objectname) %(*objectname)", "refs/tags"]);
let out = self.git(&["for-each-ref", "--format=%(objectname) %(*objectname) %(refname:lstrip=2)", "refs/tags"]);
for line in out.unwrap_or_default().lines() {
let parts: Vec<&str> = line.split_whitespace().collect();
if let [name, direct, rest @ ..] = parts.as_slice() {
found.entry(rest.first().unwrap_or(direct).to_string()).or_default().push(name.to_string());
// Tag names can't contain spaces, but an unpeeled tag leaves the middle field empty.
let mut fields = line.splitn(3, ' ');
if let (Some(direct), Some(peeled), Some(name)) = (fields.next(), fields.next(), fields.next()) {
let commit = if peeled.is_empty() { direct } else { peeled };
found.entry(commit.to_string()).or_default().push(name.to_string());
}
}
found
}
/// A cache key for rendered content of `oid` that links within this repository.
fn key(&self, kind: &str, oid: &str, extra: &str) -> String {
format!("{kind}:{}/{}:{oid}:{extra}", self.owner, self.name)
}
/// Render a Markdown file from directory `dir`, linking repository paths at `reference`.
fn markdown(&self, source: &str, dir: &str, reference: &str) -> String {
render::markdown(source, dir, &|path, image| {
fn markdown(&self, source: &str, dir: &[u8], reference: &str) -> String {
render::markdown(source, &lossy(dir), &|path, image| {
if image {
self.url("raw", &[("ref", reference), ("path", path)])
self.url_at("raw", reference, path.as_bytes(), "")
} else if path.is_empty() {
self.url("tree", &[("ref", reference)])
} else {
self.url("blob", &[("ref", reference), ("path", path)])
self.url_at("blob", reference, path.as_bytes(), "")
}
})
}
/// Name, clone address and tabs, shared by every repository page.
fn masthead(&self, active: &str, reference: &str) -> String {
let commits = self.resolve(reference).map_or(0, |c| self.commit_count(&c));
/// Name, clone address and tabs, shared by every repository page. `commit` is `reference`
/// already resolved, when the caller has it.
fn masthead(&self, active: &str, reference: &str, commit: Option<&str>) -> String {
let commit = commit.map(str::to_string).or_else(|| self.resolve(reference));
let commits = commit.map_or(0, |c| self.commit_count(&c));
let tags = self.tags().len();
let tab = |view: &str, glyph: &str, label: &str, count: Option<usize>| {
let current = if view == active { r#" aria-current="page""# } else { "" };
@@ -388,10 +537,10 @@ impl Repo {
}
/// Branch and tag menu, then the path as breadcrumbs.
fn locator(&self, view: &str, reference: &str, path: &str) -> String {
fn locator(&self, view: &str, reference: &str, path: &[u8]) -> String {
let item = |name: &String| {
let current = if name == reference { r#" aria-current="true""# } else { "" };
let href = self.url(view, &[("ref", name), ("path", path)]);
let href = self.url_at(view, name, path, "");
format!(r#"<a href="{}"{current}>{}</a>"#, attr(&href), esc(name))
};
let branches: String = self.heads().iter().map(item).collect();
@@ -402,15 +551,20 @@ impl Repo {
}
let mut crumbs = String::new();
if !path.is_empty() {
let _ = write!(crumbs, r#"<a href="{}">{}</a>"#, attr(&self.url("tree", &[("ref", reference)])), esc(&self.name));
let parts: Vec<&str> = path.split('/').collect();
let _ = write!(
crumbs,
r#"<a href="{}">{}</a>"#,
attr(&self.url("tree", &[("ref", reference)])),
esc(&self.name)
);
let parts: Vec<&[u8]> = path.split(|b| *b == b'/').collect();
for (i, part) in parts.iter().enumerate() {
crumbs += r#"<span class="sep">/</span>"#;
if i + 1 == parts.len() {
let _ = write!(crumbs, "<b>{}</b>", esc(part));
let _ = write!(crumbs, "<b>{}</b>", esc(&lossy(part)));
} else {
let href = self.url("tree", &[("ref", reference), ("path", &parts[..=i].join("/"))]);
let _ = write!(crumbs, r#"<a href="{}">{}</a>"#, attr(&href), esc(part));
let href = self.url_at("tree", reference, &parts[..=i].join(&b'/'), "");
let _ = write!(crumbs, r#"<a href="{}">{}</a>"#, attr(&href), esc(&lossy(part)));
}
}
crumbs = format!(r#"<nav class="crumbs" aria-label="Path">{crumbs}</nav>"#);
@@ -425,8 +579,51 @@ impl Repo {
}
fn sha_link(&self, oid: &str) -> String {
format!(r#"<a class="sha" href="{}">{}</a>"#, attr(&self.url("commit", &[("id", oid)])), &oid[..oid.len().min(7)])
format!(
r#"<a class="sha" href="{}">{}</a>"#,
attr(&self.url("commit", &[("id", oid)])),
&oid[..oid.len().min(7)]
)
}
}
/// One entry of a tree listing: `blob`, `tree` or `commit` (a submodule), its object id, its
/// size when it's a blob, and its name as git stores it.
struct Entry {
kind: String,
oid: String,
size: usize,
name: Vec<u8>,
}
impl Entry {
/// Parse a `git ls-tree -l -z` record: `mode type oid size<TAB>name`, size `-` for non-blobs.
fn parse(record: &[u8]) -> Option<Entry> {
let tab = record.iter().position(|b| *b == b'\t')?;
let meta = std::str::from_utf8(&record[..tab]).ok()?;
let mut fields = meta.split_whitespace().skip(1);
let (kind, oid) = (fields.next()?.to_string(), fields.next()?.to_string());
let size = fields.next().and_then(|s| s.parse().ok()).unwrap_or(0);
Some(Entry { kind, oid, size, name: record[tab + 1..].to_vec() })
}
fn list(out: &[u8]) -> Vec<Entry> {
out.split(|b| *b == 0).filter_map(Entry::parse).collect()
}
}
/// The entry at `path` in `commit`, with its type, object id and size, in one git call.
fn entry(repo: &Repo, commit: &str, path: &[u8]) -> Option<Entry> {
let args = [
OsStr::new("ls-tree"),
OsStr::new("-l"),
OsStr::new("-z"),
OsStr::new(commit),
OsStr::new("--"),
OsStr::from_bytes(path),
];
let out = repo.git_bytes(&args)?;
Entry::list(&out).into_iter().find(|e| e.name == path)
}
// ---------------------------------------------------------------------------------------------
@@ -451,7 +648,8 @@ fn view_index() -> View {
for entry in sorted_dir(&root.join(&owner)) {
let Some(name) = entry.strip_suffix(".git") else { continue };
let Some(repo) = Repo::open(&owner, name) else { continue };
let head = repo.latest(&repo.default_ref(), "");
// HEAD usually names a real branch; only look further when it doesn't.
let head = repo.latest("HEAD", b"").or_else(|| repo.latest(&repo.default_ref(), b""));
rows.push((head.as_ref().and_then(|h| h.stamp.parse::<u64>().ok()).unwrap_or(0), repo, head));
}
}
@@ -460,154 +658,182 @@ fn view_index() -> View {
.iter()
.map(|(_, repo, head)| {
let (last, when) = head.as_ref().map_or(("No commits yet".into(), String::new()), |h| {
(esc(&h.subject).into_owned(), ago(&h.stamp, &h.date))
(esc(subject_or_placeholder(&h.subject)).into_owned(), ago(&h.stamp, &h.date))
});
format!(
r#"<li><a class="repo-row" href="{}"><span class="rname"><span>{}/</span>{}</span><span class="rlast">{last}</span><span class="rwhen">{when}</span></a></li>"#,
attr(&repo.url("tree", &[])), esc(&repo.owner), esc(&repo.name)
attr(&repo.url("tree", &[])),
esc(&repo.owner),
esc(&repo.name)
)
})
.collect();
let listing = if items.is_empty() {
format!(r#"<div class="panel empty"><h2>No repositories yet</h2><p>Push to a new name and GITv creates the repository.</p>
<code>git push git@{HOST}:um9i/my-project.git main</code></div>"#)
format!(
r#"<div class="panel empty"><h2>No repositories yet</h2><p>Push to a new name and GITv creates the repository.</p>
<code>git push git@{HOST}:um9i/my-project.git main</code></div>"#
)
} else {
format!(r#"<div class="panel"><ul class="rows">{items}</ul></div>"#)
};
let count = plural(rows.len(), "repository", "repositories");
View::Html(page("Repositories", &format!(
r#"<div class="pagehead"><h1 class="title">Repositories</h1><p class="count">{count}</p></div>{listing}"#)))
View::Html(page(
"Repositories",
&format!(
r#"<div class="pagehead"><h1 class="title">Repositories</h1><p class="count">{count}</p></div>{listing}"#
),
))
}
fn view_tree(repo: &Repo, q: &Q) -> Option<View> {
let reference = q.get("ref").cloned().unwrap_or_else(|| repo.default_ref());
let path = clean_path(q.get("path").map_or("", String::as_str))?;
let reference = param(q, "ref").unwrap_or_else(|| repo.default_ref());
let path = clean_path(q.get("path").map_or(&[][..], Vec::as_slice))?;
let Some(commit) = repo.resolve(&reference) else {
if !repo.heads().is_empty() {
return None;
}
let body = repo.masthead("tree", &reference) + &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>"#, esc(&repo.owner), esc(&repo.name));
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>"#,
esc(&repo.owner),
esc(&repo.name)
);
return Some(View::Html(page(&format!("{}/{}", repo.owner, repo.name), &body)));
};
let Some(listing) = repo.git(&["ls-tree", "-l", "-z", &format!("{commit}:{path}")]) else {
let listing = [OsStr::new("ls-tree"), OsStr::new("-l"), OsStr::new("-z"), &spec(&commit, &path)];
let Some(listing) = repo.git_bytes(&listing) else {
// A file path: show it in the file view instead.
return entry(repo, &commit, &path)
.filter(|e| e.kind == "blob")
.map(|_| View::Redirect(repo.url("blob", &[("ref", &reference), ("path", &path)])));
.map(|_| View::Redirect(repo.url_at("blob", &reference, &path, "")));
};
let mut entries: Vec<Entry> = listing.split('\0').filter_map(Entry::parse).collect();
let mut entries = Entry::list(&listing);
// Folders first, then files and submodules, each alphabetically.
entries.sort_by(|a, b| (a.kind != "tree").cmp(&(b.kind != "tree")).then(a.name.to_lowercase().cmp(&b.name.to_lowercase())));
entries.sort_by_cached_key(|e| (e.kind != "tree", e.name.to_ascii_lowercase()));
let mut body = repo.masthead("tree", &reference) + &repo.locator("tree", &reference, &path);
let mut body = repo.masthead("tree", &reference, Some(&commit)) + &repo.locator("tree", &reference, &path);
body += r#"<div class="panel">"#;
if let Some(head) = repo.latest(&commit, &path) {
let _ = write!(body,
let _ = write!(
body,
r#"<div class="panel-head"><div class="lead"><b class="who">{}</b><a class="subject" href="{}">{}</a></div><div class="side">{}<span>{}</span></div></div>"#,
esc(&head.author), attr(&repo.url("commit", &[("id", &head.oid)])), esc(&head.subject),
repo.sha_link(&head.oid), ago(&head.stamp, &head.date));
esc(&head.author),
attr(&repo.url("commit", &[("id", &head.oid)])),
esc(subject_or_placeholder(&head.subject)),
repo.sha_link(&head.oid),
ago(&head.stamp, &head.date)
);
}
body += r#"<ul class="rows">"#;
if !path.is_empty() {
let up = repo.url("tree", &[("ref", &reference), ("path", parent_of(&path))]);
let _ = write!(body, r#"<li><a class="entry" href="{}">{}<span class="name">..</span></a></li>"#, attr(&up), icon("up"));
let up = repo.url_at("tree", &reference, parent_of(&path), "");
let _ = write!(
body,
r#"<li><a class="entry" href="{}">{}<span class="name">..</span></a></li>"#,
attr(&up),
icon("up")
);
}
for item in &entries {
let full = if path.is_empty() { item.name.clone() } else { format!("{path}/{}", item.name) };
let (view, class, glyph) = match item.kind.as_str() {
"tree" => ("tree", "entry dir", "dir"),
"commit" => {
// A submodule: its commits live in another repository, so there's nothing to open.
let _ = write!(body, r#"<li><span class="entry sub">{}<span class="name">{}</span><span class="quiet">Submodule at {}</span></span></li>"#,
icon("module"), esc(&item.name), &item.oid[..item.oid.len().min(7)]);
let _ = write!(
body,
r#"<li><span class="entry sub">{}<span class="name">{}</span><span class="quiet">Submodule at {}</span></span></li>"#,
icon("module"),
esc(&lossy(&item.name)),
&item.oid[..item.oid.len().min(7)]
);
continue;
}
_ => ("blob", "entry", "file"),
};
let href = repo.url(view, &[("ref", &reference), ("path", &full)]);
let _ = write!(body, r#"<li><a class="{class}" href="{}">{}<span class="name">{}</span></a></li>"#,
attr(&href), icon(glyph), esc(&item.name));
let href = repo.url_at(view, &reference, &join(&path, &item.name), "");
let _ = write!(
body,
r#"<li><a class="{class}" href="{}">{}<span class="name">{}</span></a></li>"#,
attr(&href),
icon(glyph),
esc(&lossy(&item.name))
);
}
body += "</ul></div>";
let readme = entries.iter().find(|e| e.kind == "blob" && e.name.to_ascii_lowercase().starts_with("readme"));
// README.md over README or README.txt, as people expect.
let readmes = entries.iter().filter(|e| e.kind == "blob" && e.name.to_ascii_lowercase().starts_with(b"readme"));
let readme = readmes.clone().find(|e| render::is_markdown(&lossy(&e.name))).or_else(|| readmes.clone().next());
if let Some(readme) = readme.filter(|e| e.size <= SHOW_LIMIT) {
let content = if render::is_markdown(&readme.name) {
// Links in the rendered README depend on the folder and ref as well as the content.
cached(format!("md:{}:{path}:{reference}", readme.oid), || {
let text = repo.git(&["cat-file", "blob", &readme.oid]).unwrap_or_default();
format!(r#"<article class="markdown">{}</article>"#, repo.markdown(&text, &path, &reference))
let name = lossy(&readme.name);
let content = if render::is_markdown(&name) {
// Links in the rendered README depend on the repository, folder and ref too.
cached(repo.key("md", &readme.oid, &format!("{}:{reference}", encode(&path))), || {
let text = repo.git(&["cat-file", "blob", &readme.oid])?;
Some(format!(r#"<article class="markdown">{}</article>"#, repo.markdown(&text, &path, &reference)))
})
} else {
cached(format!("code:{}:{}", readme.oid, readme.name), || {
code_view(&readme.name, &repo.git(&["cat-file", "blob", &readme.oid]).unwrap_or_default())
// Highlighted code has no links, so any repository can share it.
cached(format!("code:{}:{name}", readme.oid), || {
Some(code_view(&name, &repo.git(&["cat-file", "blob", &readme.oid])?))
})
};
let _ = write!(body, r#"<section class="panel"><div class="panel-head"><div class="lead">{}<b>{}</b></div></div>{content}</section>"#,
icon("book"), esc(&readme.name));
let content = content.unwrap_or_else(|| r#"<p class="note">This README couldn't be read.</p>"#.into());
let _ = write!(
body,
r#"<section class="panel"><div class="panel-head"><div class="lead">{}<b>{}</b></div></div>{content}</section>"#,
icon("book"),
esc(&name)
);
}
let title = if path.is_empty() { format!("{}/{}", repo.owner, repo.name) } else { format!("{path} at {reference}") };
let title = if path.is_empty() {
format!("{}/{}", repo.owner, repo.name)
} else {
format!("{} at {reference}", lossy(&path))
};
Some(View::Html(page(&title, &body)))
}
/// One entry of a tree listing: `blob`, `tree` or `commit` (a submodule), its object id, its
/// size when it's a blob, and its name.
struct Entry {
kind: String,
oid: String,
size: usize,
name: String,
}
impl Entry {
/// Parse a `git ls-tree -l -z` record: `mode type oid size<TAB>name`, size `-` for non-blobs.
fn parse(record: &str) -> Option<Entry> {
let (meta, name) = record.split_once('\t')?;
let mut fields = meta.split_whitespace().skip(1);
let (kind, oid) = (fields.next()?.to_string(), fields.next()?.to_string());
let size = fields.next().and_then(|s| s.parse().ok()).unwrap_or(0);
Some(Entry { kind, oid, size, name: name.to_string() })
}
}
/// The entry at `path` in `commit`, with its type, object id and size, in one git call.
fn entry(repo: &Repo, commit: &str, path: &str) -> Option<Entry> {
let out = repo.git(&["ls-tree", "-l", "-z", commit, "--", path])?;
out.split('\0').filter_map(Entry::parse).find(|e| e.name == path)
}
/// Highlighted source with a line-number gutter.
fn code_view(path: &str, text: &str) -> String {
let lines = text.lines().count().max(1);
let gutter: String = (1..=lines).map(|n| format!("{n}\n")).collect();
format!(r#"<div class="code-view"><pre class="gutter" aria-hidden="true">{gutter}</pre><pre class="code">{}</pre></div>"#,
render::highlight(path, text))
format!(
r#"<div class="code-view"><pre class="gutter" aria-hidden="true">{gutter}</pre><pre class="code">{}</pre></div>"#,
render::highlight(path, text)
)
}
fn view_blob(repo: &Repo, q: &Q, raw: bool) -> Option<View> {
let reference = q.get("ref").cloned().unwrap_or_else(|| repo.default_ref());
let reference = param(q, "ref").unwrap_or_else(|| repo.default_ref());
let path = clean_path(q.get("path")?)?;
let commit = repo.resolve(&reference)?;
let item = entry(repo, &commit, &path)?;
match item.kind.as_str() {
"blob" => {}
// Markdown links can't tell files from folders, so a file link to a folder lands here.
"tree" => return Some(View::Redirect(repo.url("tree", &[("ref", &reference), ("path", &path)]))),
"tree" => return Some(View::Redirect(repo.url_at("tree", &reference, &path, ""))),
_ => return None,
}
let too_big = item.size > if raw { RAW_LIMIT } else { SHOW_LIMIT };
let data = if too_big { Vec::new() } else { git(&repo.path, &["cat-file", "blob", &item.oid]).ok()? };
let binary = data.iter().take(8000).any(|b| *b == 0);
let name = lossy(file_name(&path)).into_owned();
if raw {
if too_big {
return Some(View::Html(page("File too large", &format!(
r#"<section class="notfound"><h1 class="title">This file is too large to download here</h1>
if item.size > RAW_LIMIT {
return Some(View::Html(page(
"File too large",
&format!(
r#"<section class="notfound"><h1 class="title">This file is too large to download here</h1>
<p class="count">{} is {}. Clone the repository to get it.</p><code>git clone git@{HOST}:{}/{}.git</code></section>"#,
esc(file_name(&path)), size(item.size), esc(&repo.owner), esc(&repo.name)))));
esc(&name),
size(item.size),
esc(&repo.owner),
esc(&repo.name)
),
)));
}
let kind = match path.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()).as_deref() {
let data = repo.git_bytes(&["cat-file", "blob", &item.oid])?;
let binary = data.iter().take(8000).any(|b| *b == 0);
let kind = match name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()).as_deref() {
Some("png") => "image/png",
Some("jpg" | "jpeg") => "image/jpeg",
Some("gif") => "image/gif",
@@ -617,108 +843,184 @@ fn view_blob(repo: &Repo, q: &Q, raw: bool) -> Option<View> {
_ if binary => "application/octet-stream",
_ => "text/plain; charset=utf-8",
};
let download = (kind == "application/octet-stream").then(|| file_name(&path).to_string());
let download = (kind == "application/octet-stream").then(|| file_name(&path).to_vec());
return Some(View::Raw(data, kind, download));
}
let text = String::from_utf8_lossy(&data);
let markdown = !binary && !too_big && render::is_markdown(&path);
let as_code = !markdown || q.get("view").is_some_and(|v| v == "code");
let too_big = item.size > SHOW_LIMIT;
let markdown = !too_big && render::is_markdown(&name);
let as_code = !markdown || param(q, "view").as_deref() == Some("code");
// The facts and the rendering are cached together, so a repeat view reads no blob at all.
let rendered: Arc<str> = if too_big {
format!(
"{}\x1f{}",
size(item.size),
r#"<p class="note">This file is too large to show here. Use Raw to open it.</p>"#
)
.into()
} else {
let key = if as_code {
// Highlighting depends only on the content and the file's type, so it's shared.
format!("code:{}:{name}", item.oid)
} else {
repo.key("md", &item.oid, &format!("{}:{reference}", encode(parent_of(&path))))
};
cached(key, || {
let data = repo.git_bytes(&["cat-file", "blob", &item.oid])?;
if data.iter().take(8000).any(|b| *b == 0) {
let note = r#"<p class="note">This is a binary file. Use Raw to download it.</p>"#;
return Some(format!("{}\x1f{note}", size(item.size)));
}
let text = String::from_utf8_lossy(&data);
let facts = format!("{}, {}", plural(text.lines().count(), "line", "lines"), size(item.size));
let html = if as_code {
code_view(&name, &text)
} else {
format!(r#"<article class="markdown">{}</article>"#, repo.markdown(&text, parent_of(&path), &reference))
};
Some(format!("{facts}\x1f{html}"))
})?
};
let (facts, content) = rendered.split_once('\x1f').unwrap_or(("", &rendered));
let mut side = String::new();
if markdown {
let link = |label: &str, view: &str, on: bool| {
let current = if on { r#" aria-current="true""# } else { "" };
let href = repo.url("blob", &[("ref", &reference), ("path", &path), ("view", view)]);
format!(r#"<a href="{}"{current}>{label}</a>"#, attr(&href))
let extra = if view.is_empty() { String::new() } else { format!("view={view}") };
format!(r#"<a href="{}"{current}>{label}</a>"#, attr(&repo.url_at("blob", &reference, &path, &extra)))
};
let _ = write!(side, r#"<span class="segmented">{}{}</span>"#, link("Preview", "", !as_code), link("Code", "code", as_code));
let _ = write!(
side,
r#"<span class="segmented">{}{}</span>"#,
link("Preview", "", !as_code),
link("Code", "code", as_code)
);
}
let _ = write!(side, r#"<a class="button" href="{}">Raw</a>"#, attr(&repo.url("raw", &[("ref", &reference), ("path", &path)])));
let facts = if binary || too_big { size(item.size) } else {
format!("{}, {}", plural(text.lines().count(), "line", "lines"), size(item.size))
};
let content: Arc<str> = if too_big {
r#"<p class="note">This file is too large to show here. Use Raw to open it.</p>"#.into()
} else if binary {
r#"<p class="note">This is a binary file. Use Raw to download it.</p>"#.into()
} else if as_code {
// Highlighting depends only on the content and the file's type.
cached(format!("code:{}:{}", item.oid, file_name(&path)), || code_view(&path, &text))
} else {
cached(format!("md:{}:{}:{reference}", item.oid, parent_of(&path)), || {
format!(r#"<article class="markdown">{}</article>"#, repo.markdown(&text, parent_of(&path), &reference))
})
};
let body = repo.masthead("tree", &reference) + &repo.locator("blob", &reference, &path) + &format!(
r#"<section class="panel"><div class="panel-head"><div class="lead">{}<b>{}</b><span class="quiet">{facts}</span></div><div class="side">{side}</div></div>{content}</section>"#,
icon("file"), esc(file_name(&path)));
Some(View::Html(page(&format!("{path} at {reference}"), &body)))
let _ = write!(side, r#"<a class="button" href="{}">Raw</a>"#, attr(&repo.url_at("raw", &reference, &path, "")));
let body = repo.masthead("tree", &reference, Some(&commit))
+ &repo.locator("blob", &reference, &path)
+ &format!(
r#"<section class="panel"><div class="panel-head"><div class="lead">{}<b>{}</b><span class="quiet">{facts}</span></div><div class="side">{side}</div></div>{content}</section>"#,
icon("file"),
esc(&name)
);
Some(View::Html(page(&format!("{} at {reference}", lossy(&path)), &body)))
}
fn view_log(repo: &Repo, q: &Q) -> Option<View> {
let reference = q.get("ref").cloned().unwrap_or_else(|| repo.default_ref());
let number: usize = q.get("page").and_then(|p| p.parse().ok()).unwrap_or(0);
let reference = param(q, "ref").unwrap_or_else(|| repo.default_ref());
let number: usize = param(q, "page").and_then(|p| p.parse().ok()).unwrap_or(0);
let skip = number.checked_mul(PAGE)?;
let commit = repo.resolve(&reference)?;
let out = repo.git(&[
"log", &format!("-n{}", PAGE + 1), &format!("--skip={skip}"),
"--format=%H%x1f%s%x1f%an%x1f%ct%x1f%cs", &commit, "--",
"log",
&format!("-n{}", PAGE + 1),
&format!("--skip={skip}"),
"--format=%H%x1f%s%x1f%an%x1f%ct%x1f%cs",
&commit,
"--",
])?;
let lines: Vec<&str> = out.lines().collect();
let tags = repo.tags_by_commit();
let mut rows = String::new();
for line in lines.iter().take(PAGE) {
let Ok([oid, subject, author, stamp, date]) = <[&str; 5]>::try_from(line.split('\x1f').collect::<Vec<_>>()) else {
let Ok([oid, subject, author, stamp, date]) = <[&str; 5]>::try_from(line.split('\x1f').collect::<Vec<_>>())
else {
continue;
};
let chips: String = tags.get(oid).into_iter().flatten().map(|t| {
format!(r#"<a class="tagchip" href="{}">{}{}</a>"#, attr(&repo.url("tree", &[("ref", t)])), icon("tag"), esc(t))
}).collect();
let _ = write!(rows,
let chips: String = tags
.get(oid)
.into_iter()
.flatten()
.map(|t| {
format!(
r#"<a class="tagchip" href="{}">{}{}</a>"#,
attr(&repo.url("tree", &[("ref", t)])),
icon("tag"),
esc(t)
)
})
.collect();
let _ = write!(
rows,
r#"<li class="commit-row"><div class="cmain"><a class="csubj" href="{}">{}</a>{chips}<span class="cmeta">{} committed {}</span></div>{}</li>"#,
attr(&repo.url("commit", &[("id", oid)])), esc(subject), esc(author), ago(stamp, date), repo.sha_link(oid));
attr(&repo.url("commit", &[("id", oid)])),
esc(subject_or_placeholder(subject)),
esc(author),
ago(stamp, date),
repo.sha_link(oid)
);
}
let mut pager = String::new();
let page_link = |n: usize, label: &str| {
format!(r#"<a class="button" href="{}">{label}</a>"#, attr(&repo.url("log", &[("ref", &reference), ("page", &n.to_string())])))
format!(
r#"<a class="button" href="{}">{label}</a>"#,
attr(&repo.url("log", &[("ref", &reference), ("page", &n.to_string())]))
)
};
pager += &if number > 0 { page_link(number - 1, "Newer") } else { "<span></span>".into() };
if lines.len() > PAGE {
pager += &page_link(number + 1, "Older");
}
let body = repo.masthead("log", &reference) + &repo.locator("log", &reference, "") + &format!(
r#"<div class="panel"><ul class="rows">{rows}</ul></div><nav class="pager" aria-label="Pages">{pager}</nav>"#);
let body = repo.masthead("log", &reference, Some(&commit))
+ &repo.locator("log", &reference, b"")
+ &format!(
r#"<div class="panel"><ul class="rows">{rows}</ul></div><nav class="pager" aria-label="Pages">{pager}</nav>"#
);
Some(View::Html(page(&format!("Commits on {reference}"), &body)))
}
struct FileDiff {
name: String,
/// One changed file: how git names it (raw bytes, from NUL-delimited output) and its status.
struct Change {
status: &'static str,
path: Vec<u8>,
}
/// Parse `git show -z --name-status`: a status (`M`, `A`, `D`, `R100`, ...) then one path, or
/// two (old and new) for renames and copies.
fn parse_changes(out: &[u8]) -> Vec<Change> {
let mut fields = out.split(|b| *b == 0).filter(|f| !f.is_empty());
let mut changes = Vec::new();
while let Some(code) = fields.next() {
let (status, paths) = match code.first() {
Some(b'A') => ("Added", 1),
Some(b'D') => ("Deleted", 1),
Some(b'R') => ("Renamed", 2),
Some(b'C') => ("Copied", 2),
_ => ("", 1),
};
let mut path = None;
for _ in 0..paths {
path = fields.next();
}
let Some(path) = path else { break };
changes.push(Change { status, path: path.to_vec() });
}
changes
}
/// The lines of one file's diff: (class, old number, new number, text).
struct FileDiff {
rows: Vec<(&'static str, String, String, String)>,
added: usize,
removed: usize,
binary: bool,
}
/// Split `git show` patch output into files of (class, old number, new number, text) rows.
/// Split `git show` patch output into one entry per `diff --git` section, in order. Names come
/// from [`parse_changes`], not from these human-readable headers, which quote or misplace odd names.
fn parse_diff(text: &str) -> Vec<FileDiff> {
let mut files: Vec<FileDiff> = Vec::new();
let (mut old, mut new) = (0usize, 0usize);
for line in text.lines() {
if let Some(rest) = line.strip_prefix("diff --git ") {
let name = rest.rsplit_once(" b/").map_or(rest, |(_, b)| b).to_string();
files.push(FileDiff { name, status: "", rows: Vec::new(), added: 0, removed: 0, binary: false });
if line.starts_with("diff --git ") {
files.push(FileDiff { rows: Vec::new(), added: 0, removed: 0, binary: false });
continue;
}
let Some(file) = files.last_mut() else { continue };
let in_hunk = !file.rows.is_empty();
if !in_hunk && line.starts_with("new file mode") {
file.status = "Added";
} else if !in_hunk && line.starts_with("deleted file mode") {
file.status = "Deleted";
} else if !in_hunk && line.starts_with("rename from ") {
file.status = "Renamed";
} else if !in_hunk && line.starts_with("Binary files ") {
if !in_hunk && line.starts_with("Binary files ") {
file.binary = true;
} else if line.starts_with("@@") {
let nums: Vec<usize> = line
@@ -749,87 +1051,160 @@ fn parse_diff(text: &str) -> Vec<FileDiff> {
}
fn view_commit(repo: &Repo, q: &Q) -> Option<View> {
let id = q.get("id")?;
let id = param(q, "id")?;
if !(4..=64).contains(&id.len()) || !id.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) {
return None;
}
let commit = repo.resolve(id)?;
let meta = repo.git(&["show", "-s", "--date=format:%-d %b %Y, %H:%M",
"--format=%H%x1f%P%x1f%an%x1f%ae%x1f%ad%x1f%s%x1f%b", &commit])?;
let commit = repo.resolve(&id)?;
let meta = repo.git(&[
"show",
"-s",
"--date=format:%-d %b %Y, %H:%M",
"--format=%H%x1f%P%x1f%an%x1f%ae%x1f%ad%x1f%s%x1f%b",
&commit,
])?;
let f: Vec<&str> = meta.splitn(7, '\x1f').collect();
let [oid, parents, author, email, date, subject, message] = <[&str; 7]>::try_from(f).ok()?;
// A merge shows what it brought in relative to its first parent.
let patch = git(&repo.path, &["show", "--format=", "--no-color", "-M", "--patch", "--diff-merges=first-parent", &commit]).ok()?;
let parent_links: String = parents.split_whitespace().map(|p| repo.sha_link(p)).collect::<Vec<_>>().join(" ");
let mut body = repo.masthead("log", &repo.default_ref());
let mut body = repo.masthead("log", &repo.default_ref(), None);
let message = message.trim();
let _ = write!(body, r#"<section class="panel"><div class="cmsg"><div class="chead"><h2 class="ctitle">{}</h2><a class="button" href="{}">Browse files</a></div>{}</div><dl class="facts">
let _ = write!(
body,
r#"<section class="panel"><div class="cmsg"><div class="chead"><h2 class="ctitle">{}</h2><a class="button" href="{}">Browse files</a></div>{}</div><dl class="facts">
<div><dt>Author</dt><dd>{} <span class="quiet">{}</span></dd></div><div><dt>Date</dt><dd>{}</dd></div>
<div><dt>Commit</dt><dd><span class="sha">{}</span></dd></div>{}</dl></section>"#,
esc(subject),
esc(subject_or_placeholder(subject)),
attr(&repo.url("tree", &[("ref", oid)])),
if message.is_empty() { String::new() } else { format!(r#"<p class="cbody">{}</p>"#, esc(message)) },
esc(author), esc(email), esc(date), &oid[..12],
if parent_links.is_empty() { String::new() } else { format!("<div><dt>Parent</dt><dd>{parent_links}</dd></div>") });
esc(author),
esc(email),
esc(date),
&oid[..12],
if parent_links.is_empty() {
String::new()
} else {
format!("<div><dt>Parent</dt><dd>{parent_links}</dd></div>")
}
);
// A commit's diff never changes, so its rendering is cached. If git can't produce it, the
// page still shows the commit, with a note.
let diff = cached(repo.key("diff", oid, ""), || render_diff(repo, oid, parents))
.unwrap_or_else(|| r#"<p class="note">This commit’s changes couldn’t be read.</p>"#.into());
body += &diff;
Some(View::Html(page(subject_or_placeholder(subject), &body)))
}
if patch.len() > DIFF_LIMIT {
body += r#"<p class="note">This commit’s changes are too large to show here.</p>"#;
/// A commit's changes as one panel per file. Only [`DIFF_LIMIT`] bytes of patch are read; past
/// that the files are listed without their lines.
fn render_diff(repo: &Repo, oid: &str, parents: &str) -> Option<String> {
// A merge shows what it brought in relative to its first parent.
let options = ["--format=", "--no-color", "-M", "--diff-merges=first-parent"];
let names = repo.git_bytes(&[&["show", "-z", "--name-status"][..], &options, &[oid]].concat())?;
let changes = parse_changes(&names);
let (patch, too_big) =
git_capped(&repo.path, &[&["show", "--patch"][..], &options, &[oid]].concat(), DIFF_LIMIT).ok()?;
let files = if too_big { Vec::new() } else { parse_diff(&String::from_utf8_lossy(&patch)) };
// The two listings come from the same diff, in the same order; if they ever disagree, show
// names only rather than pair lines with the wrong file.
let paired = files.len() == changes.len();
let mut body = String::new();
let (added, removed) = files.iter().fold((0, 0), |(a, r), f| (a + f.added, r + f.removed));
let totals = if paired {
format!(r#" <span class="plus">+{added}</span><span class="minus">−{removed}</span>"#)
} else {
let files = parse_diff(&String::from_utf8_lossy(&patch));
let (added, removed) = files.iter().fold((0, 0), |(a, r), f| (a + f.added, r + f.removed));
let _ = write!(body, r#"<h2 class="changes">{} changed <span class="plus">+{added}</span><span class="minus">−{removed}</span></h2>"#,
plural(files.len(), "file", "files"));
for file in &files {
let status = if file.status.is_empty() { String::new() } else { format!(r#"<span class="status">{}</span>"#, file.status) };
// A deleted file still exists in the parent commit.
let at = if file.status == "Deleted" { parents.split_whitespace().next().unwrap_or(oid) } else { oid };
let link = repo.url("blob", &[("ref", at), ("path", &file.name)]);
let _ = write!(body, r#"<section class="panel"><div class="panel-head"><div class="lead">{}<a href="{}"><b>{}</b></a>{status}</div><div class="side"><span class="plus">+{}</span><span class="minus">−{}</span></div></div>"#,
icon("file"), attr(&link), esc(&file.name), file.added, file.removed);
if file.binary {
body += r#"<p class="note">Binary file changed.</p>"#;
} else if file.rows.is_empty() {
body += r#"<p class="note">No content changes.</p>"#;
} else {
String::new()
};
let _ = write!(body, r#"<h2 class="changes">{} changed{totals}</h2>"#, plural(changes.len(), "file", "files"));
if too_big {
body += r#"<p class="note">This commit’s changes are too large to show line by line.</p>"#;
}
for (i, change) in changes.iter().enumerate() {
let file = files.get(i).filter(|_| paired);
let status = if change.status.is_empty() {
String::new()
} else {
format!(r#"<span class="status">{}</span>"#, change.status)
};
// A deleted file still exists in the parent commit.
let at = if change.status == "Deleted" { parents.split_whitespace().next().unwrap_or(oid) } else { oid };
let link = repo.url_at("blob", at, &change.path, "");
let counts = file.map_or(String::new(), |f| {
format!(r#"<span class="plus">+{}</span><span class="minus">−{}</span>"#, f.added, f.removed)
});
let _ = write!(
body,
r#"<section class="panel"><div class="panel-head"><div class="lead">{}<a href="{}"><b>{}</b></a>{status}</div><div class="side">{counts}</div></div>"#,
icon("file"),
attr(&link),
esc(&lossy(&change.path))
);
match file {
None => {}
Some(f) if f.binary => body += r#"<p class="note">Binary file changed.</p>"#,
Some(f) if f.rows.is_empty() => body += r#"<p class="note">No content changes.</p>"#,
Some(f) => {
body += r#"<div class="diff-wrap"><table class="diff">"#;
for (class, o, n, text) in &file.rows {
for (class, o, n, text) in &f.rows {
if *class == "hunk" {
let _ = write!(body, r#"<tr class="hunk"><td colspan="3">{}</td></tr>"#, esc(text));
} else {
let sign = match *class { "add" => "+", "del" => "-", _ => " " };
let _ = write!(body, r#"<tr class="{class}"><td class="num" data-n="{o}"></td><td class="num" data-n="{n}"></td><td class="line" data-s="{sign}">{}</td></tr>"#, esc(text));
let sign = match *class {
"add" => "+",
"del" => "-",
_ => " ",
};
let _ = write!(
body,
r#"<tr class="{class}"><td class="num" data-n="{o}"></td><td class="num" data-n="{n}"></td><td class="line" data-s="{sign}">{}</td></tr>"#,
esc(text)
);
}
}
body += "</table></div>";
}
body += "</section>";
}
body += "</section>";
}
Some(View::Html(page(subject, &body)))
Some(body)
}
fn view_tags(repo: &Repo) -> Option<View> {
let out = repo.git(&["for-each-ref", "--sort=-creatordate",
"--format=%(refname:short)%1f%(objectname)%1f%(*objectname)%1f%(creatordate:unix)%1f%(creatordate:short)%1f%(contents:subject)%1f%(objecttype)",
"refs/tags"])?;
let out = repo.git(&[
"for-each-ref",
"--sort=-creatordate",
"--format=%(refname:lstrip=2)%1f%(objectname)%1f%(*objectname)%1f%(creatordate:unix)%1f%(creatordate:short)%1f%(contents:subject)%1f%(objecttype)",
"refs/tags",
])?;
let mut rows = String::new();
for line in out.lines() {
let Ok([name, direct, peeled, stamp, date, note, kind]) = <[&str; 7]>::try_from(line.split('\x1f').collect::<Vec<_>>()) else {
let Ok([name, direct, peeled, stamp, date, note, kind]) =
<[&str; 7]>::try_from(line.split('\x1f').collect::<Vec<_>>())
else {
continue;
};
let target = if peeled.is_empty() { direct } else { peeled };
let note = if kind == "tag" && !note.is_empty() { format!(r#"<span class="tnote">{}</span>"#, esc(note)) } else { String::new() };
let _ = write!(rows, r#"<li class="tag-row"><span class="tname">{}</span>{note}<span class="tmeta">{}{}</span>
let note = if kind == "tag" && !note.is_empty() {
format!(r#"<span class="tnote">{}</span>"#, esc(note))
} else {
String::new()
};
let _ = write!(
rows,
r#"<li class="tag-row"><span class="tname">{}</span>{note}<span class="tmeta">{}{}</span>
<span class="tacts"><a class="button" href="{}">Browse files</a></span></li>"#,
esc(name), repo.sha_link(target), ago(stamp, date), attr(&repo.url("tree", &[("ref", name)])));
esc(name),
repo.sha_link(target),
ago(stamp, date),
attr(&repo.url("tree", &[("ref", name)]))
);
}
let listing = if rows.is_empty() {
r#"<div class="panel empty"><h2>No tags yet</h2><p>Tag a release and push it to see it here.</p><code>git tag -a v1.0.0 -m "v1.0.0" &amp;&amp; git push origin v1.0.0</code></div>"#.to_string()
} else {
format!(r#"<div class="panel"><ul class="rows">{rows}</ul></div>"#)
};
let body = repo.masthead("tags", &repo.default_ref()) + &listing;
let body = repo.masthead("tags", &repo.default_ref(), None) + &listing;
Some(View::Html(page(&format!("Tags in {}/{}", repo.owner, repo.name), &body)))
}
@@ -848,9 +1223,17 @@ fn route(owner: &str, name: &str, view: Option<&str>, q: &Q) -> View {
result.unwrap_or(View::Missing)
}
/// Pages rendered at once. Each runs several git processes, so a burst of requests queues
/// here instead of starting hundreds of them.
static RENDERS: tokio::sync::Semaphore = tokio::sync::Semaphore::const_new(16);
/// Git calls block, so every page renders on the blocking pool.
async fn blocking(f: impl FnOnce() -> View + Send + 'static) -> View {
tokio::task::spawn_blocking(f).await.unwrap_or(View::Missing)
let Ok(_permit) = RENDERS.acquire().await else { return View::Missing };
tokio::task::spawn_blocking(f).await.unwrap_or_else(|error| {
eprintln!("gitv-web: a page failed to render: {error}");
View::Missing
})
}
#[tokio::main]
@@ -865,10 +1248,18 @@ async fn main() {
.route("/fonts/display.woff2", get(|| async { static_file("font/woff2", FONT_DISPLAY) }))
.route("/fonts/text.woff2", get(|| async { static_file("font/woff2", FONT_TEXT) }))
.route("/fonts/mono.woff2", get(|| async { static_file("font/woff2", FONT_MONO) }))
.route("/{owner}/{name}", get(|Path((o, n)): Path<(String, String)>, Query(q): Query<Q>|
blocking(move || route(&o, &n, None, &q))))
.route("/{owner}/{name}/{view}", get(|Path((o, n, v)): Path<(String, String, String)>, Query(q): Query<Q>|
blocking(move || route(&o, &n, Some(&v), &q))))
.route(
"/{owner}/{name}",
get(|Path((o, n)): Path<(String, String)>, RawQuery(q): RawQuery| {
blocking(move || route(&o, &n, None, &parse_query(q.as_deref())))
}),
)
.route(
"/{owner}/{name}/{view}",
get(|Path((o, n, v)): Path<(String, String, String)>, RawQuery(q): RawQuery| {
blocking(move || route(&o, &n, Some(&v), &parse_query(q.as_deref())))
}),
)
.fallback(|| async { View::Missing });
let listener = tokio::net::TcpListener::bind(("127.0.0.1", port)).await.expect("bind port");
// Print the bound address (not the requested port), so `--port 0` works for tests.
@@ -876,3 +1267,46 @@ async fn main() {
println!("gitv-web listening on http://{address} (repos: {})", repos_root().display());
axum::serve(listener, app).await.expect("server");
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn percent_decoding_keeps_raw_bytes() {
assert_eq!(percent_decode("a%2Fb+c"), b"a/b c");
assert_eq!(percent_decode("caf%C3%A9"), "café".as_bytes());
assert_eq!(percent_decode("%FF%00"), [0xff, 0]);
assert_eq!(percent_decode("100%"), b"100%");
assert_eq!(percent_decode("%zz%4"), b"%zz%4");
}
#[test]
fn query_first_value_wins() {
let q = parse_query(Some("path=a&path=b&ref=main&flag"));
assert_eq!(q["path"], b"a");
assert_eq!(param(&q, "ref").as_deref(), Some("main"));
assert_eq!(q["flag"], b"");
}
#[test]
fn paths_are_cleaned_as_bytes() {
assert_eq!(clean_path(b"/a//b/"), Some(b"a/b".to_vec()));
assert_eq!(clean_path(b"a/../b"), None);
assert_eq!(clean_path(b"./a"), None);
assert_eq!(clean_path(b"a\0b"), None);
assert_eq!(clean_path(&[0xff, b'/', b'x']), Some(vec![0xff, b'/', b'x']));
assert_eq!(encode(&[b'a', b' ', 0xff, b'/']), "a%20%FF/");
}
#[test]
fn name_status_parsing() {
let out = b"M\0src/a b.rs\0R100\0old name\0new\tname\0D\0gone\0A\0\xffbin\0";
let changes = parse_changes(out);
let got: Vec<(&str, &[u8])> = changes.iter().map(|c| (c.status, c.path.as_slice())).collect();
assert_eq!(
got,
[("", &b"src/a b.rs"[..]), ("Renamed", b"new\tname"), ("Deleted", b"gone"), ("Added", b"\xffbin")]
);
}
}
@@ -8,8 +8,11 @@ use std::process::{Command, ExitCode, Stdio};
use base64::Engine;
use clap::{Parser, Subcommand};
use gitv::{
HOST, NAME_RULE, exists_at, git, git_base, git_command, is_real_dir, keys_path, owner_dir, repo_dir, repos_root,
valid_name,
};
use nix::fcntl::{Flock, FlockArg};
use gitv::{HOST, NAME_RULE, git, git_base, git_command, keys_path, repos_root, valid_name};
const HELP: &str = "Commands for your key, run as: ssh git@git.um9i.dev <command>
list list your repositories
@@ -27,18 +30,33 @@ struct Cli {
#[derive(Subcommand)]
enum Action {
/// Create an empty repository (root)
Create { #[arg(value_parser = name)] owner: String, #[arg(value_parser = name)] name: String },
Create {
#[arg(value_parser = name)]
owner: String,
#[arg(value_parser = name)]
name: String,
},
/// Delete a repository permanently (root)
Delete {
#[arg(value_parser = name)] owner: String,
#[arg(value_parser = name)] name: String,
#[arg(value_parser = name)]
owner: String,
#[arg(value_parser = name)]
name: String,
/// Confirm permanent deletion
#[arg(long)] yes: bool,
#[arg(long)]
yes: bool,
},
/// Register an Ed25519 public key for an owner (root)
AddKey { #[arg(value_parser = name)] owner: String, public_key: PathBuf },
AddKey {
#[arg(value_parser = name)]
owner: String,
public_key: PathBuf,
},
/// Handle one SSH request (forced command from authorized_keys)
Serve { #[arg(value_parser = name)] owner: String },
Serve {
#[arg(value_parser = name)]
owner: String,
},
}
fn name(value: &str) -> Result<String, String> {
@@ -49,28 +67,33 @@ fn check_name(value: &str) -> Result<&str, String> {
if valid_name(value) { Ok(value) } else { Err(NAME_RULE.into()) }
}
fn repo_path(owner: &str, name: &str) -> PathBuf {
repos_root().join(owner).join(format!("{name}.git"))
}
fn is_root() -> bool {
nix::unistd::geteuid().is_root()
}
/// Hand a path to the `git` account when running as root, so keys can manage it later.
/// Hand a path to the `git` account when running as root, so keys can manage it later. Uses
/// lchown, so a symlink is changed itself and never followed out of the tree.
fn chown_git(path: &Path) -> Result<(), String> {
if !is_root() {
return Ok(());
}
let user = nix::unistd::User::from_name("git")
.map_err(|e| e.to_string())?
.ok_or("no git account")?;
nix::unistd::chown(path, Some(user.uid), Some(user.gid)).map_err(|e| e.to_string())
let user = nix::unistd::User::from_name("git").map_err(|e| e.to_string())?.ok_or("no git account")?;
std::os::unix::fs::lchown(path, Some(user.uid.as_raw()), Some(user.gid.as_raw())).map_err(|e| e.to_string())
}
/// The owner's directory, created if needed. Anything else at that path, including a symlink
/// to a directory, is refused rather than followed.
fn owner_directory(owner: &str) -> Result<PathBuf, String> {
let directory = repos_root().join(owner);
fs::create_dir_all(&directory).map_err(|e| e.to_string())?;
// Another push may create it at the same moment; either way, check what's there after.
match fs::create_dir(&directory) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
Err(e) => return Err(format!("cannot create {}: {e}", directory.display())),
}
if !is_real_dir(&directory) {
return Err(format!("{} is not a directory", directory.display()));
}
chown_git(&directory)?;
Ok(directory)
}
@@ -78,7 +101,7 @@ fn owner_directory(owner: &str) -> Result<PathBuf, String> {
fn create(owner: &str, name: &str, quiet: bool) -> Result<(), String> {
let directory = owner_directory(owner)?;
let repo = directory.join(format!("{name}.git"));
if repo.exists() {
if exists_at(&repo) {
return Err("repository already exists".into());
}
// Build in a hidden staging name, then rename, so a half-made repository never serves.
@@ -99,23 +122,27 @@ fn create(owner: &str, name: &str, quiet: bool) -> Result<(), String> {
chown_git(&entry)?;
}
}
if repo.exists() {
if exists_at(&repo) {
let _ = fs::remove_dir_all(&staging);
return Err("repository already exists".into());
}
fs::rename(&staging, &repo).map_err(|e| e.to_string())?;
if let Err(error) = fs::rename(&staging, &repo) {
let _ = fs::remove_dir_all(&staging);
return Err(if exists_at(&repo) { "repository already exists".into() } else { error.to_string() });
}
if !quiet {
println!("git@{HOST}:{owner}/{name}.git");
}
Ok(())
}
/// Every path under `root`, descending only into real directories, never through symlinks.
fn walk(root: &Path) -> Vec<PathBuf> {
let mut found = vec![root.to_path_buf()];
if let Ok(entries) = fs::read_dir(root) {
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() && !path.is_symlink() {
if is_real_dir(&path) {
found.extend(walk(&path));
} else {
found.push(path);
@@ -126,11 +153,8 @@ fn walk(root: &Path) -> Vec<PathBuf> {
}
fn delete(owner: &str, name: &str) -> Result<(), String> {
let directory = repos_root().join(owner);
let repo = directory.join(format!("{name}.git"));
if !(repo.is_dir() && !repo.is_symlink() && repo.join("HEAD").is_file()) {
return Err("repository unavailable".into());
}
let repo = repo_dir(owner, name).ok_or("repository unavailable")?;
let directory = repo.parent().ok_or("repository unavailable")?;
// A hidden name stops the repository serving at once, before the slow removal.
let staging = directory.join(format!(".delete-{}-{name}", std::process::id()));
fs::rename(&repo, &staging).map_err(|e| e.to_string())?;
@@ -154,34 +178,42 @@ fn add_key(owner: &str, file: &Path) -> Result<(), String> {
return Err("invalid Ed25519 public key".into());
}
let token = engine.encode(&blob);
// Prepare everything the key needs first: publishing the key file is the last step, so a
// failure leaves no key installed and a retry starts clean.
owner_directory(owner)?;
let keys = keys_path();
let directory = keys.parent().ok_or("authorized_keys has no directory")?;
// Serialise writers, so two keys added at once can't overwrite each other.
let lock = fs::File::options()
.create(true)
.append(true)
.open(directory.join("keys.lock"))
.map_err(|e| e.to_string())?;
let lock =
fs::File::options().create(true).append(true).open(directory.join("keys.lock")).map_err(|e| e.to_string())?;
let _lock = Flock::lock(lock, FlockArg::LockExclusive).map_err(|(_, e)| e.to_string())?;
let old = match fs::read_to_string(&keys) {
Ok(text) => text,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
Err(e) => return Err(e.to_string()),
};
if old.lines().any(|row| row.split_whitespace().last() == Some(token.as_str())) {
if old.lines().any(|row| key_blob(row).as_deref() == Some(blob.as_slice())) {
return Err("key already registered".into());
}
let line = format!("restrict,command=\"/usr/local/bin/gitv serve {owner}\" ssh-ed25519 {token}\n");
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 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())?;
out.set_permissions(fs::Permissions::from_mode(0o644)).map_err(|e| e.to_string())?;
out.sync_all().map_err(|e| e.to_string())?;
fs::rename(&temporary, &keys).map_err(|e| e.to_string())?;
owner_directory(owner)?;
Ok(())
}
/// The decoded Ed25519 key in an authorized_keys line, wherever it sits: after options, and
/// before any comment.
fn key_blob(line: &str) -> Option<Vec<u8>> {
let mut words = line.split_whitespace();
words.by_ref().find(|word| *word == "ssh-ed25519")?;
base64::engine::general_purpose::STANDARD.decode(words.next()?).ok()
}
/// 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")?;
@@ -190,12 +222,13 @@ fn serve(owner: &str, command: &str) -> Result<u8, String> {
[] | ["help"] => println!("{HELP}"),
[program @ ("git-upload-pack" | "git-receive-pack"), path] => return serve_git(owner, program, path),
["list"] => {
let mut names: Vec<String> = fs::read_dir(repos_root().join(owner))
let mut names: Vec<String> = owner_dir(owner)
.and_then(|dir| fs::read_dir(dir).ok())
.into_iter()
.flatten()
.flatten()
.filter_map(|e| e.file_name().to_str()?.strip_suffix(".git").map(str::to_string))
.filter(|n| valid_name(n))
.filter(|n| repo_dir(owner, n).is_some())
.collect();
names.sort();
for name in names {
@@ -229,15 +262,24 @@ fn serve_git(owner: &str, program: &str, path: &str) -> Result<u8, String> {
if requested != owner {
return Err("repository unavailable".into());
}
let repo = repo_path(owner, name);
if !repo.is_dir() {
if program != "git-receive-pack" {
let path = repos_root().join(owner).join(format!("{name}.git"));
let repo = if let Some(repo) = repo_dir(owner, name) {
repo
} else {
// Something other than a real repository at that path (a symlink, a file) is refused,
// never created over or followed.
if program != "git-receive-pack" || exists_at(&path) {
return Err("repository unavailable".into());
}
// Pushing to a new name creates it, so a fresh project needs no setup step.
create(owner, name, true)?;
eprintln!("gitv: created {owner}/{name}.git");
}
// Pushing to a new name creates it, so a fresh project needs no setup step. When two
// first pushes race, one creates it and the other simply uses it.
match create(owner, name, true) {
Ok(()) => eprintln!("gitv: created {owner}/{name}.git"),
Err(_) if repo_dir(owner, name).is_some() => {}
Err(error) => return Err(error),
}
repo_dir(owner, name).ok_or("repository unavailable")?
};
let mut command = Command::new(program);
command.arg(&repo).env_clear().env("PATH", "/usr/bin:/bin").env("HOME", "/var/empty");
// Pass the client's protocol request through (when sshd accepts it), so clients can use the
@@ -248,11 +290,7 @@ fn serve_git(owner: &str, program: &str, path: &str) -> Result<u8, String> {
{
command.env("GIT_PROTOCOL", protocol);
}
let status = command
.stdin(Stdio::inherit())
.stdout(Stdio::inherit())
.status()
.map_err(|e| e.to_string())?;
let status = command.stdin(Stdio::inherit()).stdout(Stdio::inherit()).status().map_err(|e| e.to_string())?;
if program == "git-receive-pack" && status.success() {
fix_head(&repo)?;
}
@@ -267,10 +305,8 @@ fn fix_head(repo: &Path) -> Result<(), String> {
let out = git(repo, &["for-each-ref", "--format=%(refname)", "refs/heads"])?;
let heads: Vec<String> = String::from_utf8_lossy(&out).split_whitespace().map(str::to_string).collect();
let Some(first) = heads.first() else { return Ok(()) };
let choice = ["refs/heads/main", "refs/heads/master"]
.into_iter()
.find(|r| heads.iter().any(|h| h == r))
.unwrap_or(first);
let choice =
["refs/heads/main", "refs/heads/master"].into_iter().find(|r| heads.iter().any(|h| h == r)).unwrap_or(first);
let status = git_command(repo).args(["symbolic-ref", "HEAD", choice]).status().map_err(|e| e.to_string())?;
if !status.success() {
return Err("could not set the default branch".into());
+117−18
@@ -2,13 +2,15 @@
pub mod render;
use std::ffi::OsStr;
use std::fs;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::process::{Child, Command, Stdio};
use std::sync::mpsc::{self, RecvTimeoutError};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
use std::time::{Duration, Instant};
pub const HOST: &str = "git.um9i.dev";
@@ -40,7 +42,7 @@ pub const NAME_RULE: &str = "use 1–63 lowercase letters, digits, hyphens or un
/// How long any one git command may run before it is killed.
pub const GIT_TIMEOUT: Duration = Duration::from_secs(15);
/// The most stdout any one git command may produce before it is killed.
/// The most stdout any one git command may produce through [`git`].
pub const GIT_OUTPUT_LIMIT: usize = 64 << 20;
/// A `git` command with a minimal environment, so no user or system config (hooks templates,
@@ -67,8 +69,17 @@ pub fn git_command(git_dir: &Path) -> Command {
}
/// Run a read-only git command and return its stdout. The command is killed if it runs longer
/// than [`GIT_TIMEOUT`] or writes more than [`GIT_OUTPUT_LIMIT`] bytes.
pub fn git(git_dir: &Path, args: &[&str]) -> Result<Vec<u8>, String> {
/// than [`GIT_TIMEOUT`]; output beyond [`GIT_OUTPUT_LIMIT`] is an error.
pub fn git<S: AsRef<OsStr>>(git_dir: &Path, args: &[S]) -> Result<Vec<u8>, String> {
match git_capped(git_dir, args, GIT_OUTPUT_LIMIT)? {
(output, false) => Ok(output),
(_, true) => Err("git output too large".into()),
}
}
/// Like [`git`], but output beyond `cap` bytes stops the command and comes back truncated, with
/// `true` to say so, rather than as an error.
pub fn git_capped<S: AsRef<OsStr>>(git_dir: &Path, args: &[S], cap: usize) -> Result<(Vec<u8>, bool), String> {
let mut child = git_command(git_dir)
.args(args)
.stdout(Stdio::piped())
@@ -77,35 +88,123 @@ pub fn git(git_dir: &Path, args: &[&str]) -> Result<Vec<u8>, String> {
.map_err(|e| format!("cannot run git: {e}"))?;
let mut stdout = child.stdout.take().ok_or("git has no stdout")?;
let child = Arc::new(Mutex::new(child));
let kill = |child: &Mutex<Child>| {
// The child is never reaped while the lock is held, so this can't hit a reused pid.
if let Ok(mut child) = child.lock() {
let _ = child.kill();
}
};
let deadline = Instant::now() + GIT_TIMEOUT;
// The watchdog covers a read that blocks; nobody holds the lock while blocked.
let (finished, wait) = mpsc::channel::<()>();
let watchdog = {
let child = Arc::clone(&child);
thread::spawn(move || {
if let Err(RecvTimeoutError::Timeout) = wait.recv_timeout(GIT_TIMEOUT) {
// Still unreaped while we hold the lock, so the kill cannot hit a reused pid.
let _ = child.lock().map(|mut c| c.kill());
kill(&child);
}
})
};
let mut output = Vec::new();
let read = (&mut stdout).take(GIT_OUTPUT_LIMIT as u64 + 1).read_to_end(&mut output);
let too_big = output.len() > GIT_OUTPUT_LIMIT;
let status = {
let mut child = child.lock().map_err(|_| "git watchdog failed")?;
if too_big {
let _ = child.kill();
let read = (&mut stdout).take(cap as u64 + 1).read_to_end(&mut output);
let overflow = output.len() > cap;
if overflow {
output.truncate(cap);
kill(&child);
}
drop(stdout);
// Poll rather than block in wait(), taking the lock only briefly, so a kill can always
// get in, here or from the watchdog, even if git closed its output but kept running.
let status = loop {
let polled = child.lock().map_err(|_| "git watchdog failed")?.try_wait();
match polled {
Ok(Some(status)) => break Ok(status),
Ok(None) if Instant::now() >= deadline => kill(&child),
Ok(None) => thread::sleep(Duration::from_millis(2)),
Err(e) => break Err(format!("git failed: {e}")),
}
child.wait()
};
let _ = finished.send(());
let _ = watchdog.join();
read.map_err(|e| format!("cannot read git output: {e}"))?;
let status = status.map_err(|e| format!("git failed: {e}"))?;
if too_big {
Err("git output too large".into())
let status = status?;
if overflow {
Ok((output, true))
} else if status.success() {
Ok(output)
Ok((output, false))
} else {
Err(format!("git failed ({status})"))
}
}
/// True when `path` is a directory itself, not a symlink to one.
pub fn is_real_dir(path: &Path) -> bool {
fs::symlink_metadata(path).is_ok_and(|m| m.is_dir())
}
/// True when anything, even a dangling symlink, exists at `path`.
pub fn exists_at(path: &Path) -> bool {
fs::symlink_metadata(path).is_ok()
}
/// The owner's directory, when it is a real directory inside the repository root. A symlink
/// there could lead reads, writes or ownership changes outside the tree, so it is refused.
pub fn owner_dir(owner: &str) -> Option<PathBuf> {
let directory = repos_root().join(owner);
(valid_name(owner) && is_real_dir(&directory)).then_some(directory)
}
/// An existing repository: `<root>/<owner>/<name>.git` with neither component a symlink and a
/// real `HEAD` file inside.
pub fn repo_dir(owner: &str, name: &str) -> Option<PathBuf> {
let repo = owner_dir(owner)?.join(format!("{name}.git"));
let head = fs::symlink_metadata(repo.join("HEAD"));
(valid_name(name) && is_real_dir(&repo) && head.is_ok_and(|m| m.is_file())).then_some(repo)
}
#[cfg(test)]
mod tests {
use super::*;
/// A bare repository holding one blob of `size` bytes, and the blob's id.
fn repo_with_blob(name: &str, size: usize) -> (PathBuf, String) {
let dir = std::env::temp_dir().join(format!("gitv-lib-{name}-{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
assert!(git_base().args(["init", "-q", "--bare"]).arg(&dir).status().unwrap().success());
let mut child = git_command(&dir)
.args(["hash-object", "-w", "--stdin"])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
.unwrap();
std::io::Write::write_all(&mut child.stdin.take().unwrap(), &vec![b'x'; size]).unwrap();
let oid = String::from_utf8(child.wait_with_output().unwrap().stdout).unwrap().trim().to_string();
(dir, oid)
}
#[test]
fn capped_output_stops_early_and_says_so() {
let (dir, oid) = repo_with_blob("capped", 1 << 20);
let (out, overflow) = git_capped(&dir, &["cat-file", "blob", &oid], 1000).unwrap();
assert!(overflow);
assert_eq!(out.len(), 1000);
let (out, overflow) = git_capped(&dir, &["cat-file", "blob", &oid], 2 << 20).unwrap();
assert!(!overflow);
assert_eq!(out.len(), 1 << 20);
assert!(git(&dir, &["cat-file", "blob", "0000000000000000000000000000000000000000"]).is_err());
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn symlinks_are_not_real_directories() {
let dir = std::env::temp_dir().join(format!("gitv-lib-links-{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(dir.join("real")).unwrap();
std::os::unix::fs::symlink(dir.join("real"), dir.join("link")).unwrap();
std::os::unix::fs::symlink(dir.join("missing"), dir.join("dangling")).unwrap();
assert!(is_real_dir(&dir.join("real")));
assert!(!is_real_dir(&dir.join("link")));
assert!(exists_at(&dir.join("dangling")) && !dir.join("dangling").exists());
let _ = fs::remove_dir_all(&dir);
}
}
@@ -78,7 +78,11 @@ pub enum Target {
/// Resolve a link written in a Markdown file that lives in `dir`.
pub fn resolve_link(dir: &str, target: &str) -> Target {
let lower = target.to_ascii_lowercase();
if lower.starts_with("http://") || lower.starts_with("https://") || lower.starts_with("mailto:") || target.starts_with('#') {
if lower.starts_with("http://")
|| lower.starts_with("https://")
|| lower.starts_with("mailto:")
|| target.starts_with('#')
{
return Target::External(target.to_string());
}
let path = target.split(['#', '?']).next().unwrap_or("");
@@ -86,7 +90,8 @@ pub fn resolve_link(dir: &str, target: &str) -> Target {
if path.split('/').next().is_some_and(|first| first.contains(':')) {
return Target::Blocked;
}
let mut parts: Vec<&str> = if path.starts_with('/') { Vec::new() } else { dir.split('/').filter(|p| !p.is_empty()).collect() };
let mut parts: Vec<&str> =
if path.starts_with('/') { Vec::new() } else { dir.split('/').filter(|p| !p.is_empty()).collect() };
for part in path.split('/') {
match part {
"" | "." => {}
@@ -106,7 +111,8 @@ pub fn resolve_link(dir: &str, target: &str) -> Target {
pub fn markdown(source: &str, dir: &str, link: &dyn Fn(&str, bool) -> String) -> String {
// Heading attributes stay off: `# Title {onclick=… #main}` would let a file set any
// attribute, id or class on the page.
let options = Options::ENABLE_TABLES | Options::ENABLE_STRIKETHROUGH | Options::ENABLE_TASKLISTS | Options::ENABLE_FOOTNOTES;
let options =
Options::ENABLE_TABLES | Options::ENABLE_STRIKETHROUGH | Options::ENABLE_TASKLISTS | Options::ENABLE_FOOTNOTES;
let rewrite = |dest: CowStr<'_>, image: bool| -> CowStr<'static> {
match resolve_link(dir, &dest) {
Target::External(url) => url.into(),
@@ -122,7 +128,9 @@ pub fn markdown(source: &str, dir: &str, link: &dyn Fn(&str, bool) -> String) ->
Event::Text(text) => code.push_str(&text),
Event::End(TagEnd::CodeBlock) => {
let (syntax, code) = fence.take().unwrap_or_default();
events.push(Event::Html(format!("<pre class=\"code\">{}</pre>\n", highlight_with(&code, syntax)).into()));
events.push(Event::Html(
format!("<pre class=\"code\">{}</pre>\n", highlight_with(&code, syntax)).into(),
));
}
_ => {}
}
@@ -184,7 +192,8 @@ mod tests {
#[test]
fn rewrites_relative_links_and_images() {
let html = markdown("[a](guide.md#top) [b](/src/lib.rs) ![c](../img/logo.png) [d](https://x.dev)", "docs", &link);
let html =
markdown("[a](guide.md#top) [b](/src/lib.rs) ![c](../img/logo.png) [d](https://x.dev)", "docs", &link);
assert!(html.contains("href=\"/blob?path=docs/guide.md\""), "{html}");
assert!(html.contains("href=\"/blob?path=src/lib.rs\""), "{html}");
assert!(html.contains("src=\"/raw?path=img/logo.png\""), "{html}");
+110−0
@@ -207,3 +207,113 @@ fn admin_needs_root_outside_a_local_tree() {
assert!(!out.status.success());
assert!(stderr(&out).contains("as root"), "{}", stderr(&out));
}
#[test]
fn symlinked_repositories_are_refused() {
let host = Host::new("ssh-symlink-repo");
let dir = work("ssh-symlink-repo-work", "main");
assert!(host.git(&dir, &["push", "-q", "bob@x:bob/real.git", "main"]).status.success());
// ada/link.git points at bob's repository: following it would cross the owner boundary.
fs::create_dir_all(host.repos.join("ada")).unwrap();
std::os::unix::fs::symlink(host.repo("bob", "real"), host.repo("ada", "link")).unwrap();
let clone = scratch("ssh-symlink-repo-clone");
assert!(!host.git(&clone, &["clone", "-q", "ada@x:ada/link.git"]).status.success(), "read through a symlink");
let out = host.git(&dir, &["push", "-q", "ada@x:ada/link.git", "main:other"]);
assert!(!out.status.success(), "wrote through a symlink");
assert!(git(&host.repo("bob", "real"), &["branch", "--list", "other"]).is_empty());
assert_eq!(stdout(&host.ssh("ada", "list")), "", "symlinks aren't listed");
assert!(!host.ssh("ada", "delete link --yes").status.success());
assert!(host.repo("bob", "real").join("HEAD").is_file(), "the target survives");
}
#[test]
fn symlinked_owner_directories_are_refused() {
let host = Host::new("ssh-symlink-owner");
let outside = scratch("ssh-symlink-owner-outside");
std::os::unix::fs::symlink(&outside, host.repos.join("ada")).unwrap();
let dir = work("ssh-symlink-owner-work", "main");
let out = host.git(&dir, &["push", "-q", "ada@x:ada/new.git", "main"]);
assert!(!out.status.success(), "created a repository through a symlinked owner directory");
assert!(!host.ssh("ada", "create other").status.success());
assert!(fs::read_dir(&outside).unwrap().next().is_none(), "nothing was written outside the tree");
}
#[test]
fn simultaneous_first_pushes_all_succeed() {
let host = std::sync::Arc::new(Host::new("ssh-race"));
let dir = work("ssh-race-work", "main");
// Each push sends its own branch: racing to create one *branch* is git's business, but
// racing to create the *repository* must not fail anyone.
let pushes: Vec<_> = (0..6)
.map(|n| {
let (host, dir) = (host.clone(), dir.clone());
std::thread::spawn(move || host.git(&dir, &["push", "-q", "ada@x:ada/raced.git", &format!("main:b{n}")]))
})
.collect();
for push in pushes {
let out = push.join().unwrap();
assert!(out.status.success(), "{}", stderr(&out));
}
let leftovers: Vec<_> = fs::read_dir(host.repos.join("ada")).unwrap().flatten().map(|e| e.file_name()).collect();
assert_eq!(leftovers, [std::ffi::OsString::from("raced.git")], "no staging directories left behind");
assert_eq!(git(&host.repo("ada", "raced"), &["for-each-ref", "--format=%(refname:lstrip=2)"]).lines().count(), 6);
}
#[test]
fn add_key_failure_installs_nothing() {
let host = Host::new("admin-keys-atomic");
// A file where the owner's directory should go makes preparing the owner fail.
fs::write(host.repos.join("ada"), "not a directory").unwrap();
let key = host.dir.join("ada.pub");
fs::write(&key, ed25519_key(3)).unwrap();
let out = host.admin(&["add-key", "ada", key.to_str().unwrap()]);
assert!(!out.status.success());
assert!(!host.keys.exists(), "the key was installed although the command failed");
// Once the problem is fixed, a retry succeeds rather than finding the key already there.
fs::remove_file(host.repos.join("ada")).unwrap();
let out = host.admin(&["add-key", "ada", key.to_str().unwrap()]);
assert!(out.status.success(), "{}", stderr(&out));
}
#[test]
fn add_key_respects_existing_lines() {
let host = Host::new("admin-keys-existing");
let blob = ed25519_key(5);
let blob = blob.split_whitespace().nth(1).unwrap();
// Written by hand: options in front, a comment after, and no final newline.
fs::write(&host.keys, format!("restrict,command=\"/usr/local/bin/gitv serve ada\" ssh-ed25519 {blob} laptop"))
.unwrap();
let same = host.dir.join("same.pub");
fs::write(&same, ed25519_key(5)).unwrap();
let out = host.admin(&["add-key", "bob", same.to_str().unwrap()]);
assert!(!out.status.success(), "the same key was registered twice");
assert!(stderr(&out).contains("already registered"), "{}", stderr(&out));
let other = host.dir.join("other.pub");
fs::write(&other, ed25519_key(6)).unwrap();
assert!(host.admin(&["add-key", "bob", other.to_str().unwrap()]).status.success());
let keys = fs::read_to_string(&host.keys).unwrap();
let lines: Vec<&str> = keys.lines().collect();
assert_eq!(lines.len(), 2, "{keys}");
assert!(
lines[0].ends_with(" laptop") && lines[1].starts_with("restrict,command=\"/usr/local/bin/gitv serve bob\"")
);
}
#[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 dir = work("ssh-script-work", "main");
let out = common::git_cmd(&dir)
.env("GIT_SSH_COMMAND", &script)
.env("GITV_REPOS", &host.repos)
.args(["push", "-q", "um9i@local:um9i/demo.git", "main"])
.output()
.unwrap();
assert!(out.status.success(), "{}", stderr(&out));
assert!(host.repo("um9i", "demo").join("HEAD").is_file());
}
+133−8
@@ -3,7 +3,9 @@
mod common;
use std::ffi::OsStr;
use std::fs;
use std::os::unix::ffi::OsStrExt;
use std::path::PathBuf;
use std::sync::OnceLock;
@@ -16,6 +18,10 @@ struct Fixture {
removal: String,
merge: String,
tip: String,
/// On branch `odd`: odd file names, two READMEs and an empty message.
oddities: String,
/// On branch `odd`: a patch too large to show line by line.
huge: String,
}
const README: &str = "# Fixture {onclick=alert(1) #main .skip}
@@ -98,10 +104,40 @@ fn fixture() -> &'static Fixture {
}
git(&work, &["checkout", "-q", "main"]);
let out = host.git(&work, &["push", "-q", "ada@x:ada/site.git", "main", "side", "long", "v0.1.0", "light"]);
// Branch `odd`: names git allows that are awkward elsewhere.
git(&work, &["checkout", "-qb", "odd"]);
let non_utf8 = OsStr::from_bytes(b"latin1-caf\xe9.txt");
fs::write(work.join(non_utf8), "not UTF-8 in name\n").unwrap();
fs::create_dir_all(work.join("x b")).unwrap();
fs::write(work.join("x b/c.txt"), "in a folder ending in ' b'\n").unwrap();
fs::write(work.join("q\"uote.txt"), "quoted by git\n").unwrap();
fs::create_dir_all(work.join("pref")).unwrap();
fs::write(work.join("pref/README"), "plain readme\n").unwrap();
fs::write(work.join("pref/README.md"), "# Markdown readme\n").unwrap();
git(&work, &["add", "-A"]);
git(&work, &["commit", "-q", "--allow-empty-message", "-m", ""]);
let oddities = git(&work, &["rev-parse", "HEAD"]);
let lines: String = (0..60_000).map(|n| format!("line {n} of a very large generated file\n")).collect();
fs::write(work.join("huge.txt"), lines).unwrap();
git(&work, &["add", "huge.txt"]);
git(&work, &["commit", "-qm", "Add a huge file"]);
let huge = git(&work, &["rev-parse", "HEAD"]);
git(&work, &["checkout", "-q", "main"]);
for branch in ["release+docs", "café", "user@topic"] {
git(&work, &["branch", branch, &first]);
}
let refs = ["main", "side", "long", "odd", "release+docs", "café", "user@topic", "v0.1.0", "light"];
let out = host.git(&work, &[&["push", "-q", "ada@x:ada/site.git"][..], &refs].concat());
assert!(out.status.success(), "{}", common::stderr(&out));
assert!(host.admin(&["create", "ada", "empty"]).status.success());
Fixture { repos: host.repos.clone(), first, removal, merge, tip }
// The same README in a second repository: its links must stay in that repository.
let out = host.git(&work, &["push", "-q", "ada@x:ada/twin.git", &format!("{first}:refs/heads/main")]);
assert!(out.status.success(), "{}", common::stderr(&out));
// Symlinks in the tree, as a repository and as an owner, must never be followed.
std::os::unix::fs::symlink(host.repo("ada", "site"), host.repo("ada", "link")).unwrap();
std::os::unix::fs::symlink(host.repos.join("ada"), host.repos.join("alias")).unwrap();
Fixture { repos: host.repos.clone(), first, removal, merge, tip, oddities, huge }
})
}
@@ -119,11 +155,101 @@ fn index_lists_repositories_newest_first() {
let page = s.get("/");
assert_eq!(page.status, 200);
let html = page.text();
assert!(html.contains("2 repositories"), "{html}");
assert!(html.contains("3 repositories"), "symlinks aren't listed: {html}");
let site = html.find("ada/</span>site").expect("site listed");
let empty = html.find("ada/</span>empty").expect("empty listed");
assert!(site < empty, "the repository with commits comes first");
assert!(html.contains("No commits yet"));
assert!(!html.contains("ada/</span>link") && !html.contains("alias/"));
}
#[test]
fn symlinks_in_the_tree_are_not_served() {
let s = server();
for path in ["/ada/link/tree", "/ada/link/raw?path=README.md", "/alias/site/tree", "/alias/site/log"] {
assert_eq!(s.get(path).status, 404, "{path}");
}
}
#[test]
fn markdown_links_stay_in_their_own_repository() {
let s = server();
// Same README blob, same ref name, two repositories, one server process.
let site = s.get("/ada/site/tree").text();
let twin = s.get("/ada/twin/tree").text();
assert!(site.contains("href=\"/ada/site/blob?ref=main&amp;path=docs/guide.md\""));
assert!(twin.contains("href=\"/ada/twin/blob?ref=main&amp;path=docs/guide.md\""), "{twin}");
assert!(!twin.contains("/ada/site/"), "twin's README links into site");
let preview = s.get("/ada/twin/blob?path=README.md").text();
assert!(
preview.contains("href=\"/ada/twin/raw?ref=main&amp;path=img/logo.svg\"")
|| preview.contains("src=\"/ada/twin/raw?ref=main&amp;path=img/logo.svg\"")
);
}
#[test]
fn every_branch_name_git_allows_can_be_opened() {
let s = server();
for (name, encoded) in [("release+docs", "release%2Bdocs"), ("café", "caf%C3%A9"), ("user@topic", "user%40topic")]
{
let page = s.get(&format!("/ada/site/tree?ref={encoded}"));
assert_eq!(page.status, 200, "{name}");
assert!(page.text().contains(">old.txt<"), "{name} shows its own tree");
assert_eq!(s.get(&format!("/ada/site/log?ref={encoded}")).status, 200, "{name}");
}
// Revision syntax is still refused, even though each piece looks like a name.
for bad in ["main~1", "main%5E", "main%40%7B0%7D", "HEAD%3Aold.txt", "main..side"] {
assert_eq!(s.get(&format!("/ada/site/tree?ref={bad}")).status, 404, "{bad}");
}
}
#[test]
fn file_names_that_are_not_utf8_still_open() {
let s = server();
let html = s.get("/ada/site/tree?ref=odd").text();
assert!(html.contains("latin1-caf\u{fffd}.txt"), "shown with a replacement character");
assert!(html.contains("path=latin1-caf%E9.txt"), "linked with its real bytes");
let raw = s.get("/ada/site/raw?ref=odd&path=latin1-caf%E9.txt");
assert_eq!(raw.status, 200);
assert_eq!(raw.text(), "not UTF-8 in name\n");
assert_eq!(s.get("/ada/site/blob?ref=odd&path=latin1-caf%E9.txt").status, 200);
}
#[test]
fn diff_links_survive_odd_names() {
let s = server();
let html = s.get(&format!("/ada/site/commit?id={}", fixture().oddities)).text();
assert!(html.contains("<h2 class=\"ctitle\">(no message)</h2>"), "an empty message stays visible");
// Each changed file links to itself, whatever git's diff header does with its name.
for (shown, encoded) in
[("x b/c.txt", "x%20b/c.txt"), ("q\"uote.txt", "q%22uote.txt"), ("latin1-caf\u{fffd}.txt", "latin1-caf%E9.txt")]
{
assert!(html.contains(&format!("<b>{shown}</b>")), "{shown} missing: {html}");
let path = format!("/ada/site/blob?ref={}&path={encoded}", fixture().oddities);
assert!(html.contains(&path.replace('&', "&amp;")), "{shown} isn't linked to {path}");
assert_eq!(s.get(&path).status, 200, "{path}");
}
let log = s.get("/ada/site/log?ref=odd").text();
assert!(log.contains(">(no message)</a>"));
}
#[test]
fn a_markdown_readme_wins_over_a_plain_one() {
let s = server();
let html = s.get("/ada/site/tree?ref=odd&path=pref").text();
assert!(html.contains("<b>README.md</b>") && html.contains("<h1>Markdown readme</h1>"), "{html}");
}
#[test]
fn huge_commits_still_show_what_changed() {
let s = server();
let page = s.get(&format!("/ada/site/commit?id={}", fixture().huge));
assert_eq!(page.status, 200, "the commit exists even when its diff is huge");
let html = page.text();
assert!(html.contains("<h2 class=\"ctitle\">Add a huge file</h2>"));
assert!(html.contains("too large to show line by line"), "{html}");
assert!(html.contains("1 file changed") && html.contains("<b>huge.txt</b>"));
assert!(!html.contains("line 59999"), "the patch isn't on the page");
}
#[test]
@@ -324,10 +450,8 @@ fn history_lists_commits_with_tags_and_pages() {
let html = s.get("/ada/site/log").text();
// In git's own order, including the merged branch's commit.
let expected = git(&fixture().repos.join("ada/site.git"), &["log", "--format=%s", "main"]);
let order: Vec<usize> = expected
.lines()
.map(|subject| html.find(subject).unwrap_or_else(|| panic!("{subject} missing")))
.collect();
let order: Vec<usize> =
expected.lines().map(|subject| html.find(subject).unwrap_or_else(|| panic!("{subject} missing"))).collect();
assert_eq!(order.len(), 5);
assert!(order.windows(2).all(|w| w[0] < w[1]), "out of order: {order:?}");
assert!(html.contains(">v0.1.0</a>") && html.contains(">light</a>"), "tag chips");
@@ -441,7 +565,8 @@ fn writes_are_refused() {
let s = server();
let mut stream = std::net::TcpStream::connect(("127.0.0.1", s.port)).unwrap();
use std::io::{Read, Write};
write!(stream, "POST /ada/site/tree HTTP/1.1\r\nHost: x\r\nContent-Length: 0\r\nConnection: close\r\n\r\n").unwrap();
write!(stream, "POST /ada/site/tree HTTP/1.1\r\nHost: x\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
.unwrap();
let mut reply = String::new();
stream.read_to_string(&mut reply).unwrap();
assert!(reply.starts_with("HTTP/1.1 405"), "{reply}");