OXYGENHUB

Coverage / crates/hub/src/lib.rs 87.3%

247 of 283 lines run, 42 of 96 functions · run #517 on main · run missed

1
//! OxygenHub: a forge for Oxygen repositories (`docs/spec.md`).
2
//!
3
//! One process, or several sharing a database: an axum router serving
4
//! pages, the JSON API and the wire protocol (the web role); the background
5
//! tasks (the worker role, singletons under a leader lock: docs/roles.md);
6
//! SQLite or PostgreSQL for hub state; repositories as bare Oxygen stores.
7
8
pub mod api;
9
pub mod apt;
10
pub mod assistants;
11
pub mod auth;
12
pub mod autoland;
13
pub mod backups;
14
pub mod bus;
15
pub mod config;
16
pub mod coverage;
17
pub mod db;
18
pub mod diffusion;
19
pub mod drops;
20
pub mod events;
21
pub mod flow;
22
pub mod headers;
23
pub mod history_scan;
24
pub mod hooks;
25
pub mod images;
26
pub mod insights;
27
pub mod junit;
28
pub mod keyless;
29
pub mod keys;
30
pub mod leader;
31
pub mod levels;
32
pub mod live;
33
pub mod mail;
34
pub mod maintenance;
35
pub mod metrics;
36
pub mod mirror;
37
pub mod net;
38
pub mod notify;
39
pub mod oidc;
40
pub mod protocol;
41
pub mod provenance;
42
pub mod push;
43
pub mod push_protection;
44
pub mod queue;
45
pub mod render;
46
pub mod reports;
47
pub mod repos;
48
pub mod runner_updates;
49
pub mod secrets;
50
pub mod setup;
51
pub mod shutdown;
52
pub mod signin;
53
pub mod social;
54
pub mod storage;
55
pub mod swarm;
56
pub mod tags;
57
pub mod terraform;
58
pub mod throttle;
59
pub mod tlog;
60
pub mod variables;
61
pub mod web;
62
pub mod wiki;
63
64
use crate::config::Config;
65
use crate::repos::Repos;
66
use std::sync::Arc;
67
68
/// Everything a request handler can reach.
69
pub struct App {
70
    pub config: Config,
71
    pub db: db::Pool,
72
    pub repos: Arc<Repos>,
73
    /// Wikis, one Oxygen repository per repository (hub spec §6.11).
74
    pub wikis: Arc<Repos>,
75
    pub server: Arc<oxy_server::Server>,
76
    pub hub_key: keys::HubKey,
77
    pub cookie_key: auth::CookieKey,
78
    /// Seals AI assistants' tokens at rest (hub spec §13.4).
79
    pub assistant_key: assistants::SecretKey,
80
    /// Seals Flow secrets at rest (hub spec §13.2, #107).
81
    pub secret_key: assistants::SecretKey,
82
    /// The OIDC issuer for jobs (hub spec §13.5), made on first use.
83
    pub oidc: tokio::sync::OnceCell<oidc::Issuer>,
84
    /// Which assistants are answering which proposals, and recent calls
85
    /// per repository (hub spec §13.4).
86
    pub assistant_gate: std::sync::Mutex<assistants::Gate>,
87
    /// Failed sign-ins and the like, per account and address (oxygenhub#221).
88
    pub throttle: std::sync::Mutex<throttle::Throttle>,
89
    /// Events for live pages and workers, here and in the other processes
90
    /// sharing the database (docs/roles.md, #273).
91
    pub bus: bus::Bus,
92
    /// Who is resolving which conflict together (hub spec §6.10).
93
    pub rooms: Arc<live::Rooms>,
94
    /// Outgoing mail: hub.toml's `[email]`, overridden by what the admin
95
    /// page saved (#101).
96
    pub mail: std::sync::RwLock<config::Email>,
97
    /// The image swarm's tracker (oxygenhub#144).
98
    pub swarm: swarm::Tracker,
99
    pub started: std::time::Instant,
100
    /// The transparency log (#238).
101
    pub tlog: Arc<tlog::Log>,
102
    /// What this process does: web, worker or both (docs/roles.md, #272).
103
    pub roles: config::Roles,
104
    /// The background tasks started here and the leader locks held (#272).
105
    pub leader: leader::Leader,
106
}
107
108
impl App {
109
    /// The rootfs images this hub keeps for runners (oxygenflow#39).
11031×
    pub fn images(&self) -> images::Store {
11131×
        images::Store::new(&self.config.data)
11231×
    }
113
114
    /// The OIDC issuer, its key loaded or made the first time it is asked for.
11526×
    pub async fn oidc(&self) -> anyhow::Result<&oidc::Issuer> {
11626×
        let keys = self.config.keys_dir();
11726×
        self.oidc.get_or_try_init(|| async move { tokio::task::spawn_blocking(move || oidc::Issuer::load_or_create(&keys)).await? }).await
11826×
    }
119
}
120
121
pub type Shared = Arc<App>;
122
123
/// Open the data directory and build the application state. `init` must
124
/// have run once; `serve` and the tests call this.
125201×
pub async fn build(config: Config) -> anyhow::Result<Shared> {
126201×
    let roles = config.roles()?;
127
    // Images of this hub's file pages render as their raw files.
128200×
    render::markdown::set_origin(config.base_url());
129200×
    std::fs::create_dir_all(config.repos_dir())?;
130200×
    let db = db::open(&config).await?;
131200×
    let repos = Arc::new(Repos::new(config.repos_dir()));
132200×
    let wikis = Arc::new(Repos::new(config.data.join("wikis")));
133200×
    let hub_key = keys::ensure_identity(&config.keys_dir(), &config.site.name, config.base_url())?;
134200×
    let cookie_key = auth::CookieKey::load_or_create(&config.keys_dir())?;
135200×
    let assistant_key = assistants::SecretKey::load_or_create(&config.keys_dir())?;
136200×
    let secret_key = assistants::SecretKey::load_or_create_named(&config.keys_dir(), "secrets.key")?;
137200×
    let backend = protocol::HubBackend::new(
138200×
        repos.clone(),
139200×
        wikis.clone(),
140200×
        db.clone(),
141200×
        config.auth.push_tokens.clone(),
142200×
        tokio::runtime::Handle::current(),
143
    )
144200×
    .with_acceptor(hub_key.identity.clone(), keys::load_secret(&config.keys_dir())?.1)
145200×
    .with_scan_budget(push_protection::Budget {
146200×
        bytes: config.limits.scan_limit.0,
147200×
        file: config.limits.scan_file_limit.0,
148200×
        time: std::time::Duration::from_millis(config.limits.scan_time_ms),
149200×
    });
150200×
    let slot = backend.app_slot();
151200×
    let server = oxy_server::Server::new(backend);
152200×
    let mail = mail::load(&db, &config.email).await;
153
    // The web role appends to the log; a worker alone only reads it (#272).
154200×
    let (tlog_dir, origin) = (config.data.join("tlog"), tlog::origin_of(config.base_url()));
155200×
    let tlog = Arc::new(if roles.web { tlog::Log::open(&tlog_dir, &origin)? } else { tlog::Log::open_reader(&tlog_dir, &origin)? });
156200×
    tlog.configure(&config.tlog)?;
157200×
    let app = Arc::new(App {
158200×
        mail: std::sync::RwLock::new(mail),
159200×
        config,
160200×
        db,
161200×
        repos,
162200×
        wikis,
163200×
        server,
164200×
        hub_key,
165200×
        cookie_key,
166200×
        assistant_key,
167200×
        secret_key,
168200×
        oidc: tokio::sync::OnceCell::new(),
169200×
        assistant_gate: std::sync::Mutex::new(assistants::Gate::default()),
170200×
        throttle: std::sync::Mutex::new(throttle::Throttle::default()),
171200×
        bus: bus::Bus::default(),
172200×
        rooms: Arc::new(live::Rooms::default()),
173200×
        swarm: Default::default(),
174200×
        started: std::time::Instant::now(),
175200×
        tlog,
176200×
        roles,
177200×
        leader: leader::Leader::default(),
178200×
    });
179200×
    *slot.lock().unwrap() = Some(Arc::downgrade(&app));
180200×
    bus::start(&app).await?;
181200×
    storage::load(&app).await?;
182200×
    coverage::load(&app).await?;
183200×
    junit::load(&app).await?;
184200×
    reports::load(&app).await?;
185200×
    start_background(&app);
186200×
    setup::ensure(&app).await?;
187200×
    Ok(app)
188201×
}
189
190
/// Start this process's background tasks (docs/roles.md, #272). The
191
/// worker role's are singletons across every process sharing the database,
192
/// each run under its leader lock; the transparency log's checkpointer goes
193
/// with the web role, which appends to the log, and is a singleton too.
194200×
fn start_background(app: &Shared) {
195200×
    if app.roles.web {
196199×
        // The checkpointer signs the log this process appends to (#238).
197199×
        leader::run(app, "tlog.checkpointer", tlog::checkpointer);
198199×
    }
199200×
    if !app.roles.worker {
2002×
        return;
201198×
    }
202198×
    leader::run(app, "hooks.worker", hooks::worker);
203198×
    leader::run(app, "flow.reaper", flow::reaper);
204198×
    leader::run(app, "flow.scheduler", flow::scheduler);
205198×
    leader::run(app, "flow.placement", flow::placement);
206198×
    leader::run(app, "maintenance.nightly", maintenance::nightly);
207198×
    leader::run(app, "projects.archiver", maintenance::archiver);
208198×
    leader::run(app, "backups.scheduler", backups::scheduler);
209
    // The reverse pin index for repositories pushed before it existed (#148):
210
    // once, by whichever worker leads it first (idempotent if run again).
211396×
    leader::run(app, "diffusion.backfill", |app| async move { diffusion::backfill(&app).await });
212
    // Mend the pin index and the bumps it drives (oxygenhub#210).
213198×
    leader::run(app, "diffusion.reconciler", diffusion::reconciler);
214
    // Each repository's history scanned for secrets (#277), a budget at a
215
    // time, at low priority.
216198×
    leader::run(app, "secrets.history_scan", history_scan::worker);
217
    // The durable work queue (#276): every worker takes its due items.
218198×
    app.leader.note("queue.worker");
219198×
    tokio::spawn(queue::worker(app.clone()));
220
    // What each image is for, read or learned once (oxygenhub#173): safe
221
    // in every worker, so it takes no lock.
222198×
    app.leader.note("images.learn_archs");
223198×
    tokio::spawn({
224198×
        let app = app.clone();
225198×
        async move {
226198×
            match images::learn_archs(&app).await {
227197×
                Ok(n) if n > 0 => tracing::info!(images = n, "read the architecture of kept images"),
228197×
                Ok(_) => {}
2290×
                Err(e) => tracing::warn!(error = %e, "learning image architectures"),
230
            }
231197×
        }
232
    });
233200×
}
234
235
/// The router this process serves: everything for the web role; for a
236
/// worker alone, `/health` and `/metrics`, so it can be watched.
2372769×
pub fn router(app: Shared) -> axum::Router {
2382769×
    if !app.roles.web {
2398×
        return worker_router(app);
2402761×
    }
2412761×
    full_router(app)
2422769×
}
243
244
/// What a worker-only process answers: its health and its metrics.
2458×
fn worker_router(app: Shared) -> axum::Router {
246
    use axum::routing::get;
2478×
    let hsts = headers::hsts(app.config.base_url(), app.config.server.hsts_max_age);
2488×
    axum::Router::new()
2498×
        .route("/health", get(web::home::health))
2508×
        .route("/metrics", get(metrics::metrics))
2518×
        .with_state(app)
2528×
        .layer(axum::middleware::from_fn_with_state(hsts, headers::security_headers))
2538×
}
254
255
/// The full router: pages, API, protocol and static assets.
2562761×
fn full_router(app: Shared) -> axum::Router {
2572761×
    let https = app_https(&app);
2582761×
    let hsts = headers::hsts(app.config.base_url(), app.config.server.hsts_max_age);
2592761×
    web::router(app.clone())
2602761×
        .layer(axum::middleware::from_fn_with_state(app, agent_requests))
2612761×
        .layer(axum::middleware::from_fn(private_pages))
2622761×
        .layer(axum::middleware::from_fn(slow_requests))
2632761×
        .layer(axum::middleware::from_fn_with_state(https, https_only))
2642761×
        .layer(axum::middleware::from_fn_with_state(hsts, headers::security_headers))
2652761×
}
266
267
/// The site's https address, when it has one: what [`https_only`] redirects to.
2682761×
fn app_https(app: &Shared) -> Option<String> {
2692761×
    let base = app.config.base_url();
2702761×
    base.starts_with("https://").then(|| base.trim_end_matches('/').to_string())
2712761×
}
272
273
/// The scheme a proxy in front of the hub says the visitor used
274
/// (`X-Forwarded-Proto`, else Cloudflare's `CF-Visitor`); `None` for a
275
/// request made to the hub directly (runners and tools on its host).
2766×
fn forwarded_scheme(headers: &axum::http::HeaderMap) -> Option<String> {
2776×
    if let Some(p) = headers.get("x-forwarded-proto").and_then(|v| v.to_str().ok()) {
2784×
        return p.split(',').next().map(|s| s.trim().to_ascii_lowercase());
2792×
    }
2802×
    let visitor = headers.get("cf-visitor").and_then(|v| v.to_str().ok())?;
2811×
    serde_json::from_str::<serde_json::Value>(visitor).ok()?["scheme"].as_str().map(str::to_ascii_lowercase)
2826×
}
283
284
/// HTTPS only (oxygenhub#218): on a site whose address is https, a request
285
/// a proxy reports as plain http is sent to the https address (GET and
286
/// HEAD) or refused (anything else, so a form or a password is never taken
287
/// over http). Requests made to the hub directly carry no such report and
288
/// are untouched.
2893770×
async fn https_only(
2903770×
    axum::extract::State(https): axum::extract::State<Option<String>>,
2913770×
    req: axum::extract::Request,
2923770×
    next: axum::middleware::Next,
2933770×
) -> axum::response::Response {
294
    use axum::response::IntoResponse;
2953770×
    let Some(base) = https else { return next.run(req).await };
2966×
    if forwarded_scheme(req.headers()).as_deref() != Some("http") {
2974×
        return next.run(req).await;
2982×
    }
2992×
    let to = format!("{base}{}", req.uri().path_and_query().map(|p| p.as_str()).unwrap_or("/"));
3002×
    if matches!(*req.method(), axum::http::Method::GET | axum::http::Method::HEAD) {
3011×
        return axum::response::Redirect::permanent(&to).into_response();
3021×
    }
3031×
    (axum::http::StatusCode::BAD_REQUEST, format!("This site takes requests over HTTPS only: send it to {to}\n")).into_response()
3043770×
}
305
306
/// A request made with a token its owner marked as an agent's runs with
307
/// that token's name in [`notify::AGENT`], so what the agent does is told
308
/// to its owner (oxygenhub#183).
3093768×
async fn agent_requests(
3103768×
    axum::extract::State(app): axum::extract::State<Shared>,
3113768×
    req: axum::extract::Request,
3123768×
    next: axum::middleware::Next,
3133768×
) -> axum::response::Response {
3143768×
    let token = req
3153768×
        .headers()
3163768×
        .get(axum::http::header::AUTHORIZATION)
3173768×
        .and_then(|v| v.to_str().ok())
3183768×
        .and_then(|v| v.strip_prefix("Bearer "))
3193768×
        .map(|t| t.trim().to_string());
3203768×
    let agent = match token {
321
        // A keyless agent's grant token (#253) is always an agent's.
3221790×
        Some(t) if t.starts_with(keyless::GRANT_TOKEN_PREFIX) => db::accounts::agent_grant_by_token(&app.db, &auth::token_hash(&t))
32320×
            .await
32420×
            .ok()
32520×
            .flatten()
32620×
            .filter(|g| g.live(db::now_ms()))
32720×
            .map(|g| g.agent),
3281770×
        Some(t) => db::accounts::token_by_hash(&app.db, &auth::token_hash(&t)).await.ok().flatten().filter(|t| t.agent).map(|t| t.name),
3291978×
        None => None,
330
    };
3313768×
    notify::AGENT.scope(agent, next.run(req)).await
3323768×
}
333
334
/// Requests slower than this are logged, with their path (#145).
335
const SLOW: std::time::Duration = std::time::Duration::from_secs(2);
336
337
/// Log a slow request's method, path and time, so a slow page can be
338
/// found afterwards. Never the query, which may hold a token.
3393768×
async fn slow_requests(req: axum::extract::Request, next: axum::middleware::Next) -> axum::response::Response {
3403768×
    let (method, path) = (req.method().clone(), req.uri().path().to_string());
3413768×
    let start = std::time::Instant::now();
3423768×
    let res = next.run(req).await;
3433768×
    let took = start.elapsed();
3443768×
    metrics::observe(method.as_str(), &path, res.status().as_u16(), took.as_secs_f64());
3453768×
    if took >= SLOW {
3464×
        tracing::warn!("slow request: {method} {path} took {:.1} s ({})", took.as_secs_f64(), res.status().as_u16());
3473764×
    }
3483768×
    res
3493768×
}
350
351
/// A page for a signed-in viewer is theirs alone: it may list private
352
/// repositories, and the dashboard's sky carries their activity (#157). An
353
/// HTML response to a request with a session cookie, which has not said
354
/// how to cache itself, says `private, no-store`, so no shared cache (a
355
/// proxy or a CDN in front of the hub) ever serves it to anyone else.
3563768×
async fn private_pages(req: axum::extract::Request, next: axum::middleware::Next) -> axum::response::Response {
357
    use axum::http::header;
3583768×
    let signed_in = req
3593768×
        .headers()
3603768×
        .get_all(header::COOKIE)
3613768×
        .iter()
3623768×
        .filter_map(|v| v.to_str().ok())
3633768×
        .any(|c| c.split(';').any(|kv| kv.trim_start().starts_with("oxyhub=")));
3643768×
    let mut res = next.run(req).await;
3653768×
    let html = res.headers().get(header::CONTENT_TYPE).and_then(|v| v.to_str().ok()).is_some_and(|t| t.starts_with("text/html"));
3663768×
    if signed_in && html && !res.headers().contains_key(header::CACHE_CONTROL) {
367855×
        res.headers_mut().insert(header::CACHE_CONTROL, header::HeaderValue::from_static("private, no-store"));
3682913×
    }
3693768×
    res
3703768×
}
371
372
/// Serve on the configured addresses until the process is told to stop.
3731×
pub async fn serve(app: Shared) -> anyhow::Result<()> {
3741×
    let router = router(app.clone());
3751×
    let http = app.config.bind_addr()?;
3761×
    let https = app.config.tls_bind_addr()?;
3771×
    if http.is_none() && https.is_none() && app.roles.web {
3780×
        anyhow::bail!("nothing to bind: set server.bind or server.tls_bind");
3791×
    }
3801×
    tracing::info!("roles: {}", app.roles.names().join(", "));
381
    // Installed first: from here a SIGTERM drains rather than kills.
3821×
    let signal = shutdown::on_signal()?;
3831×
    let mut tasks = tokio::task::JoinSet::new();
3841×
    if let Some(addr) = http {
3851×
        let listener = match shutdown::systemd_listener() {
3860×
            Some(l) => {
3870×
                tracing::info!("http on the socket systemd holds ({})", l.local_addr().map(|a| a.to_string()).unwrap_or_default());
3880×
                tokio::net::TcpListener::from_std(l)?
389
            }
390
            None => {
3911×
                tracing::info!("http on {addr}");
3921×
                tokio::net::TcpListener::bind(addr).await?
393
            }
394
        };
3951×
        let r = router.clone();
3961×
        tasks.spawn(async move {
3971×
            axum::serve(listener, r.into_make_service_with_connect_info::<std::net::SocketAddr>())
3981×
                .with_graceful_shutdown(shutdown::stopping())
3991×
                .await
4001×
                .map_err(anyhow::Error::from)
4011×
        });
4020×
    }
4031×
    if let Some(addr) = https {
4040×
        let _ = rustls::crypto::ring::default_provider().install_default();
4050×
        let tls = axum_server::tls_rustls::RustlsConfig::from_pem_file(app.config.tls_cert(), app.config.tls_key())
4060×
            .await
4070×
            .map_err(|e| anyhow::anyhow!("loading TLS files: {e}"))?;
4080×
        tracing::info!("https on {addr}");
4090×
        let r = router.clone();
4100×
        let handle = axum_server::Handle::new();
4110×
        let draining = handle.clone();
4120×
        tokio::spawn(async move {
4130×
            shutdown::stopping().await;
4140×
            draining.graceful_shutdown(Some(shutdown::DRAIN));
4150×
        });
4160×
        tasks.spawn(async move {
4170×
            axum_server::bind_rustls(addr, tls)
4180×
                .handle(handle)
4190×
                .serve(r.into_make_service_with_connect_info::<std::net::SocketAddr>())
4200×
                .await
4210×
                .map_err(anyhow::Error::from)
4220×
        });
4231×
    }
4241×
    tokio::select! {
425
        // A worker with no address to serve on runs until it is stopped.
4261×
        r = tasks.join_next(), if !tasks.is_empty() => { r.transpose()?.transpose()?; Ok(()) }
4271×
        _ = signal => {
428
            // The servers stop taking connections and finish what they
429
            // have; whatever is still running after DRAIN is cut off.
4300×
            let drained = tokio::time::timeout(shutdown::DRAIN, async { while tasks.join_next().await.is_some() {} }).await;
4310×
            if drained.is_err() {
4320×
                tracing::warn!("requests still running after {} s: stopping anyway", shutdown::DRAIN.as_secs());
4330×
            }
4340×
            tracing::info!("stopped");
4350×
            Ok(())
436
        }
437
    }
4381×
}