| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | use std::os::unix::fs::{OpenOptionsExt, PermissionsExt}; |
| 10 | use std::path::Path; |
| 11 | use std::sync::Arc; |
| 12 | |
| 13 | use in_core::blob::BlobStore; |
| 14 | use in_core::blob::local::LocalBlobs; |
| 15 | use in_core::blob::s3::{S3Blobs, S3Settings}; |
| 16 | use in_core::config::{Backend, Config, S3, parse_endpoint}; |
| 17 | use in_core::error::{Error, Result}; |
| 18 | use in_core::secret; |
| 19 | use in_core::store::Store; |
| 20 | use tokio::net::TcpListener; |
| 21 | use tokio::signal::unix::{SignalKind, signal}; |
| 22 | use tokio::sync::watch; |
| 23 | use topcoat::cookie::RouterBuilderCookieExt; |
| 24 | use topcoat::router::{BodyLimit, Router, RouterBuilderDiscoverExt, RouterService, TrustedProxies}; |
| 25 | |
| 26 | use crate::backup::{self, BackupTrigger}; |
| 27 | use crate::directory; |
| 28 | use crate::family; |
| 29 | use crate::family::FamilyCache; |
| 30 | use crate::live::LiveHub; |
| 31 | use crate::oidc::OidcClient; |
| 32 | use crate::pages::files; |
| 33 | use crate::pages::not_found::NotFoundLayer; |
| 34 | use crate::security::{self, SecurityHeaders}; |
| 35 | use crate::state::{AppState, ObjectStaging}; |
| 36 | use crate::sweeper; |
| 37 | use crate::throttle::ShareThrottles; |
| 38 | use crate::thumbs_worker; |
| 39 | |
| 40 | |
| 41 | pub const KEY_FILE: &str = "in.key"; |
| 42 | |
| 43 | |
| 44 | |
| 45 | const LOCK_FILE: &str = "in.lock"; |
| 46 | |
| 47 | |
| 48 | pub const BLOB_DIR: &str = "blobs"; |
| 49 | |
| 50 | |
| 51 | |
| 52 | pub 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 | |
| 71 | |
| 72 | pub struct Offline { |
| 73 | |
| 74 | pub store: Store, |
| 75 | |
| 76 | pub blobs: Arc<dyn BlobStore>, |
| 77 | |
| 78 | _lock: std::fs::File, |
| 79 | } |
| 80 | |
| 81 | |
| 82 | pub 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 | |
| 103 | pub 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 | |
| 108 | let _lock = lock_data_dir(&config.data_dir)?; |
| 109 | let state = open_state(config).await?; |
| 110 | |
| 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 | |
| 150 | |
| 151 | fn 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 | |
| 167 | fn listen_is_loopback(config: &Config) -> bool { |
| 168 | config.listen.ip().is_loopback() |
| 169 | } |
| 170 | |
| 171 | |
| 172 | |
| 173 | async fn open_state(config: Config) -> Result<AppState> { |
| 174 | std::fs::create_dir_all(&config.data_dir)?; |
| 175 | |
| 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 | |
| 227 | |
| 228 | |
| 229 | pub 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 | |
| 244 | |
| 245 | fn 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 | |
| 262 | |
| 263 | fn 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 | |
| 275 | |
| 276 | pub fn router(state: AppState) -> Router { |
| 277 | let security = SecurityHeaders::new(security::headers_for(&state.config.base_url)); |
| 278 | |
| 279 | |
| 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 | |
| 287 | .layer(BodyLimit::max(files::SMALL_UPLOAD_CEILING).at("/files")) |
| 288 | .layer(security) |
| 289 | .layer(NotFoundLayer) |
| 290 | .build() |
| 291 | } |
| 292 | |
| 293 | |
| 294 | async fn wait_stop(mut stop: watch::Receiver<bool>) { |
| 295 | let _ = stop.wait_for(|stopped| *stopped).await; |
| 296 | } |
| 297 | |
| 298 | |
| 299 | |
| 300 | async 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)] |
| 325 | pub(crate) use tests::test_state; |
| 326 | |
| 327 | #[cfg(test)] |
| 328 | mod 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 | |
| 336 | |
| 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 | } |