forge
Explore
Log in

Don't you dare go Hollow

in

Clone
★ 0

0 watching0 forksRustAGPL-3.0528.7 KiB9215377Tahinli27 days ago37 commits

boot.rs393 lines, 14.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 the
5//! pragmas and the migrations), open the blob store the configuration names, build the router, bind
6//! the listener, and serve until SIGTERM or Ctrl-C. Stored UI overrides are not layered on the file
7//! yet, because no page writes them.
8
9use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
10use std::path::Path;
11use std::sync::Arc;
12
13use in_core::blob::BlobStore;
14use in_core::blob::local::LocalBlobs;
15use in_core::blob::s3::{S3Blobs, S3Settings};
16use in_core::config::{Backend, Config, S3, parse_endpoint};
17use in_core::error::{Error, Result};
18use in_core::secret;
19use in_core::store::Store;
20use tokio::net::TcpListener;
21use tokio::signal::unix::{SignalKind, signal};
22use tokio::sync::watch;
23use topcoat::cookie::RouterBuilderCookieExt;
24use topcoat::router::{BodyLimit, Router, RouterBuilderDiscoverExt, RouterService, TrustedProxies};
25
26use crate::backup::{self, BackupTrigger};
27use crate::directory;
28use crate::family;
29use crate::family::FamilyCache;
30use crate::live::LiveHub;
31use crate::oidc::OidcClient;
32use crate::pages::files;
33use crate::pages::not_found::NotFoundLayer;
34use crate::security::{self, SecurityHeaders};
35use crate::state::{AppState, ObjectStaging};
36use crate::sweeper;
37use crate::throttle::ShareThrottles;
38use crate::thumbs_worker;
39
40/// Name of the instance key file inside the data directory.
41pub const KEY_FILE: &str = "in.key";
42
43/// Name of the lock file inside the data directory. A running server holds it; the operator commands take it
44/// too, so they refuse to run beside a server.
45const LOCK_FILE: &str = "in.lock";
46
47/// Directory under the data directory that holds the local blob tree.
48pub const BLOB_DIR: &str = "blobs";
49
50/// Takes the data directory's lock. The file is created with mode 0600 inside the 0700 directory. The lock
51/// is held for as long as the returned file lives; a second holder gets a conflict that says what to do.
52pub fn lock_data_dir(data_dir: &Path) -> Result<std::fs::File> {
53 std::fs::create_dir_all(data_dir)?;
54 std::fs::set_permissions(data_dir, std::fs::Permissions::from_mode(0o700))?;
55 let file = std::fs::OpenOptions::new()
56 .create(true)
57 .truncate(false)
58 .write(true)
59 .mode(0o600)
60 .open(data_dir.join(LOCK_FILE))?;
61 match file.try_lock() {
62 Ok(()) => Ok(file),
63 Err(std::fs::TryLockError::WouldBlock) => Err(Error::Conflict(
64 "in is running on this data directory. Stop the server first, then run the command again.".into(),
65 )),
66 Err(std::fs::TryLockError::Error(error)) => Err(error.into()),
67 }
68}
69
70/// What an operator command needs: the configuration, the database, the blob store, and the lock that keeps a
71/// server out. Opened without the OpenID client, so the commands run even when `im` is not configured.
72pub struct Offline {
73 /// The database.
74 pub store: Store,
75 /// The blob store the configuration names.
76 pub blobs: Arc<dyn BlobStore>,
77 /// The data-directory lock. Dropping it lets a server start again.
78 _lock: std::fs::File,
79}
80
81/// Opens an [`Offline`] view of the instance. Refuses while a server holds the lock.
82pub async fn open_offline(config_path: &Path) -> Result<Offline> {
83 let config = Config::load(config_path)?;
84 let lock = lock_data_dir(&config.data_dir)?;
85 let data_dir = config.data_dir.canonicalize()?;
86 if let Some(parent) = config
87 .database
88 .parent()
89 .filter(|p| !p.as_os_str().is_empty())
90 {
91 std::fs::create_dir_all(parent)?;
92 }
93 let store = Store::open(&config.database).await?;
94 let blobs = open_blobs(&config, &data_dir)?;
95 Ok(Offline {
96 store,
97 blobs,
98 _lock: lock,
99 })
100}
101
102/// Runs the server until a stop signal arrives. Returns once every connection has finished.
103pub async fn serve(config_path: &Path) -> Result<()> {
104 let config = Config::load(config_path)?;
105 let listen = config.listen;
106 warn_about_setup(&config);
107 // Held until the server stops: an operator command started now refuses instead of racing the server.
108 let _lock = lock_data_dir(&config.data_dir)?;
109 let state = open_state(config).await?;
110 // One stop flag. The signal task sets it; the server and every worker watch it and then drain.
111 let (stop_tx, stop_rx) = watch::channel(false);
112 if state.oidc.is_some() {
113 tokio::spawn(directory::run(state.clone(), stop_rx.clone()));
114 tokio::spawn(family::run(state.clone(), stop_rx.clone()));
115 }
116 if state.config.backup.is_some() {
117 tokio::spawn(backup::run(state.clone(), stop_rx.clone()));
118 }
119 tokio::spawn(sweeper::run(state.clone(), stop_rx.clone()));
120 tokio::spawn(thumbs_worker::run(state.clone(), stop_rx.clone()));
121
122 let listener = TcpListener::bind(listen).await.map_err(|error| {
123 std::io::Error::new(error.kind(), format!("cannot bind {listen}: {error}"))
124 })?;
125 tracing::info!(
126 listen = %listen,
127 data_dir = %state.config.data_dir.display(),
128 storage = ?state.config.storage.backend,
129 build = env!("IN_BUILD_SHA"),
130 "in starting"
131 );
132
133 tokio::spawn(async move {
134 shutdown_signal().await;
135 tracing::info!("shutdown signal received");
136 stop_tx.send_replace(true);
137 });
138
139 topcoat::serve_until(
140 listener,
141 RouterService::new(router(state)),
142 wait_stop(stop_rx),
143 )
144 .await?;
145 tracing::info!("in stopped");
146 Ok(())
147}
148
149/// Logs the settings that are legal but usually a mistake. Each one is a warning, never a refusal, because
150/// a local development setup has good reasons to leave them out.
151fn warn_about_setup(config: &Config) {
152 if listen_is_loopback(config) && config.trusted_proxies.is_empty() {
153 tracing::warn!(
154 listen = %config.listen,
155 "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"
156 );
157 }
158 if config.backup.is_none() {
159 tracing::warn!("[backup] is not configured: there are no scheduled backups");
160 }
161 if config.oidc.is_none() {
162 tracing::warn!("[oidc] is not configured: sign-in is disabled");
163 }
164}
165
166/// Whether the listener is bound to a loopback address only.
167fn listen_is_loopback(config: &Config) -> bool {
168 config.listen.ip().is_loopback()
169}
170
171/// Creates the data directory and opens the key, the database and the blob store. Everything the
172/// router needs that touches the disk is ready when this returns.
173async fn open_state(config: Config) -> Result<AppState> {
174 std::fs::create_dir_all(&config.data_dir)?;
175 // The directory holds the instance key. Only this user may enter it.
176 std::fs::set_permissions(&config.data_dir, std::fs::Permissions::from_mode(0o700))?;
177 let data_dir = config.data_dir.canonicalize()?;
178 if let Some(parent) = config
179 .database
180 .parent()
181 .filter(|p| !p.as_os_str().is_empty())
182 {
183 std::fs::create_dir_all(parent)?;
184 }
185 let database_dir = std::fs::canonicalize(
186 config
187 .database
188 .parent()
189 .filter(|p| !p.as_os_str().is_empty())
190 .unwrap_or(Path::new(".")),
191 )?;
192 if !database_dir.starts_with(&data_dir) {
193 tracing::warn!(
194 database = %config.database.display(),
195 "database is outside data_dir: restore will not replace it, and the data-directory lock does not cover it"
196 );
197 }
198 let key = secret::load_or_create_key(&data_dir.join(KEY_FILE))?;
199 let store = Store::open(&config.database).await?;
200 let blobs = open_blobs(&config, &data_dir)?;
201 let oidc = match &config.oidc {
202 Some(oidc) => {
203 let client_secret = read_secret(&oidc.client_secret_file)?;
204 Some(Arc::new(OidcClient::new(
205 oidc,
206 &config.base_url,
207 client_secret,
208 )?))
209 }
210 None => None,
211 };
212 Ok(AppState {
213 config: Arc::new(config),
214 store,
215 blobs,
216 key: Arc::new(key),
217 live: Arc::new(LiveHub::default()),
218 backup: Arc::new(BackupTrigger::default()),
219 oidc,
220 throttles: Arc::new(ShareThrottles::default()),
221 family: Arc::new(FamilyCache::default()),
222 staging: Arc::new(ObjectStaging::default()),
223 })
224}
225
226/// Builds the blob store the configuration names. The local backend keeps its tree under
227/// `data_dir/blobs`. The S3 backend reads its credentials from the files the configuration names; no
228/// request is made here, so a wrong bucket shows on the first use.
229pub fn open_blobs(config: &Config, data_dir: &Path) -> Result<Arc<dyn BlobStore>> {
230 match config.storage.backend {
231 Backend::Local => Ok(Arc::new(LocalBlobs::new(data_dir.join(BLOB_DIR))?)),
232 Backend::S3 => {
233 let s3 = config
234 .storage
235 .s3
236 .as_ref()
237 .ok_or_else(|| Error::Config("storage.s3 is missing".into()))?;
238 Ok(Arc::new(S3Blobs::new(&s3_settings(s3)?)?))
239 }
240 }
241}
242
243/// Turns the `[storage.s3]` table and its credential files into the client settings. Without an
244/// endpoint the AWS endpoint of the region is used. Plain http is allowed only for a loopback endpoint.
245fn s3_settings(s3: &S3) -> Result<S3Settings> {
246 let endpoint = s3
247 .endpoint
248 .clone()
249 .unwrap_or_else(|| format!("https://s3.{}.amazonaws.com", s3.region));
250 let allow_http = parse_endpoint(&endpoint).is_some_and(|url| url.scheme() == "http");
251 Ok(S3Settings {
252 allow_http,
253 endpoint,
254 region: s3.region.clone(),
255 bucket: s3.bucket.clone(),
256 access_key_id: read_secret(&s3.access_key_id_file)?,
257 secret_access_key: read_secret(&s3.secret_access_key_file)?,
258 })
259}
260
261/// Reads a credential file and drops the trailing newline. An empty file is a configuration error, and so
262/// is a file that group or world can read.
263fn read_secret(path: &Path) -> Result<String> {
264 let text = std::fs::read_to_string(path)
265 .map_err(|e| Error::Config(format!("cannot read {}: {e}", path.display())))?;
266 secret::check_private(path)?;
267 let value = text.trim().to_owned();
268 if value.is_empty() {
269 return Err(Error::Config(format!("{} is empty", path.display())));
270 }
271 Ok(value)
272}
273
274/// The router of the server: every route and page found by `discover`, the cookie jar, the security
275/// headers on every response, and the styled 404 for browsers.
276pub fn router(state: AppState) -> Router {
277 let security = SecurityHeaders::new(security::headers_for(&state.config.base_url));
278 // Behind a reverse proxy, client_ip reads X-Forwarded-For only from these peers; without them
279 // every client would share the proxy's address and per-IP throttles would become global.
280 let proxies = TrustedProxies::new().networks(state.config.trusted_proxies.clone());
281 Router::builder()
282 .trusted_proxies(proxies)
283 .discover()
284 .app_context(state)
285 .cookies()
286 // The upload form streams, but the body limit still caps how much one request may send.
287 .layer(BodyLimit::max(files::SMALL_UPLOAD_CEILING).at("/files"))
288 .layer(security)
289 .layer(NotFoundLayer)
290 .build()
291}
292
293/// Resolves when the shared stop flag is set.
294async fn wait_stop(mut stop: watch::Receiver<bool>) {
295 let _ = stop.wait_for(|stopped| *stopped).await;
296}
297
298/// Resolves on Ctrl-C or SIGTERM. A handler that cannot be installed is logged and never resolves,
299/// so the other one still works.
300async fn shutdown_signal() {
301 let ctrl_c = async {
302 if let Err(error) = tokio::signal::ctrl_c().await {
303 tracing::error!(error = %error, "cannot listen for Ctrl-C");
304 std::future::pending::<()>().await;
305 }
306 };
307 let terminate = async {
308 match signal(SignalKind::terminate()) {
309 Ok(mut term) => {
310 term.recv().await;
311 }
312 Err(error) => {
313 tracing::error!(error = %error, "cannot listen for SIGTERM");
314 std::future::pending::<()>().await;
315 }
316 }
317 };
318 tokio::select! {
319 () = ctrl_c => {}
320 () = terminate => {}
321 }
322}
323
324#[cfg(test)]
325pub(crate) use tests::test_state;
326
327#[cfg(test)]
328mod tests {
329 use super::*;
330 use http::header::{ACCEPT, CONTENT_SECURITY_POLICY, X_CONTENT_TYPE_OPTIONS};
331 use std::net::SocketAddr;
332 use topcoat::router::response::Response;
333 use topcoat::router::{Body, to_bytes};
334
335 /// An app state over a fresh temp directory: the database, the key and the blobs live there, and
336 /// nothing is written outside it. The directory is returned so it lives as long as the state.
337 pub(crate) async fn test_state() -> (tempfile::TempDir, AppState) {
338 let dir = tempfile::tempdir().expect("temp dir");
339 let config = Config {
340 database: dir.path().join("in.db"),
341 data_dir: dir.path().to_path_buf(),
342 listen: SocketAddr::from(([127, 0, 0, 1], 17650)),
343 ..Config::default()
344 };
345 let key = secret::load_or_create_key(&dir.path().join(KEY_FILE)).expect("key");
346 let store = Store::open(&config.database).await.expect("store");
347 let blobs = open_blobs(&config, dir.path()).expect("blobs");
348 let state = AppState {
349 config: Arc::new(config),
350 store,
351 blobs,
352 key: Arc::new(key),
353 live: Arc::new(LiveHub::default()),
354 backup: Arc::new(BackupTrigger::default()),
355 oidc: None,
356 throttles: Arc::new(ShareThrottles::default()),
357 family: Arc::new(FamilyCache::default()),
358 staging: Arc::new(ObjectStaging::default()),
359 };
360 (dir, state)
361 }
362
363 async fn get(state: AppState, path: &str, accept: Option<&str>) -> Response {
364 let mut request = http::Request::get(path);
365 if let Some(accept) = accept {
366 request = request.header(ACCEPT, accept);
367 }
368 let request = request.body(Body::empty()).expect("request");
369 router(state).handle(request).await
370 }
371
372 #[tokio::test]
373 async fn an_unknown_path_gets_the_styled_404_with_the_security_headers() {
374 let (_dir, state) = test_state().await;
375 let response = get(state, "/no/such/page", Some("text/html")).await;
376 assert_eq!(response.status(), 404);
377 assert_eq!(
378 response.headers()[CONTENT_SECURITY_POLICY]
379 .to_str()
380 .expect("ascii"),
381 security::CSP
382 );
383 assert_eq!(response.headers()[X_CONTENT_TYPE_OPTIONS], "nosniff");
384 let body = to_bytes(response.into_body(), 64 * 1024)
385 .await
386 .expect("body");
387 let html = String::from_utf8_lossy(&body);
388 assert!(
389 html.contains("Page not found"),
390 "styled 404 body, got: {html}"
391 );
392 }
393}