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