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