| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | use std::os::unix::fs::DirBuilderExt; |
| 9 | use std::path::Path; |
| 10 | use std::sync::Arc; |
| 11 | |
| 12 | use iz_core::config::Config; |
| 13 | use iz_core::secret; |
| 14 | use iz_core::store::Store; |
| 15 | use tokio::net::TcpListener; |
| 16 | use tokio::signal::unix::{SignalKind, signal}; |
| 17 | use tokio::sync::watch; |
| 18 | use topcoat::cookie::RouterBuilderCookieExt; |
| 19 | use topcoat::router::{BodyLimit, Router, RouterBuilderDiscoverExt, RouterService}; |
| 20 | |
| 21 | use crate::attachments; |
| 22 | use crate::directory; |
| 23 | use crate::in_store::InStore; |
| 24 | use crate::live::LiveHub; |
| 25 | use crate::mover; |
| 26 | use crate::oidc; |
| 27 | use crate::pages::not_found::NotFoundLayer; |
| 28 | use crate::security::{self, SecurityHeaders}; |
| 29 | use crate::state::AppState; |
| 30 | |
| 31 | |
| 32 | pub const KEY_FILE: &str = "iz.key"; |
| 33 | |
| 34 | const DEFAULT_KEY_PREFIX: &str = "IZ"; |
| 35 | |
| 36 | |
| 37 | pub async fn serve(config_path: &Path) -> iz_core::Result<()> { |
| 38 | let config = Config::load(config_path)?; |
| 39 | warn_about_config(&config); |
| 40 | let listen = config.listen; |
| 41 | |
| 42 | |
| 43 | create_data_dir(&config.data_dir)?; |
| 44 | let _lock = crate::cli::lock_data_dir(&config.data_dir).map_err(iz_core::Error::Config)?; |
| 45 | let state = open_state(config).await?; |
| 46 | |
| 47 | let listener = TcpListener::bind(listen).await.map_err(|error| { |
| 48 | std::io::Error::new(error.kind(), format!("cannot bind {listen}: {error}")) |
| 49 | })?; |
| 50 | tracing::info!( |
| 51 | listen = %listen, |
| 52 | data_dir = %state.config.data_dir.display(), |
| 53 | build = env!("IZ_BUILD_SHA"), |
| 54 | "iz starting" |
| 55 | ); |
| 56 | |
| 57 | |
| 58 | let (stop_tx, stop_rx) = watch::channel(false); |
| 59 | directory::spawn(state.clone(), stop_rx.clone()); |
| 60 | attachments::spawn(state.clone(), stop_rx.clone()); |
| 61 | mover::spawn(state.clone(), stop_rx.clone()); |
| 62 | crate::mail::spawn(state.clone(), stop_rx.clone()); |
| 63 | crate::family::spawn(state.clone(), stop_rx.clone()); |
| 64 | crate::backup::spawn(state.clone(), stop_rx.clone()); |
| 65 | crate::sweeper::spawn(state.clone(), stop_rx.clone()); |
| 66 | tokio::spawn(async move { |
| 67 | shutdown_signal().await; |
| 68 | tracing::info!("shutdown signal received"); |
| 69 | stop_tx.send_replace(true); |
| 70 | }); |
| 71 | |
| 72 | topcoat::serve_until( |
| 73 | listener, |
| 74 | RouterService::new(router(state)), |
| 75 | wait_stop(stop_rx), |
| 76 | ) |
| 77 | .await?; |
| 78 | tracing::info!("iz stopped"); |
| 79 | Ok(()) |
| 80 | } |
| 81 | |
| 82 | |
| 83 | |
| 84 | fn create_data_dir(path: &Path) -> std::io::Result<()> { |
| 85 | std::fs::DirBuilder::new() |
| 86 | .recursive(true) |
| 87 | .mode(0o700) |
| 88 | .create(path) |
| 89 | } |
| 90 | |
| 91 | |
| 92 | |
| 93 | fn warn_about_config(config: &Config) { |
| 94 | if config.backup.is_none() { |
| 95 | tracing::warn!("backups are not configured; no backup sets will be written"); |
| 96 | } |
| 97 | |
| 98 | if let (Ok(database), Ok(data_dir)) = ( |
| 99 | std::path::absolute(&config.database), |
| 100 | std::path::absolute(&config.data_dir), |
| 101 | ) && !database.starts_with(&data_dir) |
| 102 | { |
| 103 | tracing::warn!( |
| 104 | database = %config.database.display(), |
| 105 | data_dir = %config.data_dir.display(), |
| 106 | "database is outside data_dir" |
| 107 | ); |
| 108 | } |
| 109 | if !config.trusted_proxies.is_empty() { |
| 110 | tracing::warn!("trusted_proxies has no effect in iz"); |
| 111 | } |
| 112 | } |
| 113 | |
| 114 | |
| 115 | |
| 116 | async fn open_state(config: Config) -> iz_core::Result<AppState> { |
| 117 | let data_dir = config.data_dir.canonicalize()?; |
| 118 | if let Some(parent) = config |
| 119 | .database |
| 120 | .parent() |
| 121 | .filter(|p| !p.as_os_str().is_empty()) |
| 122 | { |
| 123 | std::fs::create_dir_all(parent)?; |
| 124 | } |
| 125 | let key = secret::load_or_create_key(&data_dir.join(KEY_FILE))?; |
| 126 | let store = Store::open(&config.database).await?; |
| 127 | |
| 128 | store.ensure_board(DEFAULT_KEY_PREFIX).await?; |
| 129 | let oidc = match &config.oidc { |
| 130 | Some(oidc_config) => { |
| 131 | let secret = oidc::read_client_secret(&oidc_config.client_secret_file)?; |
| 132 | Some(Arc::new(oidc::OidcClient::new( |
| 133 | oidc_config, |
| 134 | &config.base_url, |
| 135 | secret, |
| 136 | )?)) |
| 137 | } |
| 138 | None => None, |
| 139 | }; |
| 140 | let in_store = match (&config.in_store, &oidc) { |
| 141 | (in_config, Some(client)) if in_config.enabled => match &in_config.url { |
| 142 | Some(url) => Some(Arc::new(InStore::new(url, client.clone())?)), |
| 143 | None => None, |
| 144 | }, |
| 145 | _ => None, |
| 146 | }; |
| 147 | Ok(AppState { |
| 148 | config: Arc::new(config), |
| 149 | store, |
| 150 | key: Arc::new(key), |
| 151 | live: Arc::new(LiveHub::default()), |
| 152 | oidc, |
| 153 | family: Arc::default(), |
| 154 | in_store, |
| 155 | blob_lock: Arc::default(), |
| 156 | backup: Arc::default(), |
| 157 | }) |
| 158 | } |
| 159 | |
| 160 | |
| 161 | |
| 162 | pub fn router(state: AppState) -> Router { |
| 163 | let security = SecurityHeaders::new(security::headers_for(&state.config.base_url)); |
| 164 | Router::builder() |
| 165 | .discover() |
| 166 | .app_context(state) |
| 167 | .cookies() |
| 168 | .layer(security) |
| 169 | .layer(NotFoundLayer) |
| 170 | .layer(BodyLimit::max(attachments::UPLOAD_REQUEST_MAX_BYTES).at("/tasks/{id}/files")) |
| 171 | .build() |
| 172 | } |
| 173 | |
| 174 | |
| 175 | async fn wait_stop(mut stop: watch::Receiver<bool>) { |
| 176 | let _ = stop.wait_for(|stopped| *stopped).await; |
| 177 | } |
| 178 | |
| 179 | |
| 180 | |
| 181 | async fn shutdown_signal() { |
| 182 | let ctrl_c = async { |
| 183 | if let Err(error) = tokio::signal::ctrl_c().await { |
| 184 | tracing::error!(error = %error, "cannot listen for Ctrl-C"); |
| 185 | std::future::pending::<()>().await; |
| 186 | } |
| 187 | }; |
| 188 | let terminate = async { |
| 189 | match signal(SignalKind::terminate()) { |
| 190 | Ok(mut term) => { |
| 191 | term.recv().await; |
| 192 | } |
| 193 | Err(error) => { |
| 194 | tracing::error!(error = %error, "cannot listen for SIGTERM"); |
| 195 | std::future::pending::<()>().await; |
| 196 | } |
| 197 | } |
| 198 | }; |
| 199 | tokio::select! { |
| 200 | () = ctrl_c => {} |
| 201 | () = terminate => {} |
| 202 | } |
| 203 | } |
| 204 | |
| 205 | #[cfg(test)] |
| 206 | pub(crate) use tests::test_state; |
| 207 | |
| 208 | #[cfg(test)] |
| 209 | mod tests { |
| 210 | use super::*; |
| 211 | use http::header::{ACCEPT, CONTENT_SECURITY_POLICY, X_CONTENT_TYPE_OPTIONS}; |
| 212 | use topcoat::router::response::Response; |
| 213 | use topcoat::router::{Body, to_bytes}; |
| 214 | |
| 215 | |
| 216 | |
| 217 | pub(crate) async fn test_state() -> (tempfile::TempDir, AppState) { |
| 218 | let dir = tempfile::tempdir().expect("temp dir"); |
| 219 | let text = format!( |
| 220 | "database = \"{}\"\ndata_dir = \"{}\"\nlisten = \"127.0.0.1:7654\"\nbase_url = \"http://127.0.0.1:7654\"\n", |
| 221 | dir.path().join("iz.db").display(), |
| 222 | dir.path().display(), |
| 223 | ); |
| 224 | let config = Config::parse(&text).expect("test config"); |
| 225 | let key = secret::load_or_create_key(&dir.path().join(KEY_FILE)).expect("key"); |
| 226 | let store = Store::open(&config.database).await.expect("store"); |
| 227 | let state = AppState { |
| 228 | config: Arc::new(config), |
| 229 | store, |
| 230 | key: Arc::new(key), |
| 231 | live: Arc::new(LiveHub::default()), |
| 232 | oidc: None, |
| 233 | family: Arc::default(), |
| 234 | in_store: None, |
| 235 | blob_lock: Arc::default(), |
| 236 | backup: Arc::default(), |
| 237 | }; |
| 238 | (dir, state) |
| 239 | } |
| 240 | |
| 241 | async fn get(state: AppState, path: &str, accept: Option<&str>) -> Response { |
| 242 | let mut request = http::Request::get(path); |
| 243 | if let Some(accept) = accept { |
| 244 | request = request.header(ACCEPT, accept); |
| 245 | } |
| 246 | let request = request.body(Body::empty()).expect("request"); |
| 247 | router(state).handle(request).await |
| 248 | } |
| 249 | |
| 250 | #[tokio::test] |
| 251 | async fn an_unknown_path_gets_the_styled_404_with_the_security_headers() { |
| 252 | let (_dir, state) = test_state().await; |
| 253 | let response = get(state, "/no/such/page", Some("text/html")).await; |
| 254 | assert_eq!(response.status(), 404); |
| 255 | assert_eq!( |
| 256 | response.headers()[CONTENT_SECURITY_POLICY] |
| 257 | .to_str() |
| 258 | .expect("ascii"), |
| 259 | security::CSP |
| 260 | ); |
| 261 | assert_eq!(response.headers()[X_CONTENT_TYPE_OPTIONS], "nosniff"); |
| 262 | let body = to_bytes(response.into_body(), 64 * 1024) |
| 263 | .await |
| 264 | .expect("body"); |
| 265 | let html = String::from_utf8_lossy(&body); |
| 266 | assert!( |
| 267 | html.contains("Page not found"), |
| 268 | "styled 404 body, got: {html}" |
| 269 | ); |
| 270 | } |
| 271 | } |