| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | use std::fs::{File, OpenOptions, TryLockError}; |
| 9 | use std::os::unix::fs::PermissionsExt; |
| 10 | use std::path::Path; |
| 11 | use std::sync::{Arc, RwLock}; |
| 12 | |
| 13 | use im_core::config::{Config, PolicyConfig, SmtpTls}; |
| 14 | use im_core::photo::MAX_UPLOAD_BYTES; |
| 15 | use im_core::secret; |
| 16 | use im_core::store::Store; |
| 17 | use tokio::net::TcpListener; |
| 18 | use tokio::signal::unix::{SignalKind, signal}; |
| 19 | use tokio::sync::{Semaphore, watch}; |
| 20 | use topcoat::cookie::RouterBuilderCookieExt; |
| 21 | use topcoat::router::{BodyLimit, Router, RouterBuilderDiscoverExt, RouterService}; |
| 22 | |
| 23 | use crate::api::directory::StreamSlots; |
| 24 | use crate::backchannel; |
| 25 | use crate::backups::BackupTrigger; |
| 26 | use crate::live::{LiveHub, MAX_ANONYMOUS_STREAMS}; |
| 27 | use crate::mail; |
| 28 | use crate::oidc::signing; |
| 29 | use crate::pages::admin::message::{MESSAGE_BODY_LIMIT, MESSAGE_ROUTE}; |
| 30 | use crate::pages::not_found::NotFoundLayer; |
| 31 | use crate::pages::profile::PHOTO_ROUTE; |
| 32 | use crate::security::{self, SecurityHeaders}; |
| 33 | use crate::service_probe; |
| 34 | use crate::state::AppState; |
| 35 | use crate::sweeper; |
| 36 | use crate::throttle::Throttle; |
| 37 | |
| 38 | |
| 39 | pub(crate) const KEY_FILE: &str = "im.key"; |
| 40 | |
| 41 | |
| 42 | |
| 43 | const LOCK_FILE: &str = "im.lock"; |
| 44 | |
| 45 | |
| 46 | |
| 47 | |
| 48 | pub fn lock_data_dir(data_dir: &Path) -> im_core::Result<File> { |
| 49 | std::fs::create_dir_all(data_dir)?; |
| 50 | std::fs::set_permissions(data_dir, std::fs::Permissions::from_mode(0o700))?; |
| 51 | let file = OpenOptions::new() |
| 52 | .create(true) |
| 53 | .truncate(false) |
| 54 | .write(true) |
| 55 | .open(data_dir.join(LOCK_FILE))?; |
| 56 | match file.try_lock() { |
| 57 | Ok(()) => Ok(file), |
| 58 | Err(TryLockError::WouldBlock) => Err(im_core::Error::Conflict( |
| 59 | "im is running on this data directory. Stop the server first, then run the command again." |
| 60 | .into(), |
| 61 | )), |
| 62 | Err(TryLockError::Error(error)) => Err(error.into()), |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | |
| 67 | pub async fn serve(config_path: &Path) -> im_core::Result<()> { |
| 68 | let config = Config::load(config_path)?; |
| 69 | let listen = config.listen; |
| 70 | let _lock = lock_data_dir(&config.data_dir)?; |
| 71 | let state = open_state(config).await?; |
| 72 | warn_weak_settings(&state); |
| 73 | |
| 74 | let listener = TcpListener::bind(listen).await.map_err(|error| { |
| 75 | std::io::Error::new(error.kind(), format!("cannot bind {listen}: {error}")) |
| 76 | })?; |
| 77 | tracing::info!( |
| 78 | listen = %listen, |
| 79 | data_dir = %state.config.data_dir.display(), |
| 80 | build = env!("IM_BUILD_SHA"), |
| 81 | "im starting" |
| 82 | ); |
| 83 | |
| 84 | |
| 85 | let (stop_tx, stop_rx) = watch::channel(false); |
| 86 | let state = AppState { |
| 87 | stop: stop_rx.clone(), |
| 88 | ..state |
| 89 | }; |
| 90 | let backup_task = crate::backups::spawn(state.clone()); |
| 91 | tokio::spawn(async move { |
| 92 | shutdown_signal().await; |
| 93 | tracing::info!("shutdown signal received"); |
| 94 | stop_tx.send_replace(true); |
| 95 | }); |
| 96 | let signing_worker = signing::spawn(state.store.clone(), state.key.clone(), stop_rx.clone()); |
| 97 | let backchannel_worker = backchannel::spawn( |
| 98 | state.store.clone(), |
| 99 | state.key.clone(), |
| 100 | state.config.base_url.clone(), |
| 101 | stop_rx.clone(), |
| 102 | ); |
| 103 | let sweeper_task = sweeper::spawn(state.store.clone(), stop_rx.clone()); |
| 104 | let probe_worker = service_probe::spawn(state.store.clone(), stop_rx.clone()); |
| 105 | let mail_worker = mail::worker::spawn( |
| 106 | state.store.clone(), |
| 107 | state.key.clone(), |
| 108 | state.config.smtp.clone(), |
| 109 | stop_rx.clone(), |
| 110 | ); |
| 111 | |
| 112 | topcoat::serve_until( |
| 113 | listener, |
| 114 | RouterService::new(router(state)), |
| 115 | wait_stop(stop_rx), |
| 116 | ) |
| 117 | .await?; |
| 118 | let _ = signing_worker.await; |
| 119 | let _ = backchannel_worker.await; |
| 120 | let _ = sweeper_task.await; |
| 121 | let _ = probe_worker.await; |
| 122 | let _ = mail_worker.await; |
| 123 | if let Some(task) = backup_task { |
| 124 | let _ = task.await; |
| 125 | } |
| 126 | tracing::info!("im stopped"); |
| 127 | Ok(()) |
| 128 | } |
| 129 | |
| 130 | |
| 131 | |
| 132 | |
| 133 | fn warn_weak_settings(state: &AppState) { |
| 134 | let config = &state.config; |
| 135 | if !state.policy().require_2fa_for_admins { |
| 136 | tracing::warn!( |
| 137 | "require_2fa_for_admins is off: administrators may sign in without two-factor sign-in" |
| 138 | ); |
| 139 | } |
| 140 | if config.smtp.tls == SmtpTls::None { |
| 141 | tracing::warn!("smtp tls is none: mail is sent to the relay without encryption"); |
| 142 | } |
| 143 | if !config.backup.enabled() { |
| 144 | tracing::warn!("backups are not configured: no scheduled copy of the database is made"); |
| 145 | } |
| 146 | if config.trusted_proxies.is_empty() && config.listen.ip().is_loopback() { |
| 147 | tracing::warn!( |
| 148 | "trusted_proxies is empty while listen is a loopback address: behind a proxy, every client shares one IP for throttling" |
| 149 | ); |
| 150 | } |
| 151 | } |
| 152 | |
| 153 | |
| 154 | |
| 155 | |
| 156 | pub(crate) async fn open_state(config: Config) -> im_core::Result<AppState> { |
| 157 | std::fs::create_dir_all(&config.data_dir)?; |
| 158 | |
| 159 | std::fs::set_permissions(&config.data_dir, std::fs::Permissions::from_mode(0o700))?; |
| 160 | let data_dir = config.data_dir.canonicalize()?; |
| 161 | if let Some(parent) = config |
| 162 | .database |
| 163 | .parent() |
| 164 | .filter(|p| !p.as_os_str().is_empty()) |
| 165 | { |
| 166 | std::fs::create_dir_all(parent)?; |
| 167 | } |
| 168 | |
| 169 | |
| 170 | let key_path = data_dir.join(KEY_FILE); |
| 171 | let store = Store::open(&config.database).await?; |
| 172 | if !key_path.exists() && store.holds_sealed_data().await? { |
| 173 | return Err(im_core::Error::Crypto( |
| 174 | "im.key is missing but im.db holds data sealed with it; restore the key file".into(), |
| 175 | )); |
| 176 | } |
| 177 | let key = secret::load_or_create_key(&key_path)?; |
| 178 | let policy = effective_policy(&config, &store).await?; |
| 179 | signing::maintain(&store, &key).await?; |
| 180 | |
| 181 | store |
| 182 | .upsert_home_service("Account", &config.base_url) |
| 183 | .await?; |
| 184 | Ok(AppState { |
| 185 | config: Arc::new(config), |
| 186 | policy_live: Arc::new(RwLock::new(policy)), |
| 187 | store, |
| 188 | key: Arc::new(key), |
| 189 | live: Arc::new(LiveHub::default()), |
| 190 | backup: Arc::new(BackupTrigger::default()), |
| 191 | throttle: Arc::new(Throttle::default()), |
| 192 | two_factor_days: Arc::new(Throttle::two_factor_days()), |
| 193 | photo_uploads: Arc::new(Throttle::photo_uploads()), |
| 194 | email_changes: Arc::new(Throttle::email_changes()), |
| 195 | per_minute: Arc::new(Throttle::per_minute()), |
| 196 | stream_slots: Arc::new(StreamSlots::default()), |
| 197 | anonymous_streams: Arc::new(Semaphore::new(MAX_ANONYMOUS_STREAMS)), |
| 198 | |
| 199 | stop: watch::channel(false).1, |
| 200 | settings_lock: Arc::new(tokio::sync::Mutex::new(())), |
| 201 | photo_lock: Arc::new(tokio::sync::Mutex::new(())), |
| 202 | }) |
| 203 | } |
| 204 | |
| 205 | |
| 206 | |
| 207 | |
| 208 | pub(crate) async fn effective_policy( |
| 209 | config: &im_core::config::Config, |
| 210 | store: &Store, |
| 211 | ) -> im_core::Result<PolicyConfig> { |
| 212 | let saved = store.settings_with_prefix("policy.").await?; |
| 213 | Ok(merge_saved_policy(&config.policy, &saved)) |
| 214 | } |
| 215 | |
| 216 | |
| 217 | |
| 218 | |
| 219 | pub(crate) fn merge_saved_policy(file: &PolicyConfig, saved: &[(String, String)]) -> PolicyConfig { |
| 220 | let mut policy = file.clone(); |
| 221 | for (key, value) in saved { |
| 222 | let name = key.trim_start_matches("policy."); |
| 223 | match policy.set(name, value) { |
| 224 | Ok(next) => policy = next, |
| 225 | Err(error) => { |
| 226 | tracing::warn!(setting = %key, error = %error, "stored policy setting ignored"); |
| 227 | } |
| 228 | } |
| 229 | } |
| 230 | policy |
| 231 | } |
| 232 | |
| 233 | |
| 234 | |
| 235 | const PHOTO_BODY_LIMIT: usize = MAX_UPLOAD_BYTES + 64 * 1024; |
| 236 | |
| 237 | |
| 238 | |
| 239 | const FORM_BODY_LIMIT: usize = 16 * 1024; |
| 240 | |
| 241 | |
| 242 | |
| 243 | |
| 244 | pub fn router(state: AppState) -> Router { |
| 245 | let security = SecurityHeaders::new(security::headers_for(&state.config.base_url)); |
| 246 | Router::builder() |
| 247 | .discover() |
| 248 | .app_context(state) |
| 249 | .cookies() |
| 250 | .layer(BodyLimit::max(FORM_BODY_LIMIT)) |
| 251 | .layer(BodyLimit::max(PHOTO_BODY_LIMIT).at(PHOTO_ROUTE)) |
| 252 | .layer(BodyLimit::max(MESSAGE_BODY_LIMIT).at(MESSAGE_ROUTE)) |
| 253 | .layer(security) |
| 254 | .layer(NotFoundLayer) |
| 255 | .build() |
| 256 | } |
| 257 | |
| 258 | |
| 259 | async fn wait_stop(mut stop: watch::Receiver<bool>) { |
| 260 | let _ = stop.wait_for(|stopped| *stopped).await; |
| 261 | } |
| 262 | |
| 263 | |
| 264 | |
| 265 | async fn shutdown_signal() { |
| 266 | let ctrl_c = async { |
| 267 | if let Err(error) = tokio::signal::ctrl_c().await { |
| 268 | tracing::error!(error = %error, "cannot listen for Ctrl-C"); |
| 269 | std::future::pending::<()>().await; |
| 270 | } |
| 271 | }; |
| 272 | let terminate = async { |
| 273 | match signal(SignalKind::terminate()) { |
| 274 | Ok(mut term) => { |
| 275 | term.recv().await; |
| 276 | } |
| 277 | Err(error) => { |
| 278 | tracing::error!(error = %error, "cannot listen for SIGTERM"); |
| 279 | std::future::pending::<()>().await; |
| 280 | } |
| 281 | } |
| 282 | }; |
| 283 | tokio::select! { |
| 284 | () = ctrl_c => {} |
| 285 | () = terminate => {} |
| 286 | } |
| 287 | } |
| 288 | |
| 289 | #[cfg(test)] |
| 290 | pub(crate) use tests::test_state; |
| 291 | |
| 292 | #[cfg(test)] |
| 293 | mod tests { |
| 294 | use super::*; |
| 295 | use http::header::{ACCEPT, CONTENT_SECURITY_POLICY, X_CONTENT_TYPE_OPTIONS}; |
| 296 | use topcoat::router::response::Response; |
| 297 | use topcoat::router::{Body, to_bytes}; |
| 298 | |
| 299 | |
| 300 | |
| 301 | pub(crate) async fn test_state() -> (tempfile::TempDir, AppState) { |
| 302 | let dir = tempfile::tempdir().expect("temp dir"); |
| 303 | let text = format!( |
| 304 | "database = \"{}\"\ndata_dir = \"{}\"\nlisten = \"127.0.0.1:7650\"\nbase_url = \"http://127.0.0.1:7650\"\n", |
| 305 | dir.path().join("im.db").display(), |
| 306 | dir.path().display(), |
| 307 | ); |
| 308 | let config = Config::parse(&text).expect("test config"); |
| 309 | let key = secret::load_or_create_key(&dir.path().join(KEY_FILE)).expect("key"); |
| 310 | let store = Store::open(&config.database).await.expect("store"); |
| 311 | let state = AppState { |
| 312 | policy_live: Arc::new(RwLock::new(config.policy.clone())), |
| 313 | config: Arc::new(config), |
| 314 | store, |
| 315 | key: Arc::new(key), |
| 316 | live: Arc::new(LiveHub::default()), |
| 317 | backup: Arc::new(BackupTrigger::default()), |
| 318 | throttle: Arc::new(Throttle::default()), |
| 319 | two_factor_days: Arc::new(Throttle::two_factor_days()), |
| 320 | photo_uploads: Arc::new(Throttle::photo_uploads()), |
| 321 | email_changes: Arc::new(Throttle::email_changes()), |
| 322 | per_minute: Arc::new(Throttle::per_minute()), |
| 323 | stream_slots: Arc::new(StreamSlots::default()), |
| 324 | anonymous_streams: Arc::new(Semaphore::new(MAX_ANONYMOUS_STREAMS)), |
| 325 | stop: watch::channel(false).1, |
| 326 | settings_lock: Arc::new(tokio::sync::Mutex::new(())), |
| 327 | photo_lock: Arc::new(tokio::sync::Mutex::new(())), |
| 328 | }; |
| 329 | (dir, state) |
| 330 | } |
| 331 | |
| 332 | async fn get(state: AppState, path: &str, accept: Option<&str>) -> Response { |
| 333 | let mut request = http::Request::get(path); |
| 334 | if let Some(accept) = accept { |
| 335 | request = request.header(ACCEPT, accept); |
| 336 | } |
| 337 | let request = request.body(Body::empty()).expect("request"); |
| 338 | router(state).handle(request).await |
| 339 | } |
| 340 | |
| 341 | #[tokio::test] |
| 342 | async fn a_page_carries_the_content_security_policy_and_nosniff() { |
| 343 | let (_dir, state) = test_state().await; |
| 344 | |
| 345 | let response = get(state, "/setup", Some("text/html")).await; |
| 346 | assert_eq!(response.status(), 200); |
| 347 | assert_eq!( |
| 348 | response.headers()[CONTENT_SECURITY_POLICY] |
| 349 | .to_str() |
| 350 | .expect("ascii"), |
| 351 | security::CSP |
| 352 | ); |
| 353 | assert_eq!(response.headers()[X_CONTENT_TYPE_OPTIONS], "nosniff"); |
| 354 | } |
| 355 | |
| 356 | #[tokio::test] |
| 357 | async fn a_missing_key_is_refused_when_the_database_holds_sealed_rows() { |
| 358 | let (dir, state) = test_state().await; |
| 359 | signing::maintain(&state.store, &state.key) |
| 360 | .await |
| 361 | .expect("signing keys"); |
| 362 | drop(state); |
| 363 | std::fs::remove_file(dir.path().join(KEY_FILE)).expect("key removed"); |
| 364 | let text = format!( |
| 365 | "database = \"{}\"\ndata_dir = \"{}\"\nlisten = \"127.0.0.1:7650\"\nbase_url = \"http://127.0.0.1:7650\"\n", |
| 366 | dir.path().join("im.db").display(), |
| 367 | dir.path().display(), |
| 368 | ); |
| 369 | let config = Config::parse(&text).expect("test config"); |
| 370 | let error = open_state(config).await.err().expect("refused"); |
| 371 | assert!(error.to_string().contains("im.key is missing"), "{error}"); |
| 372 | assert!(!dir.path().join(KEY_FILE).exists(), "no key is created"); |
| 373 | } |
| 374 | |
| 375 | #[tokio::test] |
| 376 | async fn an_unknown_path_for_a_browser_gets_the_styled_404() { |
| 377 | let (_dir, state) = test_state().await; |
| 378 | let response = get(state, "/no/such/page", Some("text/html")).await; |
| 379 | assert_eq!(response.status(), 404); |
| 380 | let body = to_bytes(response.into_body(), 64 * 1024) |
| 381 | .await |
| 382 | .expect("body"); |
| 383 | let html = String::from_utf8_lossy(&body); |
| 384 | assert!( |
| 385 | html.contains("Page not found"), |
| 386 | "styled 404 body, got: {html}" |
| 387 | ); |
| 388 | } |
| 389 | } |