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