Keep capacity for signed-in sessions and cap each anonymous client
Browse filesPage renders, raw downloads and HTTPS clones shared fixed pools with no regard to who held them, so anonymous traffic or one slow client could take every slot and lock out the owner. Renders and downloads now keep reserved slots that only signed-in sessions may use, and each anonymous client (IPv4 address or IPv6 /64) may hold only a few slots of each pool at once. Clones, which carry no session, rely on the per-client cap, and the clone request body must now arrive within 10 seconds. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Author
- Um9i vulgarmessiah@gmail.com
- Date
- 22 Nov 2026, 15:58
- Commit
- ddf3dff43a02
- Parent
- 85ff5e5
5 files changed +208−45
+2−0
| @@ -17,6 +17,8 @@ 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. | ||
| **Limits.** The web server runs at most 16 page renders, 6 raw downloads and 4 HTTPS clones at once. Some render and download slots are kept for signed-in sessions, so anonymous visitors can't crowd out the owner. Each anonymous client (an IPv4 address or IPv6 /64, as Caddy reports it) may hold at most 4 renders, 2 downloads and 2 clones at a time. Past these limits a request gets 503 at once rather than queueing. | ||
| **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 and purging move and remove 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. | ||
| **Deleting and recovering.** `delete` (over SSH or as root) never removes anything: it moves the repository to `<owner>/.trash/<name>.<unix time>`, where it stops being served. The operator manages the trash: | ||
+133−0
| @@ -0,0 +1,133 @@ | ||
| //! How many expensive requests (page renders, raw downloads, clones) may run at once, and who | ||
| //! may use the slots, so anonymous traffic can never crowd out the signed-in owner. | ||
| //! | ||
| //! A [`Pool`] has open slots, which anyone may use, and reserved slots, which only signed-in | ||
| //! sessions may use (they take an open slot when the reserved ones are busy). An anonymous | ||
| //! client may also hold only a few slots at once, so one address can't take them all; clients | ||
| //! are identified as in sign-in throttling (an IPv4 address or IPv6 /64). | ||
| use std::collections::HashMap; | ||
| use std::sync::{Arc, Mutex}; | ||
| use tokio::sync::{OwnedSemaphorePermit, Semaphore}; | ||
| use super::throttle::Client; | ||
| /// How many slots each anonymous client holds, shared between a pool and its slots. | ||
| type Held = Arc<Mutex<HashMap<Client, usize>>>; | ||
| /// Who is asking for a slot. | ||
| #[derive(Clone, Copy, Debug)] | ||
| pub struct Visitor { | ||
| pub client: Client, | ||
| pub signed_in: bool, | ||
| } | ||
| pub struct Pool { | ||
| open: Arc<Semaphore>, | ||
| reserved: Arc<Semaphore>, | ||
| per_client: usize, | ||
| held: Held, | ||
| } | ||
| /// A slot in a [`Pool`], given back when dropped. | ||
| pub struct Slot { | ||
| _permit: OwnedSemaphorePermit, | ||
| /// The anonymous client this slot counts against. | ||
| counted: Option<(Held, Client)>, | ||
| } | ||
| impl Drop for Slot { | ||
| fn drop(&mut self) { | ||
| if let Some((held, client)) = &self.counted { | ||
| let mut held = held.lock().unwrap_or_else(|e| e.into_inner()); | ||
| if let Some(count) = held.get_mut(client) { | ||
| *count -= 1; | ||
| if *count == 0 { | ||
| held.remove(client); | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
| impl Pool { | ||
| pub fn new(open: usize, reserved: usize, per_client: usize) -> Pool { | ||
| Pool { | ||
| open: Arc::new(Semaphore::new(open)), | ||
| reserved: Arc::new(Semaphore::new(reserved)), | ||
| per_client, | ||
| held: Arc::default(), | ||
| } | ||
| } | ||
| /// A slot for `visitor` now, or `None` if none is free to them: the caller answers busy. | ||
| pub fn try_acquire(&self, visitor: Visitor) -> Option<Slot> { | ||
| if visitor.signed_in { | ||
| let permit = | ||
| Arc::clone(&self.reserved).try_acquire_owned().or_else(|_| Arc::clone(&self.open).try_acquire_owned()); | ||
| return permit.ok().map(|permit| Slot { _permit: permit, counted: None }); | ||
| } | ||
| let mut held = self.held.lock().unwrap_or_else(|e| e.into_inner()); | ||
| let count = held.entry(visitor.client).or_insert(0); | ||
| let permit = (*count < self.per_client).then(|| Arc::clone(&self.open).try_acquire_owned().ok()).flatten(); | ||
| match permit { | ||
| Some(permit) => { | ||
| *count += 1; | ||
| Some(Slot { _permit: permit, counted: Some((Arc::clone(&self.held), visitor.client)) }) | ||
| } | ||
| None => { | ||
| if *count == 0 { | ||
| held.remove(&visitor.client); | ||
| } | ||
| None | ||
| } | ||
| } | ||
| } | ||
| } | ||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
| fn anonymous(address: &str) -> Visitor { | ||
| Visitor { client: Client::new(address.parse().unwrap()), signed_in: false } | ||
| } | ||
| fn owner() -> Visitor { | ||
| Visitor { signed_in: true, ..anonymous("198.51.100.1") } | ||
| } | ||
| #[test] | ||
| fn anonymous_traffic_cannot_take_the_reserved_slots() { | ||
| let pool = Pool::new(4, 2, 1); | ||
| let taken: Vec<Slot> = | ||
| (0..4).map(|i| pool.try_acquire(anonymous(&format!("203.0.113.{i}"))).unwrap()).collect(); | ||
| assert!(pool.try_acquire(anonymous("203.0.113.99")).is_none(), "the open slots are full"); | ||
| let first = pool.try_acquire(owner()).expect("the owner gets a reserved slot"); | ||
| let second = pool.try_acquire(owner()).expect("and another"); | ||
| assert!(pool.try_acquire(owner()).is_none(), "all slots are busy"); | ||
| drop(taken); | ||
| assert!(pool.try_acquire(owner()).is_some(), "the owner may also use open slots"); | ||
| drop((first, second)); | ||
| } | ||
| #[test] | ||
| fn one_anonymous_client_holds_only_its_share() { | ||
| let pool = Pool::new(8, 0, 2); | ||
| let a = anonymous("203.0.113.7"); | ||
| let held = [pool.try_acquire(a).unwrap(), pool.try_acquire(a).unwrap()]; | ||
| assert!(pool.try_acquire(a).is_none(), "a third slot for the same client"); | ||
| assert!(pool.try_acquire(anonymous("2001:db8::1")).is_some(), "another client still gets one"); | ||
| drop(held); | ||
| assert!(pool.try_acquire(a).is_some(), "slots come back when dropped"); | ||
| assert!(pool.held.lock().unwrap().is_empty(), "no client is remembered once it holds nothing"); | ||
| } | ||
| #[test] | ||
| fn signed_in_sessions_have_no_per_client_cap() { | ||
| let pool = Pool::new(4, 0, 1); | ||
| let held: Vec<Slot> = (0..4).map(|_| pool.try_acquire(owner()).unwrap()).collect(); | ||
| assert_eq!(held.len(), 4); | ||
| } | ||
| } | ||
| @@ -2,14 +2,14 @@ | ||
| use axum::body::{Body, Bytes}; | ||
| use futures_util::{StreamExt, stream}; | ||
| use std::{io, process::Stdio, time::Duration}; | ||
| #[cfg(test)] | ||
| use tokio::sync::Semaphore; | ||
| use tokio::{ | ||
| io::{AsyncReadExt, AsyncWriteExt}, | ||
| process::Command, | ||
| sync::{Semaphore, SemaphorePermit, mpsc, oneshot}, | ||
| sync::{mpsc, oneshot}, | ||
| }; | ||
| pub static RAW_TRANSFERS: Semaphore = Semaphore::const_new(4); | ||
| pub struct Output { | ||
| child: tokio::process::Child, | ||
| stdout: tokio::process::ChildStdout, | ||
| @@ -28,13 +28,7 @@ impl Output { | ||
| Ok(bytes.into()) | ||
| } | ||
| pub fn body( | ||
| mut self, | ||
| prefix: Bytes, | ||
| input: Option<Bytes>, | ||
| permit: SemaphorePermit<'static>, | ||
| timeout: Duration, | ||
| ) -> Body { | ||
| pub fn body(mut self, prefix: Bytes, input: Option<Bytes>, permit: impl Send + 'static, timeout: Duration) -> Body { | ||
| let (tx, rx) = mpsc::channel::<Bytes>(2); | ||
| let (finished, status) = oneshot::channel(); | ||
| let (body_guard, dropped) = oneshot::channel::<()>(); | ||
+51−26
| @@ -1,9 +1,12 @@ | ||
| //! Repository browser and read-only HTTP clone service. Anonymous visitors can access public repositories. | ||
| //! A session grants the shared web account access to private repositories. | ||
| mod capacity; | ||
| mod login; | ||
| mod templates; | ||
| mod throttle; | ||
| use capacity::{Pool, Visitor}; | ||
| use throttle::Client; | ||
| use std::borrow::Cow; | ||
| mod repository; | ||
| @@ -149,21 +152,24 @@ const SECURITY: [(header::HeaderName, &str); 4] = [ | ||
| ]; | ||
| impl View { | ||
| async fn response(self) -> Response { | ||
| let html = [(header::CONTENT_TYPE, "text/html; charset=utf-8")]; | ||
| /// The response for `visitor`, who may need a download slot for a raw file. | ||
| async fn response(self, visitor: Visitor) -> Response { | ||
| match self { | ||
| View::LoginRequired => StatusCode::UNAUTHORIZED.into_response(), | ||
| View::Html(body) => (SECURITY, html, body).into_response(), | ||
| View::Raw(cmd, size, name) => raw_response(*cmd, size, name).await, | ||
| View::Html(body) => (SECURITY, [(header::CONTENT_TYPE, "text/html; charset=utf-8")], body).into_response(), | ||
| View::Raw(cmd, size, name) => raw_response(visitor, *cmd, size, name).await, | ||
| View::Busy => StatusCode::SERVICE_UNAVAILABLE.into_response(), | ||
| View::Redirect(to) => Redirect::to(&to).into_response(), | ||
| View::Missing(signed_in) => { | ||
| (StatusCode::NOT_FOUND, SECURITY, html, view_missing(signed_in)).into_response() | ||
| } | ||
| View::Missing(signed_in) => missing(signed_in), | ||
| } | ||
| } | ||
| } | ||
| fn missing(signed_in: bool) -> Response { | ||
| let html = [(header::CONTENT_TYPE, "text/html; charset=utf-8")]; | ||
| (StatusCode::NOT_FOUND, SECURITY, html, view_missing(signed_in)).into_response() | ||
| } | ||
| fn static_file(kind: &'static str, data: &'static [u8]) -> Response { | ||
| ([(header::CONTENT_TYPE, kind), (header::CACHE_CONTROL, "max-age=86400")], data).into_response() | ||
| } | ||
| @@ -1200,11 +1206,15 @@ fn route(owner: &str, name: &str, view: Option<&str>, q: &Q, signed_in: bool) -> | ||
| result.unwrap_or(View::Missing(signed_in)) | ||
| } | ||
| /// Maximum simultaneous render jobs. Reject excess requests before queuing blocking work. | ||
| static RENDERS: LazyLock<Arc<tokio::sync::Semaphore>> = LazyLock::new(|| Arc::new(tokio::sync::Semaphore::new(16))); | ||
| /// Pages rendering at once: 12 for anyone, 4 more kept for signed-in sessions, and at most 4 | ||
| /// for any one anonymous client. Excess requests are refused before any blocking work queues. | ||
| static RENDERS: LazyLock<Pool> = LazyLock::new(|| Pool::new(12, 4, 4)); | ||
| /// Raw downloads streaming at once: 4 for anyone, 2 kept for signed-in sessions, 2 per | ||
| /// anonymous client. | ||
| static DOWNLOADS: LazyLock<Pool> = LazyLock::new(|| Pool::new(4, 2, 2)); | ||
| async fn raw_response(command: std::process::Command, size: usize, name: Vec<u8>) -> Response { | ||
| let Ok(permit) = git_stream::RAW_TRANSFERS.try_acquire() else { | ||
| async fn raw_response(visitor: Visitor, command: std::process::Command, size: usize, name: Vec<u8>) -> Response { | ||
| let Some(permit) = DOWNLOADS.try_acquire(visitor) else { | ||
| return StatusCode::SERVICE_UNAVAILABLE.into_response(); | ||
| }; | ||
| let Ok(mut output) = git_stream::Output::start(command.into()) else { | ||
| @@ -1239,8 +1249,8 @@ async fn raw_response(command: std::process::Command, size: usize, name: Vec<u8> | ||
| /// 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) -> Response { | ||
| let Ok(permit) = Arc::clone(&RENDERS).try_acquire_owned() else { | ||
| async fn blocking(visitor: Visitor, f: impl FnOnce() -> View + Send + 'static) -> Response { | ||
| let Some(permit) = RENDERS.try_acquire(visitor) else { | ||
| return StatusCode::SERVICE_UNAVAILABLE.into_response(); | ||
| }; | ||
| let work = move || { | ||
| @@ -1253,7 +1263,7 @@ async fn blocking(f: impl FnOnce() -> View + Send + 'static) -> Response { | ||
| eprintln!("gitv-web: a page failed to render: {error}"); | ||
| View::Missing(false) | ||
| }); | ||
| view.response().await | ||
| view.response(visitor).await | ||
| } | ||
| fn main() -> std::process::ExitCode { | ||
| @@ -1295,23 +1305,36 @@ fn serve(port: u16) -> Result<(), String> { | ||
| "/account", | ||
| get(login::account).post(login::change_password).layer(DefaultBodyLimit::max(login::FORM_LIMIT)), | ||
| ) | ||
| .fallback(|| View::Missing(true).response()) | ||
| .fallback(|| async { 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, Extension(user): Extension<bool>| { | ||
| blocking(move || route(&o, &n, None, &parse_query(q.as_deref()), user)) | ||
| "/", | ||
| get(|Extension(user): Extension<bool>, client: Client| { | ||
| blocking(Visitor { client, signed_in: user }, move || view_index(user)) | ||
| }), | ||
| ) | ||
| .route( | ||
| "/{owner}/{name}", | ||
| get( | ||
| |Path((o, n)): Path<(String, String)>, | ||
| RawQuery(q): RawQuery, | ||
| Extension(user): Extension<bool>, | ||
| client: Client| { | ||
| let visitor = Visitor { client, signed_in: user }; | ||
| blocking(visitor, 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, | ||
| Extension(user): Extension<bool>| { | ||
| blocking(move || route(&o, &n, Some(&v), &parse_query(q.as_deref()), user)) | ||
| Extension(user): Extension<bool>, | ||
| client: Client| { | ||
| let visitor = Visitor { client, signed_in: user }; | ||
| blocking(visitor, move || route(&o, &n, Some(&v), &parse_query(q.as_deref()), user)) | ||
| }, | ||
| ), | ||
| ) | ||
| @@ -1339,12 +1362,14 @@ mod tests { | ||
| use super::*; | ||
| #[tokio::test] | ||
| async fn saturated_render_pool_returns_busy_without_starting_work() { | ||
| let permits = RENDERS.try_acquire_many(RENDERS.available_permits() as u32).unwrap(); | ||
| let response = blocking(|| panic!("excess render was admitted")).await; | ||
| async fn a_client_over_its_share_is_busy_without_starting_work() { | ||
| let visitor = Visitor { client: Client::new("203.0.113.250".parse().unwrap()), signed_in: false }; | ||
| let held: Vec<_> = std::iter::from_fn(|| RENDERS.try_acquire(visitor)).collect(); | ||
| assert!(!held.is_empty()); | ||
| let response = blocking(visitor, || panic!("excess render was admitted")).await; | ||
| assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE); | ||
| drop(permits); | ||
| assert_eq!(blocking(|| View::Html(String::new())).await.status(), StatusCode::OK); | ||
| drop(held); | ||
| assert_eq!(blocking(visitor, || View::Html(String::new())).await.status(), StatusCode::OK); | ||
| } | ||
| #[test] | ||
| @@ -1,5 +1,7 @@ | ||
| //! Read-only Git smart HTTP, using upload-pack's stateless protocol. | ||
| use super::capacity::{Pool, Visitor}; | ||
| use super::git_stream::Output; | ||
| use super::throttle::Client; | ||
| use axum::{ | ||
| body::Bytes, | ||
| extract::{Path, RawQuery, Request}, | ||
| @@ -7,32 +9,39 @@ use axum::{ | ||
| response::{IntoResponse, Response}, | ||
| }; | ||
| use gitv::{git_command, repo_dir}; | ||
| use std::sync::LazyLock; | ||
| use std::{process::Stdio, time::Duration}; | ||
| use tokio::{process::Command, sync::Semaphore}; | ||
| use tokio::process::Command; | ||
| static TRANSFERS: Semaphore = Semaphore::const_new(4); | ||
| /// Clones and fetches at once. Git clients send no session cookie, so every transfer is | ||
| /// anonymous; each client may run two, so no single address can take them all. | ||
| static TRANSFERS: LazyLock<Pool> = LazyLock::new(|| Pool::new(4, 0, 2)); | ||
| pub async fn refs(Path(path): Path<(String, String)>, RawQuery(query): RawQuery) -> Response { | ||
| pub async fn refs(Path(path): Path<(String, String)>, RawQuery(query): RawQuery, client: Client) -> Response { | ||
| if query.as_deref() != Some("service=git-upload-pack") { | ||
| return StatusCode::NOT_FOUND.into_response(); | ||
| } | ||
| transfer(path, None).await | ||
| transfer(path, client, None).await | ||
| } | ||
| pub async fn pack(Path(path): Path<(String, String)>, request: Request) -> Response { | ||
| pub async fn pack(Path(path): Path<(String, String)>, client: Client, 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 | ||
| transfer(path, client, Some(request)).await | ||
| } | ||
| async fn transfer((owner, name): (String, String), request: Option<Request>) -> Response { | ||
| async fn transfer((owner, name): (String, String), client: Client, 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() }; | ||
| // Taken before the body is read, so memory for bodies stays bounded by the slots; the | ||
| // per-client cap keeps one slow sender from holding them all. | ||
| let Some(permit) = TRANSFERS.try_acquire(Visitor { client, signed_in: false }) 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()) { | ||
| @@ -41,7 +50,7 @@ async fn transfer((owner, name): (String, String), request: Option<Request>) -> | ||
| _ => 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)) | ||
| match tokio::time::timeout(Duration::from_secs(10), axum::body::to_bytes(request.into_body(), MAX_REQUEST)) | ||
| .await | ||
| { | ||
| Err(_) => return StatusCode::REQUEST_TIMEOUT.into_response(), | ||