GITv

Add public repository browsing and read-only HTTPS cloning

Browse files
Author
Um9i vulgarmessiah@gmail.com
Date
22 Nov 2026, 14:30
Commit
6a22d2aee5c1
Parent
50964bd

10 files changed +359−49

+24−0
@@ -360,6 +360,16 @@ dependencies = [
"ctutils",
]
[[package]]
name = "errno"
version = "0.3.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776"
dependencies = [
"libc",
"windows-sys",
]
[[package]]
name = "find-msvc-tools"
version = "0.1.15"
@@ -437,6 +447,8 @@ dependencies = [
"base64",
"clap",
"data-encoding",
"flate2",
"futures-util",
"getrandom",
"hmac",
"html-escape",
@@ -901,6 +913,16 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
[[package]]
name = "signal-hook-registry"
version = "1.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
dependencies = [
"errno",
"libc",
]
[[package]]
name = "simd-adler32"
version = "0.3.10"
@@ -1002,9 +1024,11 @@ version = "1.54.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3"
dependencies = [
"bytes",
"libc",
"mio",
"pin-project-lite",
"signal-hook-registry",
"socket2",
"tokio-macros",
"windows-sys",
@@ -10,6 +10,8 @@ axum = "0.8.9"
base64 = "0.23.1"
clap = { version = "4.6.9", features = ["derive"] }
data-encoding = "2.11.1"
flate2 = "1.1.11"
futures-util = { version = "0.3.34", default-features = false, features = ["std"] }
getrandom = "0.4.3"
hmac = "0.13.0"
html-escape = "0.3.1"
@@ -24,7 +26,7 @@ shlex = "2.0.1"
subtle = "2.6.1"
syntect = { version = "5.3.0", default-features = false, features = ["default-syntaxes", "html", "regex-onig"] }
thiserror = "2.0.21"
tokio = { version = "1.54.1", features = ["rt-multi-thread", "macros", "net", "sync"] }
tokio = { version = "1.54.1", features = ["rt-multi-thread", "macros", "net", "sync", "io-util", "process", "time"] }
[profile.release]
lto = "thin"
+13−3
@@ -1,12 +1,22 @@
# GITv
Private Git hosting over OpenSSH, plus a read-only web browser.
Git hosting with SSH pushes, public and private repository browsing, and read-only HTTPS cloning for public repositories.
- `gitv`: the SSH forced-command handler (`serve`) and the root admin CLI (`create`, `delete`, `add-key`)
- `gitv`: the SSH forced-command handler (`serve`) and the root admin CLI (`create`, `visibility`, `delete`, `add-key`)
- `gitv-web`: the read-only browser (repositories, tree, blob, raw, log, commit, tags), with Markdown rendering and syntax highlighting (`src/render.rs`)
**Who can read what.** Over SSH each key reaches only its owner's repositories. The web browser has one account, and whoever signs in to it can read every repository on the server. It binds to localhost only; put it behind an HTTPS reverse proxy.
Existing and newly created repositories default to private. Publish one as its SSH owner or as the server administrator:
```sh
ssh git@git.um9i.dev visibility my-project public
# Equivalent command on the server
gitv visibility um9i my-project public
```
Anyone can now find it on the repository index, browse its files and history, and run `git clone https://git.um9i.dev/um9i/my-project`. Use the same visibility command with `private` to require sign-in again and disable HTTPS fetches. Copies already downloaded remain with their recipients. Pushes use SSH.
**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.
@@ -27,7 +37,7 @@ It prints a generated password (20 random characters, shown only this once), the
- Sessions last 12 hours and end when the browser restarts. The session cookie is `Secure`, so the browser must be reached over HTTPS (or on `localhost`).
- After five failed attempts sign-in locks for a minute, doubling with each further failure up to 15 minutes. A code works once.
Until the account exists, the browser answers every page with instructions to run `gitv-web setup`.
Until the account exists, pages requiring sign-in show setup instructions. Public repositories can already be browsed and cloned.
## Run locally
@@ -296,22 +296,38 @@ fn not_set_up() -> Response {
/// route except the few public ones, which are routed separately by exact path, so no prefix
/// rule can ever make a repository page public.
pub async fn require_login(State(login): State<Arc<Login>>, mut request: Request, next: Next) -> Response {
let credentials = match login.credentials() {
Ok(credentials) => credentials,
Err(AuthError::NotSetUp(_)) => return not_set_up(),
Err(error) => {
let credentials = login.credentials();
if let Ok(creds) = &credentials
&& let Some(session) = login.session(request.headers(), creds)
{
request.extensions_mut().insert(session);
return next.run(request).await;
}
challenge(credentials.err(), request.uri())
}
pub async fn browse(State(login): State<Arc<Login>>, mut request: Request, next: Next) -> Response {
let credentials = login.credentials();
let signed_in = credentials.as_ref().ok().and_then(|c| login.session(request.headers(), c)).is_some();
request.extensions_mut().insert(signed_in);
let uri = request.uri().clone();
let response = next.run(request).await;
if response.status() == StatusCode::UNAUTHORIZED { challenge(credentials.err(), &uri) } else { response }
}
fn challenge(error: Option<AuthError>, uri: &axum::http::Uri) -> Response {
match error {
Some(AuthError::NotSetUp(_)) => return not_set_up(),
Some(error) => {
eprintln!("gitv-web: {error}");
return html(
StatusCode::SERVICE_UNAVAILABLE,
layout("Unavailable", "<p class=\"note\">Sign-in is unavailable.</p>", false),
layout("Unavailable", "<p>Sign-in is unavailable.</p>", false),
);
}
};
if let Some(signed_in) = login.session(request.headers(), &credentials) {
request.extensions_mut().insert(signed_in);
return next.run(request).await;
None => {}
}
let wanted = request.uri().path_and_query().map_or("/", |p| p.as_str());
let wanted = uri.path_and_query().map_or("/", |p| p.as_str());
redirect(&format!("/login?next={}", super::encode(wanted.as_bytes())), None)
}
@@ -17,7 +17,8 @@ use std::os::unix::ffi::{OsStrExt, OsStringExt};
use std::sync::{Arc, LazyLock, Mutex};
use std::time::{SystemTime, UNIX_EPOCH};
use axum::Router;
use axum::{Extension, Router};
mod smart_http;
use axum::extract::DefaultBodyLimit;
use axum::extract::{Path, RawQuery};
use axum::http::{StatusCode, header};
@@ -128,11 +129,12 @@ enum Action {
}
enum View {
LoginRequired,
Html(String),
/// Bytes, content type, and a download name for files the browser shouldn't display.
Raw(Vec<u8>, &'static str, Option<Vec<u8>>),
Redirect(String),
Missing,
Missing(bool),
}
const SECURITY: [(header::HeaderName, &str); 4] = [
@@ -149,6 +151,7 @@ impl IntoResponse for View {
fn into_response(self) -> Response {
let html = [(header::CONTENT_TYPE, "text/html; charset=utf-8")];
match self {
View::LoginRequired => StatusCode::UNAUTHORIZED.into_response(),
View::Html(body) => (SECURITY, html, body).into_response(),
View::Raw(data, kind, download) => {
let mut response = (SECURITY, [(header::CONTENT_TYPE, kind)], data).into_response();
@@ -160,7 +163,9 @@ impl IntoResponse for View {
response
}
View::Redirect(to) => Redirect::to(&to).into_response(),
View::Missing => (StatusCode::NOT_FOUND, SECURITY, html, view_missing()).into_response(),
View::Missing(signed_in) => {
(StatusCode::NOT_FOUND, SECURITY, html, view_missing(signed_in)).into_response()
}
}
}
}
@@ -316,12 +321,13 @@ fn layout(title: &str, body: &str, signed_in: bool) -> String {
templates::Layout { title, body, signed_in }.to_string()
}
fn view_missing() -> String {
page(
fn view_missing(signed_in: bool) -> String {
layout(
"Not found",
r#"<section class="notfound"><h1 class="title">Nothing here</h1>
<p class="count">That repository, branch, file or commit doesn’t exist, or the link is malformed.</p>
<a class="button" href="/">Back to repositories</a></section>"#,
signed_in,
)
}
@@ -329,6 +335,7 @@ fn view_missing() -> String {
// Repository access
struct Repo {
signed_in: bool,
owner: String,
name: String,
dir: RepoDir,
@@ -369,7 +376,26 @@ impl Repo {
}
fn from_dir(owner: &str, name: &str, dir: RepoDir) -> Repo {
Repo { dir, owner: owner.into(), name: name.into(), heads: OnceCell::new(), tags: OnceCell::new() }
Repo {
signed_in: false,
dir,
owner: owner.into(),
name: name.into(),
heads: OnceCell::new(),
tags: OnceCell::new(),
}
}
fn page(&self, title: &str, body: &str) -> String {
layout(title, body, self.signed_in)
}
fn clone_address(&self) -> (&'static str, String) {
if self.dir.is_public() {
("HTTPS", format!("https://{HOST}/{}/{}", self.owner, self.name))
} else {
("SSH", format!("git@{HOST}:{}/{}.git", self.owner, self.name))
}
}
fn git_bytes<S: AsRef<OsStr>>(&self, args: &[S]) -> Option<Vec<u8>> {
@@ -628,9 +654,10 @@ impl Repo {
let badge = count.map_or(String::new(), |n| format!(r#"<span class="n">{n}</span>"#));
format!(r#"<a href="{}"{current}>{}{label}{badge}</a>"#, attr(&self.url(view, query)), icon(glyph))
};
let (protocol, address) = self.clone_address();
format!(
r#"<div class="repohead"><h1 class="reponame"><a class="own" href="/">{owner}</a><span class="sep">/</span><a href="{home}">{name}</a></h1>
<label class="clone"><span>SSH</span><input readonly aria-label="Clone address" value="git@{HOST}:{owner}/{name}.git"></label></div>
<label class="clone"><span>{protocol}</span><input readonly aria-label="Clone address" value="{address}"></label></div>
<nav class="tabs" aria-label="Repository">{}{}{}</nav>"#,
tab("tree", "code", "Code", None),
tab("log", "commits", "Commits", Some(commits)),
@@ -814,7 +841,7 @@ struct Row {
head: Option<Head>,
}
fn view_index() -> View {
fn view_index(signed_in: bool) -> View {
let mut rows = Vec::new();
let root = open_root();
for owner in root.as_ref().map(sorted_names).unwrap_or_default() {
@@ -823,6 +850,9 @@ fn view_index() -> View {
for entry in sorted_names(&owner_dir) {
let Some(name) = entry.strip_suffix(".git") else { continue };
let Some(dir) = repo_in(&owner_dir, &owner, name) else { continue };
if !signed_in && !dir.is_public() {
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.
@@ -842,6 +872,9 @@ fn view_index() -> View {
rows.push(Row { owner: owner.clone(), name: name.to_string(), head });
}
}
if rows.is_empty() && !signed_in {
return View::LoginRequired;
}
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()
@@ -866,11 +899,12 @@ fn view_index() -> View {
format!(r#"<div class="panel"><ul class="rows">{items}</ul></div>"#)
};
let count = plural(rows.len(), "repository", "repositories");
View::Html(page(
View::Html(layout(
"Repositories",
&format!(
r#"<div class="pagehead"><h1 class="title">Repositories</h1><p class="count">{count}</p></div>{listing}"#
),
signed_in,
))
}
@@ -888,7 +922,7 @@ fn view_tree(repo: &Repo, q: &Q) -> Option<View> {
esc(&repo.owner),
esc(&repo.name)
);
return Some(View::Html(page(&format!("{}/{}", repo.owner, repo.name), &body)));
return Some(View::Html(repo.page(&format!("{}/{}", repo.owner, repo.name), &body)));
};
let listing = [OsStr::new("ls-tree"), OsStr::new("-l"), OsStr::new("-z"), &spec(&commit, &path)];
let Some(listing) = repo.git_bytes(&listing) else {
@@ -966,7 +1000,7 @@ fn view_tree(repo: &Repo, q: &Q) -> Option<View> {
} else {
format!("{} at {reference}", lossy(&path))
};
Some(View::Html(page(&title, &body)))
Some(View::Html(repo.page(&title, &body)))
}
/// A file rendered for display, as `facts` 0x1f `html`: highlighted code, or Markdown with
@@ -1031,15 +1065,14 @@ fn view_blob(repo: &Repo, q: &Q, raw: bool) -> Option<View> {
let name = lossy(file_name(&path)).into_owned();
if raw {
if item.size > RAW_LIMIT {
return Some(View::Html(page(
return Some(View::Html(repo.page(
"File too large",
&format!(
r#"<section class="notfound"><h1 class="title">This file is too large to download here</h1>
<p class="count">{} is {}. Clone the repository to get it.</p><code>git clone git@{HOST}:{}/{}.git</code></section>"#,
<p class="count">{} is {}. Clone the repository to get it.</p><code>git clone {}</code></section>"#,
esc(&name),
size(item.size),
esc(&repo.owner),
esc(&repo.name)
repo.clone_address().1
),
)));
}
@@ -1096,7 +1129,7 @@ fn view_blob(repo: &Repo, q: &Q, raw: bool) -> Option<View> {
icon("file"),
esc(&name)
);
Some(View::Html(page(&format!("{} at {reference}", lossy(&path)), &body)))
Some(View::Html(repo.page(&format!("{} at {reference}", lossy(&path)), &body)))
}
fn view_log(repo: &Repo, q: &Q) -> Option<View> {
@@ -1136,7 +1169,7 @@ fn view_log(repo: &Repo, q: &Q) -> Option<View> {
Some(View::Html(
templates::History {
title: format!("Commits on {reference}"),
signed_in: true,
signed_in: repo.signed_in,
masthead: repo.masthead("log", &reference, Some(&commit)),
locator: repo.locator("log", &reference, b""),
rows,
@@ -1271,7 +1304,7 @@ fn view_commit(repo: &Repo, q: &Q) -> Option<View> {
let diff = cached(repo.key("diff", oid, ""), || render_diff(repo, oid, parents))
.unwrap_or_else(|| r#"<p class="note">This commit’s changes couldn’t be read.</p>"#.into());
body += &diff;
Some(View::Html(page(subject_or_placeholder(subject), &body)))
Some(View::Html(repo.page(subject_or_placeholder(subject), &body)))
}
/// A commit's changes as one panel per file. Only [`DIFF_LIMIT`] bytes of patch are read; past
@@ -1386,11 +1419,17 @@ fn view_tags(repo: &Repo) -> Option<View> {
format!(r#"<div class="panel"><ul class="rows">{rows}</ul></div>"#)
};
let body = repo.masthead("tags", &repo.default_ref(), None) + &listing;
Some(View::Html(page(&format!("Tags in {}/{}", repo.owner, repo.name), &body)))
Some(View::Html(repo.page(&format!("Tags in {}/{}", repo.owner, repo.name), &body)))
}
fn route(owner: &str, name: &str, view: Option<&str>, q: &Q) -> View {
let Some(repo) = Repo::open(owner, name) else { return View::Missing };
fn route(owner: &str, name: &str, view: Option<&str>, q: &Q, signed_in: bool) -> View {
let Some(mut repo) = Repo::open(owner, name) else {
return if signed_in { View::Missing(true) } else { View::LoginRequired };
};
if !signed_in && !repo.dir.is_public() {
return View::LoginRequired;
}
repo.signed_in = signed_in;
let result = match view {
None => Some(View::Redirect(repo.url("tree", &[]))),
Some("tree") => view_tree(&repo, q),
@@ -1401,7 +1440,7 @@ fn route(owner: &str, name: &str, view: Option<&str>, q: &Q) -> View {
Some("tags") => view_tags(&repo),
Some(_) => None,
};
result.unwrap_or(View::Missing)
result.unwrap_or(View::Missing(signed_in))
}
/// Pages rendered at once. Each runs several git processes, so a burst of requests queues
@@ -1412,14 +1451,14 @@ static RENDERS: LazyLock<Arc<tokio::sync::Semaphore>> = LazyLock::new(|| Arc::ne
/// 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) = Arc::clone(&RENDERS).acquire_owned().await else { return View::Missing };
let Ok(permit) = Arc::clone(&RENDERS).acquire_owned().await else { return View::Missing(false) };
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
View::Missing(false)
})
}
@@ -1455,29 +1494,40 @@ fn serve(port: u16) -> Result<(), String> {
"/login",
get(login::sign_in_form).post(login::sign_in).layer(DefaultBodyLimit::max(login::FORM_LIMIT)),
);
// Everything else, including any path not matched above, needs a session.
// Account actions and unmatched paths require a session.
let private = Router::new()
.route("/", get(|| blocking(view_index)))
.route("/logout", post(login::sign_out).layer(DefaultBodyLimit::max(login::FORM_LIMIT)))
.route(
"/account",
get(login::account).post(login::change_password).layer(DefaultBodyLimit::max(login::FORM_LIMIT)),
)
.fallback(|| async { View::Missing(true) })
.layer(axum::middleware::from_fn_with_state(Arc::clone(&login), login::require_login));
let browse = Router::new()
.route("/", get(|Extension(user): Extension<bool>| blocking(move || view_index(user))))
.route(
"/{owner}/{name}",
get(|Path((o, n)): Path<(String, String)>, RawQuery(q): RawQuery| {
blocking(move || route(&o, &n, None, &parse_query(q.as_deref())))
get(|Path((o, n)): Path<(String, String)>, RawQuery(q): RawQuery, Extension(user): Extension<bool>| {
blocking(move || route(&o, &n, None, &parse_query(q.as_deref()), user))
}),
)
.route(
"/{owner}/{name}/{view}",
get(|Path((o, n, v)): Path<(String, String, String)>, RawQuery(q): RawQuery| {
blocking(move || route(&o, &n, Some(&v), &parse_query(q.as_deref())))
}),
get(
|Path((o, n, v)): Path<(String, String, String)>,
RawQuery(q): RawQuery,
Extension(user): Extension<bool>| {
blocking(move || route(&o, &n, Some(&v), &parse_query(q.as_deref()), user))
},
),
)
.fallback(|| async { View::Missing })
.layer(axum::middleware::from_fn_with_state(Arc::clone(&login), login::require_login));
let app = public.merge(private).with_state(login);
.layer(axum::middleware::from_fn_with_state(Arc::clone(&login), login::browse));
let app = public
.route("/{owner}/{name}/info/refs", get(smart_http::refs))
.route("/{owner}/{name}/git-upload-pack", post(smart_http::pack))
.merge(browse)
.merge(private)
.with_state(login);
let listener = tokio::net::TcpListener::bind(("127.0.0.1", port))
.await
.map_err(|e| format!("can't listen on port {port}: {e}"))?;
@@ -0,0 +1,131 @@
//! Read-only Git smart HTTP, using upload-pack's stateless protocol.
use axum::{
body::{Body, Bytes},
extract::{Path, RawQuery, Request},
http::{StatusCode, header},
response::{IntoResponse, Response},
};
use futures_util::stream;
use gitv::{git_command, repo_dir};
use std::{io, process::Stdio, time::Duration};
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
process::Command,
sync::{Semaphore, mpsc},
};
static TRANSFERS: Semaphore = Semaphore::const_new(4);
pub async fn refs(Path(path): Path<(String, String)>, RawQuery(query): RawQuery) -> Response {
if query.as_deref() != Some("service=git-upload-pack") {
return StatusCode::NOT_FOUND.into_response();
}
transfer(path, None).await
}
pub async fn pack(Path(path): Path<(String, String)>, request: Request) -> Response {
if request.headers().get(header::CONTENT_TYPE).map(|h| h.as_bytes())
!= Some(b"application/x-git-upload-pack-request")
{
return StatusCode::UNSUPPORTED_MEDIA_TYPE.into_response();
}
transfer(path, Some(request)).await
}
async fn transfer((owner, name): (String, String), request: Option<Request>) -> Response {
let Some(dir) = repo_dir(&owner, &name).filter(|dir| dir.is_public()) else {
return StatusCode::NOT_FOUND.into_response();
};
let Ok(permit) = TRANSFERS.try_acquire() else { return StatusCode::SERVICE_UNAVAILABLE.into_response() };
const MAX_REQUEST: usize = 2 << 20;
let input = if let Some(request) = request {
let gzip = match request.headers().get(header::CONTENT_ENCODING).map(|h| h.as_bytes()) {
None | Some(b"identity") => false,
Some(b"gzip") => true,
_ => return StatusCode::UNSUPPORTED_MEDIA_TYPE.into_response(),
};
let bytes =
match tokio::time::timeout(Duration::from_secs(30), axum::body::to_bytes(request.into_body(), MAX_REQUEST))
.await
{
Err(_) => return StatusCode::REQUEST_TIMEOUT.into_response(),
Ok(Err(_)) => return StatusCode::PAYLOAD_TOO_LARGE.into_response(),
Ok(Ok(bytes)) => bytes,
};
if gzip {
use std::io::Read;
let mut decoded = Vec::new();
if flate2::read::GzDecoder::new(bytes.as_ref())
.take(MAX_REQUEST as u64 + 1)
.read_to_end(&mut decoded)
.is_err()
{
return StatusCode::BAD_REQUEST.into_response();
}
if decoded.len() > MAX_REQUEST {
return StatusCode::PAYLOAD_TOO_LARGE.into_response();
}
Some(Bytes::from(decoded))
} else {
Some(bytes)
}
} else {
None
};
if !dir.is_public() {
return StatusCode::NOT_FOUND.into_response();
}
let advertise = input.is_none();
let mut cmd = Command::from(git_command(&dir));
cmd.args(["upload-pack", "--stateless-rpc"]);
if advertise {
cmd.arg("--advertise-refs");
}
let Ok(mut child) = cmd.arg(".").kill_on_drop(true).stdin(Stdio::piped()).stdout(Stdio::piped()).spawn() else {
return StatusCode::INTERNAL_SERVER_ERROR.into_response();
};
let mut stdin = child.stdin.take().unwrap();
let mut stdout = child.stdout.take().unwrap();
let (tx, rx) = mpsc::channel::<io::Result<Bytes>>(2);
tokio::spawn(async move {
let _permit = permit;
let write = async move {
if let Some(input) = input {
stdin.write_all(&input).await?;
}
drop(stdin);
Ok::<_, io::Error>(())
};
let send = |bytes| async { tx.send(Ok(bytes)).await.map_err(|_| io::Error::from(io::ErrorKind::BrokenPipe)) };
let read = async {
if advertise {
send(Bytes::from_static(b"001e# service=git-upload-pack\n0000")).await?;
}
let mut buffer = vec![0; 65536];
loop {
let count = stdout.read(&mut buffer).await?;
if count == 0 {
break;
}
send(Bytes::copy_from_slice(&buffer[..count])).await?;
}
if !child.wait().await?.success() {
return Err(io::Error::other("upload-pack failed"));
}
Ok(())
};
let work = async { tokio::try_join!(write, read).map(|_| ()) };
let result = tokio::select! {
_ = tx.closed() => return,
result = tokio::time::timeout(Duration::from_secs(300), work) => result.unwrap_or_else(|_| Err(io::ErrorKind::TimedOut.into())),
};
if let Err(error) = result {
let _ = child.kill().await;
let _ = tx.try_send(Err(error));
}
});
let body = Body::from_stream(stream::unfold(rx, |mut rx| async { Some((rx.recv().await?, rx)) }));
let kind =
if advertise { "application/x-git-upload-pack-advertisement" } else { "application/x-git-upload-pack-result" };
([(header::CONTENT_TYPE, kind), (header::CACHE_CONTROL, "no-store")], body).into_response()
}
@@ -24,6 +24,7 @@ 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
create <name> create an empty repository
visibility <name> public|private set web access
delete <name> --yes delete a repository permanently
Pushing to a repository that does not exist yet creates it.";
@@ -43,6 +44,8 @@ enum Action {
#[arg(value_parser = name)]
name: String,
},
/// Set repository web visibility to public or private (root)
Visibility { owner: String, name: String, visibility: String },
/// Delete a repository permanently (root)
Delete {
#[arg(value_parser = name)]
@@ -362,6 +365,18 @@ fn skip_options(line: &str) -> Option<&str> {
None
}
fn visibility(owner: &str, name: &str, visibility: &str) -> Result<(), String> {
let public = match visibility {
"public" => true,
"private" => false,
_ => return Err("choose public or private".into()),
};
repo_dir(check_name(owner)?, check_name(name)?)
.ok_or("repository unavailable")?
.set_public(public)
.map_err(|e| format!("couldn't set visibility: {e}"))
}
/// Handle one SSH request from a key registered to owner.
fn serve(owner: &str, command: &str) -> Result<u8, String> {
let args = shlex::split(command).ok_or("unreadable command; run: ssh git@git.um9i.dev help")?;
@@ -369,6 +384,7 @@ fn serve(owner: &str, command: &str) -> Result<u8, String> {
match args.as_slice() {
[] | ["help"] => println!("{HELP}"),
[program @ ("git-upload-pack" | "git-receive-pack"), path] => return serve_git(owner, program, path),
["visibility", name, value] => visibility(owner, name, value)?,
["list"] => {
// Listed and checked through one handle on the owner's directory.
let directory = open_owner(owner);
@@ -516,6 +532,7 @@ fn run() -> Result<u8, String> {
}
delete(&owner, &name)?;
}
Action::Visibility { owner, name, visibility: value } => visibility(&owner, &name, &value)?,
Action::AddKey { owner, public_key } => add_key(&owner, &public_key)?,
Action::Serve { .. } => unreachable!(),
}
+25−0
@@ -94,6 +94,31 @@ impl RepoDir {
command_in(&self.fd, program)
}
pub fn is_public(&self) -> bool {
matches!(try_kind_at(&self.fd, OsStr::new("gitv-public")), Ok(Some(SFlag::S_IFREG)))
}
pub fn set_public(&self, public: bool) -> nix::Result<()> {
let marker = "gitv-public";
if public {
match openat(
&self.fd,
marker,
OFlag::O_WRONLY | OFlag::O_CREAT | OFlag::O_EXCL | OFlag::O_CLOEXEC,
Mode::S_IRUSR,
) {
Ok(_) => Ok(()),
Err(nix::errno::Errno::EEXIST) if self.is_public() => Ok(()),
Err(error) => Err(error),
}
} else {
match unlinkat(&self.fd, marker, UnlinkatFlags::NoRemoveDir) {
Err(nix::errno::Errno::ENOENT) => Ok(()),
result => result,
}
}
}
/// The open directory, for reading it by handle.
pub fn handle(&self) -> BorrowedFd<'_> {
self.fd.as_fd()
@@ -5,5 +5,5 @@
<link rel="preload" href="/fonts/display.woff2" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="/fonts/text.woff2" as="font" type="font/woff2" crossorigin></head>
<body><a class="skip" href="#main">Skip to content</a>
<header class="top"><div class="bar"><a class="mark" href="/"><svg class="logo" viewBox="0 0 32 32" aria-hidden="true"><rect width="32" height="32" rx="8"/><g fill="none" stroke-width="2.6" stroke-linecap="round"><circle cx="11" cy="9" r="2.6"/><circle cx="11" cy="23" r="2.6"/><circle cx="22" cy="12" r="2.6"/><path d="M11 11.6v8.8M22 14.6c0 4-3.4 5-11 6"/></g></svg>GITv</a>{% if signed_in %}<a class="account" href="/account">Account</a>{% endif %}</div></header>
<header class="top"><div class="bar"><a class="mark" href="/"><svg class="logo" viewBox="0 0 32 32" aria-hidden="true"><rect width="32" height="32" rx="8"/><g fill="none" stroke-width="2.6" stroke-linecap="round"><circle cx="11" cy="9" r="2.6"/><circle cx="11" cy="23" r="2.6"/><circle cx="22" cy="12" r="2.6"/><path d="M11 11.6v8.8M22 14.6c0 4-3.4 5-11 6"/></g></svg>GITv</a>{% if signed_in %}<a class="account" href="/account">Account</a>{% else if title != "Sign in" %}<a class="account" href="/login">Sign in</a>{% endif %}</div></header>
<main id="main">{% block content %}{% endblock %}</main></body></html>
@@ -782,3 +782,38 @@ fn the_index_fingerprint_survives_many_branch_folders() {
let html = s.get("/").text();
assert!(html.contains("After"), "the index is stale: {}", &html[..html.len().min(800)]);
}
#[test]
fn public_web_clone_and_visibility_changes() {
let host = Host::new("web-visibility");
let work = common::scratch("visibility-work");
git(&work, &["init", "-qb", "main"]);
fs::write(work.join("hello"), "public content").unwrap();
git(&work, &["add", "hello"]);
git(&work, &["commit", "-qm", "Public tip"]);
assert!(host.git(&work, &["push", "ada@test:ada/sharing.git", "main"]).status.success());
assert!(host.admin(&["create", "ada", "secret"]).status.success());
let server = Server::start(&host.repos);
let url = format!("http://127.0.0.1:{}/ada/sharing", server.port);
let refs = "/ada/sharing/info/refs?service=git-upload-pack";
assert_eq!(server.get_signed_out(refs).status, 404);
assert!(host.ssh("ada", "visibility sharing public").status.success());
let index = server.get_signed_out("/").text();
assert!(index.contains("/ada/sharing/tree"));
assert!(!index.contains("/ada/secret/tree"));
assert!(server.get("/").text().contains("/ada/secret/tree"));
let page = server.get_signed_out("/ada/sharing/tree").text();
assert!(page.contains("https://git.um9i.dev/ada/sharing"));
assert_eq!(server.get_signed_out("/ada/sharing/raw?path=hello").text(), "public content");
git(&work, &["clone", &url, "copy"]);
let copy = work.join("copy");
assert_eq!(git(&copy, &["rev-parse", "HEAD"]), git(&work, &["rev-parse", "HEAD"]));
assert!(!host.git(&copy, &["push", "origin", "HEAD:forbidden"]).status.success());
assert!(host.admin(&["visibility", "ada", "sharing", "private"]).status.success());
assert_eq!(server.get_signed_out(refs).status, 404);
assert!(!host.git(&copy, &["fetch"]).status.success());
for view in ["tree", "blob?path=hello", "raw?path=hello", "log", "commit", "tags"] {
assert_eq!(server.get_signed_out(&format!("/ada/sharing/{view}")).status, 303);
}
assert_eq!(server.get("/ada/sharing/raw?path=hello").text(), "public content");
}