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