| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
pub mod api; |
| 9 |
pub mod apt; |
| 10 |
pub mod assistants; |
| 11 |
pub mod auth; |
| 12 |
pub mod autoland; |
| 13 |
pub mod backups; |
| 14 |
pub mod bus; |
| 15 |
pub mod config; |
| 16 |
pub mod coverage; |
| 17 |
pub mod db; |
| 18 |
pub mod diffusion; |
| 19 |
pub mod drops; |
| 20 |
pub mod events; |
| 21 |
pub mod flow; |
| 22 |
pub mod headers; |
| 23 |
pub mod history_scan; |
| 24 |
pub mod hooks; |
| 25 |
pub mod images; |
| 26 |
pub mod insights; |
| 27 |
pub mod junit; |
| 28 |
pub mod keyless; |
| 29 |
pub mod keys; |
| 30 |
pub mod leader; |
| 31 |
pub mod levels; |
| 32 |
pub mod live; |
| 33 |
pub mod mail; |
| 34 |
pub mod maintenance; |
| 35 |
pub mod metrics; |
| 36 |
pub mod mirror; |
| 37 |
pub mod net; |
| 38 |
pub mod notify; |
| 39 |
pub mod oidc; |
| 40 |
pub mod protocol; |
| 41 |
pub mod provenance; |
| 42 |
pub mod push_protection; |
| 43 |
pub mod queue; |
| 44 |
pub mod render; |
| 45 |
pub mod reports; |
| 46 |
pub mod repos; |
| 47 |
pub mod runner_updates; |
| 48 |
pub mod secrets; |
| 49 |
pub mod setup; |
| 50 |
pub mod shutdown; |
| 51 |
pub mod signin; |
| 52 |
pub mod social; |
| 53 |
pub mod storage; |
| 54 |
pub mod swarm; |
| 55 |
pub mod tags; |
| 56 |
pub mod terraform; |
| 57 |
pub mod throttle; |
| 58 |
pub mod tlog; |
| 59 |
pub mod variables; |
| 60 |
pub mod web; |
| 61 |
pub mod wiki; |
| 62 |
|
| 63 |
use crate::config::Config; |
| 64 |
use crate::repos::Repos; |
| 65 |
use std::sync::Arc; |
| 66 |
|
| 67 |
|
| 68 |
pub struct App { |
| 69 |
pub config: Config, |
| 70 |
pub db: db::Pool, |
| 71 |
pub repos: Arc<Repos>, |
| 72 |
|
| 73 |
pub wikis: Arc<Repos>, |
| 74 |
pub server: Arc<oxy_server::Server>, |
| 75 |
pub hub_key: keys::HubKey, |
| 76 |
pub cookie_key: auth::CookieKey, |
| 77 |
|
| 78 |
pub assistant_key: assistants::SecretKey, |
| 79 |
|
| 80 |
pub secret_key: assistants::SecretKey, |
| 81 |
|
| 82 |
pub oidc: tokio::sync::OnceCell<oidc::Issuer>, |
| 83 |
|
| 84 |
|
| 85 |
pub assistant_gate: std::sync::Mutex<assistants::Gate>, |
| 86 |
|
| 87 |
pub throttle: std::sync::Mutex<throttle::Throttle>, |
| 88 |
|
| 89 |
|
| 90 |
pub bus: bus::Bus, |
| 91 |
|
| 92 |
pub rooms: Arc<live::Rooms>, |
| 93 |
|
| 94 |
|
| 95 |
pub mail: std::sync::RwLock<config::Email>, |
| 96 |
|
| 97 |
pub swarm: swarm::Tracker, |
| 98 |
pub started: std::time::Instant, |
| 99 |
|
| 100 |
pub tlog: Arc<tlog::Log>, |
| 101 |
|
| 102 |
pub roles: config::Roles, |
| 103 |
|
| 104 |
pub leader: leader::Leader, |
| 105 |
} |
| 106 |
|
| 107 |
impl App { |
| 108 |
|
| 109 |
pub fn images(&self) -> images::Store { |
| 110 |
images::Store::new(&self.config.data) |
| 111 |
} |
| 112 |
|
| 113 |
|
| 114 |
pub async fn oidc(&self) -> anyhow::Result<&oidc::Issuer> { |
| 115 |
let keys = self.config.keys_dir(); |
| 116 |
self.oidc.get_or_try_init(|| async move { tokio::task::spawn_blocking(move || oidc::Issuer::load_or_create(&keys)).await? }).await |
| 117 |
} |
| 118 |
} |
| 119 |
|
| 120 |
pub type Shared = Arc<App>; |
| 121 |
|
| 122 |
|
| 123 |
|
| 124 |
pub async fn build(config: Config) -> anyhow::Result<Shared> { |
| 125 |
let roles = config.roles()?; |
| 126 |
std::fs::create_dir_all(config.repos_dir())?; |
| 127 |
let db = db::open(&config).await?; |
| 128 |
let repos = Arc::new(Repos::new(config.repos_dir())); |
| 129 |
let wikis = Arc::new(Repos::new(config.data.join("wikis"))); |
| 130 |
let hub_key = keys::ensure_identity(&config.keys_dir(), &config.site.name, config.base_url())?; |
| 131 |
let cookie_key = auth::CookieKey::load_or_create(&config.keys_dir())?; |
| 132 |
let assistant_key = assistants::SecretKey::load_or_create(&config.keys_dir())?; |
| 133 |
let secret_key = assistants::SecretKey::load_or_create_named(&config.keys_dir(), "secrets.key")?; |
| 134 |
let backend = protocol::HubBackend::new( |
| 135 |
repos.clone(), |
| 136 |
wikis.clone(), |
| 137 |
db.clone(), |
| 138 |
config.auth.push_tokens.clone(), |
| 139 |
tokio::runtime::Handle::current(), |
| 140 |
) |
| 141 |
.with_acceptor(hub_key.identity.clone(), keys::load_secret(&config.keys_dir())?.1) |
| 142 |
.with_scan_budget(push_protection::Budget { |
| 143 |
bytes: config.limits.scan_limit.0, |
| 144 |
file: config.limits.scan_file_limit.0, |
| 145 |
time: std::time::Duration::from_millis(config.limits.scan_time_ms), |
| 146 |
}); |
| 147 |
let slot = backend.app_slot(); |
| 148 |
let server = oxy_server::Server::new(backend); |
| 149 |
let mail = mail::load(&db, &config.email).await; |
| 150 |
|
| 151 |
let (tlog_dir, origin) = (config.data.join("tlog"), tlog::origin_of(config.base_url())); |
| 152 |
let tlog = Arc::new(if roles.web { tlog::Log::open(&tlog_dir, &origin)? } else { tlog::Log::open_reader(&tlog_dir, &origin)? }); |
| 153 |
tlog.configure(&config.tlog)?; |
| 154 |
let app = Arc::new(App { |
| 155 |
mail: std::sync::RwLock::new(mail), |
| 156 |
config, |
| 157 |
db, |
| 158 |
repos, |
| 159 |
wikis, |
| 160 |
server, |
| 161 |
hub_key, |
| 162 |
cookie_key, |
| 163 |
assistant_key, |
| 164 |
secret_key, |
| 165 |
oidc: tokio::sync::OnceCell::new(), |
| 166 |
assistant_gate: std::sync::Mutex::new(assistants::Gate::default()), |
| 167 |
throttle: std::sync::Mutex::new(throttle::Throttle::default()), |
| 168 |
bus: bus::Bus::default(), |
| 169 |
rooms: Arc::new(live::Rooms::default()), |
| 170 |
swarm: Default::default(), |
| 171 |
started: std::time::Instant::now(), |
| 172 |
tlog, |
| 173 |
roles, |
| 174 |
leader: leader::Leader::default(), |
| 175 |
}); |
| 176 |
*slot.lock().unwrap() = Some(Arc::downgrade(&app)); |
| 177 |
bus::start(&app).await?; |
| 178 |
storage::load(&app).await?; |
| 179 |
coverage::load(&app).await?; |
| 180 |
junit::load(&app).await?; |
| 181 |
reports::load(&app).await?; |
| 182 |
start_background(&app); |
| 183 |
setup::ensure(&app).await?; |
| 184 |
Ok(app) |
| 185 |
} |
| 186 |
|
| 187 |
|
| 188 |
|
| 189 |
|
| 190 |
|
| 191 |
fn start_background(app: &Shared) { |
| 192 |
if app.roles.web { |
| 193 |
|
| 194 |
leader::run(app, "tlog.checkpointer", tlog::checkpointer); |
| 195 |
} |
| 196 |
if !app.roles.worker { |
| 197 |
return; |
| 198 |
} |
| 199 |
leader::run(app, "hooks.worker", hooks::worker); |
| 200 |
leader::run(app, "flow.reaper", flow::reaper); |
| 201 |
leader::run(app, "flow.scheduler", flow::scheduler); |
| 202 |
leader::run(app, "flow.placement", flow::placement); |
| 203 |
leader::run(app, "maintenance.nightly", maintenance::nightly); |
| 204 |
leader::run(app, "projects.archiver", maintenance::archiver); |
| 205 |
leader::run(app, "backups.scheduler", backups::scheduler); |
| 206 |
|
| 207 |
|
| 208 |
leader::run(app, "diffusion.backfill", |app| async move { diffusion::backfill(&app).await }); |
| 209 |
|
| 210 |
leader::run(app, "diffusion.reconciler", diffusion::reconciler); |
| 211 |
|
| 212 |
|
| 213 |
leader::run(app, "secrets.history_scan", history_scan::worker); |
| 214 |
|
| 215 |
app.leader.note("queue.worker"); |
| 216 |
tokio::spawn(queue::worker(app.clone())); |
| 217 |
|
| 218 |
|
| 219 |
app.leader.note("images.learn_archs"); |
| 220 |
tokio::spawn({ |
| 221 |
let app = app.clone(); |
| 222 |
async move { |
| 223 |
match images::learn_archs(&app).await { |
| 224 |
Ok(n) if n > 0 => tracing::info!(images = n, "read the architecture of kept images"), |
| 225 |
Ok(_) => {} |
| 226 |
Err(e) => tracing::warn!(error = %e, "learning image architectures"), |
| 227 |
} |
| 228 |
} |
| 229 |
}); |
| 230 |
} |
| 231 |
|
| 232 |
|
| 233 |
|
| 234 |
pub fn router(app: Shared) -> axum::Router { |
| 235 |
if !app.roles.web { |
| 236 |
return worker_router(app); |
| 237 |
} |
| 238 |
full_router(app) |
| 239 |
} |
| 240 |
|
| 241 |
|
| 242 |
fn worker_router(app: Shared) -> axum::Router { |
| 243 |
use axum::routing::get; |
| 244 |
let hsts = headers::hsts(app.config.base_url(), app.config.server.hsts_max_age); |
| 245 |
axum::Router::new() |
| 246 |
.route("/health", get(web::home::health)) |
| 247 |
.route("/metrics", get(metrics::metrics)) |
| 248 |
.with_state(app) |
| 249 |
.layer(axum::middleware::from_fn_with_state(hsts, headers::security_headers)) |
| 250 |
} |
| 251 |
|
| 252 |
|
| 253 |
fn full_router(app: Shared) -> axum::Router { |
| 254 |
let https = app_https(&app); |
| 255 |
let hsts = headers::hsts(app.config.base_url(), app.config.server.hsts_max_age); |
| 256 |
web::router(app.clone()) |
| 257 |
.layer(axum::middleware::from_fn_with_state(app, agent_requests)) |
| 258 |
.layer(axum::middleware::from_fn(private_pages)) |
| 259 |
.layer(axum::middleware::from_fn(slow_requests)) |
| 260 |
.layer(axum::middleware::from_fn_with_state(https, https_only)) |
| 261 |
.layer(axum::middleware::from_fn_with_state(hsts, headers::security_headers)) |
| 262 |
} |
| 263 |
|
| 264 |
|
| 265 |
fn app_https(app: &Shared) -> Option<String> { |
| 266 |
let base = app.config.base_url(); |
| 267 |
base.starts_with("https://").then(|| base.trim_end_matches('/').to_string()) |
| 268 |
} |
| 269 |
|
| 270 |
|
| 271 |
|
| 272 |
|
| 273 |
fn forwarded_scheme(headers: &axum::http::HeaderMap) -> Option<String> { |
| 274 |
if let Some(p) = headers.get("x-forwarded-proto").and_then(|v| v.to_str().ok()) { |
| 275 |
return p.split(',').next().map(|s| s.trim().to_ascii_lowercase()); |
| 276 |
} |
| 277 |
let visitor = headers.get("cf-visitor").and_then(|v| v.to_str().ok())?; |
| 278 |
serde_json::from_str::<serde_json::Value>(visitor).ok()?["scheme"].as_str().map(str::to_ascii_lowercase) |
| 279 |
} |
| 280 |
|
| 281 |
|
| 282 |
|
| 283 |
|
| 284 |
|
| 285 |
|
| 286 |
async fn https_only( |
| 287 |
axum::extract::State(https): axum::extract::State<Option<String>>, |
| 288 |
req: axum::extract::Request, |
| 289 |
next: axum::middleware::Next, |
| 290 |
) -> axum::response::Response { |
| 291 |
use axum::response::IntoResponse; |
| 292 |
let Some(base) = https else { return next.run(req).await }; |
| 293 |
if forwarded_scheme(req.headers()).as_deref() != Some("http") { |
| 294 |
return next.run(req).await; |
| 295 |
} |
| 296 |
let to = format!("{base}{}", req.uri().path_and_query().map(|p| p.as_str()).unwrap_or("/")); |
| 297 |
if matches!(*req.method(), axum::http::Method::GET | axum::http::Method::HEAD) { |
| 298 |
return axum::response::Redirect::permanent(&to).into_response(); |
| 299 |
} |
| 300 |
(axum::http::StatusCode::BAD_REQUEST, format!("This site takes requests over HTTPS only: send it to {to}\n")).into_response() |
| 301 |
} |
| 302 |
|
| 303 |
|
| 304 |
|
| 305 |
|
| 306 |
async fn agent_requests( |
| 307 |
axum::extract::State(app): axum::extract::State<Shared>, |
| 308 |
req: axum::extract::Request, |
| 309 |
next: axum::middleware::Next, |
| 310 |
) -> axum::response::Response { |
| 311 |
let token = req |
| 312 |
.headers() |
| 313 |
.get(axum::http::header::AUTHORIZATION) |
| 314 |
.and_then(|v| v.to_str().ok()) |
| 315 |
.and_then(|v| v.strip_prefix("Bearer ")) |
| 316 |
.map(|t| auth::token_hash(t.trim())); |
| 317 |
let agent = match token { |
| 318 |
Some(hash) => db::accounts::token_by_hash(&app.db, &hash).await.ok().flatten().filter(|t| t.agent).map(|t| t.name), |
| 319 |
None => None, |
| 320 |
}; |
| 321 |
notify::AGENT.scope(agent, next.run(req)).await |
| 322 |
} |
| 323 |
|
| 324 |
|
| 325 |
const SLOW: std::time::Duration = std::time::Duration::from_secs(2); |
| 326 |
|
| 327 |
|
| 328 |
|
| 329 |
async fn slow_requests(req: axum::extract::Request, next: axum::middleware::Next) -> axum::response::Response { |
| 330 |
let (method, path) = (req.method().clone(), req.uri().path().to_string()); |
| 331 |
let start = std::time::Instant::now(); |
| 332 |
let res = next.run(req).await; |
| 333 |
let took = start.elapsed(); |
| 334 |
metrics::observe(method.as_str(), &path, res.status().as_u16(), took.as_secs_f64()); |
| 335 |
if took >= SLOW { |
| 336 |
tracing::warn!("slow request: {method} {path} took {:.1} s ({})", took.as_secs_f64(), res.status().as_u16()); |
| 337 |
} |
| 338 |
res |
| 339 |
} |
| 340 |
|
| 341 |
|
| 342 |
|
| 343 |
|
| 344 |
|
| 345 |
|
| 346 |
async fn private_pages(req: axum::extract::Request, next: axum::middleware::Next) -> axum::response::Response { |
| 347 |
use axum::http::header; |
| 348 |
let signed_in = req |
| 349 |
.headers() |
| 350 |
.get_all(header::COOKIE) |
| 351 |
.iter() |
| 352 |
.filter_map(|v| v.to_str().ok()) |
| 353 |
.any(|c| c.split(';').any(|kv| kv.trim_start().starts_with("oxyhub="))); |
| 354 |
let mut res = next.run(req).await; |
| 355 |
let html = res.headers().get(header::CONTENT_TYPE).and_then(|v| v.to_str().ok()).is_some_and(|t| t.starts_with("text/html")); |
| 356 |
if signed_in && html && !res.headers().contains_key(header::CACHE_CONTROL) { |
| 357 |
res.headers_mut().insert(header::CACHE_CONTROL, header::HeaderValue::from_static("private, no-store")); |
| 358 |
} |
| 359 |
res |
| 360 |
} |
| 361 |
|
| 362 |
|
| 363 |
pub async fn serve(app: Shared) -> anyhow::Result<()> { |
| 364 |
let router = router(app.clone()); |
| 365 |
let http = app.config.bind_addr()?; |
| 366 |
let https = app.config.tls_bind_addr()?; |
| 367 |
if http.is_none() && https.is_none() && app.roles.web { |
| 368 |
anyhow::bail!("nothing to bind: set server.bind or server.tls_bind"); |
| 369 |
} |
| 370 |
tracing::info!("roles: {}", app.roles.names().join(", ")); |
| 371 |
|
| 372 |
let signal = shutdown::on_signal()?; |
| 373 |
let mut tasks = tokio::task::JoinSet::new(); |
| 374 |
if let Some(addr) = http { |
| 375 |
let listener = match shutdown::systemd_listener() { |
| 376 |
Some(l) => { |
| 377 |
tracing::info!("http on the socket systemd holds ({})", l.local_addr().map(|a| a.to_string()).unwrap_or_default()); |
| 378 |
tokio::net::TcpListener::from_std(l)? |
| 379 |
} |
| 380 |
None => { |
| 381 |
tracing::info!("http on {addr}"); |
| 382 |
tokio::net::TcpListener::bind(addr).await? |
| 383 |
} |
| 384 |
}; |
| 385 |
let r = router.clone(); |
| 386 |
tasks.spawn(async move { |
| 387 |
axum::serve(listener, r.into_make_service_with_connect_info::<std::net::SocketAddr>()) |
| 388 |
.with_graceful_shutdown(shutdown::stopping()) |
| 389 |
.await |
| 390 |
.map_err(anyhow::Error::from) |
| 391 |
}); |
| 392 |
} |
| 393 |
if let Some(addr) = https { |
| 394 |
let _ = rustls::crypto::ring::default_provider().install_default(); |
| 395 |
let tls = axum_server::tls_rustls::RustlsConfig::from_pem_file(app.config.tls_cert(), app.config.tls_key()) |
| 396 |
.await |
| 397 |
.map_err(|e| anyhow::anyhow!("loading TLS files: {e}"))?; |
| 398 |
tracing::info!("https on {addr}"); |
| 399 |
let r = router.clone(); |
| 400 |
let handle = axum_server::Handle::new(); |
| 401 |
let draining = handle.clone(); |
| 402 |
tokio::spawn(async move { |
| 403 |
shutdown::stopping().await; |
| 404 |
draining.graceful_shutdown(Some(shutdown::DRAIN)); |
| 405 |
}); |
| 406 |
tasks.spawn(async move { |
| 407 |
axum_server::bind_rustls(addr, tls) |
| 408 |
.handle(handle) |
| 409 |
.serve(r.into_make_service_with_connect_info::<std::net::SocketAddr>()) |
| 410 |
.await |
| 411 |
.map_err(anyhow::Error::from) |
| 412 |
}); |
| 413 |
} |
| 414 |
tokio::select! { |
| 415 |
|
| 416 |
r = tasks.join_next(), if !tasks.is_empty() => { r.transpose()?.transpose()?; Ok(()) } |
| 417 |
_ = signal => { |
| 418 |
|
| 419 |
|
| 420 |
let drained = tokio::time::timeout(shutdown::DRAIN, async { while tasks.join_next().await.is_some() {} }).await; |
| 421 |
if drained.is_err() { |
| 422 |
tracing::warn!("requests still running after {} s: stopping anyway", shutdown::DRAIN.as_secs()); |
| 423 |
} |
| 424 |
tracing::info!("stopped"); |
| 425 |
Ok(()) |
| 426 |
} |
| 427 |
} |
| 428 |
} |