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