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