//! 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 cache; mod capacity; mod git_stream; mod html; mod login; mod repository; mod setup; mod smart_http; mod templates; mod throttle; mod urls; mod views; use std::sync::{Arc, LazyLock}; use std::time::Instant; use axum::extract::{DefaultBodyLimit, Path, RawQuery}; use axum::http::{StatusCode, header}; use axum::response::{IntoResponse, Redirect, Response}; use axum::routing::{get, post}; use axum::{Extension, Router}; use clap::{Parser, Subcommand}; use gitv_core::repos_root; use gitv_web::render; use crate::html::{view_failed, view_missing}; use crate::urls::{encode, lossy, parse_query}; use crate::views::{route, view_index}; use capacity::{Pool, Visitor}; use throttle::Client; const STYLESHEET: &str = include_str!("../assets/style.css"); const FONT_DISPLAY: &[u8] = include_bytes!("../assets/fonts/display.woff2"); const FONT_TEXT: &[u8] = include_bytes!("../assets/fonts/text.woff2"); const FONT_MONO: &[u8] = include_bytes!("../assets/fonts/mono.woff2"); const ICON_192: &[u8] = include_bytes!("../assets/icons/192.png"); const ICON_512: &[u8] = include_bytes!("../assets/icons/512.png"); const ICON_MASKABLE: &[u8] = include_bytes!("../assets/icons/maskable.png"); const ICON_APPLE: &[u8] = include_bytes!("../assets/icons/apple-touch.png"); /// Lets browsers install GITv as an app that opens in its own window. const MANIFEST: &str = r##"{"id":"/","name":"GITv","short_name":"GITv","start_url":"/","scope":"/","display":"standalone","background_color":"#f6f7f9","theme_color":"#ffffff","icons":[{"src":"/favicon.svg","sizes":"any","type":"image/svg+xml"},{"src":"/icons/192.png","sizes":"192x192","type":"image/png"},{"src":"/icons/512.png","sizes":"512x512","type":"image/png"},{"src":"/icons/maskable.png","sizes":"512x512","type":"image/png","purpose":"maskable"}]}"##; const FAVICON: &str = r##""##; /// The files the pages need, by path, with their media types. Anyone may load them. const ASSETS: [(&str, &str, &[u8]); 9] = [ ("/favicon.svg", "image/svg+xml", FAVICON.as_bytes()), ("/manifest.webmanifest", "application/manifest+json", MANIFEST.as_bytes()), ("/icons/192.png", "image/png", ICON_192), ("/icons/512.png", "image/png", ICON_512), ("/icons/maskable.png", "image/png", ICON_MASKABLE), ("/apple-touch-icon.png", "image/png", ICON_APPLE), ("/fonts/display.woff2", "font/woff2", FONT_DISPLAY), ("/fonts/text.woff2", "font/woff2", FONT_TEXT), ("/fonts/mono.woff2", "font/woff2", FONT_MONO), ]; /// The stylesheet's URL carries a hash of its contents, so browsers can cache it for good and /// still pick up every change. static STYLE_URL: LazyLock = LazyLock::new(|| { use std::hash::{Hash, Hasher}; let mut hasher = std::hash::DefaultHasher::new(); STYLESHEET.hash(&mut hasher); format!("/style.css?v={:012x}", hasher.finish() & 0xffff_ffff_ffff) }); // --------------------------------------------------------------------------------------------- // Responses #[derive(Parser)] #[command(about = "Read-only web browser for GITv repositories")] struct Cli { #[command(subcommand)] action: Action, } #[derive(Subcommand)] enum Action { /// Serve the browser on localhost Serve { #[arg(long, default_value_t = 8080)] port: u16, }, /// Create the web account: a generated password and an authenticator (2FA) secret Setup { /// The account name [default: the current account's with --force, otherwise admin] #[arg(long)] user: Option, /// Replace an existing account, signing every session out #[arg(long)] force: bool, }, /// Change the web account's password, typed at the terminal Password, } enum View { LoginRequired, Html(String), /// Pinned cat-file command, expected size and original download name. Raw(Box, usize, Vec), /// Pinned `git archive` command, and the download's file name. Archive(Box, String), Busy, Redirect(String), Missing(bool), } const SECURITY: [(header::HeaderName, &str); 4] = [ ( header::CONTENT_SECURITY_POLICY, "default-src 'none'; style-src 'self'; font-src 'self'; img-src 'self'; manifest-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'", ), (header::X_CONTENT_TYPE_OPTIONS, "nosniff"), (header::REFERRER_POLICY, "no-referrer"), (header::CACHE_CONTROL, "no-store"), ]; /// Headers for a raw file, which is repository content served from this site's own origin. /// The sandbox makes a file opened directly (an SVG, say) a unique origin with no scripts, so /// even a policy mistake can't let it act as the signed-in visitor. Inline styles are allowed /// so SVGs draw as their authors meant; nothing may load from anywhere. const RAW_SECURITY: [(header::HeaderName, &str); 4] = [ (header::CONTENT_SECURITY_POLICY, "sandbox; default-src 'none'; style-src 'unsafe-inline'; img-src data:"), (header::X_CONTENT_TYPE_OPTIONS, "nosniff"), (header::REFERRER_POLICY, "no-referrer"), (header::CACHE_CONTROL, "no-store"), ]; impl View { /// 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) => html(StatusCode::OK, body), View::Raw(cmd, size, name) => raw_response(visitor, *cmd, size, name).await, View::Archive(cmd, name) => archive_response(visitor, *cmd, name).await, View::Busy => StatusCode::SERVICE_UNAVAILABLE.into_response(), View::Redirect(to) => Redirect::to(&to).into_response(), View::Missing(signed_in) => missing(signed_in), } } } fn missing(signed_in: bool) -> Response { html(StatusCode::NOT_FOUND, view_missing(signed_in)) } /// An HTML page, with the security headers every page sends. fn html(status: StatusCode, body: String) -> Response { (status, SECURITY, [(header::CONTENT_TYPE, "text/html; charset=utf-8")], body).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() } fn stylesheet() -> Response { let headers = [(header::CONTENT_TYPE, "text/css; charset=utf-8"), (header::CACHE_CONTROL, "max-age=31536000, immutable")]; (headers, STYLESHEET).into_response() } /// 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 = 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 = LazyLock::new(|| Pool::new(4, 2, 2)); async fn raw_response(visitor: Visitor, command: std::process::Command, size: usize, name: Vec) -> 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 { return StatusCode::INTERNAL_SERVER_ERROR.into_response(); }; let Ok(prefix) = output.prefix(size.min(8000)).await else { return StatusCode::INTERNAL_SERVER_ERROR.into_response(); }; let binary = prefix.contains(&0); let filename = lossy(&name); let kind = match filename.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()).as_deref() { Some("png") => "image/png", Some("jpg" | "jpeg") => "image/jpeg", Some("gif") => "image/gif", Some("webp") => "image/webp", // Safe to serve as an image: the sandbox (see RAW_SECURITY) blocks any script inside it. Some("svg") => "image/svg+xml", _ if binary => "application/octet-stream", _ => "text/plain; charset=utf-8", }; let body = output.body(prefix, None, permit, std::time::Duration::from_secs(300)); let mut response = (RAW_SECURITY, [(header::CONTENT_TYPE, kind)], body).into_response(); response.headers_mut().insert(header::CONTENT_LENGTH, size.into()); if kind == "application/octet-stream" && let Ok(value) = format!("attachment; filename*=UTF-8''{}", encode(&name)).parse() { response.headers_mut().insert(header::CONTENT_DISPOSITION, value); } response } /// A source archive, streamed from `git archive` as it's made, in a download slot. Its size /// isn't known until it's done, so it goes out chunked. async fn archive_response(visitor: Visitor, command: std::process::Command, name: String) -> 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 { return StatusCode::INTERNAL_SERVER_ERROR.into_response(); }; // Every gzip stream starts with a 10-byte header. Waiting for it means a git that fails at // once (an unreadable object, say) is an error response, not a cut-off download. let Ok(prefix) = output.prefix(10).await else { return StatusCode::INTERNAL_SERVER_ERROR.into_response(); }; let body = output.body(prefix, None, permit, std::time::Duration::from_secs(300)); let disposition = format!("attachment; filename=\"{name}\""); ( RAW_SECURITY, [(header::CONTENT_TYPE, "application/gzip"), (header::CONTENT_DISPOSITION, disposition.as_str())], body, ) .into_response() } /// 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(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 || { let _permit = permit; let started = Instant::now(); let view = f(); if started.elapsed() >= gitv_core::GIT_TIMEOUT { View::Busy } else { view } }; match tokio::task::spawn_blocking(work).await { Ok(view) => view.response(visitor).await, Err(error) => { eprintln!("gitv-web: a page failed to render: {error}"); html(StatusCode::INTERNAL_SERVER_ERROR, view_failed(visitor.signed_in)) } } } /// A repository page: `/{owner}/{name}` (which redirects to its files) or /// `/{owner}/{name}/{view}`. async fn repository_page( Path(mut segments): Path>, RawQuery(query): RawQuery, Extension(signed_in): Extension, client: Client, ) -> Response { let owner = segments.remove("owner").unwrap_or_default(); let name = segments.remove("name").unwrap_or_default(); let view = segments.remove("view"); blocking(Visitor { client, signed_in }, move || { route(&owner, &name, view.as_deref(), &parse_query(query.as_deref()), signed_in) }) .await } fn main() -> std::process::ExitCode { let outcome = match Cli::parse().action { Action::Serve { port } => serve(port), Action::Setup { user, force } => setup::setup(user.as_deref(), force).map_err(|e| e.to_string()), Action::Password => setup::change_password_at_terminal(), }; match outcome { Ok(()) => std::process::ExitCode::SUCCESS, Err(error) => { eprintln!("gitv-web: {error}"); std::process::ExitCode::FAILURE } } } fn serve(port: u16) -> Result<(), String> { let config = gitv_core::config::load()?; let runtime = tokio::runtime::Builder::new_multi_thread().enable_all().build().map_err(|e| e.to_string())?; runtime.block_on(async { // Load the syntax definitions now rather than on the first visitor's request. tokio::task::spawn_blocking(render::warm_up); let login = login::Login::new(); // Anyone may load these exact paths: the sign-in page and what it needs to look right. let mut public = Router::new().route("/style.css", get(|| async { stylesheet() })); for (path, kind, data) in ASSETS { public = public.route(path, get(move || async move { static_file(kind, data) })); } let public = public.route( "/login", get(login::sign_in_form).post(login::sign_in).layer(DefaultBodyLimit::max(login::FORM_LIMIT)), ); // Account actions and unmatched paths require a session. let private = Router::new() .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 { missing(true) }) .layer(axum::middleware::from_fn_with_state(Arc::clone(&login), login::require_login)); let browse = Router::new() .route( "/", get(|Extension(user): Extension, client: Client, RawQuery(query): RawQuery| { blocking(Visitor { client, signed_in: user }, move || { view_index(user, &parse_query(query.as_deref())) }) }), ) .route("/{owner}/{name}", get(repository_page)) .route("/{owner}/{name}/{view}", get(repository_page)) .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}"))?; // Print the bound address (not the requested port), so `--port 0` works for tests. let address = listener.local_addr().map_err(|e| e.to_string())?; println!( "gitv-web listening on http://{address} (repos: {}; host {} from {})", repos_root().display(), config.host, config.host_source ); // Connection details let sign-in throttle each client separately. let app = app.into_make_service_with_connect_info::(); axum::serve(listener, app).with_graceful_shutdown(shutdown_requested()).await.map_err(|e| e.to_string())?; eprintln!("gitv-web: stopped"); Ok(()) }) } /// Resolves when systemd (SIGTERM) or a terminal (Ctrl-C) asks the server to stop. From then /// on it takes no new connections, and stops once the requests in progress (clones and /// downloads included) have finished, or systemd's stop timeout runs out. async fn shutdown_requested() { let terminate = async { match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) { Ok(mut signal) => { signal.recv().await; } Err(error) => { eprintln!("gitv-web: can't watch for SIGTERM, so it will stop at once: {error}"); std::future::pending::<()>().await; } } }; tokio::select! { () = terminate => {} _ = tokio::signal::ctrl_c() => {} } eprintln!("gitv-web: stopping; finishing requests in progress"); } #[cfg(test)] mod tests { use super::*; #[tokio::test] 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(held); // A render that fails is a server error, not a missing page. let failed = blocking(visitor, || panic!("a render bug")).await; assert_eq!(failed.status(), StatusCode::INTERNAL_SERVER_ERROR); assert_eq!(blocking(visitor, || View::Html(String::new())).await.status(), StatusCode::OK); } }