OXYGENHUB

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

247 of 283 lines run, 42 of 96 functions · run #523 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 starter;
55
pub mod storage;
56
pub mod swarm;
57
pub mod tags;
58
pub mod terraform;
59
pub mod throttle;
60
pub mod tlog;
61
pub mod variables;
62
pub mod web;
63
pub mod wiki;
64
65
use crate::config::Config;
66
use crate::repos::Repos;
67
use std::sync::Arc;
68
69
/// Everything a request handler can reach.
70
pub struct App {
71
    pub config: Config,
72
    pub db: db::Pool,
73
    pub repos: Arc<Repos>,
74
    /// Wikis, one Oxygen repository per repository (hub spec §6.11).
75
    pub wikis: Arc<Repos>,
76
    pub server: Arc<oxy_server::Server>,
77
    pub hub_key: keys::HubKey,
78
    pub cookie_key: auth::CookieKey,
79
    /// Seals AI assistants' tokens at rest (hub spec §13.4).
80
    pub assistant_key: assistants::SecretKey,
81
    /// Seals Flow secrets at rest (hub spec §13.2, #107).
82
    pub secret_key: assistants::SecretKey,
83
    /// The OIDC issuer for jobs (hub spec §13.5), made on first use.
84
    pub oidc: tokio::sync::OnceCell<oidc::Issuer>,
85
    /// Which assistants are answering which proposals, and recent calls
86
    /// per repository (hub spec §13.4).
87
    pub assistant_gate: std::sync::Mutex<assistants::Gate>,
88
    /// Failed sign-ins and the like, per account and address (oxygenhub#221).
89
    pub throttle: std::sync::Mutex<throttle::Throttle>,
90
    /// Events for live pages and workers, here and in the other processes
91
    /// sharing the database (docs/roles.md, #273).
92
    pub bus: bus::Bus,
93
    /// Who is resolving which conflict together (hub spec §6.10).
94
    pub rooms: Arc<live::Rooms>,
95
    /// Outgoing mail: hub.toml's `[email]`, overridden by what the admin
96
    /// page saved (#101).
97
    pub mail: std::sync::RwLock<config::Email>,
98
    /// The image swarm's tracker (oxygenhub#144).
99
    pub swarm: swarm::Tracker,
100
    pub started: std::time::Instant,
101
    /// The transparency log (#238).
102
    pub tlog: Arc<tlog::Log>,
103
    /// What this process does: web, worker or both (docs/roles.md, #272).
104
    pub roles: config::Roles,
105
    /// The background tasks started here and the leader locks held (#272).
106
    pub leader: leader::Leader,
107
}
108
109
impl App {
110
    /// The rootfs images this hub keeps for runners (oxygenflow#39).
11141×
    pub fn images(&self) -> images::Store {
11241×
        images::Store::new(&self.config.data)
11341×
    }
114
115
    /// The OIDC issuer, its key loaded or made the first time it is asked for.
11626×
    pub async fn oidc(&self) -> anyhow::Result<&oidc::Issuer> {
11726×
        let keys = self.config.keys_dir();
11826×
        self.oidc.get_or_try_init(|| async move { tokio::task::spawn_blocking(move || oidc::Issuer::load_or_create(&keys)).await? }).await
11926×
    }
120
}
121
122
pub type Shared = Arc<App>;
123
124
/// Open the data directory and build the application state. `init` must
125
/// have run once; `serve` and the tests call this.
126202×
pub async fn build(config: Config) -> anyhow::Result<Shared> {
127202×
    let roles = config.roles()?;
128
    // Images of this hub's file pages render as their raw files.
129201×
    render::markdown::set_origin(config.base_url());
130201×
    std::fs::create_dir_all(config.repos_dir())?;
131201×
    let db = db::open(&config).await?;
132201×
    let repos = Arc::new(Repos::new(config.repos_dir()));
133201×
    let wikis = Arc::new(Repos::new(config.data.join("wikis")));
134201×
    let hub_key = keys::ensure_identity(&config.keys_dir(), &config.site.name, config.base_url())?;
135201×
    let cookie_key = auth::CookieKey::load_or_create(&config.keys_dir())?;
136201×
    let assistant_key = assistants::SecretKey::load_or_create(&config.keys_dir())?;
137201×
    let secret_key = assistants::SecretKey::load_or_create_named(&config.keys_dir(), "secrets.key")?;
138201×
    let backend = protocol::HubBackend::new(
139201×
        repos.clone(),
140201×
        wikis.clone(),
141201×
        db.clone(),
142201×
        config.auth.push_tokens.clone(),
143201×
        tokio::runtime::Handle::current(),
144
    )
145201×
    .with_acceptor(hub_key.identity.clone(), keys::load_secret(&config.keys_dir())?.1)
146201×
    .with_scan_budget(push_protection::Budget {
147201×
        bytes: config.limits.scan_limit.0,
148201×
        file: config.limits.scan_file_limit.0,
149201×
        time: std::time::Duration::from_millis(config.limits.scan_time_ms),
150201×
    });
151201×
    let slot = backend.app_slot();
152201×
    let server = oxy_server::Server::new(backend);
153201×
    let mail = mail::load(&db, &config.email).await;
154
    // The web role appends to the log; a worker alone only reads it (#272).
155201×
    let (tlog_dir, origin) = (config.data.join("tlog"), tlog::origin_of(config.base_url()));
156201×
    let tlog = Arc::new(if roles.web { tlog::Log::open(&tlog_dir, &origin)? } else { tlog::Log::open_reader(&tlog_dir, &origin)? });
157201×
    tlog.configure(&config.tlog)?;
158201×
    let app = Arc::new(App {
159201×
        mail: std::sync::RwLock::new(mail),
160201×
        config,
161201×
        db,
162201×
        repos,
163201×
        wikis,
164201×
        server,
165201×
        hub_key,
166201×
        cookie_key,
167201×
        assistant_key,
168201×
        secret_key,
169201×
        oidc: tokio::sync::OnceCell::new(),
170201×
        assistant_gate: std::sync::Mutex::new(assistants::Gate::default()),
171201×
        throttle: std::sync::Mutex::new(throttle::Throttle::default()),
172201×
        bus: bus::Bus::default(),
173201×
        rooms: Arc::new(live::Rooms::default()),
174201×
        swarm: Default::default(),
175201×
        started: std::time::Instant::now(),
176201×
        tlog,
177201×
        roles,
178201×
        leader: leader::Leader::default(),
179201×
    });
180201×
    *slot.lock().unwrap() = Some(Arc::downgrade(&app));
181201×
    bus::start(&app).await?;
182201×
    storage::load(&app).await?;
183201×
    coverage::load(&app).await?;
184201×
    junit::load(&app).await?;
185201×
    reports::load(&app).await?;
186201×
    start_background(&app);
187201×
    setup::ensure(&app).await?;
188201×
    Ok(app)
189202×
}
190
191
/// Start this process's background tasks (docs/roles.md, #272). The
192
/// worker role's are singletons across every process sharing the database,
193
/// each run under its leader lock; the transparency log's checkpointer goes
194
/// with the web role, which appends to the log, and is a singleton too.
195201×
fn start_background(app: &Shared) {
196201×
    if app.roles.web {
197200×
        // The checkpointer signs the log this process appends to (#238).
198200×
        leader::run(app, "tlog.checkpointer", tlog::checkpointer);
199200×
    }
200201×
    if !app.roles.worker {
2012×
        return;
202199×
    }
203199×
    leader::run(app, "hooks.worker", hooks::worker);
204199×
    leader::run(app, "flow.reaper", flow::reaper);
205199×
    leader::run(app, "flow.scheduler", flow::scheduler);
206199×
    leader::run(app, "flow.placement", flow::placement);
207199×
    leader::run(app, "maintenance.nightly", maintenance::nightly);
208199×
    leader::run(app, "projects.archiver", maintenance::archiver);
209199×
    leader::run(app, "backups.scheduler", backups::scheduler);
210
    // The reverse pin index for repositories pushed before it existed (#148):
211
    // once, by whichever worker leads it first (idempotent if run again).
212397×
    leader::run(app, "diffusion.backfill", |app| async move { diffusion::backfill(&app).await });
213
    // Mend the pin index and the bumps it drives (oxygenhub#210).
214199×
    leader::run(app, "diffusion.reconciler", diffusion::reconciler);
215
    // Each repository's history scanned for secrets (#277), a budget at a
216
    // time, at low priority.
217199×
    leader::run(app, "secrets.history_scan", history_scan::worker);
218
    // The durable work queue (#276): every worker takes its due items.
219199×
    app.leader.note("queue.worker");
220199×
    tokio::spawn(queue::worker(app.clone()));
221
    // What each image is for, read or learned once (oxygenhub#173): safe
222
    // in every worker, so it takes no lock.
223199×
    app.leader.note("images.learn_archs");
224199×
    tokio::spawn({
225199×
        let app = app.clone();
226199×
        async move {
227199×
            match images::learn_archs(&app).await {
228198×
                Ok(n) if n > 0 => tracing::info!(images = n, "read the architecture of kept images"),
229198×
                Ok(_) => {}
2300×
                Err(e) => tracing::warn!(error = %e, "learning image architectures"),
231
            }
232198×
        }
233
    });
234201×
}
235
236
/// The router this process serves: everything for the web role; for a
237
/// worker alone, `/health` and `/metrics`, so it can be watched.
2382822×
pub fn router(app: Shared) -> axum::Router {
2392822×
    if !app.roles.web {
2408×
        return worker_router(app);
2412814×
    }
2422814×
    full_router(app)
2432822×
}
244
245
/// What a worker-only process answers: its health and its metrics.
2468×
fn worker_router(app: Shared) -> axum::Router {
247
    use axum::routing::get;
2488×
    let hsts = headers::hsts(app.config.base_url(), app.config.server.hsts_max_age);
2498×
    axum::Router::new()
2508×
        .route("/health", get(web::home::health))
2518×
        .route("/metrics", get(metrics::metrics))
2528×
        .with_state(app)
2538×
        .layer(axum::middleware::from_fn_with_state(hsts, headers::security_headers))
2548×
}
255
256
/// The full router: pages, API, protocol and static assets.
2572814×
fn full_router(app: Shared) -> axum::Router {
2582814×
    let https = app_https(&app);
2592814×
    let hsts = headers::hsts(app.config.base_url(), app.config.server.hsts_max_age);
2602814×
    web::router(app.clone())
2612814×
        .layer(axum::middleware::from_fn_with_state(app, agent_requests))
2622814×
        .layer(axum::middleware::from_fn(private_pages))
2632814×
        .layer(axum::middleware::from_fn(slow_requests))
2642814×
        .layer(axum::middleware::from_fn_with_state(https, https_only))
2652814×
        .layer(axum::middleware::from_fn_with_state(hsts, headers::security_headers))
2662814×
}
267
268
/// The site's https address, when it has one: what [`https_only`] redirects to.
2692814×
fn app_https(app: &Shared) -> Option<String> {
2702814×
    let base = app.config.base_url();
2712814×
    base.starts_with("https://").then(|| base.trim_end_matches('/').to_string())
2722814×
}
273
274
/// The scheme a proxy in front of the hub says the visitor used
275
/// (`X-Forwarded-Proto`, else Cloudflare's `CF-Visitor`); `None` for a
276
/// request made to the hub directly (runners and tools on its host).
2776×
fn forwarded_scheme(headers: &axum::http::HeaderMap) -> Option<String> {
2786×
    if let Some(p) = headers.get("x-forwarded-proto").and_then(|v| v.to_str().ok()) {
2794×
        return p.split(',').next().map(|s| s.trim().to_ascii_lowercase());
2802×
    }
2812×
    let visitor = headers.get("cf-visitor").and_then(|v| v.to_str().ok())?;
2821×
    serde_json::from_str::<serde_json::Value>(visitor).ok()?["scheme"].as_str().map(str::to_ascii_lowercase)
2836×
}
284
285
/// HTTPS only (oxygenhub#218): on a site whose address is https, a request
286
/// a proxy reports as plain http is sent to the https address (GET and
287
/// HEAD) or refused (anything else, so a form or a password is never taken
288
/// over http). Requests made to the hub directly carry no such report and
289
/// are untouched.
2903822×
async fn https_only(
2913822×
    axum::extract::State(https): axum::extract::State<Option<String>>,
2923822×
    req: axum::extract::Request,
2933822×
    next: axum::middleware::Next,
2943822×
) -> axum::response::Response {
295
    use axum::response::IntoResponse;
2963822×
    let Some(base) = https else { return next.run(req).await };
2976×
    if forwarded_scheme(req.headers()).as_deref() != Some("http") {
2984×
        return next.run(req).await;
2992×
    }
3002×
    let to = format!("{base}{}", req.uri().path_and_query().map(|p| p.as_str()).unwrap_or("/"));
3012×
    if matches!(*req.method(), axum::http::Method::GET | axum::http::Method::HEAD) {
3021×
        return axum::response::Redirect::permanent(&to).into_response();
3031×
    }
3041×
    (axum::http::StatusCode::BAD_REQUEST, format!("This site takes requests over HTTPS only: send it to {to}\n")).into_response()
3053822×
}
306
307
/// A request made with a token its owner marked as an agent's runs with
308
/// that token's name in [`notify::AGENT`], so what the agent does is told
309
/// to its owner (oxygenhub#183).
3103820×
async fn agent_requests(
3113820×
    axum::extract::State(app): axum::extract::State<Shared>,
3123820×
    req: axum::extract::Request,
3133820×
    next: axum::middleware::Next,
3143820×
) -> axum::response::Response {
3153820×
    let token = req
3163820×
        .headers()
3173820×
        .get(axum::http::header::AUTHORIZATION)
3183820×
        .and_then(|v| v.to_str().ok())
3193820×
        .and_then(|v| v.strip_prefix("Bearer "))
3203820×
        .map(|t| t.trim().to_string());
3213820×
    let agent = match token {
322
        // A keyless agent's grant token (#253) is always an agent's.
3231816×
        Some(t) if t.starts_with(keyless::GRANT_TOKEN_PREFIX) => db::accounts::agent_grant_by_token(&app.db, &auth::token_hash(&t))
32420×
            .await
32520×
            .ok()
32620×
            .flatten()
32720×
            .filter(|g| g.live(db::now_ms()))
32820×
            .map(|g| g.agent),
3291796×
        Some(t) => db::accounts::token_by_hash(&app.db, &auth::token_hash(&t)).await.ok().flatten().filter(|t| t.agent).map(|t| t.name),
3302004×
        None => None,
331
    };
3323820×
    notify::AGENT.scope(agent, next.run(req)).await
3333820×
}
334
335
/// Requests slower than this are logged, with their path (#145).
336
const SLOW: std::time::Duration = std::time::Duration::from_secs(2);
337
338
/// Log a slow request's method, path and time, so a slow page can be
339
/// found afterwards. Never the query, which may hold a token.
3403820×
async fn slow_requests(req: axum::extract::Request, next: axum::middleware::Next) -> axum::response::Response {
3413820×
    let (method, path) = (req.method().clone(), req.uri().path().to_string());
3423820×
    let start = std::time::Instant::now();
3433820×
    let res = next.run(req).await;
3443820×
    let took = start.elapsed();
3453820×
    metrics::observe(method.as_str(), &path, res.status().as_u16(), took.as_secs_f64());
3463820×
    if took >= SLOW {
3474×
        tracing::warn!("slow request: {method} {path} took {:.1} s ({})", took.as_secs_f64(), res.status().as_u16());
3483816×
    }
3493820×
    res
3503820×
}
351
352
/// A page for a signed-in viewer is theirs alone: it may list private
353
/// repositories, and the dashboard's sky carries their activity (#157). An
354
/// HTML response to a request with a session cookie, which has not said
355
/// how to cache itself, says `private, no-store`, so no shared cache (a
356
/// proxy or a CDN in front of the hub) ever serves it to anyone else.
3573820×
async fn private_pages(req: axum::extract::Request, next: axum::middleware::Next) -> axum::response::Response {
358
    use axum::http::header;
3593820×
    let signed_in = req
3603820×
        .headers()
3613820×
        .get_all(header::COOKIE)
3623820×
        .iter()
3633820×
        .filter_map(|v| v.to_str().ok())
3643820×
        .any(|c| c.split(';').any(|kv| kv.trim_start().starts_with("oxyhub=")));
3653820×
    let mut res = next.run(req).await;
3663820×
    let html = res.headers().get(header::CONTENT_TYPE).and_then(|v| v.to_str().ok()).is_some_and(|t| t.starts_with("text/html"));
3673820×
    if signed_in && html && !res.headers().contains_key(header::CACHE_CONTROL) {
368857×
        res.headers_mut().insert(header::CACHE_CONTROL, header::HeaderValue::from_static("private, no-store"));
3692963×
    }
3703820×
    res
3713820×
}
372
373
/// Serve on the configured addresses until the process is told to stop.
3741×
pub async fn serve(app: Shared) -> anyhow::Result<()> {
3751×
    let router = router(app.clone());
3761×
    let http = app.config.bind_addr()?;
3771×
    let https = app.config.tls_bind_addr()?;
3781×
    if http.is_none() && https.is_none() && app.roles.web {
3790×
        anyhow::bail!("nothing to bind: set server.bind or server.tls_bind");
3801×
    }
3811×
    tracing::info!("roles: {}", app.roles.names().join(", "));
382
    // Installed first: from here a SIGTERM drains rather than kills.
3831×
    let signal = shutdown::on_signal()?;
3841×
    let mut tasks = tokio::task::JoinSet::new();
3851×
    if let Some(addr) = http {
3861×
        let listener = match shutdown::systemd_listener() {
3870×
            Some(l) => {
3880×
                tracing::info!("http on the socket systemd holds ({})", l.local_addr().map(|a| a.to_string()).unwrap_or_default());
3890×
                tokio::net::TcpListener::from_std(l)?
390
            }
391
            None => {
3921×
                tracing::info!("http on {addr}");
3931×
                tokio::net::TcpListener::bind(addr).await?
394
            }
395
        };
3961×
        let r = router.clone();
3971×
        tasks.spawn(async move {
3981×
            axum::serve(listener, r.into_make_service_with_connect_info::<std::net::SocketAddr>())
3991×
                .with_graceful_shutdown(shutdown::stopping())
4001×
                .await
4011×
                .map_err(anyhow::Error::from)
4021×
        });
4030×
    }
4041×
    if let Some(addr) = https {
4050×
        let _ = rustls::crypto::ring::default_provider().install_default();
4060×
        let tls = axum_server::tls_rustls::RustlsConfig::from_pem_file(app.config.tls_cert(), app.config.tls_key())
4070×
            .await
4080×
            .map_err(|e| anyhow::anyhow!("loading TLS files: {e}"))?;
4090×
        tracing::info!("https on {addr}");
4100×
        let r = router.clone();
4110×
        let handle = axum_server::Handle::new();
4120×
        let draining = handle.clone();
4130×
        tokio::spawn(async move {
4140×
            shutdown::stopping().await;
4150×
            draining.graceful_shutdown(Some(shutdown::DRAIN));
4160×
        });
4170×
        tasks.spawn(async move {
4180×
            axum_server::bind_rustls(addr, tls)
4190×
                .handle(handle)
4200×
                .serve(r.into_make_service_with_connect_info::<std::net::SocketAddr>())
4210×
                .await
4220×
                .map_err(anyhow::Error::from)
4230×
        });
4241×
    }
4251×
    tokio::select! {
426
        // A worker with no address to serve on runs until it is stopped.
4271×
        r = tasks.join_next(), if !tasks.is_empty() => { r.transpose()?.transpose()?; Ok(()) }
4281×
        _ = signal => {
429
            // The servers stop taking connections and finish what they
430
            // have; whatever is still running after DRAIN is cut off.
4310×
            let drained = tokio::time::timeout(shutdown::DRAIN, async { while tasks.join_next().await.is_some() {} }).await;
4320×
            if drained.is_err() {
4330×
                tracing::warn!("requests still running after {} s: stopping anyway", shutdown::DRAIN.as_secs());
4340×
            }
4350×
            tracing::info!("stopped");
4360×
            Ok(())
437
        }
438
    }
4391×
}