//! 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), open the blob store the configuration names, 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::{OpenOptionsExt, PermissionsExt}; use std::path::Path; use std::sync::Arc; use in_core::blob::BlobStore; use in_core::blob::local::LocalBlobs; use in_core::blob::s3::{S3Blobs, S3Settings}; use in_core::config::{Backend, Config, S3, parse_endpoint}; use in_core::error::{Error, Result}; use in_core::secret; use in_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, TrustedProxies}; use crate::backup::{self, BackupTrigger}; use crate::directory; use crate::family; use crate::family::FamilyCache; use crate::live::LiveHub; use crate::oidc::OidcClient; use crate::pages::files; use crate::pages::not_found::NotFoundLayer; use crate::security::{self, SecurityHeaders}; use crate::state::{AppState, ObjectStaging}; use crate::sweeper; use crate::throttle::ShareThrottles; use crate::thumbs_worker; /// Name of the instance key file inside the data directory. pub const KEY_FILE: &str = "in.key"; /// Name of the lock file inside the data directory. A running server holds it; the operator commands take it /// too, so they refuse to run beside a server. const LOCK_FILE: &str = "in.lock"; /// Directory under the data directory that holds the local blob tree. pub const BLOB_DIR: &str = "blobs"; /// Takes the data directory's lock. The file is created with mode 0600 inside the 0700 directory. The lock /// is held for as long as the returned file lives; a second holder gets a conflict that says what to do. pub fn lock_data_dir(data_dir: &Path) -> Result { std::fs::create_dir_all(data_dir)?; std::fs::set_permissions(data_dir, std::fs::Permissions::from_mode(0o700))?; let file = std::fs::OpenOptions::new() .create(true) .truncate(false) .write(true) .mode(0o600) .open(data_dir.join(LOCK_FILE))?; match file.try_lock() { Ok(()) => Ok(file), Err(std::fs::TryLockError::WouldBlock) => Err(Error::Conflict( "in is running on this data directory. Stop the server first, then run the command again.".into(), )), Err(std::fs::TryLockError::Error(error)) => Err(error.into()), } } /// What an operator command needs: the configuration, the database, the blob store, and the lock that keeps a /// server out. Opened without the OpenID client, so the commands run even when `im` is not configured. pub struct Offline { /// The database. pub store: Store, /// The blob store the configuration names. pub blobs: Arc, /// The data-directory lock. Dropping it lets a server start again. _lock: std::fs::File, } /// Opens an [`Offline`] view of the instance. Refuses while a server holds the lock. pub async fn open_offline(config_path: &Path) -> Result { let config = Config::load(config_path)?; let lock = lock_data_dir(&config.data_dir)?; 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 store = Store::open(&config.database).await?; let blobs = open_blobs(&config, &data_dir)?; Ok(Offline { store, blobs, _lock: lock, }) } /// Runs the server until a stop signal arrives. Returns once every connection has finished. pub async fn serve(config_path: &Path) -> Result<()> { let config = Config::load(config_path)?; let listen = config.listen; warn_about_setup(&config); // Held until the server stops: an operator command started now refuses instead of racing the server. let _lock = lock_data_dir(&config.data_dir)?; let state = open_state(config).await?; // One stop flag. The signal task sets it; the server and every worker watch it and then drain. let (stop_tx, stop_rx) = watch::channel(false); if state.oidc.is_some() { tokio::spawn(directory::run(state.clone(), stop_rx.clone())); tokio::spawn(family::run(state.clone(), stop_rx.clone())); } if state.config.backup.is_some() { tokio::spawn(backup::run(state.clone(), stop_rx.clone())); } tokio::spawn(sweeper::run(state.clone(), stop_rx.clone())); tokio::spawn(thumbs_worker::run(state.clone(), stop_rx.clone())); 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(), storage = ?state.config.storage.backend, build = env!("IN_BUILD_SHA"), "in starting" ); 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!("in stopped"); Ok(()) } /// Logs the settings that are legal but usually a mistake. Each one is a warning, never a refusal, because /// a local development setup has good reasons to leave them out. fn warn_about_setup(config: &Config) { if listen_is_loopback(config) && config.trusted_proxies.is_empty() { tracing::warn!( listen = %config.listen, "listen is a loopback address and trusted_proxies is empty: behind a proxy on this host, every client shares its address for the rate limits" ); } if config.backup.is_none() { tracing::warn!("[backup] is not configured: there are no scheduled backups"); } if config.oidc.is_none() { tracing::warn!("[oidc] is not configured: sign-in is disabled"); } } /// Whether the listener is bound to a loopback address only. fn listen_is_loopback(config: &Config) -> bool { config.listen.ip().is_loopback() } /// Creates the data directory and opens the key, the database and the blob store. Everything the /// router needs that touches the disk is ready when this returns. async fn open_state(config: Config) -> 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)?; } let database_dir = std::fs::canonicalize( config .database .parent() .filter(|p| !p.as_os_str().is_empty()) .unwrap_or(Path::new(".")), )?; if !database_dir.starts_with(&data_dir) { tracing::warn!( database = %config.database.display(), "database is outside data_dir: restore will not replace it, and the data-directory lock does not cover it" ); } let key = secret::load_or_create_key(&data_dir.join(KEY_FILE))?; let store = Store::open(&config.database).await?; let blobs = open_blobs(&config, &data_dir)?; let oidc = match &config.oidc { Some(oidc) => { let client_secret = read_secret(&oidc.client_secret_file)?; Some(Arc::new(OidcClient::new( oidc, &config.base_url, client_secret, )?)) } None => None, }; Ok(AppState { config: Arc::new(config), store, blobs, key: Arc::new(key), live: Arc::new(LiveHub::default()), backup: Arc::new(BackupTrigger::default()), oidc, throttles: Arc::new(ShareThrottles::default()), family: Arc::new(FamilyCache::default()), staging: Arc::new(ObjectStaging::default()), }) } /// Builds the blob store the configuration names. The local backend keeps its tree under /// `data_dir/blobs`. The S3 backend reads its credentials from the files the configuration names; no /// request is made here, so a wrong bucket shows on the first use. pub fn open_blobs(config: &Config, data_dir: &Path) -> Result> { match config.storage.backend { Backend::Local => Ok(Arc::new(LocalBlobs::new(data_dir.join(BLOB_DIR))?)), Backend::S3 => { let s3 = config .storage .s3 .as_ref() .ok_or_else(|| Error::Config("storage.s3 is missing".into()))?; Ok(Arc::new(S3Blobs::new(&s3_settings(s3)?)?)) } } } /// Turns the `[storage.s3]` table and its credential files into the client settings. Without an /// endpoint the AWS endpoint of the region is used. Plain http is allowed only for a loopback endpoint. fn s3_settings(s3: &S3) -> Result { let endpoint = s3 .endpoint .clone() .unwrap_or_else(|| format!("https://s3.{}.amazonaws.com", s3.region)); let allow_http = parse_endpoint(&endpoint).is_some_and(|url| url.scheme() == "http"); Ok(S3Settings { allow_http, endpoint, region: s3.region.clone(), bucket: s3.bucket.clone(), access_key_id: read_secret(&s3.access_key_id_file)?, secret_access_key: read_secret(&s3.secret_access_key_file)?, }) } /// Reads a credential file and drops the trailing newline. An empty file is a configuration error, and so /// is a file that group or world can read. fn read_secret(path: &Path) -> Result { let text = std::fs::read_to_string(path) .map_err(|e| Error::Config(format!("cannot read {}: {e}", path.display())))?; secret::check_private(path)?; let value = text.trim().to_owned(); if value.is_empty() { return Err(Error::Config(format!("{} is empty", path.display()))); } Ok(value) } /// 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)); // Behind a reverse proxy, client_ip reads X-Forwarded-For only from these peers; without them // every client would share the proxy's address and per-IP throttles would become global. let proxies = TrustedProxies::new().networks(state.config.trusted_proxies.clone()); Router::builder() .trusted_proxies(proxies) .discover() .app_context(state) .cookies() // The upload form streams, but the body limit still caps how much one request may send. .layer(BodyLimit::max(files::SMALL_UPLOAD_CEILING).at("/files")) .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 std::net::SocketAddr; use topcoat::router::response::Response; use topcoat::router::{Body, to_bytes}; /// An app state over a fresh temp directory: the database, the key and the blobs 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 config = Config { database: dir.path().join("in.db"), data_dir: dir.path().to_path_buf(), listen: SocketAddr::from(([127, 0, 0, 1], 17650)), ..Config::default() }; let key = secret::load_or_create_key(&dir.path().join(KEY_FILE)).expect("key"); let store = Store::open(&config.database).await.expect("store"); let blobs = open_blobs(&config, dir.path()).expect("blobs"); let state = AppState { config: Arc::new(config), store, blobs, key: Arc::new(key), live: Arc::new(LiveHub::default()), backup: Arc::new(BackupTrigger::default()), oidc: None, throttles: Arc::new(ShareThrottles::default()), family: Arc::new(FamilyCache::default()), staging: Arc::new(ObjectStaging::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}" ); } }