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