forge
Explore
Log in

Don't you dare go Hollow

iz

Clone
★ 0

0 watching0 forksRustAGPL-3.0567.3 KiB3950aceTahinli27 days ago34 commits

boot.rs271 lines, 9.9 KiBHistoryRawDownload
1//! Boot: the order in which the server comes up, the router it serves, and the shutdown.
2//!
3//! The order follows `docs/conventions.md` section 2: load the configuration, create the data
4//! directory with mode 0700, load or create the instance key, open the database (which applies
5//! the pragmas and the migrations), build the router, bind the listener, and serve until SIGTERM or
6//! Ctrl-C. Stored UI overrides are not layered on the file yet, because no page writes them.
7
8use std::os::unix::fs::DirBuilderExt;
9use std::path::Path;
10use std::sync::Arc;
11
12use iz_core::config::Config;
13use iz_core::secret;
14use iz_core::store::Store;
15use tokio::net::TcpListener;
16use tokio::signal::unix::{SignalKind, signal};
17use tokio::sync::watch;
18use topcoat::cookie::RouterBuilderCookieExt;
19use topcoat::router::{BodyLimit, Router, RouterBuilderDiscoverExt, RouterService};
20
21use crate::attachments;
22use crate::directory;
23use crate::in_store::InStore;
24use crate::live::LiveHub;
25use crate::mover;
26use crate::oidc;
27use crate::pages::not_found::NotFoundLayer;
28use crate::security::{self, SecurityHeaders};
29use crate::state::AppState;
30
31/// Name of the instance key file inside the data directory.
32pub const KEY_FILE: &str = "iz.key";
33/// The prefix of task keys (`IZ-42`) until the setting that changes it exists. Two to six capitals.
34const DEFAULT_KEY_PREFIX: &str = "IZ";
35
36/// Runs the server until a stop signal arrives. Returns once every connection has finished.
37pub 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 // One server per data directory: the lock is held until this function returns, so a second `iz`
42 // (or an operator command) refuses to touch the same files while this one runs.
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 // One stop flag. The signal task sets it; the mirror worker and the server both watch it.
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/// Creates the data directory with mode 0700 when it is missing. The directory holds the instance key, so
83/// only this user may enter it. An existing directory keeps its mode.
84fn 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/// Logs the settings that have no effect, and the ones that probably are not what the operator meant. Nothing
92/// here stops the start.
93fn 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 // Absolute paths compare the same whether the config wrote them relative or not.
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/// Opens the key and the database. Everything the router needs that touches the disk is ready when this
115/// returns.
116async 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 // The one board of this installation, with its columns and default project, made on first boot.
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/// The router of the server: every route and page found by `discover`, the cookie jar, the security
161/// headers on every response, and the styled 404 for browsers.
162pub 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/// Resolves when the shared stop flag is set.
175async fn wait_stop(mut stop: watch::Receiver<bool>) {
176 let _ = stop.wait_for(|stopped| *stopped).await;
177}
178
179/// Resolves on Ctrl-C or SIGTERM. A handler that cannot be installed is logged and never resolves,
180/// so the other one still works.
181async 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)]
206pub(crate) use tests::test_state;
207
208#[cfg(test)]
209mod 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 /// An app state over a fresh temp directory: the database and the key live there, and nothing
216 /// is written outside it. The directory is returned so it lives as long as the state.
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}