//! Boot: the order in which the server comes up, the router it serves, and the shutdown. //! //! The order follows `docs/conventions.md` section 2: load the configuration, create the data //! directory with mode 0700, load or create the instance key, open the database (which applies //! the pragmas and the migrations), build the router, bind the listener, and serve until SIGTERM or //! Ctrl-C. Stored UI overrides of the policy are layered on the file values here, once, at boot. use std::fs::{File, OpenOptions, TryLockError}; use std::os::unix::fs::PermissionsExt; use std::path::Path; use std::sync::{Arc, RwLock}; use im_core::config::{Config, PolicyConfig, SmtpTls}; use im_core::photo::MAX_UPLOAD_BYTES; use im_core::secret; use im_core::store::Store; use tokio::net::TcpListener; use tokio::signal::unix::{SignalKind, signal}; use tokio::sync::{Semaphore, watch}; use topcoat::cookie::RouterBuilderCookieExt; use topcoat::router::{BodyLimit, Router, RouterBuilderDiscoverExt, RouterService}; use crate::api::directory::StreamSlots; use crate::backchannel; use crate::backups::BackupTrigger; use crate::live::{LiveHub, MAX_ANONYMOUS_STREAMS}; use crate::mail; use crate::oidc::signing; use crate::pages::admin::message::{MESSAGE_BODY_LIMIT, MESSAGE_ROUTE}; use crate::pages::not_found::NotFoundLayer; use crate::pages::profile::PHOTO_ROUTE; use crate::security::{self, SecurityHeaders}; use crate::service_probe; use crate::state::AppState; use crate::sweeper; use crate::throttle::Throttle; /// Name of the instance key file inside the data directory. pub(crate) const KEY_FILE: &str = "im.key"; /// Name of the lock file inside the data directory. The server holds it for its whole life, and so does /// every operator command, so the two never open the database at once. const LOCK_FILE: &str = "im.lock"; /// Takes the exclusive lock of the data directory, creating the directory (mode 0700) when needed. The /// returned file keeps the lock; dropping it releases the lock. Fails with a message that tells the /// operator to stop the server when it is held. pub fn lock_data_dir(data_dir: &Path) -> im_core::Result { std::fs::create_dir_all(data_dir)?; std::fs::set_permissions(data_dir, std::fs::Permissions::from_mode(0o700))?; let file = OpenOptions::new() .create(true) .truncate(false) .write(true) .open(data_dir.join(LOCK_FILE))?; match file.try_lock() { Ok(()) => Ok(file), Err(TryLockError::WouldBlock) => Err(im_core::Error::Conflict( "im is running on this data directory. Stop the server first, then run the command again." .into(), )), Err(TryLockError::Error(error)) => Err(error.into()), } } /// Runs the server until a stop signal arrives. Returns once every connection has finished. pub async fn serve(config_path: &Path) -> im_core::Result<()> { let config = Config::load(config_path)?; let listen = config.listen; let _lock = lock_data_dir(&config.data_dir)?; let state = open_state(config).await?; warn_weak_settings(&state); let listener = TcpListener::bind(listen).await.map_err(|error| { std::io::Error::new(error.kind(), format!("cannot bind {listen}: {error}")) })?; tracing::info!( listen = %listen, data_dir = %state.config.data_dir.display(), build = env!("IM_BUILD_SHA"), "im starting" ); // One stop flag. The signal task sets it; the server watches it and then drains. let (stop_tx, stop_rx) = watch::channel(false); let state = AppState { stop: stop_rx.clone(), ..state }; let backup_task = crate::backups::spawn(state.clone()); tokio::spawn(async move { shutdown_signal().await; tracing::info!("shutdown signal received"); stop_tx.send_replace(true); }); let signing_worker = signing::spawn(state.store.clone(), state.key.clone(), stop_rx.clone()); let backchannel_worker = backchannel::spawn( state.store.clone(), state.key.clone(), state.config.base_url.clone(), stop_rx.clone(), ); let sweeper_task = sweeper::spawn(state.store.clone(), stop_rx.clone()); let probe_worker = service_probe::spawn(state.store.clone(), stop_rx.clone()); let mail_worker = mail::worker::spawn( state.store.clone(), state.key.clone(), state.config.smtp.clone(), stop_rx.clone(), ); topcoat::serve_until( listener, RouterService::new(router(state)), wait_stop(stop_rx), ) .await?; let _ = signing_worker.await; let _ = backchannel_worker.await; let _ = sweeper_task.await; let _ = probe_worker.await; let _ = mail_worker.await; if let Some(task) = backup_task { let _ = task.await; } tracing::info!("im stopped"); Ok(()) } /// Logs one warning for each setting that weakens the instance or does not fit its deployment. The server /// still starts: each is a choice an operator may have made on purpose. The policy is the one in effect, /// so an administrator's saved setting counts too. fn warn_weak_settings(state: &AppState) { let config = &state.config; if !state.policy().require_2fa_for_admins { tracing::warn!( "require_2fa_for_admins is off: administrators may sign in without two-factor sign-in" ); } if config.smtp.tls == SmtpTls::None { tracing::warn!("smtp tls is none: mail is sent to the relay without encryption"); } if !config.backup.enabled() { tracing::warn!("backups are not configured: no scheduled copy of the database is made"); } if config.trusted_proxies.is_empty() && config.listen.ip().is_loopback() { tracing::warn!( "trusted_proxies is empty while listen is a loopback address: behind a proxy, every client shares one IP for throttling" ); } } /// Creates the data directory and opens the key and the database. Everything the router needs /// that touches the disk is ready when this returns. The signing keys are made ready too, so the /// first token can be signed. The operator commands use this as well. pub(crate) async fn open_state(config: Config) -> im_core::Result { std::fs::create_dir_all(&config.data_dir)?; // The directory holds the instance key. Only this user may enter it. std::fs::set_permissions(&config.data_dir, std::fs::Permissions::from_mode(0o700))?; let data_dir = config.data_dir.canonicalize()?; if let Some(parent) = config .database .parent() .filter(|p| !p.as_os_str().is_empty()) { std::fs::create_dir_all(parent)?; } // The database opens before the key so that a missing key can be checked against it. A key is created // only for a data directory that holds no sealed rows; otherwise the sealed rows would be unreadable. let key_path = data_dir.join(KEY_FILE); let store = Store::open(&config.database).await?; if !key_path.exists() && store.holds_sealed_data().await? { return Err(im_core::Error::Crypto( "im.key is missing but im.db holds data sealed with it; restore the key file".into(), )); } let key = secret::load_or_create_key(&key_path)?; let policy = effective_policy(&config, &store).await?; signing::maintain(&store, &key).await?; // im is in its own switcher list. The row follows the configured origin at every boot. store .upsert_home_service("Account", &config.base_url) .await?; Ok(AppState { config: Arc::new(config), policy_live: Arc::new(RwLock::new(policy)), store, key: Arc::new(key), live: Arc::new(LiveHub::default()), backup: Arc::new(BackupTrigger::default()), throttle: Arc::new(Throttle::default()), two_factor_days: Arc::new(Throttle::two_factor_days()), photo_uploads: Arc::new(Throttle::photo_uploads()), email_changes: Arc::new(Throttle::email_changes()), per_minute: Arc::new(Throttle::per_minute()), stream_slots: Arc::new(StreamSlots::default()), anonymous_streams: Arc::new(Semaphore::new(MAX_ANONYMOUS_STREAMS)), // Replaced by the stop flag of `serve` before any listener starts. The CLI never serves. stop: watch::channel(false).1, settings_lock: Arc::new(tokio::sync::Mutex::new(())), photo_lock: Arc::new(tokio::sync::Mutex::new(())), }) } /// The policy in effect at boot: the file values, with each `policy.` setting saved in the admin UI /// layered on top. A stored value that no longer validates is logged and ignored, so a bad row cannot stop /// the server from starting; the file value applies instead. pub(crate) async fn effective_policy( config: &im_core::config::Config, store: &Store, ) -> im_core::Result { let saved = store.settings_with_prefix("policy.").await?; Ok(merge_saved_policy(&config.policy, &saved)) } /// The policy that the file values and the saved `policy.` values give. A saved value that does not parse /// or is out of range is logged and ignored, so one bad row cannot keep the server from starting. The /// settings page calls this on the values it reads inside its transaction. pub(crate) fn merge_saved_policy(file: &PolicyConfig, saved: &[(String, String)]) -> PolicyConfig { let mut policy = file.clone(); for (key, value) in saved { let name = key.trim_start_matches("policy."); match policy.set(name, value) { Ok(next) => policy = next, Err(error) => { tracing::warn!(setting = %key, error = %error, "stored policy setting ignored"); } } } policy } /// The request body limit of the photo upload: the picture plus room for the multipart framing and /// the CSRF field. The handler enforces the picture limit itself while streaming. const PHOTO_BODY_LIMIT: usize = MAX_UPLOAD_BYTES + 64 * 1024; /// The request body limit of every other route. A form is a few hundred bytes, so 16 KiB is generous. It /// replaces the 2 MiB default of the framework, which no form needs. const FORM_BODY_LIMIT: usize = 16 * 1024; /// The router of the server: every route and page found by `discover`, the cookie jar, the security /// headers on every response, the styled 404 for browsers, the body limit of forms, and the larger limits /// of the photo upload and the admin message (which override the form limit under their paths). pub fn router(state: AppState) -> Router { let security = SecurityHeaders::new(security::headers_for(&state.config.base_url)); Router::builder() .discover() .app_context(state) .cookies() .layer(BodyLimit::max(FORM_BODY_LIMIT)) .layer(BodyLimit::max(PHOTO_BODY_LIMIT).at(PHOTO_ROUTE)) .layer(BodyLimit::max(MESSAGE_BODY_LIMIT).at(MESSAGE_ROUTE)) .layer(security) .layer(NotFoundLayer) .build() } /// Resolves when the shared stop flag is set. async fn wait_stop(mut stop: watch::Receiver) { let _ = stop.wait_for(|stopped| *stopped).await; } /// Resolves on Ctrl-C or SIGTERM. A handler that cannot be installed is logged and never resolves, /// so the other one still works. async fn shutdown_signal() { let ctrl_c = async { if let Err(error) = tokio::signal::ctrl_c().await { tracing::error!(error = %error, "cannot listen for Ctrl-C"); std::future::pending::<()>().await; } }; let terminate = async { match signal(SignalKind::terminate()) { Ok(mut term) => { term.recv().await; } Err(error) => { tracing::error!(error = %error, "cannot listen for SIGTERM"); std::future::pending::<()>().await; } } }; tokio::select! { () = ctrl_c => {} () = terminate => {} } } #[cfg(test)] pub(crate) use tests::test_state; #[cfg(test)] mod tests { use super::*; use http::header::{ACCEPT, CONTENT_SECURITY_POLICY, X_CONTENT_TYPE_OPTIONS}; use topcoat::router::response::Response; use topcoat::router::{Body, to_bytes}; /// An app state over a fresh temp directory: the database and the key live there, and nothing /// is written outside it. The directory is returned so it lives as long as the state. pub(crate) async fn test_state() -> (tempfile::TempDir, AppState) { let dir = tempfile::tempdir().expect("temp dir"); let text = format!( "database = \"{}\"\ndata_dir = \"{}\"\nlisten = \"127.0.0.1:7650\"\nbase_url = \"http://127.0.0.1:7650\"\n", dir.path().join("im.db").display(), dir.path().display(), ); let config = Config::parse(&text).expect("test config"); let key = secret::load_or_create_key(&dir.path().join(KEY_FILE)).expect("key"); let store = Store::open(&config.database).await.expect("store"); let state = AppState { policy_live: Arc::new(RwLock::new(config.policy.clone())), config: Arc::new(config), store, key: Arc::new(key), live: Arc::new(LiveHub::default()), backup: Arc::new(BackupTrigger::default()), throttle: Arc::new(Throttle::default()), two_factor_days: Arc::new(Throttle::two_factor_days()), photo_uploads: Arc::new(Throttle::photo_uploads()), email_changes: Arc::new(Throttle::email_changes()), per_minute: Arc::new(Throttle::per_minute()), stream_slots: Arc::new(StreamSlots::default()), anonymous_streams: Arc::new(Semaphore::new(MAX_ANONYMOUS_STREAMS)), stop: watch::channel(false).1, settings_lock: Arc::new(tokio::sync::Mutex::new(())), photo_lock: Arc::new(tokio::sync::Mutex::new(())), }; (dir, state) } async fn get(state: AppState, path: &str, accept: Option<&str>) -> Response { let mut request = http::Request::get(path); if let Some(accept) = accept { request = request.header(ACCEPT, accept); } let request = request.body(Body::empty()).expect("request"); router(state).handle(request).await } #[tokio::test] async fn a_page_carries_the_content_security_policy_and_nosniff() { let (_dir, state) = test_state().await; // No user yet, so the setup page answers. let response = get(state, "/setup", Some("text/html")).await; assert_eq!(response.status(), 200); assert_eq!( response.headers()[CONTENT_SECURITY_POLICY] .to_str() .expect("ascii"), security::CSP ); assert_eq!(response.headers()[X_CONTENT_TYPE_OPTIONS], "nosniff"); } #[tokio::test] async fn a_missing_key_is_refused_when_the_database_holds_sealed_rows() { let (dir, state) = test_state().await; signing::maintain(&state.store, &state.key) .await .expect("signing keys"); drop(state); std::fs::remove_file(dir.path().join(KEY_FILE)).expect("key removed"); let text = format!( "database = \"{}\"\ndata_dir = \"{}\"\nlisten = \"127.0.0.1:7650\"\nbase_url = \"http://127.0.0.1:7650\"\n", dir.path().join("im.db").display(), dir.path().display(), ); let config = Config::parse(&text).expect("test config"); let error = open_state(config).await.err().expect("refused"); assert!(error.to_string().contains("im.key is missing"), "{error}"); assert!(!dir.path().join(KEY_FILE).exists(), "no key is created"); } #[tokio::test] async fn an_unknown_path_for_a_browser_gets_the_styled_404() { let (_dir, state) = test_state().await; let response = get(state, "/no/such/page", Some("text/html")).await; assert_eq!(response.status(), 404); let body = to_bytes(response.into_body(), 64 * 1024) .await .expect("body"); let html = String::from_utf8_lossy(&body); assert!( html.contains("Page not found"), "styled 404 body, got: {html}" ); } }