//! The instance configuration, read from TOML. //! //! Only non-secret, deployment-level settings live here. Secrets are never in this file: they are //! entered in the admin UI and sealed in the database, or kept in a separate file that only the //! service user can read. Every struct rejects unknown keys, so a typo fails at boot instead of //! silently doing nothing. use std::net::SocketAddr; use std::path::{Path, PathBuf}; use ipnet::IpNet; use serde::{Deserialize, Deserializer}; use crate::error::{Error, Result}; /// The example file. It is written to the config path on first run when that path is missing. const EXAMPLE: &str = include_str!("../../../config/im.example.toml"); /// Parses each entry as a CIDR network, or as a single address (a /32 or /128). fn deserialize_trusted_proxies<'de, D: Deserializer<'de>>( deserializer: D, ) -> std::result::Result, D::Error> { let entries = Vec::::deserialize(deserializer)?; entries .iter() .map(|entry| { entry .parse::() .or_else(|_| entry.parse::().map(IpNet::from)) .map_err(|_| serde::de::Error::custom(format!("invalid trusted proxy `{entry}`"))) }) .collect() } /// Outbound mail settings that do not involve a secret. #[derive(Debug, Clone, Default, Deserialize)] #[serde(deny_unknown_fields, default)] pub struct MailConfig { /// Reserved for a development mail log. It has no effect yet: mail is always queued in the outbox /// and sent through `[smtp]`. pub log_only: bool, } /// How the SMTP connection is secured. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)] #[serde(rename_all = "lowercase")] pub enum SmtpTls { /// TLS from the first byte of the connection (port 465 by convention). #[default] Implicit, /// A plain connection that is upgraded with STARTTLS. The upgrade is required. Starttls, /// No TLS. Only for a relay on localhost, where the traffic never leaves the machine. None, } /// The outbound SMTP sender. Empty `host` means no sender: mail waits in the outbox and no attempt is /// spent. The password is never in this file; `password_file` names a file that only the service user /// can read (mode 0600 or stricter), and it is read again before each batch, so it can be rotated. #[derive(Debug, Clone, Deserialize)] #[serde(deny_unknown_fields, default)] pub struct SmtpConfig { /// Host name or address of the submission server. Empty for none. pub host: String, /// TCP port. 465 for implicit TLS, 587 for STARTTLS. pub port: u16, /// Transport security. `none` is refused unless `host` is localhost. pub tls: SmtpTls, /// Login name. Empty for an unauthenticated relay. pub username: String, /// File holding the password, first line only. Empty when there is no login. pub password_file: PathBuf, /// Address mail is sent from. Required when `host` is set. pub from: String, /// Display name of the sender. pub from_name: String, } impl Default for SmtpConfig { fn default() -> Self { Self { host: String::new(), port: 465, tls: SmtpTls::Implicit, username: String::new(), password_file: PathBuf::new(), from: String::new(), from_name: "im".to_owned(), } } } impl SmtpConfig { /// True when a sender is configured. pub fn enabled(&self) -> bool { !self.host.is_empty() } } /// True for `localhost` and for loopback addresses, the only places plaintext SMTP is allowed. pub fn is_localhost(host: &str) -> bool { host.eq_ignore_ascii_case("localhost") || host .parse::() .is_ok_and(|addr| addr.is_loopback()) } /// Scheduled backups. Off while `dir` is empty. #[derive(Debug, Clone, Deserialize)] #[serde(deny_unknown_fields, default)] pub struct BackupConfig { /// Directory that receives one snapshot set per run. Empty turns backups off. pub dir: PathBuf, /// Hours between two scheduled backups. Must be at least 1 when backups are on. pub interval_hours: u64, /// Number of snapshot sets kept; older sets are deleted after a successful run. At least 1. pub keep: u32, /// Dead-man URL pinged after each run (`/start`, then success or `/fail`). Empty for none. pub healthcheck_url: String, } impl Default for BackupConfig { fn default() -> Self { Self { dir: PathBuf::new(), interval_hours: 24, keep: 7, healthcheck_url: String::new(), } } } impl BackupConfig { /// True when a backup directory is set. pub fn enabled(&self) -> bool { !self.dir.as_os_str().is_empty() } } /// Sign-in policy. These are the file values. A value saved in the admin UI is stored in `settings` /// under `policy.` and wins over them (`docs/architecture.md` section 7); see /// [`PolicyConfig::set`] and [`Config::explicit_policy`]. #[derive(Debug, Clone, PartialEq, Eq, Deserialize)] #[serde(deny_unknown_fields, default)] pub struct PolicyConfig { /// An administrator without two-factor sign-in is sent to enrol it after signing in, and cannot /// reach the admin pages until they do. pub require_2fa_for_admins: bool, /// Sessions one person may hold at once. The oldest is ended when a new sign-in would exceed it. /// At least 1. pub max_sessions: u32, /// Hard cap of a browser session, in days from sign-in. A session is idle-extended on use (30 days /// since its last use) but never lives longer than this. Between 1 and 365. pub session_max_days: u32, /// Days an invitation stays usable. Between 1 and 30. pub invite_days: u32, /// Minutes a password-reset link stays usable. Between 5 and 1440. pub reset_minutes: u32, /// Hours both halves of an email change stay usable. Between 1 and 168. pub email_change_hours: u32, } /// The policy keys, in the order the admin page shows them. Each is stored as `policy.`. pub const POLICY_KEYS: [&str; 6] = [ "require_2fa_for_admins", "max_sessions", "session_max_days", "invite_days", "reset_minutes", "email_change_hours", ]; impl Default for PolicyConfig { fn default() -> Self { Self { require_2fa_for_admins: true, max_sessions: 10, session_max_days: 30, invite_days: 7, reset_minutes: 60, email_change_hours: 24, } } } impl PolicyConfig { /// The ranges of the policy values. Used for the file and for every value saved in the UI. pub fn validate(&self) -> Result<()> { if self.max_sessions == 0 { return Err(Error::Config( "[policy] max_sessions must be at least 1".into(), )); } if !(1..=365).contains(&self.session_max_days) { return Err(Error::Config( "[policy] session_max_days must be between 1 and 365".into(), )); } if !(1..=30).contains(&self.invite_days) { return Err(Error::Config( "[policy] invite_days must be between 1 and 30".into(), )); } if !(5..=1440).contains(&self.reset_minutes) { return Err(Error::Config( "[policy] reset_minutes must be between 5 and 1440".into(), )); } if !(1..=168).contains(&self.email_change_hours) { return Err(Error::Config( "[policy] email_change_hours must be between 1 and 168".into(), )); } Ok(()) } /// Returns a copy with `key` set to `value`, checked. A key outside [`POLICY_KEYS`] or a value /// that does not parse or is out of range is an error that names the key. pub fn set(&self, key: &str, value: &str) -> Result { let mut next = self.clone(); let number = |text: &str| -> Result { text.trim() .parse::() .map_err(|_| Error::Invalid(format!("{key} must be a whole number"))) }; match key { "require_2fa_for_admins" => { next.require_2fa_for_admins = match value.trim() { "true" | "on" | "1" => true, "false" | "off" | "0" | "" => false, _ => return Err(Error::Invalid(format!("{key} must be true or false"))), }; } "max_sessions" => next.max_sessions = number(value)?, "session_max_days" => next.session_max_days = number(value)?, "invite_days" => next.invite_days = number(value)?, "reset_minutes" => next.reset_minutes = number(value)?, "email_change_hours" => next.email_change_hours = number(value)?, other => return Err(Error::Invalid(format!("{other} is not a policy setting"))), } next.validate().map_err(|e| Error::Invalid(e.to_string()))?; Ok(next) } } /// The whole file. Field names are the TOML keys. #[derive(Debug, Clone, Deserialize)] #[serde(deny_unknown_fields)] pub struct Config { /// Path of the SQLite-format database file. pub database: PathBuf, /// Directory for the instance key, photos, backups and other files beside the database. pub data_dir: PathBuf, /// Address the HTTP server binds to. pub listen: SocketAddr, /// Public origin of this instance, such as `https://id.example.com`. No trailing slash. Used /// for links in mail and for the OpenID issuer. pub base_url: String, /// Peers whose `X-Forwarded-For` header is believed. Entries are addresses or CIDR networks. /// Empty by default, so the TCP peer is always the client. #[serde(default, deserialize_with = "deserialize_trusted_proxies")] pub trusted_proxies: Vec, /// Mail settings without secrets. #[serde(default)] pub mail: MailConfig, /// The SMTP sender. #[serde(default)] pub smtp: SmtpConfig, /// Scheduled backups. #[serde(default)] pub backup: BackupConfig, /// Sign-in policy. #[serde(default)] pub policy: PolicyConfig, /// The policy keys that the file sets explicitly, so the admin page can say "file" rather than /// "default". Not read from TOML: [`Config::parse`] fills it. #[serde(skip)] pub explicit_policy: Vec, } impl Config { /// Reads and validates the file at `path`. /// /// When the file does not exist, the example file is written there first (creating its parent /// directory), so a fresh checkout runs with 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()), }; Self::parse(&text).map_err(|e| Error::Config(format!("{}: {e}", path.display()))) } /// Parses and validates TOML text. Used by [`Config::load`] and by tests. pub fn parse(text: &str) -> Result { let mut config: Config = toml::from_str(text).map_err(|e| Error::Config(format!("{e}")))?; config.validate()?; // A second, loose read of the same text: which [policy] keys the file names. if let Ok(table) = text.parse::() && let Some(toml::Value::Table(policy)) = table.get("policy") { config.explicit_policy = policy.keys().cloned().collect(); } Ok(config) } /// The cross-field rules that cannot be expressed per field. Run after parsing. pub fn validate(&self) -> Result<()> { if self.database.as_os_str().is_empty() { return Err(Error::Config("database must not be empty".into())); } if self.data_dir.as_os_str().is_empty() { return Err(Error::Config("data_dir must not be empty".into())); } validate_base_url(&self.base_url)?; if self.backup.enabled() { if self.backup.interval_hours == 0 { return Err(Error::Config( "[backup] interval_hours must be at least 1".into(), )); } if self.backup.keep == 0 { return Err(Error::Config("[backup] keep must be at least 1".into())); } } self.policy.validate()?; self.validate_smtp()?; let hc = &self.backup.healthcheck_url; if !hc.is_empty() && !(hc.starts_with("https://") || hc.starts_with("http://")) { return Err(Error::Config( "[backup] healthcheck_url must be an http or https URL".into(), )); } Ok(()) } } impl Config { /// The SMTP rules: plaintext only on localhost, a valid sender address, and a password file when /// there is a login. Checked only when a sender is configured. fn validate_smtp(&self) -> Result<()> { let smtp = &self.smtp; if !smtp.enabled() { return Ok(()); } if smtp.port == 0 { return Err(Error::Config( "[smtp] port must be between 1 and 65535".into(), )); } if smtp.tls == SmtpTls::None && !is_localhost(&smtp.host) { return Err(Error::Config( "[smtp] tls = \"none\" is allowed only for a localhost host".into(), )); } if !smtp.username.is_empty() && smtp.password_file.as_os_str().is_empty() { return Err(Error::Config( "[smtp] a username needs a password_file".into(), )); } crate::names::parse_email(&smtp.from) .map_err(|_| Error::Config("[smtp] from must be an email address".into()))?; crate::names::parse_display_name(&smtp.from_name) .map_err(|_| Error::Config("[smtp] from_name is not a valid name".into()))?; Ok(()) } } /// Checks that `base_url` is an origin with a path of at most `/`. It must be https, except for a localhost /// or loopback host, where plain http never leaves the machine (the same rule as the SMTP `tls = "none"`). fn validate_base_url(url: &str) -> Result<()> { let (secure, rest) = match url.strip_prefix("https://") { Some(rest) => (true, rest), None => ( false, url.strip_prefix("http://").ok_or_else(|| { Error::Config("base_url must start with http:// or https://".into()) })?, ), }; if rest.is_empty() || rest.ends_with('/') || url.chars().any(char::is_whitespace) { return Err(Error::Config( "base_url must be an origin with no trailing slash or spaces".into(), )); } let authority = rest.split('/').next().unwrap_or(rest); let host = match authority.strip_prefix('[') { Some(bracketed) => bracketed.split(']').next().unwrap_or(bracketed), None => authority.split(':').next().unwrap_or(authority), }; if !secure && !is_localhost(host) { return Err(Error::Config( "base_url must use https:// unless its host is localhost or a loopback address".into(), )); } Ok(()) } #[cfg(test)] mod tests { use super::*; #[test] fn example_file_parses_and_rejects_unknown_keys() { Config::parse(EXAMPLE).expect("the example must be valid"); let typo = format!("{EXAMPLE}\nlisen = \"0.0.0.0:1\"\n"); assert!(Config::parse(&typo).is_err()); } #[test] fn plaintext_smtp_is_refused_unless_the_host_is_localhost() { let base = "database = \"d\"\ndata_dir = \"x\"\nlisten = \"127.0.0.1:1\"\nbase_url = \"https://a\"\n"; let remote = format!( "{base}[smtp]\nhost = \"mail.example.com\"\ntls = \"none\"\nfrom = \"im@example.com\"\n" ); assert!(Config::parse(&remote).is_err()); let local = format!( "{base}[smtp]\nhost = \"127.0.0.1\"\nport = 2525\ntls = \"none\"\nfrom = \"im@example.com\"\n" ); Config::parse(&local).expect("localhost may be plain"); let no_from = format!("{base}[smtp]\nhost = \"mail.example.com\"\n"); assert!(Config::parse(&no_from).is_err()); } #[test] fn plain_http_base_url_is_refused_unless_the_host_is_loopback() { let base_url = |url: &str| { format!( "database = \"d\"\ndata_dir = \"x\"\nlisten = \"127.0.0.1:1\"\nbase_url = \"{url}\"\n" ) }; assert!(Config::parse(&base_url("http://id.example.com")).is_err()); assert!(Config::parse(&base_url("http://127.0.0.1:7650")).is_ok()); assert!(Config::parse(&base_url("http://[::1]:7650")).is_ok()); assert!(Config::parse(&base_url("https://id.example.com")).is_ok()); } }