GITv
master
main.rs385 lines, 16.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
//! 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##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect width="32" height="32" rx="8" fill="#0f6b5f"/><g fill="none" stroke="#fff" 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>"##;

/// 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<String> = 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<String>,
        /// 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<std::process::Command>, usize, Vec<u8>),
    /// Pinned `git archive` command, and the download's file name.
    Archive(Box<std::process::Command>, 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<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(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 {
        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<std::collections::HashMap<String, String>>,
    RawQuery(query): RawQuery,
    Extension(signed_in): Extension<bool>,
    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<bool>, 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::<std::net::SocketAddr>();
        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);
    }
}