//! File configuration (`config/in.toml`). Secrets never live here: the OIDC client secret and the //! S3 keys are read from files or entered in the admin UI. Every struct rejects unknown keys, so a //! typo fails at boot instead of being silently ignored. use std::fmt; use std::net::{IpAddr, SocketAddr}; use std::path::{Path, PathBuf}; use std::str::FromStr; use ipnet::IpNet; use serde::{Deserialize, Deserializer}; use url::{Host, Url}; use crate::error::{Error, Result}; use crate::secret::Redacted; /// The example file. It is committed, and it is written to `config/in.toml` when that file is missing. pub const EXAMPLE: &str = include_str!("../../../config/in.example.toml"); /// The whole file configuration. #[derive(Debug, Clone, PartialEq, Deserialize)] #[serde(deny_unknown_fields, default)] pub struct Config { /// Path of the database file. Relative paths are relative to the working directory. pub database: PathBuf, /// Directory for blobs, staging files, the instance key and caches. Created at boot with mode 0700. pub data_dir: PathBuf, /// Address the HTTP server binds to. pub listen: SocketAddr, /// Public URL of the instance, with scheme and no trailing slash. Decides cookie `Secure` and HSTS. pub base_url: String, /// Proxies whose `X-Forwarded-For` is believed. Each entry is a CIDR range or a bare address. #[serde(deserialize_with = "deserialize_trusted_proxies")] pub trusted_proxies: Vec, /// Sign-in through `im`. Without it the instance cannot sign anyone in. pub oidc: Option, /// Where blobs are kept. pub storage: Storage, /// Scheduled backups. Absent means no scheduled backups. pub backup: Option, /// Defaults the admin page may override at run time. See `settings.rs` for the precedence rule. pub limits: Limits, } impl Default for Config { fn default() -> Self { Self { database: PathBuf::from("data/in.db"), data_dir: PathBuf::from("data"), listen: SocketAddr::from(([127, 0, 0, 1], 7655)), base_url: "http://127.0.0.1:7655".into(), trusted_proxies: Vec::new(), oidc: None, storage: Storage::default(), backup: None, limits: Limits::default(), } } } /// The `[oidc]` table: where `im` lives and which client id `in` uses. The secret is not here. #[derive(Debug, Clone, PartialEq, Eq, Deserialize)] #[serde(deny_unknown_fields)] pub struct Oidc { /// Issuer URL of `im`, as published in its discovery document. pub issuer: String, /// The OAuth client id registered for `in` in `im`. pub client_id: String, /// File holding the client secret, readable only by the service user. Read at boot. pub client_secret_file: PathBuf, } /// The `[limits]` table: file-level values of the settings the admin page can override. A value that is /// absent here falls back to the built-in default. Each one is checked by `settings::check_file`. #[derive(Debug, Clone, PartialEq, Eq, Default, Deserialize)] #[serde(deny_unknown_fields, default)] pub struct Limits { /// Quota of a person who first appears, in bytes. pub default_quota_bytes: Option, /// Quota of a service namespace that makes its first call, in bytes. pub default_service_quota_bytes: Option, /// Days a trashed item waits before it is purged. pub purge_after_days: Option, /// Largest upload accepted, in bytes. pub max_upload_bytes: Option, /// Longest a share link may last, in days. pub link_max_days: Option, } /// The `[storage]` table. #[derive(Debug, Clone, PartialEq, Eq, Default, Deserialize)] #[serde(deny_unknown_fields, default)] pub struct Storage { /// Which blob backend to use. pub backend: Backend, /// S3 settings. Required when `backend` is `s3`, and an error when `backend` is `local`. pub s3: Option, } /// Blob backends. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)] #[serde(rename_all = "lowercase")] pub enum Backend { /// Files in `data_dir/blobs`. #[default] Local, /// An S3-compatible bucket (AWS, R2, Hetzner Object Storage, ...). S3, } /// The `[storage.s3]` table. Credentials are files readable only by the service user. #[derive(Debug, Clone, PartialEq, Eq, Deserialize)] #[serde(deny_unknown_fields)] pub struct S3 { /// Endpoint URL for a non-AWS service. Absent means AWS. #[serde(default)] pub endpoint: Option, /// Region name the service expects (`auto` for R2). pub region: String, /// Bucket that holds the blob tree. pub bucket: String, /// File holding the access key id. pub access_key_id_file: PathBuf, /// File holding the secret access key. pub secret_access_key_file: PathBuf, } /// The `[backup]` table. #[derive(Clone, PartialEq, Eq, Deserialize)] #[serde(deny_unknown_fields)] pub struct Backup { /// Directory that receives one snapshot set per run. pub dir: PathBuf, /// Hours between backup runs. Must be at least 1. #[serde(default = "default_interval_hours")] pub interval_hours: u32, /// Snapshot sets kept; older ones are removed after a successful run. Must be at least 1. #[serde(default = "default_keep")] pub keep: u32, /// Dead-man URL pinged after each successful run. Absent means no pings. #[serde(default)] pub healthcheck_url: Option, } impl fmt::Debug for Backup { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Backup") .field("dir", &self.dir) .field("interval_hours", &self.interval_hours) .field("keep", &self.keep) .field( "healthcheck_url", &self.healthcheck_url.as_ref().map(|_| Redacted), ) .finish() } } fn default_interval_hours() -> u32 { 24 } fn default_keep() -> u32 { 7 } impl Config { /// Reads and validates the file at `path`. A missing file is first created from [`EXAMPLE`], so a /// first run starts with working development defaults. pub fn load(path: &Path) -> Result { let text = match std::fs::read_to_string(path) { Ok(text) => text, Err(e) if e.kind() == std::io::ErrorKind::NotFound => { if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) { std::fs::create_dir_all(parent)?; } std::fs::write(path, EXAMPLE)?; EXAMPLE.to_owned() } Err(e) => return Err(e.into()), }; let config: Config = toml::from_str(&text).map_err(|e| Error::Config(format!("{}: {e}", path.display())))?; config.validate()?; Ok(config) } /// Checks the rules that span fields. Called by [`Config::load`] and again whenever a setting /// is changed from the admin UI. pub fn validate(&self) -> Result<()> { if self.data_dir.as_os_str().is_empty() { return Err(config_err("data_dir must not be empty")); } if self.database.as_os_str().is_empty() { return Err(config_err("database must not be empty")); } validate_base_url("base_url", &self.base_url)?; if let Some(oidc) = &self.oidc { validate_base_url("oidc.issuer", &oidc.issuer)?; if oidc.client_id.trim().is_empty() || oidc.client_id.chars().any(char::is_control) { return Err(config_err( "oidc.client_id must be a non-empty plain string", )); } if oidc.client_secret_file.as_os_str().is_empty() { return Err(config_err("oidc.client_secret_file must not be empty")); } } self.storage.validate()?; crate::settings::check_file(&self.limits)?; if let Some(backup) = &self.backup { backup.validate()?; } Ok(()) } } impl Storage { fn validate(&self) -> Result<()> { match (self.backend, &self.s3) { (Backend::Local, Some(_)) => Err(config_err( "storage.s3 is set but storage.backend is \"local\"", )), (Backend::Local, None) => Ok(()), (Backend::S3, None) => Err(config_err( "storage.backend is \"s3\" but [storage.s3] is missing", )), (Backend::S3, Some(s3)) => s3.validate(), } } } impl S3 { fn validate(&self) -> Result<()> { if let Some(endpoint) = &self.endpoint { validate_base_url("storage.s3.endpoint", endpoint)?; } if self.region.trim().is_empty() { return Err(config_err("storage.s3.region must not be empty")); } if self.bucket.trim().is_empty() { return Err(config_err("storage.s3.bucket must not be empty")); } if self.access_key_id_file.as_os_str().is_empty() || self.secret_access_key_file.as_os_str().is_empty() { return Err(config_err( "storage.s3 credential file paths must not be empty", )); } Ok(()) } } impl Backup { fn validate(&self) -> Result<()> { if self.dir.as_os_str().is_empty() { return Err(config_err("backup.dir must not be empty")); } if self.interval_hours == 0 { return Err(config_err("backup.interval_hours must be at least 1")); } if self.keep == 0 { return Err(config_err("backup.keep must be at least 1")); } if let Some(url) = &self.healthcheck_url { validate_base_url("backup.healthcheck_url", url)?; } Ok(()) } } fn config_err(message: &str) -> Error { Error::Config(message.to_string()) } /// Parses `url` and returns it only when `in` may connect to it: `https` always, and `http` only for a /// loopback host with no userinfo, so plain text never leaves the machine. Every URL `in` is given /// goes through here, the configuration and the family switcher alike. pub fn parse_endpoint(url: &str) -> Option { let parsed = Url::parse(url).ok()?; let plain_ok = parsed.scheme() == "http" && parsed.username().is_empty() && parsed.password().is_none() && is_loopback(&parsed); (parsed.scheme() == "https" || plain_ok).then_some(parsed) } /// Whether the host of `url` is `localhost`, an IPv4 address in 127.0.0.0/8, or `::1`. fn is_loopback(url: &Url) -> bool { match url.host() { Some(Host::Domain(name)) => name == "localhost", Some(Host::Ipv4(ip)) => ip.is_loopback(), Some(Host::Ipv6(ip)) => ip.is_loopback(), None => false, } } /// A URL that [`parse_endpoint`] accepts, with no trailing slash and no whitespace. The rest is left to /// the component that uses the URL, which reports its own error. fn validate_base_url(field: &str, url: &str) -> Result<()> { if parse_endpoint(url).is_none() { return Err(config_err(&format!( "{field} must be an https:// URL, or an http:// URL for a loopback host" ))); } if url.ends_with('/') || url.chars().any(char::is_whitespace) { return Err(config_err(&format!( "{field} must have no trailing slash and no whitespace" ))); } Ok(()) } /// Accepts `10.0.0.1`, `fd00::1` (a single address, which becomes a host range) or a CIDR range. fn deserialize_trusted_proxies<'de, D>(deserializer: D) -> std::result::Result, D::Error> where D: Deserializer<'de>, { let items = Vec::::deserialize(deserializer)?; items .iter() .map(|item| parse_proxy(item).map_err(serde::de::Error::custom)) .collect() } /// Parses one trusted-proxy entry. A bare address becomes a single-host range. pub fn parse_proxy(text: &str) -> std::result::Result { let text = text.trim(); if text.contains('/') { return IpNet::from_str(text).map_err(|e| format!("trusted proxy {text:?}: {e}")); } let ip = IpAddr::from_str(text).map_err(|e| format!("trusted proxy {text:?}: {e}"))?; let host_len = if ip.is_ipv4() { 32 } else { 128 }; IpNet::new(ip, host_len).map_err(|e| format!("trusted proxy {text:?}: {e}")) } #[cfg(test)] mod tests { use super::*; #[test] fn plain_http_is_allowed_only_for_loopback_hosts() { for url in [ "http://127.0.0.1:7655", "http://127.4.5.6", "http://localhost:7650", "http://[::1]:7650", "https://im.example.com", ] { assert!(parse_endpoint(url).is_some(), "{url}"); } for url in [ "http://localhost.evil.example", "http://localhost@evil.example", "http://192.168.1.5", "http://evil.example", "ftp://127.0.0.1", ] { assert!(parse_endpoint(url).is_none(), "{url}"); } } #[test] fn example_is_valid_and_bare_proxy_addresses_are_accepted() { let config: Config = toml::from_str(EXAMPLE).unwrap(); config.validate().unwrap(); let text = "trusted_proxies = [\"10.0.0.1\", \"fd00::/8\"]"; let config: Config = toml::from_str(text).unwrap(); assert_eq!(config.trusted_proxies.len(), 2); assert_eq!(config.trusted_proxies[0].prefix_len(), 32); assert!(toml::from_str::("databse = \"typo.db\"").is_err()); } }