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