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