//! 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 are not layered on the file yet, because no page writes them. use std::os::unix::fs::DirBuilderExt; use std::path::Path; use std::sync::Arc; use iz_core::config::Config; use iz_core::secret; use iz_core::store::Store; use tokio::net::TcpListener; use tokio::signal::unix::{SignalKind, signal}; use tokio::sync::watch; use topcoat::cookie::RouterBuilderCookieExt; use topcoat::router::{BodyLimit, Router, RouterBuilderDiscoverExt, RouterService}; use crate::attachments; use crate::directory; use crate::in_store::InStore; use crate::live::LiveHub; use crate::mover; use crate::oidc; use crate::pages::not_found::NotFoundLayer; use crate::security::{self, SecurityHeaders}; use crate::state::AppState; /// Name of the instance key file inside the data directory. pub const KEY_FILE: &str = "iz.key"; /// The prefix of task keys (`IZ-42`) until the setting that changes it exists. Two to six capitals. const DEFAULT_KEY_PREFIX: &str = "IZ"; /// Runs the server until a stop signal arrives. Returns once every connection has finished. pub async fn serve(config_path: &Path) -> iz_core::Result<()> { let config = Config::load(config_path)?; warn_about_config(&config); let listen = config.listen; // One server per data directory: the lock is held until this function returns, so a second `iz` // (or an operator command) refuses to touch the same files while this one runs. create_data_dir(&config.data_dir)?; let _lock = crate::cli::lock_data_dir(&config.data_dir).map_err(iz_core::Error::Config)?; let state = open_state(config).await?; 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!("IZ_BUILD_SHA"), "iz starting" ); // One stop flag. The signal task sets it; the mirror worker and the server both watch it. let (stop_tx, stop_rx) = watch::channel(false); directory::spawn(state.clone(), stop_rx.clone()); attachments::spawn(state.clone(), stop_rx.clone()); mover::spawn(state.clone(), stop_rx.clone()); crate::mail::spawn(state.clone(), stop_rx.clone()); crate::family::spawn(state.clone(), stop_rx.clone()); crate::backup::spawn(state.clone(), stop_rx.clone()); crate::sweeper::spawn(state.clone(), stop_rx.clone()); tokio::spawn(async move { shutdown_signal().await; tracing::info!("shutdown signal received"); stop_tx.send_replace(true); }); topcoat::serve_until( listener, RouterService::new(router(state)), wait_stop(stop_rx), ) .await?; tracing::info!("iz stopped"); Ok(()) } /// Creates the data directory with mode 0700 when it is missing. The directory holds the instance key, so /// only this user may enter it. An existing directory keeps its mode. fn create_data_dir(path: &Path) -> std::io::Result<()> { std::fs::DirBuilder::new() .recursive(true) .mode(0o700) .create(path) } /// Logs the settings that have no effect, and the ones that probably are not what the operator meant. Nothing /// here stops the start. fn warn_about_config(config: &Config) { if config.backup.is_none() { tracing::warn!("backups are not configured; no backup sets will be written"); } // Absolute paths compare the same whether the config wrote them relative or not. if let (Ok(database), Ok(data_dir)) = ( std::path::absolute(&config.database), std::path::absolute(&config.data_dir), ) && !database.starts_with(&data_dir) { tracing::warn!( database = %config.database.display(), data_dir = %config.data_dir.display(), "database is outside data_dir" ); } if !config.trusted_proxies.is_empty() { tracing::warn!("trusted_proxies has no effect in iz"); } } /// Opens the key and the database. Everything the router needs that touches the disk is ready when this /// returns. async fn open_state(config: Config) -> iz_core::Result { 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)?; } let key = secret::load_or_create_key(&data_dir.join(KEY_FILE))?; let store = Store::open(&config.database).await?; // The one board of this installation, with its columns and default project, made on first boot. store.ensure_board(DEFAULT_KEY_PREFIX).await?; let oidc = match &config.oidc { Some(oidc_config) => { let secret = oidc::read_client_secret(&oidc_config.client_secret_file)?; Some(Arc::new(oidc::OidcClient::new( oidc_config, &config.base_url, secret, )?)) } None => None, }; let in_store = match (&config.in_store, &oidc) { (in_config, Some(client)) if in_config.enabled => match &in_config.url { Some(url) => Some(Arc::new(InStore::new(url, client.clone())?)), None => None, }, _ => None, }; Ok(AppState { config: Arc::new(config), store, key: Arc::new(key), live: Arc::new(LiveHub::default()), oidc, family: Arc::default(), in_store, blob_lock: Arc::default(), backup: Arc::default(), }) } /// The router of the server: every route and page found by `discover`, the cookie jar, the security /// headers on every response, and the styled 404 for browsers. 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(security) .layer(NotFoundLayer) .layer(BodyLimit::max(attachments::UPLOAD_REQUEST_MAX_BYTES).at("/tasks/{id}/files")) .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:7654\"\nbase_url = \"http://127.0.0.1:7654\"\n", dir.path().join("iz.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 { config: Arc::new(config), store, key: Arc::new(key), live: Arc::new(LiveHub::default()), oidc: None, family: Arc::default(), in_store: None, blob_lock: Arc::default(), backup: Arc::default(), }; (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 an_unknown_path_gets_the_styled_404_with_the_security_headers() { let (_dir, state) = test_state().await; let response = get(state, "/no/such/page", Some("text/html")).await; assert_eq!(response.status(), 404); assert_eq!( response.headers()[CONTENT_SECURITY_POLICY] .to_str() .expect("ascii"), security::CSP ); assert_eq!(response.headers()[X_CONTENT_TYPE_OPTIONS], "nosniff"); 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}" ); } }