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