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