OXYGENHUB

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

246 of 282 lines run, 42 of 96 functions · run #493 on diffusion-pin-bookmark · 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_protection;
43
pub mod queue;
44
pub mod render;
45
pub mod reports;
46
pub mod repos;
47
pub mod runner_updates;
48
pub mod secrets;
49
pub mod setup;
50
pub mod shutdown;
51
pub mod signin;
52
pub mod social;
53
pub mod storage;
54
pub mod swarm;
55
pub mod tags;
56
pub mod terraform;
57
pub mod throttle;
58
pub mod tlog;
59
pub mod variables;
60
pub mod web;
61
pub mod wiki;
62
63
use crate::config::Config;
64
use crate::repos::Repos;
65
use std::sync::Arc;
66
67
/// Everything a request handler can reach.
68
pub struct App {
69
    pub config: Config,
70
    pub db: db::Pool,
71
    pub repos: Arc<Repos>,
72
    /// Wikis, one Oxygen repository per repository (hub spec §6.11).
73
    pub wikis: Arc<Repos>,
74
    pub server: Arc<oxy_server::Server>,
75
    pub hub_key: keys::HubKey,
76
    pub cookie_key: auth::CookieKey,
77
    /// Seals AI assistants' tokens at rest (hub spec §13.4).
78
    pub assistant_key: assistants::SecretKey,
79
    /// Seals Flow secrets at rest (hub spec §13.2, #107).
80
    pub secret_key: assistants::SecretKey,
81
    /// The OIDC issuer for jobs (hub spec §13.5), made on first use.
82
    pub oidc: tokio::sync::OnceCell<oidc::Issuer>,
83
    /// Which assistants are answering which proposals, and recent calls
84
    /// per repository (hub spec §13.4).
85
    pub assistant_gate: std::sync::Mutex<assistants::Gate>,
86
    /// Failed sign-ins and the like, per account and address (oxygenhub#221).
87
    pub throttle: std::sync::Mutex<throttle::Throttle>,
88
    /// Events for live pages and workers, here and in the other processes
89
    /// sharing the database (docs/roles.md, #273).
90
    pub bus: bus::Bus,
91
    /// Who is resolving which conflict together (hub spec §6.10).
92
    pub rooms: Arc<live::Rooms>,
93
    /// Outgoing mail: hub.toml's `[email]`, overridden by what the admin
94
    /// page saved (#101).
95
    pub mail: std::sync::RwLock<config::Email>,
96
    /// The image swarm's tracker (oxygenhub#144).
97
    pub swarm: swarm::Tracker,
98
    pub started: std::time::Instant,
99
    /// The transparency log (#238).
100
    pub tlog: Arc<tlog::Log>,
101
    /// What this process does: web, worker or both (docs/roles.md, #272).
102
    pub roles: config::Roles,
103
    /// The background tasks started here and the leader locks held (#272).
104
    pub leader: leader::Leader,
105
}
106
107
impl App {
108
    /// The rootfs images this hub keeps for runners (oxygenflow#39).
10925×
    pub fn images(&self) -> images::Store {
11025×
        images::Store::new(&self.config.data)
11125×
    }
112
113
    /// The OIDC issuer, its key loaded or made the first time it is asked for.
11426×
    pub async fn oidc(&self) -> anyhow::Result<&oidc::Issuer> {
11526×
        let keys = self.config.keys_dir();
11626×
        self.oidc.get_or_try_init(|| async move { tokio::task::spawn_blocking(move || oidc::Issuer::load_or_create(&keys)).await? }).await
11726×
    }
118
}
119
120
pub type Shared = Arc<App>;
121
122
/// Open the data directory and build the application state. `init` must
123
/// have run once; `serve` and the tests call this.
124194×
pub async fn build(config: Config) -> anyhow::Result<Shared> {
125194×
    let roles = config.roles()?;
126193×
    std::fs::create_dir_all(config.repos_dir())?;
127193×
    let db = db::open(&config).await?;
128193×
    let repos = Arc::new(Repos::new(config.repos_dir()));
129193×
    let wikis = Arc::new(Repos::new(config.data.join("wikis")));
130193×
    let hub_key = keys::ensure_identity(&config.keys_dir(), &config.site.name, config.base_url())?;
131193×
    let cookie_key = auth::CookieKey::load_or_create(&config.keys_dir())?;
132193×
    let assistant_key = assistants::SecretKey::load_or_create(&config.keys_dir())?;
133193×
    let secret_key = assistants::SecretKey::load_or_create_named(&config.keys_dir(), "secrets.key")?;
134193×
    let backend = protocol::HubBackend::new(
135193×
        repos.clone(),
136193×
        wikis.clone(),
137193×
        db.clone(),
138193×
        config.auth.push_tokens.clone(),
139193×
        tokio::runtime::Handle::current(),
140
    )
141193×
    .with_acceptor(hub_key.identity.clone(), keys::load_secret(&config.keys_dir())?.1)
142193×
    .with_scan_budget(push_protection::Budget {
143193×
        bytes: config.limits.scan_limit.0,
144193×
        file: config.limits.scan_file_limit.0,
145193×
        time: std::time::Duration::from_millis(config.limits.scan_time_ms),
146193×
    });
147193×
    let slot = backend.app_slot();
148193×
    let server = oxy_server::Server::new(backend);
149193×
    let mail = mail::load(&db, &config.email).await;
150
    // The web role appends to the log; a worker alone only reads it (#272).
151193×
    let (tlog_dir, origin) = (config.data.join("tlog"), tlog::origin_of(config.base_url()));
152193×
    let tlog = Arc::new(if roles.web { tlog::Log::open(&tlog_dir, &origin)? } else { tlog::Log::open_reader(&tlog_dir, &origin)? });
153193×
    tlog.configure(&config.tlog)?;
154193×
    let app = Arc::new(App {
155193×
        mail: std::sync::RwLock::new(mail),
156193×
        config,
157193×
        db,
158193×
        repos,
159193×
        wikis,
160193×
        server,
161193×
        hub_key,
162193×
        cookie_key,
163193×
        assistant_key,
164193×
        secret_key,
165193×
        oidc: tokio::sync::OnceCell::new(),
166193×
        assistant_gate: std::sync::Mutex::new(assistants::Gate::default()),
167193×
        throttle: std::sync::Mutex::new(throttle::Throttle::default()),
168193×
        bus: bus::Bus::default(),
169193×
        rooms: Arc::new(live::Rooms::default()),
170193×
        swarm: Default::default(),
171193×
        started: std::time::Instant::now(),
172193×
        tlog,
173193×
        roles,
174193×
        leader: leader::Leader::default(),
175193×
    });
176193×
    *slot.lock().unwrap() = Some(Arc::downgrade(&app));
177193×
    bus::start(&app).await?;
178193×
    storage::load(&app).await?;
179193×
    coverage::load(&app).await?;
180193×
    junit::load(&app).await?;
181193×
    reports::load(&app).await?;
182193×
    start_background(&app);
183193×
    setup::ensure(&app).await?;
184193×
    Ok(app)
185194×
}
186
187
/// Start this process's background tasks (docs/roles.md, #272). The
188
/// worker role's are singletons across every process sharing the database,
189
/// each run under its leader lock; the transparency log's checkpointer goes
190
/// with the web role, which appends to the log, and is a singleton too.
191193×
fn start_background(app: &Shared) {
192193×
    if app.roles.web {
193192×
        // The checkpointer signs the log this process appends to (#238).
194192×
        leader::run(app, "tlog.checkpointer", tlog::checkpointer);
195192×
    }
196193×
    if !app.roles.worker {
1972×
        return;
198191×
    }
199191×
    leader::run(app, "hooks.worker", hooks::worker);
200191×
    leader::run(app, "flow.reaper", flow::reaper);
201191×
    leader::run(app, "flow.scheduler", flow::scheduler);
202191×
    leader::run(app, "flow.placement", flow::placement);
203191×
    leader::run(app, "maintenance.nightly", maintenance::nightly);
204191×
    leader::run(app, "projects.archiver", maintenance::archiver);
205191×
    leader::run(app, "backups.scheduler", backups::scheduler);
206
    // The reverse pin index for repositories pushed before it existed (#148):
207
    // once, by whichever worker leads it first (idempotent if run again).
208382×
    leader::run(app, "diffusion.backfill", |app| async move { diffusion::backfill(&app).await });
209
    // Mend the pin index and the bumps it drives (oxygenhub#210).
210191×
    leader::run(app, "diffusion.reconciler", diffusion::reconciler);
211
    // Each repository's history scanned for secrets (#277), a budget at a
212
    // time, at low priority.
213191×
    leader::run(app, "secrets.history_scan", history_scan::worker);
214
    // The durable work queue (#276): every worker takes its due items.
215191×
    app.leader.note("queue.worker");
216191×
    tokio::spawn(queue::worker(app.clone()));
217
    // What each image is for, read or learned once (oxygenhub#173): safe
218
    // in every worker, so it takes no lock.
219191×
    app.leader.note("images.learn_archs");
220191×
    tokio::spawn({
221191×
        let app = app.clone();
222191×
        async move {
223191×
            match images::learn_archs(&app).await {
224190×
                Ok(n) if n > 0 => tracing::info!(images = n, "read the architecture of kept images"),
225190×
                Ok(_) => {}
2260×
                Err(e) => tracing::warn!(error = %e, "learning image architectures"),
227
            }
228190×
        }
229
    });
230193×
}
231
232
/// The router this process serves: everything for the web role; for a
233
/// worker alone, `/health` and `/metrics`, so it can be watched.
2342673×
pub fn router(app: Shared) -> axum::Router {
2352673×
    if !app.roles.web {
2368×
        return worker_router(app);
2372665×
    }
2382665×
    full_router(app)
2392673×
}
240
241
/// What a worker-only process answers: its health and its metrics.
2428×
fn worker_router(app: Shared) -> axum::Router {
243
    use axum::routing::get;
2448×
    let hsts = headers::hsts(app.config.base_url(), app.config.server.hsts_max_age);
2458×
    axum::Router::new()
2468×
        .route("/health", get(web::home::health))
2478×
        .route("/metrics", get(metrics::metrics))
2488×
        .with_state(app)
2498×
        .layer(axum::middleware::from_fn_with_state(hsts, headers::security_headers))
2508×
}
251
252
/// The full router: pages, API, protocol and static assets.
2532665×
fn full_router(app: Shared) -> axum::Router {
2542665×
    let https = app_https(&app);
2552665×
    let hsts = headers::hsts(app.config.base_url(), app.config.server.hsts_max_age);
2562665×
    web::router(app.clone())
2572665×
        .layer(axum::middleware::from_fn_with_state(app, agent_requests))
2582665×
        .layer(axum::middleware::from_fn(private_pages))
2592665×
        .layer(axum::middleware::from_fn(slow_requests))
2602665×
        .layer(axum::middleware::from_fn_with_state(https, https_only))
2612665×
        .layer(axum::middleware::from_fn_with_state(hsts, headers::security_headers))
2622665×
}
263
264
/// The site's https address, when it has one: what [`https_only`] redirects to.
2652665×
fn app_https(app: &Shared) -> Option<String> {
2662665×
    let base = app.config.base_url();
2672665×
    base.starts_with("https://").then(|| base.trim_end_matches('/').to_string())
2682665×
}
269
270
/// The scheme a proxy in front of the hub says the visitor used
271
/// (`X-Forwarded-Proto`, else Cloudflare's `CF-Visitor`); `None` for a
272
/// request made to the hub directly (runners and tools on its host).
2736×
fn forwarded_scheme(headers: &axum::http::HeaderMap) -> Option<String> {
2746×
    if let Some(p) = headers.get("x-forwarded-proto").and_then(|v| v.to_str().ok()) {
2754×
        return p.split(',').next().map(|s| s.trim().to_ascii_lowercase());
2762×
    }
2772×
    let visitor = headers.get("cf-visitor").and_then(|v| v.to_str().ok())?;
2781×
    serde_json::from_str::<serde_json::Value>(visitor).ok()?["scheme"].as_str().map(str::to_ascii_lowercase)
2796×
}
280
281
/// HTTPS only (oxygenhub#218): on a site whose address is https, a request
282
/// a proxy reports as plain http is sent to the https address (GET and
283
/// HEAD) or refused (anything else, so a form or a password is never taken
284
/// over http). Requests made to the hub directly carry no such report and
285
/// are untouched.
2863656×
async fn https_only(
2873656×
    axum::extract::State(https): axum::extract::State<Option<String>>,
2883656×
    req: axum::extract::Request,
2893656×
    next: axum::middleware::Next,
2903656×
) -> axum::response::Response {
291
    use axum::response::IntoResponse;
2923656×
    let Some(base) = https else { return next.run(req).await };
2936×
    if forwarded_scheme(req.headers()).as_deref() != Some("http") {
2944×
        return next.run(req).await;
2952×
    }
2962×
    let to = format!("{base}{}", req.uri().path_and_query().map(|p| p.as_str()).unwrap_or("/"));
2972×
    if matches!(*req.method(), axum::http::Method::GET | axum::http::Method::HEAD) {
2981×
        return axum::response::Redirect::permanent(&to).into_response();
2991×
    }
3001×
    (axum::http::StatusCode::BAD_REQUEST, format!("This site takes requests over HTTPS only: send it to {to}\n")).into_response()
3013656×
}
302
303
/// A request made with a token its owner marked as an agent's runs with
304
/// that token's name in [`notify::AGENT`], so what the agent does is told
305
/// to its owner (oxygenhub#183).
3063654×
async fn agent_requests(
3073654×
    axum::extract::State(app): axum::extract::State<Shared>,
3083654×
    req: axum::extract::Request,
3093654×
    next: axum::middleware::Next,
3103654×
) -> axum::response::Response {
3113654×
    let token = req
3123654×
        .headers()
3133654×
        .get(axum::http::header::AUTHORIZATION)
3143654×
        .and_then(|v| v.to_str().ok())
3153654×
        .and_then(|v| v.strip_prefix("Bearer "))
3163654×
        .map(|t| t.trim().to_string());
3173654×
    let agent = match token {
318
        // A keyless agent's grant token (#253) is always an agent's.
3191735×
        Some(t) if t.starts_with(keyless::GRANT_TOKEN_PREFIX) => db::accounts::agent_grant_by_token(&app.db, &auth::token_hash(&t))
32020×
            .await
32120×
            .ok()
32220×
            .flatten()
32320×
            .filter(|g| g.live(db::now_ms()))
32420×
            .map(|g| g.agent),
3251715×
        Some(t) => db::accounts::token_by_hash(&app.db, &auth::token_hash(&t)).await.ok().flatten().filter(|t| t.agent).map(|t| t.name),
3261919×
        None => None,
327
    };
3283654×
    notify::AGENT.scope(agent, next.run(req)).await
3293654×
}
330
331
/// Requests slower than this are logged, with their path (#145).
332
const SLOW: std::time::Duration = std::time::Duration::from_secs(2);
333
334
/// Log a slow request's method, path and time, so a slow page can be
335
/// found afterwards. Never the query, which may hold a token.
3363654×
async fn slow_requests(req: axum::extract::Request, next: axum::middleware::Next) -> axum::response::Response {
3373654×
    let (method, path) = (req.method().clone(), req.uri().path().to_string());
3383654×
    let start = std::time::Instant::now();
3393654×
    let res = next.run(req).await;
3403654×
    let took = start.elapsed();
3413654×
    metrics::observe(method.as_str(), &path, res.status().as_u16(), took.as_secs_f64());
3423654×
    if took >= SLOW {
3433×
        tracing::warn!("slow request: {method} {path} took {:.1} s ({})", took.as_secs_f64(), res.status().as_u16());
3443651×
    }
3453654×
    res
3463654×
}
347
348
/// A page for a signed-in viewer is theirs alone: it may list private
349
/// repositories, and the dashboard's sky carries their activity (#157). An
350
/// HTML response to a request with a session cookie, which has not said
351
/// how to cache itself, says `private, no-store`, so no shared cache (a
352
/// proxy or a CDN in front of the hub) ever serves it to anyone else.
3533654×
async fn private_pages(req: axum::extract::Request, next: axum::middleware::Next) -> axum::response::Response {
354
    use axum::http::header;
3553654×
    let signed_in = req
3563654×
        .headers()
3573654×
        .get_all(header::COOKIE)
3583654×
        .iter()
3593654×
        .filter_map(|v| v.to_str().ok())
3603654×
        .any(|c| c.split(';').any(|kv| kv.trim_start().starts_with("oxyhub=")));
3613654×
    let mut res = next.run(req).await;
3623654×
    let html = res.headers().get(header::CONTENT_TYPE).and_then(|v| v.to_str().ok()).is_some_and(|t| t.starts_with("text/html"));
3633654×
    if signed_in && html && !res.headers().contains_key(header::CACHE_CONTROL) {
364819×
        res.headers_mut().insert(header::CACHE_CONTROL, header::HeaderValue::from_static("private, no-store"));
3652835×
    }
3663654×
    res
3673654×
}
368
369
/// Serve on the configured addresses until the process is told to stop.
3701×
pub async fn serve(app: Shared) -> anyhow::Result<()> {
3711×
    let router = router(app.clone());
3721×
    let http = app.config.bind_addr()?;
3731×
    let https = app.config.tls_bind_addr()?;
3741×
    if http.is_none() && https.is_none() && app.roles.web {
3750×
        anyhow::bail!("nothing to bind: set server.bind or server.tls_bind");
3761×
    }
3771×
    tracing::info!("roles: {}", app.roles.names().join(", "));
378
    // Installed first: from here a SIGTERM drains rather than kills.
3791×
    let signal = shutdown::on_signal()?;
3801×
    let mut tasks = tokio::task::JoinSet::new();
3811×
    if let Some(addr) = http {
3821×
        let listener = match shutdown::systemd_listener() {
3830×
            Some(l) => {
3840×
                tracing::info!("http on the socket systemd holds ({})", l.local_addr().map(|a| a.to_string()).unwrap_or_default());
3850×
                tokio::net::TcpListener::from_std(l)?
386
            }
387
            None => {
3881×
                tracing::info!("http on {addr}");
3891×
                tokio::net::TcpListener::bind(addr).await?
390
            }
391
        };
3921×
        let r = router.clone();
3931×
        tasks.spawn(async move {
3941×
            axum::serve(listener, r.into_make_service_with_connect_info::<std::net::SocketAddr>())
3951×
                .with_graceful_shutdown(shutdown::stopping())
3961×
                .await
3971×
                .map_err(anyhow::Error::from)
3981×
        });
3990×
    }
4001×
    if let Some(addr) = https {
4010×
        let _ = rustls::crypto::ring::default_provider().install_default();
4020×
        let tls = axum_server::tls_rustls::RustlsConfig::from_pem_file(app.config.tls_cert(), app.config.tls_key())
4030×
            .await
4040×
            .map_err(|e| anyhow::anyhow!("loading TLS files: {e}"))?;
4050×
        tracing::info!("https on {addr}");
4060×
        let r = router.clone();
4070×
        let handle = axum_server::Handle::new();
4080×
        let draining = handle.clone();
4090×
        tokio::spawn(async move {
4100×
            shutdown::stopping().await;
4110×
            draining.graceful_shutdown(Some(shutdown::DRAIN));
4120×
        });
4130×
        tasks.spawn(async move {
4140×
            axum_server::bind_rustls(addr, tls)
4150×
                .handle(handle)
4160×
                .serve(r.into_make_service_with_connect_info::<std::net::SocketAddr>())
4170×
                .await
4180×
                .map_err(anyhow::Error::from)
4190×
        });
4201×
    }
4211×
    tokio::select! {
422
        // A worker with no address to serve on runs until it is stopped.
4231×
        r = tasks.join_next(), if !tasks.is_empty() => { r.transpose()?.transpose()?; Ok(()) }
4241×
        _ = signal => {
425
            // The servers stop taking connections and finish what they
426
            // have; whatever is still running after DRAIN is cut off.
4270×
            let drained = tokio::time::timeout(shutdown::DRAIN, async { while tasks.join_next().await.is_some() {} }).await;
4280×
            if drained.is_err() {
4290×
                tracing::warn!("requests still running after {} s: stopping anyway", shutdown::DRAIN.as_secs());
4300×
            }
4310×
            tracing::info!("stopped");
4320×
            Ok(())
433
        }
434
    }
4351×
}