OXYGENHUB
◆ v0.7.0 oxygenhub / crates / hub / src / lib.rs
17.5 KiB · Rust · last changed A durable work queue, first slice (refs #276) 15 days ago source blame history raw
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 secrets;
48
pub mod setup;
49
pub mod shutdown;
50
pub mod signin;
51
pub mod social;
52
pub mod storage;
53
pub mod swarm;
54
pub mod terraform;
55
pub mod throttle;
56
pub mod tlog;
57
pub mod variables;
58
pub mod web;
59
pub mod wiki;
60
61
use crate::config::Config;
62
use crate::repos::Repos;
63
use std::sync::Arc;
64
65
/// Everything a request handler can reach.
66
pub struct App {
67
    pub config: Config,
68
    pub db: db::Pool,
69
    pub repos: Arc<Repos>,
70
    /// Wikis, one Oxygen repository per repository (hub spec §6.11).
71
    pub wikis: Arc<Repos>,
72
    pub server: Arc<oxy_server::Server>,
73
    pub hub_key: keys::HubKey,
74
    pub cookie_key: auth::CookieKey,
75
    /// Seals AI assistants' tokens at rest (hub spec §13.4).
76
    pub assistant_key: assistants::SecretKey,
77
    /// Seals Flow secrets at rest (hub spec §13.2, #107).
78
    pub secret_key: assistants::SecretKey,
79
    /// The OIDC issuer for jobs (hub spec §13.5), made on first use.
80
    pub oidc: tokio::sync::OnceCell<oidc::Issuer>,
81
    /// Which assistants are answering which proposals, and recent calls
82
    /// per repository (hub spec §13.4).
83
    pub assistant_gate: std::sync::Mutex<assistants::Gate>,
84
    /// Failed sign-ins and the like, per account and address (oxygenhub#221).
85
    pub throttle: std::sync::Mutex<throttle::Throttle>,
86
    /// Events for live pages and workers, here and in the other processes
87
    /// sharing the database (docs/roles.md, #273).
88
    pub bus: bus::Bus,
89
    /// Who is resolving which conflict together (hub spec §6.10).
90
    pub rooms: Arc<live::Rooms>,
91
    /// Outgoing mail: hub.toml's `[email]`, overridden by what the admin
92
    /// page saved (#101).
93
    pub mail: std::sync::RwLock<config::Email>,
94
    /// The image swarm's tracker (oxygenhub#144).
95
    pub swarm: swarm::Tracker,
96
    pub started: std::time::Instant,
97
    /// The transparency log (#238).
98
    pub tlog: Arc<tlog::Log>,
99
    /// What this process does: web, worker or both (docs/roles.md, #272).
100
    pub roles: config::Roles,
101
    /// The background tasks started here and the leader locks held (#272).
102
    pub leader: leader::Leader,
103
}
104
105
impl App {
106
    /// The rootfs images this hub keeps for runners (oxygenflow#39).
107
    pub fn images(&self) -> images::Store {
108
        images::Store::new(&self.config.data)
109
    }
110
111
    /// The OIDC issuer, its key loaded or made the first time it is asked for.
112
    pub async fn oidc(&self) -> anyhow::Result<&oidc::Issuer> {
113
        let keys = self.config.keys_dir();
114
        self.oidc.get_or_try_init(|| async move { tokio::task::spawn_blocking(move || oidc::Issuer::load_or_create(&keys)).await? }).await
115
    }
116
}
117
118
pub type Shared = Arc<App>;
119
120
/// Open the data directory and build the application state. `init` must
121
/// have run once; `serve` and the tests call this.
122
pub async fn build(config: Config) -> anyhow::Result<Shared> {
123
    let roles = config.roles()?;
124
    std::fs::create_dir_all(config.repos_dir())?;
125
    let db = db::open(&config).await?;
126
    let repos = Arc::new(Repos::new(config.repos_dir()));
127
    let wikis = Arc::new(Repos::new(config.data.join("wikis")));
128
    let hub_key = keys::ensure_identity(&config.keys_dir(), &config.site.name, config.base_url())?;
129
    let cookie_key = auth::CookieKey::load_or_create(&config.keys_dir())?;
130
    let assistant_key = assistants::SecretKey::load_or_create(&config.keys_dir())?;
131
    let secret_key = assistants::SecretKey::load_or_create_named(&config.keys_dir(), "secrets.key")?;
132
    let backend = protocol::HubBackend::new(
133
        repos.clone(),
134
        wikis.clone(),
135
        db.clone(),
136
        config.auth.push_tokens.clone(),
137
        tokio::runtime::Handle::current(),
138
    )
139
    .with_acceptor(hub_key.identity.clone(), keys::load_secret(&config.keys_dir())?.1)
140
    .with_scan_budget(push_protection::Budget {
141
        bytes: config.limits.scan_limit.0,
142
        file: config.limits.scan_file_limit.0,
143
        time: std::time::Duration::from_millis(config.limits.scan_time_ms),
144
    });
145
    let slot = backend.app_slot();
146
    let server = oxy_server::Server::new(backend);
147
    let mail = mail::load(&db, &config.email).await;
148
    // The web role appends to the log; a worker alone only reads it (#272).
149
    let (tlog_dir, origin) = (config.data.join("tlog"), tlog::origin_of(config.base_url()));
150
    let tlog = Arc::new(if roles.web { tlog::Log::open(&tlog_dir, &origin)? } else { tlog::Log::open_reader(&tlog_dir, &origin)? });
151
    tlog.configure(&config.tlog)?;
152
    let app = Arc::new(App {
153
        mail: std::sync::RwLock::new(mail),
154
        config,
155
        db,
156
        repos,
157
        wikis,
158
        server,
159
        hub_key,
160
        cookie_key,
161
        assistant_key,
162
        secret_key,
163
        oidc: tokio::sync::OnceCell::new(),
164
        assistant_gate: std::sync::Mutex::new(assistants::Gate::default()),
165
        throttle: std::sync::Mutex::new(throttle::Throttle::default()),
166
        bus: bus::Bus::default(),
167
        rooms: Arc::new(live::Rooms::default()),
168
        swarm: Default::default(),
169
        started: std::time::Instant::now(),
170
        tlog,
171
        roles,
172
        leader: leader::Leader::default(),
173
    });
174
    *slot.lock().unwrap() = Some(Arc::downgrade(&app));
175
    bus::start(&app).await?;
176
    storage::load(&app).await?;
177
    coverage::load(&app).await?;
178
    junit::load(&app).await?;
179
    reports::load(&app).await?;
180
    start_background(&app);
181
    setup::ensure(&app).await?;
182
    Ok(app)
183
}
184
185
/// Start this process's background tasks (docs/roles.md, #272). The
186
/// worker role's are singletons across every process sharing the database,
187
/// each run under its leader lock; the transparency log's checkpointer goes
188
/// with the web role, which appends to the log, and is a singleton too.
189
fn start_background(app: &Shared) {
190
    if app.roles.web {
191
        // The checkpointer signs the log this process appends to (#238).
192
        leader::run(app, "tlog.checkpointer", tlog::checkpointer);
193
    }
194
    if !app.roles.worker {
195
        return;
196
    }
197
    leader::run(app, "hooks.worker", hooks::worker);
198
    leader::run(app, "flow.reaper", flow::reaper);
199
    leader::run(app, "flow.scheduler", flow::scheduler);
200
    leader::run(app, "flow.placement", flow::placement);
201
    leader::run(app, "maintenance.nightly", maintenance::nightly);
202
    leader::run(app, "backups.scheduler", backups::scheduler);
203
    // The reverse pin index for repositories pushed before it existed (#148):
204
    // once, by whichever worker leads it first (idempotent if run again).
205
    leader::run(app, "diffusion.backfill", |app| async move { diffusion::backfill(&app).await });
206
    // Mend the pin index and the bumps it drives (oxygenhub#210).
207
    leader::run(app, "diffusion.reconciler", diffusion::reconciler);
208
    // Each repository's history scanned for secrets (#277), a budget at a
209
    // time, at low priority.
210
    leader::run(app, "secrets.history_scan", history_scan::worker);
211
    // The durable work queue (#276): every worker takes its due items.
212
    app.leader.note("queue.worker");
213
    tokio::spawn(queue::worker(app.clone()));
214
    // What each image is for, read or learned once (oxygenhub#173): safe
215
    // in every worker, so it takes no lock.
216
    app.leader.note("images.learn_archs");
217
    tokio::spawn({
218
        let app = app.clone();
219
        async move {
220
            match images::learn_archs(&app).await {
221
                Ok(n) if n > 0 => tracing::info!(images = n, "read the architecture of kept images"),
222
                Ok(_) => {}
223
                Err(e) => tracing::warn!(error = %e, "learning image architectures"),
224
            }
225
        }
226
    });
227
}
228
229
/// The router this process serves: everything for the web role; for a
230
/// worker alone, `/health` and `/metrics`, so it can be watched.
231
pub fn router(app: Shared) -> axum::Router {
232
    if !app.roles.web {
233
        return worker_router(app);
234
    }
235
    full_router(app)
236
}
237
238
/// What a worker-only process answers: its health and its metrics.
239
fn worker_router(app: Shared) -> axum::Router {
240
    use axum::routing::get;
241
    let hsts = headers::hsts(app.config.base_url(), app.config.server.hsts_max_age);
242
    axum::Router::new()
243
        .route("/health", get(web::home::health))
244
        .route("/metrics", get(metrics::metrics))
245
        .with_state(app)
246
        .layer(axum::middleware::from_fn_with_state(hsts, headers::security_headers))
247
}
248
249
/// The full router: pages, API, protocol and static assets.
250
fn full_router(app: Shared) -> axum::Router {
251
    let https = app_https(&app);
252
    let hsts = headers::hsts(app.config.base_url(), app.config.server.hsts_max_age);
253
    web::router(app.clone())
254
        .layer(axum::middleware::from_fn_with_state(app, agent_requests))
255
        .layer(axum::middleware::from_fn(private_pages))
256
        .layer(axum::middleware::from_fn(slow_requests))
257
        .layer(axum::middleware::from_fn_with_state(https, https_only))
258
        .layer(axum::middleware::from_fn_with_state(hsts, headers::security_headers))
259
}
260
261
/// The site's https address, when it has one: what [`https_only`] redirects to.
262
fn app_https(app: &Shared) -> Option<String> {
263
    let base = app.config.base_url();
264
    base.starts_with("https://").then(|| base.trim_end_matches('/').to_string())
265
}
266
267
/// The scheme a proxy in front of the hub says the visitor used
268
/// (`X-Forwarded-Proto`, else Cloudflare's `CF-Visitor`); `None` for a
269
/// request made to the hub directly (runners and tools on its host).
270
fn forwarded_scheme(headers: &axum::http::HeaderMap) -> Option<String> {
271
    if let Some(p) = headers.get("x-forwarded-proto").and_then(|v| v.to_str().ok()) {
272
        return p.split(',').next().map(|s| s.trim().to_ascii_lowercase());
273
    }
274
    let visitor = headers.get("cf-visitor").and_then(|v| v.to_str().ok())?;
275
    serde_json::from_str::<serde_json::Value>(visitor).ok()?["scheme"].as_str().map(str::to_ascii_lowercase)
276
}
277
278
/// HTTPS only (oxygenhub#218): on a site whose address is https, a request
279
/// a proxy reports as plain http is sent to the https address (GET and
280
/// HEAD) or refused (anything else, so a form or a password is never taken
281
/// over http). Requests made to the hub directly carry no such report and
282
/// are untouched.
283
async fn https_only(
284
    axum::extract::State(https): axum::extract::State<Option<String>>,
285
    req: axum::extract::Request,
286
    next: axum::middleware::Next,
287
) -> axum::response::Response {
288
    use axum::response::IntoResponse;
289
    let Some(base) = https else { return next.run(req).await };
290
    if forwarded_scheme(req.headers()).as_deref() != Some("http") {
291
        return next.run(req).await;
292
    }
293
    let to = format!("{base}{}", req.uri().path_and_query().map(|p| p.as_str()).unwrap_or("/"));
294
    if matches!(*req.method(), axum::http::Method::GET | axum::http::Method::HEAD) {
295
        return axum::response::Redirect::permanent(&to).into_response();
296
    }
297
    (axum::http::StatusCode::BAD_REQUEST, format!("This site takes requests over HTTPS only: send it to {to}\n")).into_response()
298
}
299
300
/// A request made with a token its owner marked as an agent's runs with
301
/// that token's name in [`notify::AGENT`], so what the agent does is told
302
/// to its owner (oxygenhub#183).
303
async fn agent_requests(
304
    axum::extract::State(app): axum::extract::State<Shared>,
305
    req: axum::extract::Request,
306
    next: axum::middleware::Next,
307
) -> axum::response::Response {
308
    let token = req
309
        .headers()
310
        .get(axum::http::header::AUTHORIZATION)
311
        .and_then(|v| v.to_str().ok())
312
        .and_then(|v| v.strip_prefix("Bearer "))
313
        .map(|t| t.trim().to_string());
314
    let agent = match token {
315
        // A keyless agent's grant token (#253) is always an agent's.
316
        Some(t) if t.starts_with(keyless::GRANT_TOKEN_PREFIX) => db::accounts::agent_grant_by_token(&app.db, &auth::token_hash(&t))
317
            .await
318
            .ok()
319
            .flatten()
320
            .filter(|g| g.live(db::now_ms()))
321
            .map(|g| g.agent),
322
        Some(t) => db::accounts::token_by_hash(&app.db, &auth::token_hash(&t)).await.ok().flatten().filter(|t| t.agent).map(|t| t.name),
323
        None => None,
324
    };
325
    notify::AGENT.scope(agent, next.run(req)).await
326
}
327
328
/// Requests slower than this are logged, with their path (#145).
329
const SLOW: std::time::Duration = std::time::Duration::from_secs(2);
330
331
/// Log a slow request's method, path and time, so a slow page can be
332
/// found afterwards. Never the query, which may hold a token.
333
async fn slow_requests(req: axum::extract::Request, next: axum::middleware::Next) -> axum::response::Response {
334
    let (method, path) = (req.method().clone(), req.uri().path().to_string());
335
    let start = std::time::Instant::now();
336
    let res = next.run(req).await;
337
    let took = start.elapsed();
338
    metrics::observe(method.as_str(), &path, res.status().as_u16(), took.as_secs_f64());
339
    if took >= SLOW {
340
        tracing::warn!("slow request: {method} {path} took {:.1} s ({})", took.as_secs_f64(), res.status().as_u16());
341
    }
342
    res
343
}
344
345
/// A page for a signed-in viewer is theirs alone: it may list private
346
/// repositories, and the dashboard's sky carries their activity (#157). An
347
/// HTML response to a request with a session cookie, which has not said
348
/// how to cache itself, says `private, no-store`, so no shared cache (a
349
/// proxy or a CDN in front of the hub) ever serves it to anyone else.
350
async fn private_pages(req: axum::extract::Request, next: axum::middleware::Next) -> axum::response::Response {
351
    use axum::http::header;
352
    let signed_in = req
353
        .headers()
354
        .get_all(header::COOKIE)
355
        .iter()
356
        .filter_map(|v| v.to_str().ok())
357
        .any(|c| c.split(';').any(|kv| kv.trim_start().starts_with("oxyhub=")));
358
    let mut res = next.run(req).await;
359
    let html = res.headers().get(header::CONTENT_TYPE).and_then(|v| v.to_str().ok()).is_some_and(|t| t.starts_with("text/html"));
360
    if signed_in && html && !res.headers().contains_key(header::CACHE_CONTROL) {
361
        res.headers_mut().insert(header::CACHE_CONTROL, header::HeaderValue::from_static("private, no-store"));
362
    }
363
    res
364
}
365
366
/// Serve on the configured addresses until the process is told to stop.
367
pub async fn serve(app: Shared) -> anyhow::Result<()> {
368
    let router = router(app.clone());
369
    let http = app.config.bind_addr()?;
370
    let https = app.config.tls_bind_addr()?;
371
    if http.is_none() && https.is_none() && app.roles.web {
372
        anyhow::bail!("nothing to bind: set server.bind or server.tls_bind");
373
    }
374
    tracing::info!("roles: {}", app.roles.names().join(", "));
375
    // Installed first: from here a SIGTERM drains rather than kills.
376
    let signal = shutdown::on_signal()?;
377
    let mut tasks = tokio::task::JoinSet::new();
378
    if let Some(addr) = http {
379
        let listener = match shutdown::systemd_listener() {
380
            Some(l) => {
381
                tracing::info!("http on the socket systemd holds ({})", l.local_addr().map(|a| a.to_string()).unwrap_or_default());
382
                tokio::net::TcpListener::from_std(l)?
383
            }
384
            None => {
385
                tracing::info!("http on {addr}");
386
                tokio::net::TcpListener::bind(addr).await?
387
            }
388
        };
389
        let r = router.clone();
390
        tasks.spawn(async move {
391
            axum::serve(listener, r.into_make_service_with_connect_info::<std::net::SocketAddr>())
392
                .with_graceful_shutdown(shutdown::stopping())
393
                .await
394
                .map_err(anyhow::Error::from)
395
        });
396
    }
397
    if let Some(addr) = https {
398
        let _ = rustls::crypto::ring::default_provider().install_default();
399
        let tls = axum_server::tls_rustls::RustlsConfig::from_pem_file(app.config.tls_cert(), app.config.tls_key())
400
            .await
401
            .map_err(|e| anyhow::anyhow!("loading TLS files: {e}"))?;
402
        tracing::info!("https on {addr}");
403
        let r = router.clone();
404
        let handle = axum_server::Handle::new();
405
        let draining = handle.clone();
406
        tokio::spawn(async move {
407
            shutdown::stopping().await;
408
            draining.graceful_shutdown(Some(shutdown::DRAIN));
409
        });
410
        tasks.spawn(async move {
411
            axum_server::bind_rustls(addr, tls)
412
                .handle(handle)
413
                .serve(r.into_make_service_with_connect_info::<std::net::SocketAddr>())
414
                .await
415
                .map_err(anyhow::Error::from)
416
        });
417
    }
418
    tokio::select! {
419
        // A worker with no address to serve on runs until it is stopped.
420
        r = tasks.join_next(), if !tasks.is_empty() => { r.transpose()?.transpose()?; Ok(()) }
421
        _ = signal => {
422
            // The servers stop taking connections and finish what they
423
            // have; whatever is still running after DRAIN is cut off.
424
            let drained = tokio::time::timeout(shutdown::DRAIN, async { while tasks.join_next().await.is_some() {} }).await;
425
            if drained.is_err() {
426
                tracing::warn!("requests still running after {} s: stopping anyway", shutdown::DRAIN.as_secs());
427
            }
428
            tracing::info!("stopped");
429
            Ok(())
430
        }
431
    }
432
}