OXYGENHUB
# c4027e038d25 oxygenhub / crates / hub / src / lib.rs
12.1 KiB · Rust · last changed Security headers on every response; CSP report-only with a report endpoint 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
    web::router(app.clone())
169
        .layer(axum::middleware::from_fn_with_state(app, agent_requests))
170
        .layer(axum::middleware::from_fn(private_pages))
171
        .layer(axum::middleware::from_fn(slow_requests))
172
        .layer(axum::middleware::from_fn_with_state(https, https_only))
173
        .layer(axum::middleware::from_fn(headers::security_headers))
174
}
175
176
/// The site's https address, when it has one: what [`https_only`] redirects to.
177
fn app_https(app: &Shared) -> Option<String> {
178
    let base = app.config.base_url();
179
    base.starts_with("https://").then(|| base.trim_end_matches('/').to_string())
180
}
181
182
/// The scheme a proxy in front of the hub says the visitor used
183
/// (`X-Forwarded-Proto`, else Cloudflare's `CF-Visitor`); `None` for a
184
/// request made to the hub directly (runners and tools on its host).
185
fn forwarded_scheme(headers: &axum::http::HeaderMap) -> Option<String> {
186
    if let Some(p) = headers.get("x-forwarded-proto").and_then(|v| v.to_str().ok()) {
187
        return p.split(',').next().map(|s| s.trim().to_ascii_lowercase());
188
    }
189
    let visitor = headers.get("cf-visitor").and_then(|v| v.to_str().ok())?;
190
    serde_json::from_str::<serde_json::Value>(visitor).ok()?["scheme"].as_str().map(str::to_ascii_lowercase)
191
}
192
193
/// HTTPS only (oxygenhub#218): on a site whose address is https, a request
194
/// a proxy reports as plain http is sent to the https address (GET and
195
/// HEAD) or refused (anything else, so a form or a password is never taken
196
/// over http). Requests made to the hub directly carry no such report and
197
/// are untouched.
198
async fn https_only(
199
    axum::extract::State(https): axum::extract::State<Option<String>>,
200
    req: axum::extract::Request,
201
    next: axum::middleware::Next,
202
) -> axum::response::Response {
203
    use axum::response::IntoResponse;
204
    let Some(base) = https else { return next.run(req).await };
205
    if forwarded_scheme(req.headers()).as_deref() != Some("http") {
206
        return next.run(req).await;
207
    }
208
    let to = format!("{base}{}", req.uri().path_and_query().map(|p| p.as_str()).unwrap_or("/"));
209
    if matches!(*req.method(), axum::http::Method::GET | axum::http::Method::HEAD) {
210
        return axum::response::Redirect::permanent(&to).into_response();
211
    }
212
    (axum::http::StatusCode::BAD_REQUEST, format!("This site takes requests over HTTPS only: send it to {to}\n")).into_response()
213
}
214
215
/// A request made with a token its owner marked as an agent's runs with
216
/// that token's name in [`notify::AGENT`], so what the agent does is told
217
/// to its owner (oxygenhub#183).
218
async fn agent_requests(
219
    axum::extract::State(app): axum::extract::State<Shared>,
220
    req: axum::extract::Request,
221
    next: axum::middleware::Next,
222
) -> axum::response::Response {
223
    let token = req
224
        .headers()
225
        .get(axum::http::header::AUTHORIZATION)
226
        .and_then(|v| v.to_str().ok())
227
        .and_then(|v| v.strip_prefix("Bearer "))
228
        .map(|t| auth::token_hash(t.trim()));
229
    let agent = match token {
230
        Some(hash) => db::accounts::token_by_hash(&app.db, &hash).await.ok().flatten().filter(|t| t.agent).map(|t| t.name),
231
        None => None,
232
    };
233
    notify::AGENT.scope(agent, next.run(req)).await
234
}
235
236
/// Requests slower than this are logged, with their path (#145).
237
const SLOW: std::time::Duration = std::time::Duration::from_secs(2);
238
239
/// Log a slow request's method, path and time, so a slow page can be
240
/// found afterwards. Never the query, which may hold a token.
241
async fn slow_requests(req: axum::extract::Request, next: axum::middleware::Next) -> axum::response::Response {
242
    let (method, path) = (req.method().clone(), req.uri().path().to_string());
243
    let start = std::time::Instant::now();
244
    let res = next.run(req).await;
245
    let took = start.elapsed();
246
    if took >= SLOW {
247
        tracing::warn!("slow request: {method} {path} took {:.1} s ({})", took.as_secs_f64(), res.status().as_u16());
248
    }
249
    res
250
}
251
252
/// A page for a signed-in viewer is theirs alone: it may list private
253
/// repositories, and the dashboard's sky carries their activity (#157). An
254
/// HTML response to a request with a session cookie, which has not said
255
/// how to cache itself, says `private, no-store`, so no shared cache (a
256
/// proxy or a CDN in front of the hub) ever serves it to anyone else.
257
async fn private_pages(req: axum::extract::Request, next: axum::middleware::Next) -> axum::response::Response {
258
    use axum::http::header;
259
    let signed_in = req
260
        .headers()
261
        .get_all(header::COOKIE)
262
        .iter()
263
        .filter_map(|v| v.to_str().ok())
264
        .any(|c| c.split(';').any(|kv| kv.trim_start().starts_with("oxyhub=")));
265
    let mut res = next.run(req).await;
266
    let html = res.headers().get(header::CONTENT_TYPE).and_then(|v| v.to_str().ok()).is_some_and(|t| t.starts_with("text/html"));
267
    if signed_in && html && !res.headers().contains_key(header::CACHE_CONTROL) {
268
        res.headers_mut().insert(header::CACHE_CONTROL, header::HeaderValue::from_static("private, no-store"));
269
    }
270
    res
271
}
272
273
/// Serve on the configured addresses until the process is told to stop.
274
pub async fn serve(app: Shared) -> anyhow::Result<()> {
275
    let router = router(app.clone());
276
    let http = app.config.bind_addr()?;
277
    let https = app.config.tls_bind_addr()?;
278
    if http.is_none() && https.is_none() {
279
        anyhow::bail!("nothing to bind: set server.bind or server.tls_bind");
280
    }
281
    let mut tasks = tokio::task::JoinSet::new();
282
    if let Some(addr) = http {
283
        let listener = tokio::net::TcpListener::bind(addr).await?;
284
        tracing::info!("http on {addr}");
285
        let r = router.clone();
286
        tasks.spawn(async move {
287
            axum::serve(listener, r.into_make_service_with_connect_info::<std::net::SocketAddr>()).await.map_err(anyhow::Error::from)
288
        });
289
    }
290
    if let Some(addr) = https {
291
        let _ = rustls::crypto::ring::default_provider().install_default();
292
        let tls = axum_server::tls_rustls::RustlsConfig::from_pem_file(app.config.tls_cert(), app.config.tls_key())
293
            .await
294
            .map_err(|e| anyhow::anyhow!("loading TLS files: {e}"))?;
295
        tracing::info!("https on {addr}");
296
        let r = router.clone();
297
        tasks.spawn(async move {
298
            axum_server::bind_rustls(addr, tls)
299
                .serve(r.into_make_service_with_connect_info::<std::net::SocketAddr>())
300
                .await
301
                .map_err(anyhow::Error::from)
302
        });
303
    }
304
    tokio::select! {
305
        r = tasks.join_next() => { r.transpose()?.transpose()?; Ok(()) }
306
        _ = tokio::signal::ctrl_c() => { tracing::info!("stopping"); Ok(()) }
307
    }
308
}