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