OXYGENHUB
# 0ee5c3fb32eb oxygenhub / crates / hub / src / lib.rs
14.1 KiB · Rust · last changed Push protection: refuse a push that adds what looks like a secret 16 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 provenance;
33
pub mod push_protection;
34
pub mod render;
35
pub mod reports;
36
pub mod repos;
37
pub mod secrets;
38
pub mod setup;
39
pub mod shutdown;
40
pub mod signin;
41
pub mod social;
42
pub mod storage;
43
pub mod swarm;
44
pub mod throttle;
45
pub mod tlog;
46
pub mod variables;
47
pub mod web;
48
pub mod wiki;
49
50
use crate::config::Config;
51
use crate::repos::Repos;
52
use std::sync::Arc;
53
54
/// Everything a request handler can reach.
55
pub struct App {
56
    pub config: Config,
57
    pub db: db::Pool,
58
    pub repos: Arc<Repos>,
59
    /// Wikis, one Oxygen repository per repository (hub spec §6.11).
60
    pub wikis: Arc<Repos>,
61
    pub server: Arc<oxy_server::Server>,
62
    pub hub_key: keys::HubKey,
63
    pub cookie_key: auth::CookieKey,
64
    /// Seals AI assistants' tokens at rest (hub spec §13.4).
65
    pub assistant_key: assistants::SecretKey,
66
    /// Seals Flow secrets at rest (hub spec §13.2, #107).
67
    pub secret_key: assistants::SecretKey,
68
    /// The OIDC issuer for jobs (hub spec §13.5), made on first use.
69
    pub oidc: tokio::sync::OnceCell<oidc::Issuer>,
70
    /// Which assistants are answering which proposals, and recent calls
71
    /// per repository (hub spec §13.4).
72
    pub assistant_gate: std::sync::Mutex<assistants::Gate>,
73
    /// Failed sign-ins and the like, per account and address (oxygenhub#221).
74
    pub throttle: std::sync::Mutex<throttle::Throttle>,
75
    pub events: events::Events,
76
    /// Who is resolving which conflict together (hub spec §6.10).
77
    pub rooms: Arc<live::Rooms>,
78
    /// Outgoing mail: hub.toml's `[email]`, overridden by what the admin
79
    /// page saved (#101).
80
    pub mail: std::sync::RwLock<config::Email>,
81
    /// The image swarm's tracker (oxygenhub#144).
82
    pub swarm: swarm::Tracker,
83
    pub started: std::time::Instant,
84
    /// The transparency log (#238).
85
    pub tlog: Arc<tlog::Log>,
86
}
87
88
impl App {
89
    /// The rootfs images this hub keeps for runners (oxygenflow#39).
90
    pub fn images(&self) -> images::Store {
91
        images::Store::new(&self.config.data)
92
    }
93
94
    /// The OIDC issuer, its key loaded or made the first time it is asked for.
95
    pub async fn oidc(&self) -> anyhow::Result<&oidc::Issuer> {
96
        let keys = self.config.keys_dir();
97
        self.oidc.get_or_try_init(|| async move { tokio::task::spawn_blocking(move || oidc::Issuer::load_or_create(&keys)).await? }).await
98
    }
99
}
100
101
pub type Shared = Arc<App>;
102
103
/// Open the data directory and build the application state. `init` must
104
/// have run once; `serve` and the tests call this.
105
pub async fn build(config: Config) -> anyhow::Result<Shared> {
106
    std::fs::create_dir_all(config.repos_dir())?;
107
    let db = db::open(&config).await?;
108
    let repos = Arc::new(Repos::new(config.repos_dir()));
109
    let wikis = Arc::new(Repos::new(config.data.join("wikis")));
110
    let hub_key = keys::ensure_identity(&config.keys_dir(), &config.site.name, config.base_url())?;
111
    let cookie_key = auth::CookieKey::load_or_create(&config.keys_dir())?;
112
    let assistant_key = assistants::SecretKey::load_or_create(&config.keys_dir())?;
113
    let secret_key = assistants::SecretKey::load_or_create_named(&config.keys_dir(), "secrets.key")?;
114
    let backend = protocol::HubBackend::new(
115
        repos.clone(),
116
        wikis.clone(),
117
        db.clone(),
118
        config.auth.push_tokens.clone(),
119
        tokio::runtime::Handle::current(),
120
    )
121
    .with_acceptor(hub_key.identity.clone(), keys::load_secret(&config.keys_dir())?.1)
122
    .with_scan_budget(push_protection::Budget {
123
        bytes: config.limits.scan_limit.0,
124
        file: config.limits.scan_file_limit.0,
125
        time: std::time::Duration::from_millis(config.limits.scan_time_ms),
126
    });
127
    let slot = backend.app_slot();
128
    let server = oxy_server::Server::new(backend);
129
    let mail = mail::load(&db, &config.email).await;
130
    let tlog = Arc::new(tlog::Log::open(&config.data.join("tlog"), &tlog::origin_of(config.base_url()))?);
131
    let app = Arc::new(App {
132
        mail: std::sync::RwLock::new(mail),
133
        config,
134
        db,
135
        repos,
136
        wikis,
137
        server,
138
        hub_key,
139
        cookie_key,
140
        assistant_key,
141
        secret_key,
142
        oidc: tokio::sync::OnceCell::new(),
143
        assistant_gate: std::sync::Mutex::new(assistants::Gate::default()),
144
        throttle: std::sync::Mutex::new(throttle::Throttle::default()),
145
        events: events::Events::default(),
146
        rooms: Arc::new(live::Rooms::default()),
147
        swarm: Default::default(),
148
        started: std::time::Instant::now(),
149
        tlog,
150
    });
151
    *slot.lock().unwrap() = Some(Arc::downgrade(&app));
152
    storage::load(&app).await?;
153
    coverage::load(&app).await?;
154
    junit::load(&app).await?;
155
    reports::load(&app).await?;
156
    tokio::spawn(hooks::worker(app.clone()));
157
    tokio::spawn(tlog::checkpointer(app.clone()));
158
    tokio::spawn(flow::reaper(app.clone()));
159
    tokio::spawn(flow::scheduler(app.clone()));
160
    tokio::spawn(flow::placement(app.clone()));
161
    tokio::spawn(maintenance::nightly(app.clone()));
162
    tokio::spawn(backups::scheduler(app.clone()));
163
    // The reverse pin index for repositories pushed before it existed (#148).
164
    tokio::spawn({
165
        let app = app.clone();
166
        async move { diffusion::backfill(&app).await }
167
    });
168
    // Mend the pin index and the bumps it drives (oxygenhub#210).
169
    tokio::spawn(diffusion::reconciler(app.clone()));
170
    // What each image is for, read or learned once (oxygenhub#173).
171
    tokio::spawn({
172
        let app = app.clone();
173
        async move {
174
            match images::learn_archs(&app).await {
175
                Ok(n) if n > 0 => tracing::info!(images = n, "read the architecture of kept images"),
176
                Ok(_) => {}
177
                Err(e) => tracing::warn!(error = %e, "learning image architectures"),
178
            }
179
        }
180
    });
181
    setup::ensure(&app).await?;
182
    Ok(app)
183
}
184
185
/// The full router: pages, API, protocol and static assets.
186
pub fn router(app: Shared) -> axum::Router {
187
    let https = app_https(&app);
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))
192
        .layer(axum::middleware::from_fn_with_state(https, https_only))
193
        .layer(axum::middleware::from_fn(headers::security_headers))
194
}
195
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
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 "))
248
        .map(|t| auth::token_hash(t.trim()));
249
    let agent = match token {
250
        Some(hash) => db::accounts::token_by_hash(&app.db, &hash).await.ok().flatten().filter(|t| t.agent).map(|t| t.name),
251
        None => None,
252
    };
253
    notify::AGENT.scope(agent, next.run(req)).await
254
}
255
256
/// Requests slower than this are logged, with their path (#145).
257
const SLOW: std::time::Duration = std::time::Duration::from_secs(2);
258
259
/// Log a slow request's method, path and time, so a slow page can be
260
/// found afterwards. Never the query, which may hold a token.
261
async fn slow_requests(req: axum::extract::Request, next: axum::middleware::Next) -> axum::response::Response {
262
    let (method, path) = (req.method().clone(), req.uri().path().to_string());
263
    let start = std::time::Instant::now();
264
    let res = next.run(req).await;
265
    let took = start.elapsed();
266
    if took >= SLOW {
267
        tracing::warn!("slow request: {method} {path} took {:.1} s ({})", took.as_secs_f64(), res.status().as_u16());
268
    }
269
    res
270
}
271
272
/// A page for a signed-in viewer is theirs alone: it may list private
273
/// repositories, and the dashboard's sky carries their activity (#157). An
274
/// HTML response to a request with a session cookie, which has not said
275
/// how to cache itself, says `private, no-store`, so no shared cache (a
276
/// proxy or a CDN in front of the hub) ever serves it to anyone else.
277
async fn private_pages(req: axum::extract::Request, next: axum::middleware::Next) -> axum::response::Response {
278
    use axum::http::header;
279
    let signed_in = req
280
        .headers()
281
        .get_all(header::COOKIE)
282
        .iter()
283
        .filter_map(|v| v.to_str().ok())
284
        .any(|c| c.split(';').any(|kv| kv.trim_start().starts_with("oxyhub=")));
285
    let mut res = next.run(req).await;
286
    let html = res.headers().get(header::CONTENT_TYPE).and_then(|v| v.to_str().ok()).is_some_and(|t| t.starts_with("text/html"));
287
    if signed_in && html && !res.headers().contains_key(header::CACHE_CONTROL) {
288
        res.headers_mut().insert(header::CACHE_CONTROL, header::HeaderValue::from_static("private, no-store"));
289
    }
290
    res
291
}
292
293
/// Serve on the configured addresses until the process is told to stop.
294
pub async fn serve(app: Shared) -> anyhow::Result<()> {
295
    let router = router(app.clone());
296
    let http = app.config.bind_addr()?;
297
    let https = app.config.tls_bind_addr()?;
298
    if http.is_none() && https.is_none() {
299
        anyhow::bail!("nothing to bind: set server.bind or server.tls_bind");
300
    }
301
    // Installed first: from here a SIGTERM drains rather than kills.
302
    let signal = shutdown::on_signal()?;
303
    let mut tasks = tokio::task::JoinSet::new();
304
    if let Some(addr) = http {
305
        let listener = match shutdown::systemd_listener() {
306
            Some(l) => {
307
                tracing::info!("http on the socket systemd holds ({})", l.local_addr().map(|a| a.to_string()).unwrap_or_default());
308
                tokio::net::TcpListener::from_std(l)?
309
            }
310
            None => {
311
                tracing::info!("http on {addr}");
312
                tokio::net::TcpListener::bind(addr).await?
313
            }
314
        };
315
        let r = router.clone();
316
        tasks.spawn(async move {
317
            axum::serve(listener, r.into_make_service_with_connect_info::<std::net::SocketAddr>())
318
                .with_graceful_shutdown(shutdown::stopping())
319
                .await
320
                .map_err(anyhow::Error::from)
321
        });
322
    }
323
    if let Some(addr) = https {
324
        let _ = rustls::crypto::ring::default_provider().install_default();
325
        let tls = axum_server::tls_rustls::RustlsConfig::from_pem_file(app.config.tls_cert(), app.config.tls_key())
326
            .await
327
            .map_err(|e| anyhow::anyhow!("loading TLS files: {e}"))?;
328
        tracing::info!("https on {addr}");
329
        let r = router.clone();
330
        let handle = axum_server::Handle::new();
331
        let draining = handle.clone();
332
        tokio::spawn(async move {
333
            shutdown::stopping().await;
334
            draining.graceful_shutdown(Some(shutdown::DRAIN));
335
        });
336
        tasks.spawn(async move {
337
            axum_server::bind_rustls(addr, tls)
338
                .handle(handle)
339
                .serve(r.into_make_service_with_connect_info::<std::net::SocketAddr>())
340
                .await
341
                .map_err(anyhow::Error::from)
342
        });
343
    }
344
    tokio::select! {
345
        r = tasks.join_next() => { r.transpose()?.transpose()?; Ok(()) }
346
        _ = signal => {
347
            // The servers stop taking connections and finish what they
348
            // have; whatever is still running after DRAIN is cut off.
349
            let drained = tokio::time::timeout(shutdown::DRAIN, async { while tasks.join_next().await.is_some() {} }).await;
350
            if drained.is_err() {
351
                tracing::warn!("requests still running after {} s: stopping anyway", shutdown::DRAIN.as_secs());
352
            }
353
            tracing::info!("stopped");
354
            Ok(())
355
        }
356
    }
357
}