OXYGENHUB

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

247 of 283 lines run, 42 of 96 functions · run #542 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 board_stats;
15
pub mod bus;
16
pub mod config;
17
pub mod coverage;
18
pub mod db;
19
pub mod diffusion;
20
pub mod drops;
21
pub mod events;
22
pub mod flow;
23
pub mod headers;
24
pub mod history_scan;
25
pub mod hooks;
26
pub mod images;
27
pub mod insights;
28
pub mod junit;
29
pub mod keyless;
30
pub mod keys;
31
pub mod leader;
32
pub mod levels;
33
pub mod live;
34
pub mod mail;
35
pub mod maintenance;
36
pub mod metrics;
37
pub mod mirror;
38
pub mod net;
39
pub mod notify;
40
pub mod oidc;
41
pub mod protocol;
42
pub mod provenance;
43
pub mod push;
44
pub mod push_protection;
45
pub mod queue;
46
pub mod render;
47
pub mod reports;
48
pub mod repos;
49
pub mod runner_updates;
50
pub mod secrets;
51
pub mod setup;
52
pub mod shutdown;
53
pub mod signin;
54
pub mod social;
55
pub mod starter;
56
pub mod storage;
57
pub mod swarm;
58
pub mod tags;
59
pub mod terraform;
60
pub mod throttle;
61
pub mod tlog;
62
pub mod variables;
63
pub mod web;
64
pub mod wiki;
65
66
use crate::config::Config;
67
use crate::repos::Repos;
68
use std::sync::Arc;
69
70
/// Everything a request handler can reach.
71
pub struct App {
72
    pub config: Config,
73
    pub db: db::Pool,
74
    pub repos: Arc<Repos>,
75
    /// Wikis, one Oxygen repository per repository (hub spec §6.11).
76
    pub wikis: Arc<Repos>,
77
    pub server: Arc<oxy_server::Server>,
78
    pub hub_key: keys::HubKey,
79
    pub cookie_key: auth::CookieKey,
80
    /// Seals AI assistants' tokens at rest (hub spec §13.4).
81
    pub assistant_key: assistants::SecretKey,
82
    /// Seals Flow secrets at rest (hub spec §13.2, #107).
83
    pub secret_key: assistants::SecretKey,
84
    /// The OIDC issuer for jobs (hub spec §13.5), made on first use.
85
    pub oidc: tokio::sync::OnceCell<oidc::Issuer>,
86
    /// Which assistants are answering which proposals, and recent calls
87
    /// per repository (hub spec §13.4).
88
    pub assistant_gate: std::sync::Mutex<assistants::Gate>,
89
    /// Failed sign-ins and the like, per account and address (oxygenhub#221).
90
    pub throttle: std::sync::Mutex<throttle::Throttle>,
91
    /// Events for live pages and workers, here and in the other processes
92
    /// sharing the database (docs/roles.md, #273).
93
    pub bus: bus::Bus,
94
    /// Who is resolving which conflict together (hub spec §6.10).
95
    pub rooms: Arc<live::Rooms>,
96
    /// Outgoing mail: hub.toml's `[email]`, overridden by what the admin
97
    /// page saved (#101).
98
    pub mail: std::sync::RwLock<config::Email>,
99
    /// The image swarm's tracker (oxygenhub#144).
100
    pub swarm: swarm::Tracker,
101
    pub started: std::time::Instant,
102
    /// The transparency log (#238).
103
    pub tlog: Arc<tlog::Log>,
104
    /// What this process does: web, worker or both (docs/roles.md, #272).
105
    pub roles: config::Roles,
106
    /// The background tasks started here and the leader locks held (#272).
107
    pub leader: leader::Leader,
108
}
109
110
impl App {
111
    /// The rootfs images this hub keeps for runners (oxygenflow#39).
11241×
    pub fn images(&self) -> images::Store {
11341×
        images::Store::new(&self.config.data)
11441×
    }
115
116
    /// The OIDC issuer, its key loaded or made the first time it is asked for.
11726×
    pub async fn oidc(&self) -> anyhow::Result<&oidc::Issuer> {
11826×
        let keys = self.config.keys_dir();
11926×
        self.oidc.get_or_try_init(|| async move { tokio::task::spawn_blocking(move || oidc::Issuer::load_or_create(&keys)).await? }).await
12026×
    }
121
}
122
123
pub type Shared = Arc<App>;
124
125
/// Open the data directory and build the application state. `init` must
126
/// have run once; `serve` and the tests call this.
127208×
pub async fn build(config: Config) -> anyhow::Result<Shared> {
128208×
    let roles = config.roles()?;
129
    // Images of this hub's file pages render as their raw files.
130207×
    render::markdown::set_origin(config.base_url());
131207×
    std::fs::create_dir_all(config.repos_dir())?;
132207×
    let db = db::open(&config).await?;
133207×
    let repos = Arc::new(Repos::new(config.repos_dir()));
134207×
    let wikis = Arc::new(Repos::new(config.data.join("wikis")));
135207×
    let hub_key = keys::ensure_identity(&config.keys_dir(), &config.site.name, config.base_url())?;
136207×
    let cookie_key = auth::CookieKey::load_or_create(&config.keys_dir())?;
137207×
    let assistant_key = assistants::SecretKey::load_or_create(&config.keys_dir())?;
138207×
    let secret_key = assistants::SecretKey::load_or_create_named(&config.keys_dir(), "secrets.key")?;
139207×
    let backend = protocol::HubBackend::new(
140207×
        repos.clone(),
141207×
        wikis.clone(),
142207×
        db.clone(),
143207×
        config.auth.push_tokens.clone(),
144207×
        tokio::runtime::Handle::current(),
145
    )
146207×
    .with_acceptor(hub_key.identity.clone(), keys::load_secret(&config.keys_dir())?.1)
147207×
    .with_scan_budget(push_protection::Budget {
148207×
        bytes: config.limits.scan_limit.0,
149207×
        file: config.limits.scan_file_limit.0,
150207×
        time: std::time::Duration::from_millis(config.limits.scan_time_ms),
151207×
    });
152207×
    let slot = backend.app_slot();
153207×
    let server = oxy_server::Server::new(backend);
154207×
    let mail = mail::load(&db, &config.email).await;
155
    // The web role appends to the log; a worker alone only reads it (#272).
156207×
    let (tlog_dir, origin) = (config.data.join("tlog"), tlog::origin_of(config.base_url()));
157207×
    let tlog = Arc::new(if roles.web { tlog::Log::open(&tlog_dir, &origin)? } else { tlog::Log::open_reader(&tlog_dir, &origin)? });
158207×
    tlog.configure(&config.tlog)?;
159207×
    let app = Arc::new(App {
160207×
        mail: std::sync::RwLock::new(mail),
161207×
        config,
162207×
        db,
163207×
        repos,
164207×
        wikis,
165207×
        server,
166207×
        hub_key,
167207×
        cookie_key,
168207×
        assistant_key,
169207×
        secret_key,
170207×
        oidc: tokio::sync::OnceCell::new(),
171207×
        assistant_gate: std::sync::Mutex::new(assistants::Gate::default()),
172207×
        throttle: std::sync::Mutex::new(throttle::Throttle::default()),
173207×
        bus: bus::Bus::default(),
174207×
        rooms: Arc::new(live::Rooms::default()),
175207×
        swarm: Default::default(),
176207×
        started: std::time::Instant::now(),
177207×
        tlog,
178207×
        roles,
179207×
        leader: leader::Leader::default(),
180207×
    });
181207×
    *slot.lock().unwrap() = Some(Arc::downgrade(&app));
182207×
    bus::start(&app).await?;
183207×
    storage::load(&app).await?;
184207×
    coverage::load(&app).await?;
185207×
    junit::load(&app).await?;
186207×
    reports::load(&app).await?;
187207×
    start_background(&app);
188207×
    setup::ensure(&app).await?;
189207×
    Ok(app)
190208×
}
191
192
/// Start this process's background tasks (docs/roles.md, #272). The
193
/// worker role's are singletons across every process sharing the database,
194
/// each run under its leader lock; the transparency log's checkpointer goes
195
/// with the web role, which appends to the log, and is a singleton too.
196207×
fn start_background(app: &Shared) {
197207×
    if app.roles.web {
198206×
        // The checkpointer signs the log this process appends to (#238).
199206×
        leader::run(app, "tlog.checkpointer", tlog::checkpointer);
200206×
    }
201207×
    if !app.roles.worker {
2022×
        return;
203205×
    }
204205×
    leader::run(app, "hooks.worker", hooks::worker);
205205×
    leader::run(app, "flow.reaper", flow::reaper);
206205×
    leader::run(app, "flow.scheduler", flow::scheduler);
207205×
    leader::run(app, "flow.placement", flow::placement);
208205×
    leader::run(app, "maintenance.nightly", maintenance::nightly);
209205×
    leader::run(app, "projects.archiver", maintenance::archiver);
210205×
    leader::run(app, "backups.scheduler", backups::scheduler);
211
    // The reverse pin index for repositories pushed before it existed (#148):
212
    // once, by whichever worker leads it first (idempotent if run again).
213409×
    leader::run(app, "diffusion.backfill", |app| async move { diffusion::backfill(&app).await });
214
    // Mend the pin index and the bumps it drives (oxygenhub#210).
215205×
    leader::run(app, "diffusion.reconciler", diffusion::reconciler);
216
    // Each repository's history scanned for secrets (#277), a budget at a
217
    // time, at low priority.
218205×
    leader::run(app, "secrets.history_scan", history_scan::worker);
219
    // The durable work queue (#276): every worker takes its due items.
220205×
    app.leader.note("queue.worker");
221205×
    tokio::spawn(queue::worker(app.clone()));
222
    // What each image is for, read or learned once (oxygenhub#173): safe
223
    // in every worker, so it takes no lock.
224205×
    app.leader.note("images.learn_archs");
225205×
    tokio::spawn({
226205×
        let app = app.clone();
227205×
        async move {
228205×
            match images::learn_archs(&app).await {
229204×
                Ok(n) if n > 0 => tracing::info!(images = n, "read the architecture of kept images"),
230204×
                Ok(_) => {}
2310×
                Err(e) => tracing::warn!(error = %e, "learning image architectures"),
232
            }
233204×
        }
234
    });
235207×
}
236
237
/// The router this process serves: everything for the web role; for a
238
/// worker alone, `/health` and `/metrics`, so it can be watched.
2392931×
pub fn router(app: Shared) -> axum::Router {
2402931×
    if !app.roles.web {
2418×
        return worker_router(app);
2422923×
    }
2432923×
    full_router(app)
2442931×
}
245
246
/// What a worker-only process answers: its health and its metrics.
2478×
fn worker_router(app: Shared) -> axum::Router {
248
    use axum::routing::get;
2498×
    let hsts = headers::hsts(app.config.base_url(), app.config.server.hsts_max_age);
2508×
    axum::Router::new()
2518×
        .route("/health", get(web::home::health))
2528×
        .route("/metrics", get(metrics::metrics))
2538×
        .with_state(app)
2548×
        .layer(axum::middleware::from_fn_with_state(hsts, headers::security_headers))
2558×
}
256
257
/// The full router: pages, API, protocol and static assets.
2582923×
fn full_router(app: Shared) -> axum::Router {
2592923×
    let https = app_https(&app);
2602923×
    let hsts = headers::hsts(app.config.base_url(), app.config.server.hsts_max_age);
2612923×
    web::router(app.clone())
2622923×
        .layer(axum::middleware::from_fn_with_state(app, agent_requests))
2632923×
        .layer(axum::middleware::from_fn(private_pages))
2642923×
        .layer(axum::middleware::from_fn(slow_requests))
2652923×
        .layer(axum::middleware::from_fn_with_state(https, https_only))
2662923×
        .layer(axum::middleware::from_fn_with_state(hsts, headers::security_headers))
2672923×
}
268
269
/// The site's https address, when it has one: what [`https_only`] redirects to.
2702923×
fn app_https(app: &Shared) -> Option<String> {
2712923×
    let base = app.config.base_url();
2722923×
    base.starts_with("https://").then(|| base.trim_end_matches('/').to_string())
2732923×
}
274
275
/// The scheme a proxy in front of the hub says the visitor used
276
/// (`X-Forwarded-Proto`, else Cloudflare's `CF-Visitor`); `None` for a
277
/// request made to the hub directly (runners and tools on its host).
2786×
fn forwarded_scheme(headers: &axum::http::HeaderMap) -> Option<String> {
2796×
    if let Some(p) = headers.get("x-forwarded-proto").and_then(|v| v.to_str().ok()) {
2804×
        return p.split(',').next().map(|s| s.trim().to_ascii_lowercase());
2812×
    }
2822×
    let visitor = headers.get("cf-visitor").and_then(|v| v.to_str().ok())?;
2831×
    serde_json::from_str::<serde_json::Value>(visitor).ok()?["scheme"].as_str().map(str::to_ascii_lowercase)
2846×
}
285
286
/// HTTPS only (oxygenhub#218): on a site whose address is https, a request
287
/// a proxy reports as plain http is sent to the https address (GET and
288
/// HEAD) or refused (anything else, so a form or a password is never taken
289
/// over http). Requests made to the hub directly carry no such report and
290
/// are untouched.
2913951×
async fn https_only(
2923951×
    axum::extract::State(https): axum::extract::State<Option<String>>,
2933951×
    req: axum::extract::Request,
2943951×
    next: axum::middleware::Next,
2953951×
) -> axum::response::Response {
296
    use axum::response::IntoResponse;
2973951×
    let Some(base) = https else { return next.run(req).await };
2986×
    if forwarded_scheme(req.headers()).as_deref() != Some("http") {
2994×
        return next.run(req).await;
3002×
    }
3012×
    let to = format!("{base}{}", req.uri().path_and_query().map(|p| p.as_str()).unwrap_or("/"));
3022×
    if matches!(*req.method(), axum::http::Method::GET | axum::http::Method::HEAD) {
3031×
        return axum::response::Redirect::permanent(&to).into_response();
3041×
    }
3051×
    (axum::http::StatusCode::BAD_REQUEST, format!("This site takes requests over HTTPS only: send it to {to}\n")).into_response()
3063951×
}
307
308
/// A request made with a token its owner marked as an agent's runs with
309
/// that token's name in [`notify::AGENT`], so what the agent does is told
310
/// to its owner (oxygenhub#183).
3113949×
async fn agent_requests(
3123949×
    axum::extract::State(app): axum::extract::State<Shared>,
3133949×
    req: axum::extract::Request,
3143949×
    next: axum::middleware::Next,
3153949×
) -> axum::response::Response {
3163949×
    let token = req
3173949×
        .headers()
3183949×
        .get(axum::http::header::AUTHORIZATION)
3193949×
        .and_then(|v| v.to_str().ok())
3203949×
        .and_then(|v| v.strip_prefix("Bearer "))
3213949×
        .map(|t| t.trim().to_string());
3223949×
    let agent = match token {
323
        // A keyless agent's grant token (#253) is always an agent's.
3241874×
        Some(t) if t.starts_with(keyless::GRANT_TOKEN_PREFIX) => db::accounts::agent_grant_by_token(&app.db, &auth::token_hash(&t))
32520×
            .await
32620×
            .ok()
32720×
            .flatten()
32820×
            .filter(|g| g.live(db::now_ms()))
32920×
            .map(|g| g.agent),
3301854×
        Some(t) => db::accounts::token_by_hash(&app.db, &auth::token_hash(&t)).await.ok().flatten().filter(|t| t.agent).map(|t| t.name),
3312075×
        None => None,
332
    };
3333949×
    notify::AGENT.scope(agent, next.run(req)).await
3343949×
}
335
336
/// Requests slower than this are logged, with their path (#145).
337
const SLOW: std::time::Duration = std::time::Duration::from_secs(2);
338
339
/// Log a slow request's method, path and time, so a slow page can be
340
/// found afterwards. Never the query, which may hold a token.
3413949×
async fn slow_requests(req: axum::extract::Request, next: axum::middleware::Next) -> axum::response::Response {
3423949×
    let (method, path) = (req.method().clone(), req.uri().path().to_string());
3433949×
    let start = std::time::Instant::now();
3443949×
    let res = next.run(req).await;
3453949×
    let took = start.elapsed();
3463949×
    metrics::observe(method.as_str(), &path, res.status().as_u16(), took.as_secs_f64());
3473949×
    if took >= SLOW {
3483×
        tracing::warn!("slow request: {method} {path} took {:.1} s ({})", took.as_secs_f64(), res.status().as_u16());
3493946×
    }
3503949×
    res
3513949×
}
352
353
/// A page for a signed-in viewer is theirs alone: it may list private
354
/// repositories, and the dashboard's sky carries their activity (#157). An
355
/// HTML response to a request with a session cookie, which has not said
356
/// how to cache itself, says `private, no-store`, so no shared cache (a
357
/// proxy or a CDN in front of the hub) ever serves it to anyone else.
3583949×
async fn private_pages(req: axum::extract::Request, next: axum::middleware::Next) -> axum::response::Response {
359
    use axum::http::header;
3603949×
    let signed_in = req
3613949×
        .headers()
3623949×
        .get_all(header::COOKIE)
3633949×
        .iter()
3643949×
        .filter_map(|v| v.to_str().ok())
3653949×
        .any(|c| c.split(';').any(|kv| kv.trim_start().starts_with("oxyhub=")));
3663949×
    let mut res = next.run(req).await;
3673949×
    let html = res.headers().get(header::CONTENT_TYPE).and_then(|v| v.to_str().ok()).is_some_and(|t| t.starts_with("text/html"));
3683949×
    if signed_in && html && !res.headers().contains_key(header::CACHE_CONTROL) {
369882×
        res.headers_mut().insert(header::CACHE_CONTROL, header::HeaderValue::from_static("private, no-store"));
3703067×
    }
3713949×
    res
3723949×
}
373
374
/// Serve on the configured addresses until the process is told to stop.
3751×
pub async fn serve(app: Shared) -> anyhow::Result<()> {
3761×
    let router = router(app.clone());
3771×
    let http = app.config.bind_addr()?;
3781×
    let https = app.config.tls_bind_addr()?;
3791×
    if http.is_none() && https.is_none() && app.roles.web {
3800×
        anyhow::bail!("nothing to bind: set server.bind or server.tls_bind");
3811×
    }
3821×
    tracing::info!("roles: {}", app.roles.names().join(", "));
383
    // Installed first: from here a SIGTERM drains rather than kills.
3841×
    let signal = shutdown::on_signal()?;
3851×
    let mut tasks = tokio::task::JoinSet::new();
3861×
    if let Some(addr) = http {
3871×
        let listener = match shutdown::systemd_listener() {
3880×
            Some(l) => {
3890×
                tracing::info!("http on the socket systemd holds ({})", l.local_addr().map(|a| a.to_string()).unwrap_or_default());
3900×
                tokio::net::TcpListener::from_std(l)?
391
            }
392
            None => {
3931×
                tracing::info!("http on {addr}");
3941×
                tokio::net::TcpListener::bind(addr).await?
395
            }
396
        };
3971×
        let r = router.clone();
3981×
        tasks.spawn(async move {
3991×
            axum::serve(listener, r.into_make_service_with_connect_info::<std::net::SocketAddr>())
4001×
                .with_graceful_shutdown(shutdown::stopping())
4011×
                .await
4021×
                .map_err(anyhow::Error::from)
4031×
        });
4040×
    }
4051×
    if let Some(addr) = https {
4060×
        let _ = rustls::crypto::ring::default_provider().install_default();
4070×
        let tls = axum_server::tls_rustls::RustlsConfig::from_pem_file(app.config.tls_cert(), app.config.tls_key())
4080×
            .await
4090×
            .map_err(|e| anyhow::anyhow!("loading TLS files: {e}"))?;
4100×
        tracing::info!("https on {addr}");
4110×
        let r = router.clone();
4120×
        let handle = axum_server::Handle::new();
4130×
        let draining = handle.clone();
4140×
        tokio::spawn(async move {
4150×
            shutdown::stopping().await;
4160×
            draining.graceful_shutdown(Some(shutdown::DRAIN));
4170×
        });
4180×
        tasks.spawn(async move {
4190×
            axum_server::bind_rustls(addr, tls)
4200×
                .handle(handle)
4210×
                .serve(r.into_make_service_with_connect_info::<std::net::SocketAddr>())
4220×
                .await
4230×
                .map_err(anyhow::Error::from)
4240×
        });
4251×
    }
4261×
    tokio::select! {
427
        // A worker with no address to serve on runs until it is stopped.
4281×
        r = tasks.join_next(), if !tasks.is_empty() => { r.transpose()?.transpose()?; Ok(()) }
4291×
        _ = signal => {
430
            // The servers stop taking connections and finish what they
431
            // have; whatever is still running after DRAIN is cut off.
4320×
            let drained = tokio::time::timeout(shutdown::DRAIN, async { while tasks.join_next().await.is_some() {} }).await;
4330×
            if drained.is_err() {
4340×
                tracing::warn!("requests still running after {} s: stopping anyway", shutdown::DRAIN.as_secs());
4350×
            }
4360×
            tracing::info!("stopped");
4370×
            Ok(())
438
        }
439
    }
4401×
}