forge
Explore
Log in

Don't you dare go Hollow

im

Clone
★ 0

0 watching0 forksRustAGPL-3.0542.8 KiBb9f0726Tahinli27 days ago34 commits

boot.rs389 lines, 16.0 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 of the policy are layered on the file values here, once, at boot.
7
8use std::fs::{File, OpenOptions, TryLockError};
9use std::os::unix::fs::PermissionsExt;
10use std::path::Path;
11use std::sync::{Arc, RwLock};
12
13use im_core::config::{Config, PolicyConfig, SmtpTls};
14use im_core::photo::MAX_UPLOAD_BYTES;
15use im_core::secret;
16use im_core::store::Store;
17use tokio::net::TcpListener;
18use tokio::signal::unix::{SignalKind, signal};
19use tokio::sync::{Semaphore, watch};
20use topcoat::cookie::RouterBuilderCookieExt;
21use topcoat::router::{BodyLimit, Router, RouterBuilderDiscoverExt, RouterService};
22
23use crate::api::directory::StreamSlots;
24use crate::backchannel;
25use crate::backups::BackupTrigger;
26use crate::live::{LiveHub, MAX_ANONYMOUS_STREAMS};
27use crate::mail;
28use crate::oidc::signing;
29use crate::pages::admin::message::{MESSAGE_BODY_LIMIT, MESSAGE_ROUTE};
30use crate::pages::not_found::NotFoundLayer;
31use crate::pages::profile::PHOTO_ROUTE;
32use crate::security::{self, SecurityHeaders};
33use crate::service_probe;
34use crate::state::AppState;
35use crate::sweeper;
36use crate::throttle::Throttle;
37
38/// Name of the instance key file inside the data directory.
39pub(crate) const KEY_FILE: &str = "im.key";
40
41/// Name of the lock file inside the data directory. The server holds it for its whole life, and so does
42/// every operator command, so the two never open the database at once.
43const LOCK_FILE: &str = "im.lock";
44
45/// Takes the exclusive lock of the data directory, creating the directory (mode 0700) when needed. The
46/// returned file keeps the lock; dropping it releases the lock. Fails with a message that tells the
47/// operator to stop the server when it is held.
48pub fn lock_data_dir(data_dir: &Path) -> im_core::Result<File> {
49 std::fs::create_dir_all(data_dir)?;
50 std::fs::set_permissions(data_dir, std::fs::Permissions::from_mode(0o700))?;
51 let file = OpenOptions::new()
52 .create(true)
53 .truncate(false)
54 .write(true)
55 .open(data_dir.join(LOCK_FILE))?;
56 match file.try_lock() {
57 Ok(()) => Ok(file),
58 Err(TryLockError::WouldBlock) => Err(im_core::Error::Conflict(
59 "im is running on this data directory. Stop the server first, then run the command again."
60 .into(),
61 )),
62 Err(TryLockError::Error(error)) => Err(error.into()),
63 }
64}
65
66/// Runs the server until a stop signal arrives. Returns once every connection has finished.
67pub async fn serve(config_path: &Path) -> im_core::Result<()> {
68 let config = Config::load(config_path)?;
69 let listen = config.listen;
70 let _lock = lock_data_dir(&config.data_dir)?;
71 let state = open_state(config).await?;
72 warn_weak_settings(&state);
73
74 let listener = TcpListener::bind(listen).await.map_err(|error| {
75 std::io::Error::new(error.kind(), format!("cannot bind {listen}: {error}"))
76 })?;
77 tracing::info!(
78 listen = %listen,
79 data_dir = %state.config.data_dir.display(),
80 build = env!("IM_BUILD_SHA"),
81 "im starting"
82 );
83
84 // One stop flag. The signal task sets it; the server watches it and then drains.
85 let (stop_tx, stop_rx) = watch::channel(false);
86 let state = AppState {
87 stop: stop_rx.clone(),
88 ..state
89 };
90 let backup_task = crate::backups::spawn(state.clone());
91 tokio::spawn(async move {
92 shutdown_signal().await;
93 tracing::info!("shutdown signal received");
94 stop_tx.send_replace(true);
95 });
96 let signing_worker = signing::spawn(state.store.clone(), state.key.clone(), stop_rx.clone());
97 let backchannel_worker = backchannel::spawn(
98 state.store.clone(),
99 state.key.clone(),
100 state.config.base_url.clone(),
101 stop_rx.clone(),
102 );
103 let sweeper_task = sweeper::spawn(state.store.clone(), stop_rx.clone());
104 let probe_worker = service_probe::spawn(state.store.clone(), stop_rx.clone());
105 let mail_worker = mail::worker::spawn(
106 state.store.clone(),
107 state.key.clone(),
108 state.config.smtp.clone(),
109 stop_rx.clone(),
110 );
111
112 topcoat::serve_until(
113 listener,
114 RouterService::new(router(state)),
115 wait_stop(stop_rx),
116 )
117 .await?;
118 let _ = signing_worker.await;
119 let _ = backchannel_worker.await;
120 let _ = sweeper_task.await;
121 let _ = probe_worker.await;
122 let _ = mail_worker.await;
123 if let Some(task) = backup_task {
124 let _ = task.await;
125 }
126 tracing::info!("im stopped");
127 Ok(())
128}
129
130/// Logs one warning for each setting that weakens the instance or does not fit its deployment. The server
131/// still starts: each is a choice an operator may have made on purpose. The policy is the one in effect,
132/// so an administrator's saved setting counts too.
133fn warn_weak_settings(state: &AppState) {
134 let config = &state.config;
135 if !state.policy().require_2fa_for_admins {
136 tracing::warn!(
137 "require_2fa_for_admins is off: administrators may sign in without two-factor sign-in"
138 );
139 }
140 if config.smtp.tls == SmtpTls::None {
141 tracing::warn!("smtp tls is none: mail is sent to the relay without encryption");
142 }
143 if !config.backup.enabled() {
144 tracing::warn!("backups are not configured: no scheduled copy of the database is made");
145 }
146 if config.trusted_proxies.is_empty() && config.listen.ip().is_loopback() {
147 tracing::warn!(
148 "trusted_proxies is empty while listen is a loopback address: behind a proxy, every client shares one IP for throttling"
149 );
150 }
151}
152
153/// Creates the data directory and opens the key and the database. Everything the router needs
154/// that touches the disk is ready when this returns. The signing keys are made ready too, so the
155/// first token can be signed. The operator commands use this as well.
156pub(crate) async fn open_state(config: Config) -> im_core::Result<AppState> {
157 std::fs::create_dir_all(&config.data_dir)?;
158 // The directory holds the instance key. Only this user may enter it.
159 std::fs::set_permissions(&config.data_dir, std::fs::Permissions::from_mode(0o700))?;
160 let data_dir = config.data_dir.canonicalize()?;
161 if let Some(parent) = config
162 .database
163 .parent()
164 .filter(|p| !p.as_os_str().is_empty())
165 {
166 std::fs::create_dir_all(parent)?;
167 }
168 // The database opens before the key so that a missing key can be checked against it. A key is created
169 // only for a data directory that holds no sealed rows; otherwise the sealed rows would be unreadable.
170 let key_path = data_dir.join(KEY_FILE);
171 let store = Store::open(&config.database).await?;
172 if !key_path.exists() && store.holds_sealed_data().await? {
173 return Err(im_core::Error::Crypto(
174 "im.key is missing but im.db holds data sealed with it; restore the key file".into(),
175 ));
176 }
177 let key = secret::load_or_create_key(&key_path)?;
178 let policy = effective_policy(&config, &store).await?;
179 signing::maintain(&store, &key).await?;
180 // im is in its own switcher list. The row follows the configured origin at every boot.
181 store
182 .upsert_home_service("Account", &config.base_url)
183 .await?;
184 Ok(AppState {
185 config: Arc::new(config),
186 policy_live: Arc::new(RwLock::new(policy)),
187 store,
188 key: Arc::new(key),
189 live: Arc::new(LiveHub::default()),
190 backup: Arc::new(BackupTrigger::default()),
191 throttle: Arc::new(Throttle::default()),
192 two_factor_days: Arc::new(Throttle::two_factor_days()),
193 photo_uploads: Arc::new(Throttle::photo_uploads()),
194 email_changes: Arc::new(Throttle::email_changes()),
195 per_minute: Arc::new(Throttle::per_minute()),
196 stream_slots: Arc::new(StreamSlots::default()),
197 anonymous_streams: Arc::new(Semaphore::new(MAX_ANONYMOUS_STREAMS)),
198 // Replaced by the stop flag of `serve` before any listener starts. The CLI never serves.
199 stop: watch::channel(false).1,
200 settings_lock: Arc::new(tokio::sync::Mutex::new(())),
201 photo_lock: Arc::new(tokio::sync::Mutex::new(())),
202 })
203}
204
205/// The policy in effect at boot: the file values, with each `policy.<key>` setting saved in the admin UI
206/// layered on top. A stored value that no longer validates is logged and ignored, so a bad row cannot stop
207/// the server from starting; the file value applies instead.
208pub(crate) async fn effective_policy(
209 config: &im_core::config::Config,
210 store: &Store,
211) -> im_core::Result<PolicyConfig> {
212 let saved = store.settings_with_prefix("policy.").await?;
213 Ok(merge_saved_policy(&config.policy, &saved))
214}
215
216/// The policy that the file values and the saved `policy.` values give. A saved value that does not parse
217/// or is out of range is logged and ignored, so one bad row cannot keep the server from starting. The
218/// settings page calls this on the values it reads inside its transaction.
219pub(crate) fn merge_saved_policy(file: &PolicyConfig, saved: &[(String, String)]) -> PolicyConfig {
220 let mut policy = file.clone();
221 for (key, value) in saved {
222 let name = key.trim_start_matches("policy.");
223 match policy.set(name, value) {
224 Ok(next) => policy = next,
225 Err(error) => {
226 tracing::warn!(setting = %key, error = %error, "stored policy setting ignored");
227 }
228 }
229 }
230 policy
231}
232
233/// The request body limit of the photo upload: the picture plus room for the multipart framing and
234/// the CSRF field. The handler enforces the picture limit itself while streaming.
235const PHOTO_BODY_LIMIT: usize = MAX_UPLOAD_BYTES + 64 * 1024;
236
237/// The request body limit of every other route. A form is a few hundred bytes, so 16 KiB is generous. It
238/// replaces the 2 MiB default of the framework, which no form needs.
239const FORM_BODY_LIMIT: usize = 16 * 1024;
240
241/// The router of the server: every route and page found by `discover`, the cookie jar, the security
242/// headers on every response, the styled 404 for browsers, the body limit of forms, and the larger limits
243/// of the photo upload and the admin message (which override the form limit under their paths).
244pub fn router(state: AppState) -> Router {
245 let security = SecurityHeaders::new(security::headers_for(&state.config.base_url));
246 Router::builder()
247 .discover()
248 .app_context(state)
249 .cookies()
250 .layer(BodyLimit::max(FORM_BODY_LIMIT))
251 .layer(BodyLimit::max(PHOTO_BODY_LIMIT).at(PHOTO_ROUTE))
252 .layer(BodyLimit::max(MESSAGE_BODY_LIMIT).at(MESSAGE_ROUTE))
253 .layer(security)
254 .layer(NotFoundLayer)
255 .build()
256}
257
258/// Resolves when the shared stop flag is set.
259async fn wait_stop(mut stop: watch::Receiver<bool>) {
260 let _ = stop.wait_for(|stopped| *stopped).await;
261}
262
263/// Resolves on Ctrl-C or SIGTERM. A handler that cannot be installed is logged and never resolves,
264/// so the other one still works.
265async fn shutdown_signal() {
266 let ctrl_c = async {
267 if let Err(error) = tokio::signal::ctrl_c().await {
268 tracing::error!(error = %error, "cannot listen for Ctrl-C");
269 std::future::pending::<()>().await;
270 }
271 };
272 let terminate = async {
273 match signal(SignalKind::terminate()) {
274 Ok(mut term) => {
275 term.recv().await;
276 }
277 Err(error) => {
278 tracing::error!(error = %error, "cannot listen for SIGTERM");
279 std::future::pending::<()>().await;
280 }
281 }
282 };
283 tokio::select! {
284 () = ctrl_c => {}
285 () = terminate => {}
286 }
287}
288
289#[cfg(test)]
290pub(crate) use tests::test_state;
291
292#[cfg(test)]
293mod tests {
294 use super::*;
295 use http::header::{ACCEPT, CONTENT_SECURITY_POLICY, X_CONTENT_TYPE_OPTIONS};
296 use topcoat::router::response::Response;
297 use topcoat::router::{Body, to_bytes};
298
299 /// An app state over a fresh temp directory: the database and the key live there, and nothing
300 /// is written outside it. The directory is returned so it lives as long as the state.
301 pub(crate) async fn test_state() -> (tempfile::TempDir, AppState) {
302 let dir = tempfile::tempdir().expect("temp dir");
303 let text = format!(
304 "database = \"{}\"\ndata_dir = \"{}\"\nlisten = \"127.0.0.1:7650\"\nbase_url = \"http://127.0.0.1:7650\"\n",
305 dir.path().join("im.db").display(),
306 dir.path().display(),
307 );
308 let config = Config::parse(&text).expect("test config");
309 let key = secret::load_or_create_key(&dir.path().join(KEY_FILE)).expect("key");
310 let store = Store::open(&config.database).await.expect("store");
311 let state = AppState {
312 policy_live: Arc::new(RwLock::new(config.policy.clone())),
313 config: Arc::new(config),
314 store,
315 key: Arc::new(key),
316 live: Arc::new(LiveHub::default()),
317 backup: Arc::new(BackupTrigger::default()),
318 throttle: Arc::new(Throttle::default()),
319 two_factor_days: Arc::new(Throttle::two_factor_days()),
320 photo_uploads: Arc::new(Throttle::photo_uploads()),
321 email_changes: Arc::new(Throttle::email_changes()),
322 per_minute: Arc::new(Throttle::per_minute()),
323 stream_slots: Arc::new(StreamSlots::default()),
324 anonymous_streams: Arc::new(Semaphore::new(MAX_ANONYMOUS_STREAMS)),
325 stop: watch::channel(false).1,
326 settings_lock: Arc::new(tokio::sync::Mutex::new(())),
327 photo_lock: Arc::new(tokio::sync::Mutex::new(())),
328 };
329 (dir, state)
330 }
331
332 async fn get(state: AppState, path: &str, accept: Option<&str>) -> Response {
333 let mut request = http::Request::get(path);
334 if let Some(accept) = accept {
335 request = request.header(ACCEPT, accept);
336 }
337 let request = request.body(Body::empty()).expect("request");
338 router(state).handle(request).await
339 }
340
341 #[tokio::test]
342 async fn a_page_carries_the_content_security_policy_and_nosniff() {
343 let (_dir, state) = test_state().await;
344 // No user yet, so the setup page answers.
345 let response = get(state, "/setup", Some("text/html")).await;
346 assert_eq!(response.status(), 200);
347 assert_eq!(
348 response.headers()[CONTENT_SECURITY_POLICY]
349 .to_str()
350 .expect("ascii"),
351 security::CSP
352 );
353 assert_eq!(response.headers()[X_CONTENT_TYPE_OPTIONS], "nosniff");
354 }
355
356 #[tokio::test]
357 async fn a_missing_key_is_refused_when_the_database_holds_sealed_rows() {
358 let (dir, state) = test_state().await;
359 signing::maintain(&state.store, &state.key)
360 .await
361 .expect("signing keys");
362 drop(state);
363 std::fs::remove_file(dir.path().join(KEY_FILE)).expect("key removed");
364 let text = format!(
365 "database = \"{}\"\ndata_dir = \"{}\"\nlisten = \"127.0.0.1:7650\"\nbase_url = \"http://127.0.0.1:7650\"\n",
366 dir.path().join("im.db").display(),
367 dir.path().display(),
368 );
369 let config = Config::parse(&text).expect("test config");
370 let error = open_state(config).await.err().expect("refused");
371 assert!(error.to_string().contains("im.key is missing"), "{error}");
372 assert!(!dir.path().join(KEY_FILE).exists(), "no key is created");
373 }
374
375 #[tokio::test]
376 async fn an_unknown_path_for_a_browser_gets_the_styled_404() {
377 let (_dir, state) = test_state().await;
378 let response = get(state, "/no/such/page", Some("text/html")).await;
379 assert_eq!(response.status(), 404);
380 let body = to_bytes(response.into_body(), 64 * 1024)
381 .await
382 .expect("body");
383 let html = String::from_utf8_lossy(&body);
384 assert!(
385 html.contains("Page not found"),
386 "styled 404 body, got: {html}"
387 );
388 }
389}