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