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