GITv

Work through directory handles, and fix ref, key and cache edge cases

Browse files

Repositories are now opened, created, deleted and listed through open directory handles, never by re-resolving checked paths: - Git runs inside the opened repository via fchdir and --git-dir=., and each command owns a duplicate of the descriptor; setup errors are raised without allocating after fork. - Creation builds inside a private 0700 staging directory under the open owner directory, sets permissions and ownership by handle, and publishes with renameat2(RENAME_NOREPLACE) from the staging handle. Rollback only removes what this run made, and cleanup failures are reported. - Deletion keeps one owner handle through rename and recursive removal, which never follows symlinks. Walks that change the tree fail loudly on anything they can't list or inspect. - The index lists owners and repositories by handle, keeps no handle per row, and caches rows against a depth-first fingerprint of ref folder times, discarded whenever any folder can't be read. Other fixes: - A push that loses the race to create a repository opens the winner's. - Default-branch repair and the web's default branch keep branch names exactly (bytes, trailing Unicode whitespace). - Ref links carry refs/heads/ or refs/tags/ whenever a plain name could be misread; qualified names resolve first; commit ids resolve as objects only. - README and file views share one cached rendering; oversized entries bypass the cache; render permits are held by the blocking work. - Markdown link paths are decoded once and keep folder bytes. - Subjects and tag messages containing 0x1f stay whole. - authorized_keys parsing skips comments, handles quoted options and tab-separated fields, and checks the key type. 82 tests, including regression tests for each fix. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Author
Um9i vulgarmessiah@gmail.com
Date
22 Nov 2026, 12:05
Commit
da000f0b3054
Parent
e03ba74

9 files changed +1245−321

@@ -8,7 +8,7 @@ axum = "0.8.9"
base64 = "0.23.1"
clap = { version = "4.6.9", features = ["derive"] }
html-escape = "0.3.1"
nix = { version = "0.32.0", features = ["user", "fs"] }
nix = { version = "0.32.0", features = ["user", "fs", "dir", "resource"] }
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"] }
+1−1
@@ -7,7 +7,7 @@ Private Git hosting over OpenSSH, plus a read-only web browser.
**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.
**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. Everything works through open directory handles: git runs inside the repository directory it opened, new repositories are built and published inside the open owner directory (never replacing anything already at the name), deletion removes through handles without following links, and the web index lists and fingerprints repositories the same way. A path swapped for a symlink after a check can't redirect any of it.
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.
@@ -10,7 +10,6 @@ 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};
@@ -20,8 +19,13 @@ use axum::response::{IntoResponse, Redirect, Response};
use axum::{Router, routing::get};
use clap::{Parser, Subcommand};
use gitv::render;
use gitv::{HOST, git, git_capped, repo_dir, repos_root};
use gitv::{
HOST, RepoDir, entries, git, git_capped, open_dir_at, open_owner, open_root, percent_decode, repo_dir, repo_in,
repos_root, try_entries, try_kind_at,
};
use html_escape::{encode_double_quoted_attribute as attr, encode_text as esc};
use nix::sys::stat::SFlag;
use std::os::fd::{AsFd, OwnedFd};
const STYLESHEET: &str = include_str!("../../assets/style.css");
const FONT_DISPLAY: &[u8] = include_bytes!("../../assets/fonts/display.woff2");
@@ -71,6 +75,10 @@ fn cached(key: String, make: impl FnOnce() -> Option<String>) -> Option<Arc<str>
return Some(hit);
}
let value: Arc<str> = make()?.into();
// Something this big would evict much of everything else to fit; serve it uncached.
if key.len() + value.len() > CACHE_BUDGET / 4 {
return Some(value);
}
if let Ok(mut cache) = CACHE.lock() {
let key_len = key.len();
if cache.bytes + key_len + value.len() > CACHE_BUDGET {
@@ -167,35 +175,15 @@ 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));
// In a query string `+` is a space; an encoded plus (`%2B`) stays a plus.
let (key, value) = (key.replace('+', " "), value.replace('+', " "));
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())
@@ -335,7 +323,7 @@ fn view_missing() -> String {
struct Repo {
owner: String,
name: String,
path: PathBuf,
dir: RepoDir,
heads: OnceCell<Vec<String>>,
tags: OnceCell<Vec<String>>,
}
@@ -349,21 +337,35 @@ struct Head {
date: String,
}
impl Head {
/// Parse `%H %an %ct %cs %s`, separated by 0x1f. The subject goes last and the split stops
/// at five fields, so a subject that itself contains the separator byte stays whole.
fn parse(out: &str) -> Option<Head> {
let f: Vec<&str> = out.trim_end_matches('\n').splitn(5, '\x1f').collect();
let [oid, author, stamp, date, subject] = <[&str; 5]>::try_from(f).ok()?;
Some(Head {
oid: oid.into(),
subject: subject.into(),
author: author.into(),
stamp: stamp.into(),
date: date.into(),
})
}
}
impl Repo {
/// A repository whose owner and repository directories are real directories, never
/// symlinks that could lead outside the tree.
/// A repository opened through its owner and repository directories with symlinks refused;
/// every git command then runs inside that open directory.
fn open(owner: &str, name: &str) -> Option<Repo> {
Some(Repo {
path: repo_dir(owner, name)?,
owner: owner.into(),
name: name.into(),
heads: OnceCell::new(),
tags: OnceCell::new(),
})
Some(Repo::from_dir(owner, name, repo_dir(owner, name)?))
}
fn from_dir(owner: &str, name: &str, dir: RepoDir) -> Repo {
Repo { dir, owner: owner.into(), name: name.into(), heads: OnceCell::new(), tags: OnceCell::new() }
}
fn git_bytes<S: AsRef<OsStr>>(&self, args: &[S]) -> Option<Vec<u8>> {
git(&self.path, args).ok()
git(&self.dir, args).ok()
}
fn git<S: AsRef<OsStr>>(&self, args: &[S]) -> Option<String> {
@@ -394,17 +396,22 @@ impl Repo {
/// 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", "HEAD"]);
let head = head.as_deref().map(str::trim).and_then(|h| h.strip_prefix("refs/heads/"));
// Strip only git's newline: a branch name can end in other (Unicode) whitespace.
let head =
head.as_deref().map(|h| h.strip_suffix('\n').unwrap_or(h)).and_then(|h| h.strip_prefix("refs/heads/"));
let heads = self.heads();
if let Some(head) = head.filter(|h| heads.iter().any(|b| b == h)) {
return head.to_string();
}
["main", "master"]
.into_iter()
.map(String::from)
.find(|b| heads.contains(b))
.or_else(|| heads.first().cloned())
.unwrap_or_else(|| "HEAD".into())
let name = match head.filter(|h| heads.iter().any(|b| b == h)) {
Some(head) => head.to_string(),
None => match ["main", "master"].into_iter().map(String::from).find(|b| heads.contains(b)) {
Some(branch) => branch,
None => match heads.first() {
Some(first) => first.clone(),
None => return "HEAD".into(),
},
},
};
// In the form links use, so a branch named like a commit id still opens itself.
self.branch_ref(&name)
}
/// Names under a namespace exactly as git stores them (not `refname:short`, which can
@@ -423,18 +430,32 @@ impl Repo {
self.tags.get_or_init(|| self.list_refs("refs/tags"))
}
/// 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.
/// The commit a reference names, in this order:
///
/// - `refs/heads/NAME` or `refs/tags/NAME` for an existing branch or tag: the form links
/// use whenever a plain name could be misread (see [`Repo::branch_ref`]);
/// - a full commit id, always as an object, whatever refs are named;
/// - a branch, then a tag, by exact name, so any name git allows works and none is read as
/// revision syntax;
/// - `HEAD`, then an abbreviated commit id, again only as an object.
fn resolve(&self, reference: &str) -> Option<String> {
let full = if self.heads().iter().any(|h| h == reference) {
let is_head = |n: &str| self.heads().iter().any(|h| h == n);
let is_tag = |n: &str| self.tags().iter().any(|t| t == n);
let hex = reference.bytes().all(|b| b.is_ascii_hexdigit());
let full = if let Some(name) = reference.strip_prefix("refs/heads/").filter(|n| is_head(n)) {
format!("refs/heads/{name}")
} else if let Some(name) = reference.strip_prefix("refs/tags/").filter(|n| is_tag(n)) {
format!("refs/tags/{name}")
} else if hex && matches!(reference.len(), 40 | 64) {
return self.commit_object(reference);
} else if is_head(reference) {
format!("refs/heads/{reference}")
} else if self.tags().iter().any(|t| t == reference) {
} else if is_tag(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 if reference == "HEAD" {
"HEAD".to_string()
} else if hex && reference.len() >= 4 {
return self.commit_object(reference);
} else {
return None;
};
@@ -442,37 +463,78 @@ impl Repo {
self.git(&["rev-parse", "--verify", "--quiet", "--end-of-options", &spec]).map(|s| s.trim().into())
}
/// The commit whose id is or starts with `id`, looked up among objects only: a branch or
/// tag that happens to be named like an id can't redirect it. Annotated tag objects peel to
/// their commit. An ambiguous abbreviation finds nothing.
fn commit_object(&self, id: &str) -> Option<String> {
if !(4..=64).contains(&id.len()) || !id.bytes().all(|b| b.is_ascii_hexdigit()) {
return None;
}
let id = id.to_ascii_lowercase();
let candidates = self.git(&["rev-parse", &format!("--disambiguate={id}")])?;
let found: Vec<String> = candidates
.lines()
.filter_map(|oid| {
// A full id: git reads 40 or 64 hex digits as an object before any ref.
let peeled = self.git(&["rev-parse", "--verify", "--quiet", &format!("{oid}^{{commit}}")])?;
Some(peeled.trim().to_string())
})
.collect();
match found.as_slice() {
[one] => Some(one.clone()),
_ => None,
}
}
/// Whether a plain name in a link would resolve to itself: it mustn't look like a full
/// commit id or a qualified ref, which [`Repo::resolve`] reads first.
fn plain_is_safe(name: &str) -> bool {
let full_id = matches!(name.len(), 40 | 64) && name.bytes().all(|b| b.is_ascii_hexdigit());
!full_id && !name.starts_with("refs/") && name != "HEAD"
}
/// How a link names a branch: plainly when that can't be misread, else `refs/heads/NAME`.
fn branch_ref(&self, name: &str) -> String {
if Self::plain_is_safe(name) { name.to_string() } else { format!("refs/heads/{name}") }
}
/// How a link names a tag: plainly when that can't be misread or taken by a same-named
/// branch, else `refs/tags/NAME`.
fn tag_ref(&self, name: &str) -> String {
if Self::plain_is_safe(name) && !self.heads().iter().any(|h| h == name) {
name.to_string()
} else {
format!("refs/tags/{name}")
}
}
/// 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> {
Head::parse(&self.latest_raw(rev, path)?)
}
/// [`Repo::latest`] as git printed it, for callers that cache it themselves.
fn latest_raw(&self, rev: &str, path: &[u8]) -> Option<String> {
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();
["log", "-1", "--format=%H%x1f%an%x1f%ct%x1f%cs%x1f%s", 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()
if is_oid {
Some(cached(format!("latest:{}:{rev}:{}", self.dir.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(),
})
lookup()
}
}
/// 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 key = format!("count:{}:{commit}", self.dir.path.display());
cached(key, || self.git(&["rev-list", "--count", commit, "--"]).map(|s| s.trim().to_string()))
.and_then(|count| count.parse().ok())
.unwrap_or(0)
@@ -500,13 +562,13 @@ impl Repo {
/// Render a Markdown file from directory `dir`, linking repository paths at `reference`.
fn markdown(&self, source: &str, dir: &[u8], reference: &str) -> String {
render::markdown(source, &lossy(dir), &|path, image| {
render::markdown(source, dir, &|path, image| {
if image {
self.url_at("raw", reference, path.as_bytes(), "")
self.url_at("raw", reference, path, "")
} else if path.is_empty() {
self.url("tree", &[("ref", reference)])
} else {
self.url_at("blob", reference, path.as_bytes(), "")
self.url_at("blob", reference, path, "")
}
})
}
@@ -538,13 +600,14 @@ impl Repo {
/// Branch and tag menu, then the path as breadcrumbs.
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_at(view, name, path, "");
// `link` is what the URL carries; `name` is what people see.
let item = |link: String, name: &str| {
let current = if link == reference { r#" aria-current="true""# } else { "" };
let href = self.url_at(view, &link, path, "");
format!(r#"<a href="{}"{current}>{}</a>"#, attr(&href), esc(name))
};
let branches: String = self.heads().iter().map(item).collect();
let tags: String = self.tags().iter().map(item).collect();
let branches: String = self.heads().iter().map(|b| item(self.branch_ref(b), b)).collect();
let tags: String = self.tags().iter().map(|t| item(self.tag_ref(t), t)).collect();
let mut menu = format!("<h2>Branches</h2>{branches}");
if !tags.is_empty() {
menu += &format!("<h2>Tags</h2>{tags}");
@@ -573,7 +636,10 @@ impl Repo {
r#"<div class="locator"><details class="refmenu"><summary>{}{}{}</summary><div class="menu">{menu}</div></details>
{crumbs}</div>"#,
icon("branch"),
esc(reference),
esc(reference
.strip_prefix("refs/heads/")
.or_else(|| reference.strip_prefix("refs/tags/"))
.unwrap_or(reference)),
icon("chevron"),
)
}
@@ -629,42 +695,122 @@ fn entry(repo: &Repo, commit: &str, path: &[u8]) -> Option<Entry> {
// ---------------------------------------------------------------------------------------------
// Views
fn sorted_dir(path: &std::path::Path) -> Vec<String> {
let mut names: Vec<String> = std::fs::read_dir(path)
.into_iter()
.flatten()
.flatten()
.filter_map(|e| e.file_name().into_string().ok())
.filter(|n| !n.starts_with('.'))
.collect();
/// The names in an open directory, sorted, skipping hidden ones and any that aren't UTF-8
/// (no valid owner or repository name is).
fn sorted_names(dir: &impl AsFd) -> Vec<String> {
let mut names: Vec<String> =
entries(dir).into_iter().filter_map(|n| n.into_string().ok()).filter(|n| !n.starts_with('.')).collect();
names.sort();
names
}
/// A fingerprint of a repository's branches, for caching its row on the index. Git updates a
/// ref by renaming a file into place (a loose ref under `refs/heads`, or `packed-refs` and
/// `HEAD` in the repository directory, or a table under `reftable`), and a rename changes the
/// directory's modification time. So the times of those directories change whenever a branch
/// or HEAD does. It reads them through the repository's open handle, the same directory git
/// reads, never through a path. The current minute is included too, which bounds staleness
/// should two pushes land within the filesystem's timestamp granularity.
fn refs_fingerprint(repo: &RepoDir) -> Option<String> {
/// Append a directory's modification time.
fn note(stamp: &mut String, dir: &impl AsFd) -> Option<()> {
let meta = nix::sys::stat::fstat(dir.as_fd()).ok()?;
let _ = write!(stamp, ":{}.{}", meta.st_mtime, meta.st_mtime_nsec);
Some(())
}
/// Note `dir` and every directory under it, depth first, holding open only the directories
/// on the current path, never all the siblings at once. Any directory that can't be read
/// makes the whole fingerprint `None`, so a partial one is never trusted.
fn walk(stamp: &mut String, dir: &OwnedFd) -> Option<()> {
note(stamp, dir)?;
let mut names = try_entries(dir).ok()?;
names.sort();
// Ref files (and entries deleted since the listing) are covered by their directory's
// time; only subdirectories need visiting.
for name in names {
// An entry that can't be inspected might be a folder; a fingerprint that skipped it
// could miss a change, so the whole fingerprint is abandoned instead.
if try_kind_at(dir, &name).ok()? == Some(SFlag::S_IFDIR) {
stamp.push('/');
walk(stamp, &open_dir_at(dir, &name).ok()?)?;
}
}
Some(())
}
/// A directory that may legitimately be absent: absent is a fact, unreadable is not.
fn optional(parent: &impl AsFd, name: &str) -> Option<Option<OwnedFd>> {
match open_dir_at(parent, OsStr::new(name)) {
Ok(dir) => Some(Some(dir)),
Err(nix::errno::Errno::ENOENT) => Some(None),
Err(_) => None,
}
}
let minute = SystemTime::now().duration_since(UNIX_EPOCH).ok()?.as_secs() / 60;
let mut stamp = format!("{minute}");
note(&mut stamp, &repo.handle())?;
let refs = optional(&repo.handle(), "refs")?;
for dir in [refs.as_ref(), optional(&repo.handle(), "reftable")?.as_ref()] {
match dir {
Some(dir) => note(&mut stamp, dir)?,
None => stamp.push_str(":-"),
}
}
if let Some(refs) = refs.as_ref()
&& let Some(heads) = optional(refs, "heads")?
{
walk(&mut stamp, &heads)?;
}
Some(stamp)
}
/// One row of the index: everything it shows, and no open repository handle, so a large
/// installation holds one handle at a time however many repositories it lists.
struct Row {
owner: String,
name: String,
head: Option<Head>,
}
fn view_index() -> View {
let root = repos_root();
let mut rows = Vec::new();
for owner in sorted_dir(&root) {
for entry in sorted_dir(&root.join(&owner)) {
let root = open_root();
for owner in root.as_ref().map(sorted_names).unwrap_or_default() {
// Read through the owner's open directory: a symlinked owner isn't followed or listed.
let Some(owner_dir) = open_owner(&owner) else { continue };
for entry in sorted_names(&owner_dir) {
let Some(name) = entry.strip_suffix(".git") else { continue };
let Some(repo) = Repo::open(&owner, name) else { continue };
// 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));
let Some(dir) = repo_in(&owner_dir, &owner, name) else { continue };
let repo = Repo::from_dir(&owner, name, dir);
// HEAD usually names a real branch; only look further when it doesn't. An empty
// repository caches as an empty answer.
let lookup = || {
Some(
repo.latest_raw("HEAD", b"")
.or_else(|| repo.latest_raw(&repo.default_ref(), b""))
.unwrap_or_default(),
)
};
let raw = match refs_fingerprint(&repo.dir) {
Some(stamp) => cached(format!("index:{}:{stamp}", repo.dir.path.display()), lookup),
None => lookup().map(Arc::from),
};
let head = raw.as_deref().and_then(Head::parse);
// `repo`, and with it the directory handle, is dropped here.
rows.push(Row { owner: owner.clone(), name: name.to_string(), head });
}
}
rows.sort_by_key(|row| Reverse(row.0));
rows.sort_by_key(|row| Reverse(row.head.as_ref().and_then(|h| h.stamp.parse::<u64>().ok()).unwrap_or(0)));
let items: String = rows
.iter()
.map(|(_, repo, head)| {
.map(|Row { owner, name, head }| {
let (last, when) = head.as_ref().map_or(("No commits yet".into(), String::new()), |h| {
(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(&format!("/{owner}/{name}/tree")),
esc(owner),
esc(name)
)
})
.collect();
@@ -767,19 +913,12 @@ fn view_tree(repo: &Repo, q: &Q) -> Option<View> {
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 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 {
// 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 content = content.unwrap_or_else(|| r#"<p class="note">This README couldn't be read.</p>"#.into());
let rendered =
render_file(repo, &readme.oid, readme.size, &name, &path, &reference, !render::is_markdown(&name));
let content = rendered
.as_deref()
.and_then(|r| r.split_once('\x1f'))
.map_or(r#"<p class="note">This README couldn't be read.</p>"#, |(_, html)| html);
let _ = write!(
body,
r#"<section class="panel"><div class="panel-head"><div class="lead">{}<b>{}</b></div></div>{content}</section>"#,
@@ -795,6 +934,44 @@ fn view_tree(repo: &Repo, q: &Q) -> Option<View> {
Some(View::Html(page(&title, &body)))
}
/// A file rendered for display, as `facts` 0x1f `html`: highlighted code, or Markdown with
/// links into this repository at `reference` (the file lives in `dir`). The file view and the
/// README panel both use this, so they share one cached value per rendering instead of
/// storing different shapes under one key. The facts and the rendering are cached together,
/// so a repeat view reads no blob at all.
fn render_file(
repo: &Repo,
oid: &str,
file_size: usize,
name: &str,
dir: &[u8],
reference: &str,
as_code: bool,
) -> Option<Arc<str>> {
let key = if as_code {
// Highlighting depends only on the content and the file's type, so it's shared.
format!("code:{oid}:{name}")
} else {
// Links depend on the repository, folder and ref too.
repo.key("md", oid, &format!("{}:{reference}", encode(dir)))
};
cached(key, || {
let data = repo.git_bytes(&["cat-file", "blob", 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(file_size)));
}
let text = String::from_utf8_lossy(&data);
let facts = format!("{}, {}", plural(text.lines().count(), "line", "lines"), size(file_size));
let html = if as_code {
code_view(name, &text)
} else {
format!(r#"<article class="markdown">{}</article>"#, repo.markdown(&text, dir, reference))
};
Some(format!("{facts}\x1f{html}"))
})
}
/// Highlighted source with a line-number gutter.
fn code_view(path: &str, text: &str) -> String {
let lines = text.lines().count().max(1);
@@ -850,7 +1027,6 @@ fn view_blob(repo: &Repo, q: &Q, raw: bool) -> Option<View> {
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{}",
@@ -859,27 +1035,7 @@ fn view_blob(repo: &Repo, q: &Q, raw: bool) -> Option<View> {
)
.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}"))
})?
render_file(repo, &item.oid, item.size, &name, parent_of(&path), &reference, as_code)?
};
let (facts, content) = rendered.split_once('\x1f').unwrap_or(("", &rendered));
@@ -917,7 +1073,7 @@ fn view_log(repo: &Repo, q: &Q) -> Option<View> {
"log",
&format!("-n{}", PAGE + 1),
&format!("--skip={skip}"),
"--format=%H%x1f%s%x1f%an%x1f%ct%x1f%cs",
"--format=%H%x1f%an%x1f%ct%x1f%cs%x1f%s",
&commit,
"--",
])?;
@@ -925,10 +1081,9 @@ fn view_log(repo: &Repo, q: &Q) -> Option<View> {
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 {
continue;
};
// Subject last, split at most five ways: a subject containing 0x1f stays whole.
let Some(head) = Head::parse(line) else { continue };
let Head { oid, subject, author, stamp, date } = &head;
let chips: String = tags
.get(oid)
.into_iter()
@@ -936,7 +1091,7 @@ fn view_log(repo: &Repo, q: &Q) -> Option<View> {
.map(|t| {
format!(
r#"<a class="tagchip" href="{}">{}{}</a>"#,
attr(&repo.url("tree", &[("ref", t)])),
attr(&repo.url("tree", &[("ref", &repo.tag_ref(t))])),
icon("tag"),
esc(t)
)
@@ -1055,15 +1210,18 @@ fn view_commit(repo: &Repo, q: &Q) -> Option<View> {
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)?;
// Looked up as an object only: a branch named like this id can't redirect the page.
let commit = repo.commit_object(&id)?;
// NUL between fields: a commit message can't contain one, so the subject and body can hold
// any other byte, the separator git output elsewhere uses included.
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",
"--format=%H%x00%P%x00%an%x00%ae%x00%ad%x00%s%x00%b",
&commit,
])?;
let f: Vec<&str> = meta.splitn(7, '\x1f').collect();
let f: Vec<&str> = meta.splitn(7, '\0').collect();
let [oid, parents, author, email, date, subject, message] = <[&str; 7]>::try_from(f).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(), None);
@@ -1102,7 +1260,7 @@ fn render_diff(repo: &Repo, oid: &str, parents: &str) -> Option<String> {
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()?;
git_capped(&repo.dir, &[&["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.
@@ -1173,13 +1331,14 @@ fn view_tags(repo: &Repo) -> Option<View> {
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)",
"--format=%(refname:lstrip=2)%1f%(objectname)%1f%(*objectname)%1f%(creatordate:unix)%1f%(creatordate:short)%1f%(objecttype)%1f%(contents:subject)",
"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<_>>())
// The tag's message goes last, so one containing the separator stays whole.
let Ok([name, direct, peeled, stamp, date, kind, note]) =
<[&str; 7]>::try_from(line.splitn(7, '\x1f').collect::<Vec<_>>())
else {
continue;
};
@@ -1196,7 +1355,7 @@ fn view_tags(repo: &Repo) -> Option<View> {
esc(name),
repo.sha_link(target),
ago(stamp, date),
attr(&repo.url("tree", &[("ref", name)]))
attr(&repo.url("tree", &[("ref", &repo.tag_ref(name))]))
);
}
let listing = if rows.is_empty() {
@@ -1225,12 +1384,18 @@ fn route(owner: &str, name: &str, view: Option<&str>, q: &Q) -> View {
/// 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);
static RENDERS: LazyLock<Arc<tokio::sync::Semaphore>> = LazyLock::new(|| Arc::new(tokio::sync::Semaphore::new(16)));
/// Git calls block, so every page renders on the blocking pool.
/// Git calls block, so every page renders on the blocking pool. The permit moves into the
/// blocking work itself: if the request is cancelled while rendering, the slot stays taken
/// until the work actually ends.
async fn blocking(f: impl FnOnce() -> View + Send + 'static) -> View {
let Ok(_permit) = RENDERS.acquire().await else { return View::Missing };
tokio::task::spawn_blocking(f).await.unwrap_or_else(|error| {
let Ok(permit) = Arc::clone(&RENDERS).acquire_owned().await else { return View::Missing };
let work = move || {
let _permit = permit;
f()
};
tokio::task::spawn_blocking(work).await.unwrap_or_else(|error| {
eprintln!("gitv-web: a page failed to render: {error}");
View::Missing
})
@@ -1274,7 +1439,8 @@ mod tests {
#[test]
fn percent_decoding_keeps_raw_bytes() {
assert_eq!(percent_decode("a%2Fb+c"), b"a/b c");
assert_eq!(percent_decode("a%2Fb+c"), b"a/b+c", "a plus is literal outside query strings");
assert_eq!(parse_query(Some("p=a+b%2Bc"))["p"], 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%");
@@ -1299,6 +1465,29 @@ mod tests {
assert_eq!(encode(&[b'a', b' ', 0xff, b'/']), "a%20%FF/");
}
#[test]
fn an_incomplete_fingerprint_is_never_trusted() {
if nix::unistd::geteuid().is_root() {
return; // Root reads anything, so the unreadable folder below can't be made.
}
use std::os::unix::fs::PermissionsExt;
let dir = std::env::temp_dir().join(format!("gitv-web-fingerprint-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
for folder in ["refs/heads/open", "refs/heads/locked/inner"] {
std::fs::create_dir_all(dir.join(folder)).unwrap();
}
let repo = RepoDir::at(&dir).unwrap();
assert!(refs_fingerprint(&repo).is_some());
// A branch folder that can't be read: its refs could change unseen.
std::fs::set_permissions(dir.join("refs/heads/locked"), std::fs::Permissions::from_mode(0o000)).unwrap();
assert_eq!(refs_fingerprint(&repo), None, "a fingerprint missing a folder was trusted");
// Names readable but not searchable: the folder's children can't be inspected.
std::fs::set_permissions(dir.join("refs/heads/locked"), std::fs::Permissions::from_mode(0o444)).unwrap();
assert_eq!(refs_fingerprint(&repo), None, "a fingerprint with an uninspectable folder was trusted");
std::fs::set_permissions(dir.join("refs/heads/locked"), std::fs::Permissions::from_mode(0o755)).unwrap();
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn name_status_parsing() {
let out = b"M\0src/a b.rs\0R100\0old name\0new\tname\0D\0gone\0A\0\xffbin\0";
+220−104
@@ -4,15 +4,22 @@ use std::fs;
use std::io::Write;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::process::{Command, ExitCode, Stdio};
use std::process::{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,
HOST, NAME_RULE, RepoDir, chown_tree, entries, git, git_command, git_in, keys_path, kind_at, open_dir_at,
open_owner, open_root, remove_tree_at, repo_dir, repo_in, repos_root, valid_name,
};
use nix::fcntl::{Flock, FlockArg};
use nix::errno::Errno;
use nix::fcntl::{Flock, FlockArg, RenameFlags, renameat, renameat2};
use nix::sys::stat::{Mode, fchmod, fstat, mkdirat};
use nix::unistd::{Gid, Uid, UnlinkatFlags, fchown, geteuid, unlinkat};
use std::ffi::OsStr;
use std::os::fd::{AsFd, OwnedFd};
use std::os::unix::ffi::OsStrExt;
use std::time::{SystemTime, UNIX_EPOCH};
const HELP: &str = "Commands for your key, run as: ssh git@git.um9i.dev <command>
list list your repositories
@@ -71,94 +78,125 @@ 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. Uses
/// lchown, so a symlink is changed itself and never followed out of the tree.
fn chown_git(path: &Path) -> Result<(), String> {
/// The `git` account's ids, when running as root and new files must be handed to it.
fn git_account() -> Result<Option<(Uid, Gid)>, String> {
if !is_root() {
return Ok(());
return Ok(None);
}
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())
Ok(Some((user.uid, user.gid)))
}
/// 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);
// 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())),
/// The owner's directory, created if needed and returned open. Anything else at that name,
/// including a symlink to a directory, is refused rather than followed.
fn owner_directory(owner: &str) -> Result<OwnedFd, String> {
let root = open_root().ok_or("cannot open the repository root")?;
let display = repos_root().join(owner);
// Another push may create it at the same moment; either way, open what's there after.
match mkdirat(&root, owner, Mode::from_bits_truncate(0o755)) {
Ok(()) | Err(Errno::EEXIST) => {}
Err(e) => return Err(format!("cannot create {}: {e}", display.display())),
}
if !is_real_dir(&directory) {
return Err(format!("{} is not a directory", directory.display()));
let directory =
open_dir_at(&root, OsStr::new(owner)).map_err(|_| format!("{} is not a directory", display.display()))?;
if let Some((uid, gid)) = git_account()? {
fchown(&directory, Some(uid), Some(gid)).map_err(|e| e.to_string())?;
}
chown_git(&directory)?;
Ok(directory)
}
/// Create `<owner>/<name>.git`.
///
/// The repository is built inside a private staging directory (mode 0700, made fresh under the
/// open owner directory), so no other user can rename, replace or remove anything inside it.
/// Initialisation, permissions and ownership all go through handles, and publication renames
/// out of the staging directory's own handle into the owner directory's, refusing to replace
/// anything at the name. What gets published is therefore exactly what git initialised.
fn create(owner: &str, name: &str, quiet: bool) -> Result<(), String> {
let directory = owner_directory(owner)?;
let repo = directory.join(format!("{name}.git"));
if exists_at(&repo) {
let target = format!("{name}.git");
if kind_at(&directory, OsStr::new(&target)).is_some() {
return Err("repository already exists".into());
}
// Build in a hidden staging name, then rename, so a half-made repository never serves.
let staging = directory.join(format!(".create-{}-{name}", std::process::id()));
// A clean environment, so no caller's init.templateDir can plant hooks in the repository.
let status = git_base()
.args(["init", "--quiet", "--bare", "--initial-branch=main"])
.arg(&staging)
.status()
.map_err(|e| e.to_string())?;
if !status.success() {
let _ = fs::remove_dir_all(&staging);
return Err("git init failed".into());
}
fs::set_permissions(&staging, fs::Permissions::from_mode(0o750)).map_err(|e| e.to_string())?;
if is_root() {
for entry in walk(&staging) {
chown_git(&entry)?;
let nanos = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.subsec_nanos());
let staging_name = format!(".create-{}-{nanos}-{name}", std::process::id());
mkdirat(&directory, staging_name.as_str(), Mode::S_IRWXU).map_err(|e| e.to_string())?;
let built = open_dir_at(&directory, OsStr::new(&staging_name)).map_err(|e| e.to_string()).and_then(|staging| {
// The directory just made must be ours and private; anything else at the name means
// someone got there first, so give up rather than build in it.
let stat = fstat(staging.as_fd()).map_err(|e| e.to_string())?;
if stat.st_uid != geteuid().as_raw() || stat.st_mode & 0o077 != 0 {
return Err("staging directory isn't private".to_string());
}
build_and_publish(&directory, &staging, &target)
});
// The staging directory is empty now, whether the repository was published or rolled
// back. Removing it by name only ever removes an empty directory.
let leftover = unlinkat(&directory, staging_name.as_str(), UnlinkatFlags::RemoveDir).err().map(|e| {
format!("couldn't remove the staging directory {}: {e}", repos_root().join(owner).join(&staging_name).display())
});
match built {
Ok(()) => {
// Created: say so, and mention any leftover separately; retrying would only find
// the repository already there.
if let Some(leftover) = leftover {
eprintln!("gitv: created {owner}/{name}.git, but {leftover}");
}
if !quiet {
println!("git@{HOST}:{owner}/{name}.git");
}
Ok(())
}
Err(error) => Err(match leftover {
Some(leftover) => format!("{error}; also {leftover}"),
None => error,
}),
}
if exists_at(&repo) {
let _ = fs::remove_dir_all(&staging);
return Err("repository already exists".into());
}
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 is_real_dir(&path) {
found.extend(walk(&path));
} else {
found.push(path);
}
/// Build a bare repository at `repo` inside the private `staging` directory, then move it to
/// `target` in `directory`. If anything fails after `repo` was made, it is removed again; it
/// never removes a `repo` this call didn't make.
fn build_and_publish(directory: &OwnedFd, staging: &OwnedFd, target: &str) -> Result<(), String> {
// Only once this succeeds is `repo` ours to roll back.
mkdirat(staging, "repo", Mode::from_bits_truncate(0o750)).map_err(|e| e.to_string())?;
let built = (|| {
let repo = open_dir_at(staging, OsStr::new("repo")).map_err(|e| e.to_string())?;
// A clean environment, so no caller's init.templateDir can plant hooks in it.
let status = git_in(&repo)
.args(["init", "--quiet", "--bare", "--initial-branch=main", "."])
.stdout(Stdio::null())
.status()
.map_err(|e| e.to_string())?;
if !status.success() {
return Err("git init failed".to_string());
}
fchmod(&repo, Mode::from_bits_truncate(0o750)).map_err(|e| e.to_string())?;
if let Some((uid, gid)) = git_account()? {
chown_tree(&repo, uid, gid).map_err(|e| e.to_string())?;
}
renameat2(staging, "repo", directory, target, RenameFlags::RENAME_NOREPLACE)
.map_err(|e| if e == Errno::EEXIST { "repository already exists".to_string() } else { e.to_string() })
})();
if let Err(error) = built {
return Err(match remove_tree_at(staging, OsStr::new("repo")) {
Ok(()) => error,
Err(e) => format!("{error}; also couldn't remove the half-built repository: {e}"),
});
}
found
Ok(())
}
/// Delete `<owner>/<name>.git`. One handle on the owner directory serves the check, the rename
/// and the removal, which works through handles all the way down and never follows a symlink.
fn delete(owner: &str, name: &str) -> Result<(), String> {
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())?;
fs::remove_dir_all(&staging).map_err(|e| e.to_string())?;
let directory = open_owner(owner).ok_or("repository unavailable")?;
repo_in(&directory, owner, name).ok_or("repository unavailable")?;
// A hidden name stops the repository serving at once, before the slow removal. If the
// entry were swapped for a symlink after the check, only the link would be moved and removed.
let staging = format!(".delete-{}-{name}", std::process::id());
renameat(&directory, format!("{name}.git").as_str(), &directory, staging.as_str()).map_err(|e| e.to_string())?;
remove_tree_at(&directory, OsStr::new(&staging)).map_err(|e| e.to_string())?;
println!("deleted {owner}/{name}.git");
Ok(())
}
@@ -208,10 +246,40 @@ fn add_key(owner: &str, file: &Path) -> Result<(), String> {
/// The decoded Ed25519 key in an authorized_keys line, wherever it sits: after options, and
/// before any comment.
///
/// A line is `[options] type key [comment]`. Blank and `#` lines are skipped, options are
/// skipped as one field (they can hold quoted spaces), and only the key field itself is read,
/// so a key mentioned in a comment or a commented-out line doesn't count.
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()
const TYPES: [&str; 4] = ["ssh-ed25519", "ssh-rsa", "ecdsa-sha2-nistp256", "sk-ssh-ed25519@openssh.com"];
let line = line.trim_start();
if line.is_empty() || line.starts_with('#') {
return None;
}
// Fields are separated by spaces or tabs. The first is the key type, or else the options.
let first = line.split([' ', '\t']).next()?;
let rest = if TYPES.contains(&first) { line } else { skip_options(line)? };
let mut fields = rest.split([' ', '\t']).filter(|f| !f.is_empty());
if !TYPES.contains(&fields.next()?) {
return None;
}
base64::engine::general_purpose::STANDARD.decode(fields.next()?).ok()
}
/// What follows the options field: its end is the first whitespace outside double quotes.
fn skip_options(line: &str) -> Option<&str> {
let mut quoted = false;
let mut escaped = false;
for (i, c) in line.char_indices() {
match c {
_ if escaped => escaped = false,
'\\' => escaped = true,
'"' => quoted = !quoted,
c if c.is_whitespace() && !quoted => return Some(line[i..].trim_start()),
_ => {}
}
}
None
}
/// Handle one SSH request from a key registered to owner.
@@ -222,13 +290,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> = 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| repo_dir(owner, n).is_some())
// Listed and checked through one handle on the owner's directory.
let directory = open_owner(owner);
let mut names: Vec<String> = directory
.iter()
.flat_map(entries)
.filter_map(|e| e.to_str()?.strip_suffix(".git").map(str::to_string))
.filter(|n| directory.as_ref().is_some_and(|d| repo_in(d, owner, n).is_some()))
.collect();
names.sort();
for name in names {
@@ -262,26 +330,25 @@ fn serve_git(owner: &str, program: &str, path: &str) -> Result<u8, String> {
if requested != owner {
return Err("repository unavailable".into());
}
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. 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),
let repo = match repo_dir(owner, name) {
Some(repo) => repo,
None if program != "git-receive-pack" => return Err("repository unavailable".into()),
None => {
// Pushing to a new name creates it, so a fresh project needs no setup step. create()
// never replaces anything at the name, so a symlink or file there is refused. If a
// racing push created the repository first, at any moment, this one opens it afresh;
// either way what it gets must be a real repository.
match create(owner, name, true) {
Ok(()) => eprintln!("gitv: created {owner}/{name}.git"),
Err(_) if repo_dir(owner, name).is_some() => {}
Err(_) => return Err("repository unavailable".into()),
}
repo_dir(owner, name).ok_or("repository unavailable")?
}
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");
// Run inside the opened directory, so the path can't be swapped for a symlink meanwhile.
let mut command = repo.command(program);
command.arg(".").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
// faster protocol v2.
if let Ok(protocol) = std::env::var("GIT_PROTOCOL")
@@ -297,21 +364,27 @@ fn serve_git(owner: &str, program: &str, path: &str) -> Result<u8, String> {
Ok(status.code().unwrap_or(1) as u8)
}
/// Point HEAD at a pushed branch when its current target does not exist.
fn fix_head(repo: &Path) -> Result<(), String> {
/// Point HEAD at a pushed branch when its current target does not exist. Branch names are
/// bytes (one per line; a ref can't contain a newline), so names with spaces, non-breaking
/// spaces or non-UTF-8 bytes are passed to git exactly as they are.
fn fix_head(repo: &RepoDir) -> Result<(), String> {
if git(repo, &["rev-parse", "--verify", "--quiet", "HEAD"]).is_ok() {
return Ok(());
}
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 heads: Vec<&[u8]> = out.split(|b| *b == b'\n').filter(|h| !h.is_empty()).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 status = git_command(repo).args(["symbolic-ref", "HEAD", choice]).status().map_err(|e| e.to_string())?;
let preferred: [&[u8]; 2] = [b"refs/heads/main", b"refs/heads/master"];
let choice = preferred.into_iter().find(|r| heads.contains(r)).unwrap_or(first);
let status = git_command(repo)
.args([OsStr::new("symbolic-ref"), OsStr::new("HEAD"), OsStr::from_bytes(choice)])
.status()
.map_err(|e| e.to_string())?;
if !status.success() {
return Err("could not set the default branch".into());
}
eprintln!("gitv: default branch is now {}", choice.trim_start_matches("refs/heads/"));
let name = String::from_utf8_lossy(&choice[b"refs/heads/".len()..]).into_owned();
eprintln!("gitv: default branch is now {name}");
Ok(())
}
@@ -347,3 +420,46 @@ fn main() -> ExitCode {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use nix::fcntl::{OFlag, open};
fn open_path(path: &Path) -> OwnedFd {
open(path, OFlag::O_DIRECTORY | OFlag::O_CLOEXEC, Mode::empty()).unwrap()
}
#[test]
fn a_failed_build_never_removes_what_it_did_not_make() {
let dir = std::env::temp_dir().join(format!("gitv-build-{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
// A staging directory that already holds someone's `repo`, as it would if the staging
// name had been swapped for another private directory before it was opened.
fs::create_dir_all(dir.join("owner/.staging/repo")).unwrap();
fs::write(dir.join("owner/.staging/repo/sentinel"), "precious").unwrap();
let owner = open_path(&dir.join("owner"));
let staging = open_path(&dir.join("owner/.staging"));
let result = build_and_publish(&owner, &staging, "new.git");
assert!(result.is_err(), "building over an existing repo succeeded");
assert_eq!(fs::read_to_string(dir.join("owner/.staging/repo/sentinel")).unwrap(), "precious");
assert!(!dir.join("owner/new.git").exists(), "nothing was published");
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn a_failed_build_cleans_up_what_it_made() {
let dir = std::env::temp_dir().join(format!("gitv-build-clean-{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(dir.join("owner/.staging")).unwrap();
// The target is taken, so publication fails after the repository was built.
fs::create_dir_all(dir.join("owner/new.git")).unwrap();
let owner = open_path(&dir.join("owner"));
let staging = open_path(&dir.join("owner/.staging"));
let error = build_and_publish(&owner, &staging, "new.git").unwrap_err();
assert!(error.contains("already exists"), "{error}");
assert!(fs::read_dir(dir.join("owner/.staging")).unwrap().next().is_none(), "the half-built repo is gone");
assert!(fs::read_dir(dir.join("owner/new.git")).unwrap().next().is_none(), "the target is untouched");
let _ = fs::remove_dir_all(&dir);
}
}
+301−35
@@ -2,9 +2,11 @@
pub mod render;
use std::ffi::OsStr;
use std::fs;
use std::ffi::{OsStr, OsString};
use std::io::Read;
use std::os::fd::{AsFd, AsRawFd, BorrowedFd, OwnedFd};
use std::os::unix::ffi::OsStrExt;
use std::os::unix::process::CommandExt;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::sync::mpsc::{self, RecvTimeoutError};
@@ -12,6 +14,11 @@ use std::sync::{Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant};
use nix::dir::Dir;
use nix::fcntl::{AtFlags, OFlag, open, openat};
use nix::sys::stat::{Mode, SFlag, fstatat};
use nix::unistd::{Gid, Uid, UnlinkatFlags, fchown, fchownat, unlinkat};
pub const HOST: &str = "git.um9i.dev";
/// Where bare repositories live: `<root>/<owner>/<name>.git`. `GITV_REPOS` overrides it for local runs.
@@ -49,6 +56,11 @@ pub const GIT_OUTPUT_LIMIT: usize = 64 << 20;
/// aliases, pagers) leaks in, and with pathspecs taken literally rather than as globs or magic.
pub fn git_base() -> Command {
let mut command = Command::new("git");
configure(&mut command);
command
}
fn configure(command: &mut Command) {
command
.env_clear()
.env("PATH", "/usr/bin:/bin")
@@ -58,19 +70,73 @@ pub fn git_base() -> Command {
.env("GIT_LITERAL_PATHSPECS", "1")
.env("LC_ALL", "C.UTF-8")
.stdin(Stdio::null());
}
/// An open repository directory. Holding the directory itself, not its path, means a symlink
/// swapped in after the checks can't redirect anything: git runs inside this exact directory.
pub struct RepoDir {
/// Where it was found, for messages and cache keys only; never reopened.
pub path: PathBuf,
fd: OwnedFd,
}
impl RepoDir {
/// Open `path` as a repository directory. For tests and tools with a trusted path; serving
/// code finds repositories through [`repo_dir`] or [`repo_in`].
pub fn at(path: &Path) -> Option<RepoDir> {
let fd = open(path, OFlag::O_DIRECTORY | OFlag::O_CLOEXEC | OFlag::O_NOFOLLOW, Mode::empty()).ok()?;
Some(RepoDir { path: path.to_path_buf(), fd })
}
/// A command that starts inside this directory, whatever happens to its path meanwhile.
pub fn command(&self, program: &str) -> Command {
command_in(&self.fd, program)
}
/// The open directory, for reading it by handle.
pub fn handle(&self) -> BorrowedFd<'_> {
self.fd.as_fd()
}
}
/// A command that starts inside the open directory `dir`. The command owns its own duplicate
/// of the descriptor, so it stays valid however long the command outlives the caller's handle.
pub fn command_in(dir: &OwnedFd, program: &str) -> Command {
let mut command = Command::new(program);
// Everything that can fail or allocate happens here, in the parent. The child, between
// fork and exec in a multithreaded process, only calls fchdir and builds errors from raw
// error numbers, neither of which allocates.
let fd = dir.try_clone().map_err(|e| e.raw_os_error().unwrap_or(nix::libc::EBADF));
// SAFETY: fchdir is async-signal-safe, and from_raw_os_error doesn't allocate.
unsafe {
command.pre_exec(move || match &fd {
Ok(fd) if nix::libc::fchdir(fd.as_raw_fd()) == 0 => Ok(()),
Ok(_) => Err(std::io::Error::last_os_error()),
Err(code) => Err(std::io::Error::from_raw_os_error(*code)),
});
}
command
}
/// [`git_base`] run inside an open directory, without pointing it at a repository: for `git
/// init` in a directory being built.
pub fn git_in(dir: &OwnedFd) -> Command {
let mut command = command_in(dir, "git");
configure(&mut command);
command
}
/// [`git_base`] pointed at a bare repository.
pub fn git_command(git_dir: &Path) -> Command {
let mut command = git_base();
command.args(["-c", "safe.directory=*", "-c", "core.quotePath=false", "--git-dir"]).arg(git_dir);
/// [`git_base`] run inside an open repository.
pub fn git_command(dir: &RepoDir) -> Command {
let mut command = dir.command("git");
configure(&mut command);
command.args(["-c", "safe.directory=*", "-c", "core.quotePath=false", "--git-dir=."]);
command
}
/// Run a read-only git command and return its stdout. The command is killed if it runs longer
/// 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> {
pub fn git<S: AsRef<OsStr>>(git_dir: &RepoDir, 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()),
@@ -79,7 +145,7 @@ pub fn git<S: AsRef<OsStr>>(git_dir: &Path, args: &[S]) -> Result<Vec<u8>, Strin
/// 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> {
pub fn git_capped<S: AsRef<OsStr>>(git_dir: &RepoDir, args: &[S], cap: usize) -> Result<(Vec<u8>, bool), String> {
let mut child = git_command(git_dir)
.args(args)
.stdout(Stdio::piped())
@@ -137,40 +203,156 @@ pub fn git_capped<S: AsRef<OsStr>>(git_dir: &Path, args: &[S], cap: usize) -> Re
}
}
/// 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())
/// Decode `%XX` escapes to raw bytes, as in a URL path or a Markdown link destination. `+`
/// stays a plus (only query strings use it for a space). A malformed escape is kept as written.
pub 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'%' 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
}
// ---------------------------------------------------------------------------------------------
// Working through directory handles
//
// Everything that creates, removes or changes repositories, or decides which ones exist, works
// through open directory handles and never follows a symlink, so a path swapped after a check
// can't redirect it.
const DIR_FLAGS: OFlag = OFlag::O_DIRECTORY.union(OFlag::O_CLOEXEC).union(OFlag::O_NOFOLLOW);
/// The repository root. Its own path is trusted configuration, so it is opened normally.
pub fn open_root() -> Option<OwnedFd> {
open(&repos_root(), OFlag::O_DIRECTORY | OFlag::O_CLOEXEC, Mode::empty()).ok()
}
/// The directory `name` inside `dir`; refused if it is a symlink or not a directory.
pub fn open_dir_at(dir: &impl AsFd, name: &OsStr) -> nix::Result<OwnedFd> {
openat(dir, name, DIR_FLAGS, Mode::empty())
}
/// True when anything, even a dangling symlink, exists at `path`.
pub fn exists_at(path: &Path) -> bool {
fs::symlink_metadata(path).is_ok()
/// What kind of entry `name` is inside `dir`, without following a symlink; `None` if absent
/// or if it can't be inspected. For display and quick checks; anything that must not skip an
/// entry silently uses [`try_kind_at`].
pub fn kind_at(dir: &impl AsFd, name: &OsStr) -> Option<SFlag> {
try_kind_at(dir, name).ok().flatten()
}
/// 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)
/// What kind of entry `name` is inside `dir`: `Ok(None)` only when it's absent, and the error
/// when it exists but can't be inspected (no search permission, I/O error, ...).
pub fn try_kind_at(dir: &impl AsFd, name: &OsStr) -> nix::Result<Option<SFlag>> {
match fstatat(dir, name, AtFlags::AT_SYMLINK_NOFOLLOW) {
Ok(stat) => Ok(Some(SFlag::from_bits_truncate(stat.st_mode) & SFlag::S_IFMT)),
Err(nix::errno::Errno::ENOENT) => Ok(None),
Err(e) => Err(e),
}
}
/// The names in an open directory, without `.` and `..`. Reads through a fresh open of the
/// same directory, so the caller's handle keeps its own position.
///
/// For display only: a directory that can't be read lists as empty. Anything that changes the
/// tree uses [`try_entries`], which reports the failure instead.
pub fn entries(dir: &impl AsFd) -> Vec<OsString> {
try_entries(dir).unwrap_or_default()
}
/// 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)
/// The names in an open directory, or the error that stopped the listing part way.
pub fn try_entries(dir: &impl AsFd) -> nix::Result<Vec<OsString>> {
let fresh = openat(dir, ".", OFlag::O_DIRECTORY | OFlag::O_CLOEXEC, Mode::empty())?;
let mut listing = Dir::from_fd(fresh)?;
let mut names = Vec::new();
for entry in listing.iter() {
let name = OsStr::from_bytes(entry?.file_name().to_bytes()).to_os_string();
if name != "." && name != ".." {
names.push(name);
}
}
Ok(names)
}
/// Remove `name` from `dir` and, if it is a directory, everything inside it, working through
/// handles all the way down. A symlink is removed itself, never followed.
pub fn remove_tree_at(dir: &impl AsFd, name: &OsStr) -> nix::Result<()> {
if try_kind_at(dir, name)? == Some(SFlag::S_IFDIR) {
let inner = open_dir_at(dir, name)?;
for entry in try_entries(&inner)? {
remove_tree_at(&inner, &entry)?;
}
unlinkat(dir, name, UnlinkatFlags::RemoveDir)
} else {
unlinkat(dir, name, UnlinkatFlags::NoRemoveDir)
}
}
/// Give the open directory `dir` and everything under it to `uid` and `gid`, working through
/// handles and changing symlinks themselves rather than what they point at. Any entry it can't
/// read or change is an error, never a silent skip.
pub fn chown_tree(dir: &OwnedFd, uid: Uid, gid: Gid) -> nix::Result<()> {
fchown(dir, Some(uid), Some(gid))?;
for entry in try_entries(dir)? {
if try_kind_at(dir, &entry)? == Some(SFlag::S_IFDIR) {
chown_tree(&open_dir_at(dir, &entry)?, uid, gid)?;
} else {
fchownat(dir, entry.as_os_str(), Some(uid), Some(gid), AtFlags::AT_SYMLINK_NOFOLLOW)?;
}
}
Ok(())
}
/// The owner's directory, opened with symlinks refused.
pub fn open_owner(owner: &str) -> Option<OwnedFd> {
if !valid_name(owner) {
return None;
}
open_dir_at(&open_root()?, OsStr::new(owner)).ok()
}
/// An existing repository, `<owner>/<name>.git`, opened through the owner's open directory:
/// a real directory (not a symlink) holding a real `HEAD` file. Everything after this works
/// through the open directory, so there is no window between checking and using it.
pub fn repo_in(owner_dir: &impl AsFd, owner: &str, name: &str) -> Option<RepoDir> {
if !(valid_name(owner) && valid_name(name)) {
return None;
}
let file = format!("{name}.git");
let fd = open_dir_at(owner_dir, OsStr::new(&file)).ok()?;
if kind_at(&fd, OsStr::new("HEAD")) != Some(SFlag::S_IFREG) {
return None;
}
Some(RepoDir { path: repos_root().join(owner).join(file), fd })
}
/// [`repo_in`], opening the owner's directory first.
pub fn repo_dir(owner: &str, name: &str) -> Option<RepoDir> {
repo_in(&open_owner(owner)?, owner, name)
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
/// A bare repository holding one blob of `size` bytes, and the blob's id.
fn repo_with_blob(name: &str, size: usize) -> (PathBuf, String) {
fn repo_with_blob(name: &str, size: usize) -> (RepoDir, 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 dir = RepoDir::at(&dir).unwrap();
let mut child = git_command(&dir)
.args(["hash-object", "-w", "--stdin"])
.stdin(Stdio::piped())
@@ -192,19 +374,103 @@ mod tests {
assert!(!overflow);
assert_eq!(out.len(), 1 << 20);
assert!(git(&dir, &["cat-file", "blob", "0000000000000000000000000000000000000000"]).is_err());
let _ = fs::remove_dir_all(&dir);
let _ = fs::remove_dir_all(&dir.path);
}
#[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();
fn an_open_repository_stays_bound_to_its_directory() {
// Open one repository, then swap another into its path: git must still see the first.
let (dir, oid) = repo_with_blob("bound", 10);
let (other, _) = repo_with_blob("bound-other", 20);
let moved = dir.path.with_extension("moved");
fs::rename(&dir.path, &moved).unwrap();
std::os::unix::fs::symlink(&other.path, &dir.path).unwrap();
assert_eq!(git(&dir, &["cat-file", "-s", &oid]).unwrap(), b"10\n");
let _ = fs::remove_file(&dir.path);
let _ = fs::remove_dir_all(&moved);
let _ = fs::remove_dir_all(&other.path);
}
/// A scratch directory for one test.
fn scratch(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("gitv-lib-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
fn open_path(path: &Path) -> OwnedFd {
open(path, OFlag::O_DIRECTORY | OFlag::O_CLOEXEC, Mode::empty()).unwrap()
}
#[test]
fn handles_see_symlinks_as_symlinks() {
let dir = scratch("kinds");
std::fs::create_dir(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);
let fd = open_path(&dir);
assert_eq!(kind_at(&fd, OsStr::new("real")), Some(SFlag::S_IFDIR));
assert_eq!(kind_at(&fd, OsStr::new("link")), Some(SFlag::S_IFLNK));
assert_eq!(kind_at(&fd, OsStr::new("dangling")), Some(SFlag::S_IFLNK));
assert_eq!(kind_at(&fd, OsStr::new("absent")), None);
assert!(open_dir_at(&fd, OsStr::new("link")).is_err(), "a symlinked directory isn't opened");
let mut names = entries(&fd);
names.sort();
assert_eq!(names, ["dangling", "link", "real"]);
assert_eq!(entries(&fd).len(), 3, "listing twice gives the same answer");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn removing_a_tree_never_follows_symlinks() {
let dir = scratch("remove");
let outside = dir.join("outside");
std::fs::create_dir(&outside).unwrap();
std::fs::write(outside.join("keep.txt"), "keep").unwrap();
std::fs::create_dir_all(dir.join("doomed/a/b")).unwrap();
std::fs::write(dir.join("doomed/a/b/file"), "x").unwrap();
std::os::unix::fs::symlink(&outside, dir.join("doomed/a/escape")).unwrap();
std::os::unix::fs::symlink(outside.join("keep.txt"), dir.join("doomed/link-to-file")).unwrap();
remove_tree_at(&open_path(&dir), OsStr::new("doomed")).unwrap();
assert!(!dir.join("doomed").exists());
assert_eq!(std::fs::read_to_string(outside.join("keep.txt")).unwrap(), "keep", "outside is untouched");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn walks_that_change_the_tree_fail_loudly() {
if nix::unistd::geteuid().is_root() {
return; // Root reads anything, so the unreadable directory below can't be made.
}
use std::os::unix::fs::PermissionsExt;
let dir = scratch("loud");
std::fs::create_dir(dir.join("sub")).unwrap();
std::fs::write(dir.join("sub/file"), "x").unwrap();
let sub = open_path(&dir.join("sub"));
// Opened, then made unreadable: listing it now fails.
std::fs::set_permissions(dir.join("sub"), std::fs::Permissions::from_mode(0o300)).unwrap();
let (uid, gid) = (nix::unistd::getuid(), nix::unistd::getgid());
assert!(try_entries(&sub).is_err());
assert!(chown_tree(&sub, uid, gid).is_err(), "an incomplete ownership walk reported success");
assert!(remove_tree_at(&open_path(&dir), OsStr::new("sub")).is_err());
assert!(entries(&sub).is_empty(), "display listings stay forgiving");
std::fs::set_permissions(dir.join("sub"), std::fs::Permissions::from_mode(0o755)).unwrap();
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_command_keeps_its_directory_after_the_handle_is_dropped() {
let dir = scratch("command");
let mut command = {
let repo = RepoDir::at(&dir).unwrap();
repo.command("pwd")
};
// Use up low descriptor numbers so a recycled number would point elsewhere.
let _noise: Vec<OwnedFd> = (0..8).map(|_| open_path(&std::env::temp_dir())).collect();
let out = command.output().unwrap();
assert!(out.status.success());
assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), dir.to_string_lossy());
let _ = std::fs::remove_dir_all(&dir);
}
}
@@ -69,14 +69,16 @@ pub fn is_markdown(path: &str) -> bool {
pub enum Target {
/// Kept as written: web, mail and in-page links.
External(String),
/// A repository path, already normalised against the Markdown file's directory.
Repo(String),
/// A repository path as bytes, decoded once and normalised against the file's directory.
Repo(Vec<u8>),
/// Anything else (other schemes, paths escaping the repository): dropped.
Blocked,
}
/// Resolve a link written in a Markdown file that lives in `dir`.
pub fn resolve_link(dir: &str, target: &str) -> Target {
/// Resolve a link written in a Markdown file that lives in `dir` (bytes, as git stores it).
/// Each path segment is percent-decoded once, so `My%20File.md` names `My File.md`; a segment
/// that decodes to something no file name can hold (a `/` or NUL) is dropped.
pub fn resolve_link(dir: &[u8], target: &str) -> Target {
let lower = target.to_ascii_lowercase();
if lower.starts_with("http://")
|| lower.starts_with("https://")
@@ -90,25 +92,30 @@ 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() };
for part in path.split('/') {
match part {
"" | "." => {}
".." => {
let mut parts: Vec<Vec<u8>> = if path.starts_with('/') {
Vec::new()
} else {
dir.split(|b| *b == b'/').filter(|p| !p.is_empty()).map(<[u8]>::to_vec).collect()
};
for raw in path.split('/') {
let part = crate::percent_decode(raw);
match part.as_slice() {
b"" | b"." => {}
b".." => {
if parts.pop().is_none() {
return Target::Blocked;
}
}
part => parts.push(part),
part if part.contains(&b'/') || part.contains(&0) => return Target::Blocked,
_ => parts.push(part),
}
}
Target::Repo(parts.join("/"))
Target::Repo(parts.join(&b'/'))
}
/// Render Markdown to HTML. Raw HTML in the source is escaped, fenced code is highlighted, and
/// `link(path, is_image)` turns repository paths into URLs.
pub fn markdown(source: &str, dir: &str, link: &dyn Fn(&str, bool) -> String) -> String {
pub fn markdown(source: &str, dir: &[u8], link: &dyn Fn(&[u8], 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 =
@@ -165,27 +172,27 @@ pub fn markdown(source: &str, dir: &str, link: &dyn Fn(&str, bool) -> String) ->
mod tests {
use super::*;
fn link(path: &str, image: bool) -> String {
format!("/{}?path={path}", if image { "raw" } else { "blob" })
fn link(path: &[u8], image: bool) -> String {
format!("/{}?path={}", if image { "raw" } else { "blob" }, String::from_utf8_lossy(path))
}
#[test]
fn escapes_raw_html() {
let html = markdown("hi <script>alert(1)</script>\n\n<div onclick=x>", "", &link);
let html = markdown("hi <script>alert(1)</script>\n\n<div onclick=x>", b"", &link);
assert!(!html.contains("<script"), "{html}");
assert!(!html.contains("<div"), "{html}");
}
#[test]
fn ignores_heading_attributes() {
let html = markdown("# Title {onclick=alert(1) #main .skip style=x}", "", &link);
let html = markdown("# Title {onclick=alert(1) #main .skip style=x}", b"", &link);
// The braces stay as heading text instead of becoming attributes.
assert_eq!(html.trim(), "<h1>Title {onclick=alert(1) #main .skip style=x}</h1>");
}
#[test]
fn blocks_dangerous_links() {
let html = markdown("[x](javascript:alert(1)) [y](../../etc/passwd)", "docs", &link);
let html = markdown("[x](javascript:alert(1)) [y](../../etc/passwd)", b"docs", &link);
assert!(!html.contains("javascript:"), "{html}");
assert!(!html.contains("passwd"), "{html}");
}
@@ -193,16 +200,31 @@ 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);
markdown("[a](guide.md#top) [b](/src/lib.rs) ![c](../img/logo.png) [d](https://x.dev)", b"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}");
assert!(html.contains("href=\"https://x.dev\""), "{html}");
}
#[test]
fn link_destinations_are_decoded_once() {
let repo = |dir: &[u8], target: &str| match resolve_link(dir, target) {
Target::Repo(path) => Some(path),
_ => None,
};
assert_eq!(repo(b"docs", "My%20File.md"), Some(b"docs/My File.md".to_vec()));
assert_eq!(repo(b"docs", "a+b.md"), Some(b"docs/a+b.md".to_vec()), "a plus is a plus");
assert_eq!(repo(b"docs", "100%25.md"), Some(b"docs/100%.md".to_vec()));
assert_eq!(repo(b"caf\xe9", "x.md"), Some(b"caf\xe9/x.md".to_vec()), "the folder keeps its bytes");
assert_eq!(repo(b"a/b", "%2E%2E/c"), Some(b"a/c".to_vec()), "an encoded .. is still ..");
assert_eq!(repo(b"", "a%2Fb"), None, "no file name contains a slash");
assert_eq!(repo(b"", "a%00b"), None);
}
#[test]
fn highlights_fenced_code_and_files() {
let html = markdown("```rust\nfn main() {}\n```", "", &link);
let html = markdown("```rust\nfn main() {}\n```", b"", &link);
assert!(html.contains("<pre class=\"code\">") && html.contains("hl-"), "{html}");
assert!(highlight("x.py", "def f(): pass\n").contains("hl-"));
assert!(highlight("run", "#!/bin/sh\necho hi\n").contains("hl-"));
@@ -126,7 +126,27 @@ pub struct Server {
impl Server {
pub fn start(repos: &Path) -> Server {
let mut child = Command::new(GITV_WEB)
Server::start_with(repos, None)
}
/// Start with at most `limit` open file descriptors.
pub fn start_limited(repos: &Path, limit: u64) -> Server {
Server::start_with(repos, Some(limit))
}
fn start_with(repos: &Path, limit: Option<u64>) -> Server {
let mut command = Command::new(GITV_WEB);
if let Some(limit) = limit {
use std::os::unix::process::CommandExt;
// SAFETY: setrlimit is async-signal-safe and the closure does nothing else.
unsafe {
command.pre_exec(move || {
nix::sys::resource::setrlimit(nix::sys::resource::Resource::RLIMIT_NOFILE, limit, limit)
.map_err(std::io::Error::from)
});
}
}
let mut child = command
.args(["serve", "--port", "0"])
.env("GITV_REPOS", repos)
.stdout(Stdio::piped())
+115−0
@@ -317,3 +317,118 @@ fn the_readme_fake_ssh_script_works() {
assert!(out.status.success(), "{}", stderr(&out));
assert!(host.repo("um9i", "demo").join("HEAD").is_file());
}
#[test]
fn default_branch_repair_keeps_branch_names_exact() {
use std::os::unix::ffi::OsStrExt;
// Names that whitespace splitting or UTF-8 conversion would mangle.
let names: [&[u8]; 2] = ["trunk\u{a0}line".as_bytes(), b"caf\xe9"];
for (n, name) in names.iter().enumerate() {
let host = Host::new(&format!("ssh-head-bytes-{n}"));
let dir = work(&format!("ssh-head-bytes-{n}-work"), "main");
let target = [b"main:refs/heads/".as_slice(), name].concat();
let out = common::git_cmd(&dir)
.env("GIT_SSH_COMMAND", host.ssh_script())
.args([std::ffi::OsStr::new("push"), "-q".as_ref(), "ada@x:ada/odd.git".as_ref()])
.arg(std::ffi::OsStr::from_bytes(&target))
.output()
.unwrap();
assert!(out.status.success(), "{}", stderr(&out));
let head = common::git_cmd(&host.repo("ada", "odd")).args(["symbolic-ref", "HEAD"]).output().unwrap();
assert_eq!(
head.stdout,
[b"refs/heads/".as_slice(), name, b"\n"].concat(),
"HEAD names the pushed branch exactly"
);
let clone = scratch(&format!("ssh-head-bytes-{n}-clone"));
let out = host.git(&clone, &["clone", "-q", "ada@x:ada/odd.git", "copy"]);
assert!(out.status.success(), "{}", stderr(&out));
assert!(clone.join("copy/hello.txt").is_file(), "the clone checked out the default branch");
}
}
#[test]
fn commented_keys_do_not_block_registration() {
let host = Host::new("admin-keys-comments");
let key = ed25519_key(8);
let blob = key.split_whitespace().nth(1).unwrap();
// The key is retired (commented out) and also mentioned in another key's comment.
let other = ed25519_key(9);
let other_blob = other.split_whitespace().nth(1).unwrap();
fs::write(
&host.keys,
format!(
"# restrict,command=\"/usr/local/bin/gitv serve ada\" ssh-ed25519 {blob}\n\
# ssh-ed25519 {blob} old laptop\n\
command=\"/usr/local/bin/gitv serve bob\",from=\"10.0.0.1, 10.0.0.2\" ssh-ed25519 {other_blob} replaces ssh-ed25519 {blob}\n"
),
)
.unwrap();
let file = host.dir.join("ada.pub");
fs::write(&file, &key).unwrap();
let out = host.admin(&["add-key", "ada", file.to_str().unwrap()]);
assert!(out.status.success(), "{}", stderr(&out));
// A real duplicate behind quoted options with spaces is still caught.
let again = host.dir.join("bob.pub");
fs::write(&again, &other).unwrap();
let out = host.admin(&["add-key", "carol", again.to_str().unwrap()]);
assert!(!out.status.success());
assert!(stderr(&out).contains("already registered"), "{}", stderr(&out));
}
#[test]
fn tab_separated_keys_are_recognised() {
let host = Host::new("admin-keys-tabs");
let key = ed25519_key(11);
let blob = key.split_whitespace().nth(1).unwrap();
// An active key written with tabs between its fields, with and without options.
fs::write(
&host.keys,
format!("ssh-ed25519\t{blob}\tlaptop\nrestrict\tssh-ed25519\t{}\n", {
let other = ed25519_key(12);
other.split_whitespace().nth(1).unwrap().to_string()
}),
)
.unwrap();
for (seed, owner) in [(11, "bob"), (12, "carol")] {
let file = host.dir.join(format!("{owner}.pub"));
fs::write(&file, ed25519_key(seed)).unwrap();
let out = host.admin(&["add-key", owner, file.to_str().unwrap()]);
assert!(!out.status.success(), "key {seed} was registered a second time");
assert!(stderr(&out).contains("already registered"), "{}", stderr(&out));
}
}
#[test]
fn creation_never_replaces_what_is_at_the_name() {
let host = Host::new("admin-create-noreplace");
// An empty directory (which a plain rename would silently replace) and a symlink.
fs::create_dir_all(host.repo("ada", "empty")).unwrap();
let elsewhere = scratch("admin-create-noreplace-elsewhere");
std::os::unix::fs::symlink(&elsewhere, host.repo("ada", "link")).unwrap();
for name in ["empty", "link"] {
let out = host.admin(&["create", "ada", name]);
assert!(!out.status.success(), "{name} was created over");
assert!(stderr(&out).contains("already exists"), "{name}: {}", stderr(&out));
}
assert!(fs::read_dir(host.repo("ada", "empty")).unwrap().next().is_none(), "the directory is untouched");
assert!(fs::read_dir(&elsewhere).unwrap().next().is_none(), "nothing was written through the symlink");
let names: Vec<_> = fs::read_dir(host.repos.join("ada")).unwrap().flatten().map(|e| e.file_name()).collect();
assert_eq!(names.len(), 2, "no staging directory left behind: {names:?}");
}
#[test]
fn deletion_removes_links_inside_a_repository_without_following_them() {
let host = Host::new("admin-delete-links");
assert!(host.admin(&["create", "ada", "tools"]).status.success());
let outside = scratch("admin-delete-links-outside");
fs::write(outside.join("precious.txt"), "keep").unwrap();
std::os::unix::fs::symlink(&outside, host.repo("ada", "tools").join("escape")).unwrap();
let out = host.admin(&["delete", "ada", "tools", "--yes"]);
assert!(out.status.success(), "{}", stderr(&out));
assert!(!host.repo("ada", "tools").exists());
assert_eq!(fs::read_to_string(outside.join("precious.txt")).unwrap(), "keep");
assert!(fs::read_dir(host.repos.join("ada")).unwrap().next().is_none(), "no staging directory left behind");
}
+201−5
@@ -11,6 +11,9 @@ use std::sync::OnceLock;
use common::{Host, Server, git};
/// A branch named like a full commit id that isn't one.
const HEX_BRANCH: &str = "0123456789abcdef0123456789abcdef01234567";
/// Object ids in the fixture that tests link to.
struct Fixture {
repos: PathBuf,
@@ -38,7 +41,8 @@ fn main() {}
```
";
const GUIDE: &str = "# Guide\n\nBack to [main.rs](../src/main.rs).\n\n| a | b |\n|---|---|\n| 1 | 2 |\n";
const GUIDE: &str =
"# Guide\n\nBack to [main.rs](../src/main.rs). See [spaced](My%20File.md).\n\n| a | b |\n|---|---|\n| 1 | 2 |\n";
/// Build the fixture once per test run:
///
@@ -63,6 +67,7 @@ fn fixture() -> &'static Fixture {
("star*.txt", "a star\n"),
("old.txt", "going away\n"),
("glob*/inside.txt", "a folder whose name is a glob\n"),
("docs/My File.md", "# Spaced\n"),
] {
let file = work.join(path);
fs::create_dir_all(file.parent().unwrap()).unwrap();
@@ -122,13 +127,34 @@ fn fixture() -> &'static Fixture {
git(&work, &["add", "huge.txt"]);
git(&work, &["commit", "-qm", "Add a huge file"]);
let huge = git(&work, &["rev-parse", "HEAD"]);
// A folder whose name isn't UTF-8, with a README linking a neighbour.
let folder = work.join(OsStr::from_bytes(b"dir-caf\xe9"));
fs::create_dir_all(&folder).unwrap();
fs::write(folder.join("README.md"), "[next door](x.md)\n").unwrap();
fs::write(folder.join("x.md"), "# Next door\n").unwrap();
git(&work, &["add", "-A"]);
// The byte git output uses between fields, inside a subject.
git(&work, &["commit", "-qm", "unit\u{1f}separator"]);
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());
// A tag sharing a branch's name, at a different commit than the branch.
git(&work, &["tag", "side", &first]);
// A branch named like the first commit's abbreviated id, pointing somewhere else.
git(&work, &["branch", &first[..10], &tip]);
// Branch names that read like other things: a qualified tag, and a full commit id.
git(&work, &["branch", "refs/tags/side", &tip]);
git(&work, &["branch", HEX_BRANCH, &first]);
let refs = ["main", "refs/heads/side", "long", "odd", "release+docs", "café", "user@topic", "v0.1.0", "light"];
let id_branch = format!("refs/heads/{}", &first[..10]);
let hex_branch = format!("refs/heads/{HEX_BRANCH}");
// The lightweight tag `side` is pushed by commit id: once a branch is literally named
// refs/tags/side, that name is ambiguous on the sending side.
let tag_side = format!("{first}:refs/tags/side");
let extra = [tag_side.as_str(), id_branch.as_str(), "refs/heads/refs/tags/side", hex_branch.as_str()];
let out = host.git(&work, &[&["push", "-q", "ada@x:ada/site.git"][..], &refs, &extra].concat());
assert!(out.status.success(), "{}", common::stderr(&out));
assert!(host.admin(&["create", "ada", "empty"]).status.success());
// The same README in a second repository: its links must stay in that repository.
@@ -306,7 +332,7 @@ fn tree_lists_folders_first_and_renders_the_readme() {
let readme = html.find(">README.md<").unwrap();
assert!(docs < readme, "folders come before files");
assert!(html.contains("Commits<span class=\"n\">5</span>"), "commit count on main, side included");
assert!(html.contains("Tags<span class=\"n\">2</span>"));
assert!(html.contains("Tags<span class=\"n\">3</span>"));
assert!(html.contains("Add a submodule and a big file"), "latest commit in the header");
assert!(html.contains("git@git.um9i.dev:ada/site.git"), "clone address");
@@ -571,3 +597,173 @@ fn writes_are_refused() {
stream.read_to_string(&mut reply).unwrap();
assert!(reply.starts_with("HTTP/1.1 405"), "{reply}");
}
#[test]
fn readme_and_file_views_agree_in_either_order() {
// Each server starts with an empty cache, so each visits in its own order.
let tree_first = server();
let tree = tree_first.get("/ada/site/tree").text();
let file = tree_first.get("/ada/site/blob?path=README.md").text();
let file_first = server();
let file_again = file_first.get("/ada/site/blob?path=README.md").text();
let tree_again = file_first.get("/ada/site/tree").text();
for html in [&file, &file_again] {
assert!(html.contains("<span class=\"quiet\">12 lines, 257 bytes"), "the file view keeps its facts: {html}");
}
for html in [&tree, &tree_again] {
assert!(!html.contains('\u{1f}'), "no internal separator in the README panel");
assert!(html.contains("<b>README.md</b></div></div><article class=\"markdown\">"), "{html}");
}
assert_eq!(tree, tree_again);
assert_eq!(file, file_again);
}
#[test]
fn tag_links_open_the_tag_even_when_a_branch_shares_its_name() {
let s = server();
let tags = s.get("/ada/site/tags").text();
assert!(tags.contains("href=\"/ada/site/tree?ref=refs/tags/side\">Browse files"), "{tags}");
let tag = s.get("/ada/site/tree?ref=refs/tags/side").text();
assert!(tag.contains(">old.txt<"), "the tag is at the first commit");
assert!(tag.contains("<summary><svg class=\"ic\" viewBox=\"0 0 16 16\" aria-hidden=\"true\">"));
let branch = s.get("/ada/site/tree?ref=side").text();
assert!(!branch.contains(">old.txt<"), "a plain name is the branch");
assert!(branch.contains("href=\"/ada/site/tree?ref=refs/tags/side\""), "the menu links the tag by its full name");
// Tag chips in the history do the same.
let log = s.get("/ada/site/log").text();
assert!(log.contains("tree?ref=refs/tags/side\">"), "{log}");
}
#[test]
fn commit_ids_are_looked_up_as_objects() {
let s = server();
let f = fixture();
// A branch is named after the first commit's abbreviated id but points at the tip.
let page = s.get(&format!("/ada/site/commit?id={}", &f.first[..10])).text();
assert!(page.contains("<h2 class=\"ctitle\">First commit</h2>"), "{page}");
let full = s.get(&format!("/ada/site/tree?ref={}", f.first)).text();
assert!(full.contains(">old.txt<"), "a full id is always the commit");
}
#[test]
fn markdown_links_are_decoded_once_and_keep_folder_bytes() {
let s = server();
let guide = s.get("/ada/site/blob?path=docs/guide.md").text();
assert!(guide.contains("href=\"/ada/site/blob?ref=main&amp;path=docs/My%20File.md\""), "{guide}");
assert_eq!(s.get("/ada/site/blob?ref=main&path=docs/My%20File.md").status, 200);
let folder = s.get("/ada/site/tree?ref=odd&path=dir-caf%E9").text();
assert!(folder.contains("href=\"/ada/site/blob?ref=odd&amp;path=dir-caf%E9/x.md\""), "{folder}");
assert_eq!(s.get("/ada/site/blob?ref=odd&path=dir-caf%E9/x.md").status, 200);
}
#[test]
fn subjects_containing_the_separator_byte_are_listed() {
let s = server();
let log = s.get("/ada/site/log?ref=odd").text();
assert!(log.contains("unit\u{1f}separator"), "{log}");
assert!(log.contains("Add a huge file") && log.contains("(no message)"));
}
#[test]
fn the_index_notices_new_pushes() {
let host = Host::new("web-index-fresh");
let work = common::scratch("web-index-fresh-work");
git(&work, &["init", "-q", "-b", "main"]);
git(&work, &["commit", "-q", "--allow-empty", "-m", "Before"]);
assert!(host.git(&work, &["push", "-q", "ada@x:ada/live.git", "main"]).status.success());
let s = Server::start(&host.repos);
assert!(s.get("/").text().contains("Before"));
assert!(s.get("/").text().contains("Before"), "a repeat visit, from the cache");
git(&work, &["commit", "-q", "--allow-empty", "-m", "After"]);
assert!(host.git(&work, &["push", "-q", "ada@x:ada/live.git", "main"]).status.success());
let html = s.get("/").text();
assert!(html.contains("After") && !html.contains("Before"), "{html}");
}
#[test]
fn branches_named_like_other_things_open_themselves() {
let s = server();
let html = s.get("/ada/site/tree").text();
// Each menu link carries the namespace when a plain name could be misread.
for link in [
"href=\"/ada/site/tree?ref=refs/heads/refs/tags/side\"",
&format!("href=\"/ada/site/tree?ref=refs/heads/{HEX_BRANCH}\""),
"href=\"/ada/site/tree?ref=refs/tags/side\"",
] {
assert!(html.contains(link), "missing {link}");
}
// The branch literally named refs/tags/side is at the tip (no old.txt); the tag is at the
// first commit (old.txt). Each link opens its own.
let branch = s.get("/ada/site/tree?ref=refs/heads/refs/tags/side").text();
assert!(!branch.contains(">old.txt<"), "the branch opened something else");
let tag = s.get("/ada/site/tree?ref=refs/tags/side").text();
assert!(tag.contains(">old.txt<"), "the tag link was taken by the branch");
let hex = s.get(&format!("/ada/site/tree?ref=refs/heads/{HEX_BRANCH}"));
assert_eq!(hex.status, 200);
assert!(hex.text().contains(">old.txt<"), "the hex-named branch is at the first commit");
}
#[test]
fn the_index_lists_every_repository_under_a_tight_descriptor_limit() {
let host = Host::new("web-index-many");
let count = 120;
for n in 0..count {
assert!(host.admin(&["create", "ada", &format!("r{n:03}")]).status.success());
}
// Far fewer descriptors than repositories: holding one per row would run out.
let s = Server::start_limited(&host.repos, 64);
let html = s.get("/").text();
assert!(html.contains(&format!("{count} repositories")), "{}", &html[..html.len().min(600)]);
assert_eq!(html.matches("class=\"repo-row\"").count(), count);
}
#[test]
fn a_default_branch_ending_in_unicode_whitespace_is_kept() {
let host = Host::new("web-default-nbsp");
let work = common::scratch("web-default-nbsp-work");
git(&work, &["init", "-q", "-b", "main"]);
fs::write(work.join("main.txt"), "on main\n").unwrap();
git(&work, &["add", "."]);
git(&work, &["commit", "-qm", "Main"]);
git(&work, &["checkout", "-q", "-b", "release\u{a0}"]);
fs::write(work.join("release.txt"), "on release\n").unwrap();
git(&work, &["add", "."]);
git(&work, &["commit", "-qm", "Release"]);
let out = host.git(&work, &["push", "-q", "ada@x:ada/rel.git", "main", "release\u{a0}"]);
assert!(out.status.success(), "{}", common::stderr(&out));
git(&host.repo("ada", "rel"), &["symbolic-ref", "HEAD", "refs/heads/release\u{a0}"]);
let s = Server::start(&host.repos);
let html = s.get("/ada/rel/tree").text();
assert!(html.contains(">release.txt<"), "opened the wrong branch: {html}");
}
#[test]
fn the_index_fingerprint_survives_many_branch_folders() {
let host = Host::new("web-index-folders");
assert!(host.admin(&["create", "ada", "many"]).status.success());
let heads = host.repo("ada", "many").join("refs/heads");
// Hundreds of sibling branch folders (git leaves such folders in place; pushes that pack
// refs wouldn't create them), made before the default branch's own folder.
for n in 0..300 {
fs::create_dir_all(heads.join(format!("ns{n:03}"))).unwrap();
}
let work = common::scratch("web-index-folders-work");
git(&work, &["init", "-q", "-b", "main"]);
git(&work, &["commit", "-q", "--allow-empty", "-m", "Before"]);
let out = host.git(&work, &["push", "-q", "ada@x:ada/many.git", "main:refs/heads/zz/main"]);
assert!(out.status.success(), "{}", common::stderr(&out));
git(&host.repo("ada", "many"), &["symbolic-ref", "HEAD", "refs/heads/zz/main"]);
assert!(heads.join("zz/main").is_file(), "the default branch is a loose ref in its own folder");
// Far fewer descriptors than branch folders: the fingerprint walk must work within them.
// (Git also touches the repository directory on every ref change, so this can't tell an
// incomplete walk from a complete one; the unit test on refs_fingerprint covers that.)
let s = Server::start_limited(&host.repos, 40);
assert!(s.get("/").text().contains("Before"));
git(&work, &["commit", "-q", "--allow-empty", "-m", "After"]);
let out = host.git(&work, &["push", "-q", "ada@x:ada/many.git", "main:refs/heads/zz/main"]);
assert!(out.status.success(), "{}", common::stderr(&out));
let html = s.get("/").text();
assert!(html.contains("After"), "the index is stale: {}", &html[..html.len().min(800)]);
}