forge
Explore
Log in

Don't you dare go Hollow

im

Clone
★ 0

0 watching0 forksRustAGPL-3.0542.8 KiBb9f0726Tahinli27 days ago34 commits

config.rs444 lines, 16.9 KiBHistoryRawDownload
1//! The instance configuration, read from TOML.
2//!
3//! Only non-secret, deployment-level settings live here. Secrets are never in this file: they are
4//! entered in the admin UI and sealed in the database, or kept in a separate file that only the
5//! service user can read. Every struct rejects unknown keys, so a typo fails at boot instead of
6//! silently doing nothing.
7
8use std::net::SocketAddr;
9use std::path::{Path, PathBuf};
10
11use ipnet::IpNet;
12use serde::{Deserialize, Deserializer};
13
14use crate::error::{Error, Result};
15
16/// The example file. It is written to the config path on first run when that path is missing.
17const EXAMPLE: &str = include_str!("../../../config/im.example.toml");
18
19/// Parses each entry as a CIDR network, or as a single address (a /32 or /128).
20fn deserialize_trusted_proxies<'de, D: Deserializer<'de>>(
21 deserializer: D,
22) -> std::result::Result<Vec<IpNet>, D::Error> {
23 let entries = Vec::<String>::deserialize(deserializer)?;
24 entries
25 .iter()
26 .map(|entry| {
27 entry
28 .parse::<IpNet>()
29 .or_else(|_| entry.parse::<std::net::IpAddr>().map(IpNet::from))
30 .map_err(|_| serde::de::Error::custom(format!("invalid trusted proxy `{entry}`")))
31 })
32 .collect()
33}
34
35/// Outbound mail settings that do not involve a secret.
36#[derive(Debug, Clone, Default, Deserialize)]
37#[serde(deny_unknown_fields, default)]
38pub struct MailConfig {
39 /// Reserved for a development mail log. It has no effect yet: mail is always queued in the outbox
40 /// and sent through `[smtp]`.
41 pub log_only: bool,
42}
43
44/// How the SMTP connection is secured.
45#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
46#[serde(rename_all = "lowercase")]
47pub enum SmtpTls {
48 /// TLS from the first byte of the connection (port 465 by convention).
49 #[default]
50 Implicit,
51 /// A plain connection that is upgraded with STARTTLS. The upgrade is required.
52 Starttls,
53 /// No TLS. Only for a relay on localhost, where the traffic never leaves the machine.
54 None,
55}
56
57/// The outbound SMTP sender. Empty `host` means no sender: mail waits in the outbox and no attempt is
58/// spent. The password is never in this file; `password_file` names a file that only the service user
59/// can read (mode 0600 or stricter), and it is read again before each batch, so it can be rotated.
60#[derive(Debug, Clone, Deserialize)]
61#[serde(deny_unknown_fields, default)]
62pub struct SmtpConfig {
63 /// Host name or address of the submission server. Empty for none.
64 pub host: String,
65 /// TCP port. 465 for implicit TLS, 587 for STARTTLS.
66 pub port: u16,
67 /// Transport security. `none` is refused unless `host` is localhost.
68 pub tls: SmtpTls,
69 /// Login name. Empty for an unauthenticated relay.
70 pub username: String,
71 /// File holding the password, first line only. Empty when there is no login.
72 pub password_file: PathBuf,
73 /// Address mail is sent from. Required when `host` is set.
74 pub from: String,
75 /// Display name of the sender.
76 pub from_name: String,
77}
78
79impl Default for SmtpConfig {
80 fn default() -> Self {
81 Self {
82 host: String::new(),
83 port: 465,
84 tls: SmtpTls::Implicit,
85 username: String::new(),
86 password_file: PathBuf::new(),
87 from: String::new(),
88 from_name: "im".to_owned(),
89 }
90 }
91}
92
93impl SmtpConfig {
94 /// True when a sender is configured.
95 pub fn enabled(&self) -> bool {
96 !self.host.is_empty()
97 }
98}
99
100/// True for `localhost` and for loopback addresses, the only places plaintext SMTP is allowed.
101pub fn is_localhost(host: &str) -> bool {
102 host.eq_ignore_ascii_case("localhost")
103 || host
104 .parse::<std::net::IpAddr>()
105 .is_ok_and(|addr| addr.is_loopback())
106}
107
108/// Scheduled backups. Off while `dir` is empty.
109#[derive(Debug, Clone, Deserialize)]
110#[serde(deny_unknown_fields, default)]
111pub struct BackupConfig {
112 /// Directory that receives one snapshot set per run. Empty turns backups off.
113 pub dir: PathBuf,
114 /// Hours between two scheduled backups. Must be at least 1 when backups are on.
115 pub interval_hours: u64,
116 /// Number of snapshot sets kept; older sets are deleted after a successful run. At least 1.
117 pub keep: u32,
118 /// Dead-man URL pinged after each run (`/start`, then success or `/fail`). Empty for none.
119 pub healthcheck_url: String,
120}
121
122impl Default for BackupConfig {
123 fn default() -> Self {
124 Self {
125 dir: PathBuf::new(),
126 interval_hours: 24,
127 keep: 7,
128 healthcheck_url: String::new(),
129 }
130 }
131}
132
133impl BackupConfig {
134 /// True when a backup directory is set.
135 pub fn enabled(&self) -> bool {
136 !self.dir.as_os_str().is_empty()
137 }
138}
139
140/// Sign-in policy. These are the file values. A value saved in the admin UI is stored in `settings`
141/// under `policy.<name>` and wins over them (`docs/architecture.md` section 7); see
142/// [`PolicyConfig::set`] and [`Config::explicit_policy`].
143#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
144#[serde(deny_unknown_fields, default)]
145pub struct PolicyConfig {
146 /// An administrator without two-factor sign-in is sent to enrol it after signing in, and cannot
147 /// reach the admin pages until they do.
148 pub require_2fa_for_admins: bool,
149 /// Sessions one person may hold at once. The oldest is ended when a new sign-in would exceed it.
150 /// At least 1.
151 pub max_sessions: u32,
152 /// Hard cap of a browser session, in days from sign-in. A session is idle-extended on use (30 days
153 /// since its last use) but never lives longer than this. Between 1 and 365.
154 pub session_max_days: u32,
155 /// Days an invitation stays usable. Between 1 and 30.
156 pub invite_days: u32,
157 /// Minutes a password-reset link stays usable. Between 5 and 1440.
158 pub reset_minutes: u32,
159 /// Hours both halves of an email change stay usable. Between 1 and 168.
160 pub email_change_hours: u32,
161}
162
163/// The policy keys, in the order the admin page shows them. Each is stored as `policy.<key>`.
164pub const POLICY_KEYS: [&str; 6] = [
165 "require_2fa_for_admins",
166 "max_sessions",
167 "session_max_days",
168 "invite_days",
169 "reset_minutes",
170 "email_change_hours",
171];
172
173impl Default for PolicyConfig {
174 fn default() -> Self {
175 Self {
176 require_2fa_for_admins: true,
177 max_sessions: 10,
178 session_max_days: 30,
179 invite_days: 7,
180 reset_minutes: 60,
181 email_change_hours: 24,
182 }
183 }
184}
185
186impl PolicyConfig {
187 /// The ranges of the policy values. Used for the file and for every value saved in the UI.
188 pub fn validate(&self) -> Result<()> {
189 if self.max_sessions == 0 {
190 return Err(Error::Config(
191 "[policy] max_sessions must be at least 1".into(),
192 ));
193 }
194 if !(1..=365).contains(&self.session_max_days) {
195 return Err(Error::Config(
196 "[policy] session_max_days must be between 1 and 365".into(),
197 ));
198 }
199 if !(1..=30).contains(&self.invite_days) {
200 return Err(Error::Config(
201 "[policy] invite_days must be between 1 and 30".into(),
202 ));
203 }
204 if !(5..=1440).contains(&self.reset_minutes) {
205 return Err(Error::Config(
206 "[policy] reset_minutes must be between 5 and 1440".into(),
207 ));
208 }
209 if !(1..=168).contains(&self.email_change_hours) {
210 return Err(Error::Config(
211 "[policy] email_change_hours must be between 1 and 168".into(),
212 ));
213 }
214 Ok(())
215 }
216
217 /// Returns a copy with `key` set to `value`, checked. A key outside [`POLICY_KEYS`] or a value
218 /// that does not parse or is out of range is an error that names the key.
219 pub fn set(&self, key: &str, value: &str) -> Result<PolicyConfig> {
220 let mut next = self.clone();
221 let number = |text: &str| -> Result<u32> {
222 text.trim()
223 .parse::<u32>()
224 .map_err(|_| Error::Invalid(format!("{key} must be a whole number")))
225 };
226 match key {
227 "require_2fa_for_admins" => {
228 next.require_2fa_for_admins = match value.trim() {
229 "true" | "on" | "1" => true,
230 "false" | "off" | "0" | "" => false,
231 _ => return Err(Error::Invalid(format!("{key} must be true or false"))),
232 };
233 }
234 "max_sessions" => next.max_sessions = number(value)?,
235 "session_max_days" => next.session_max_days = number(value)?,
236 "invite_days" => next.invite_days = number(value)?,
237 "reset_minutes" => next.reset_minutes = number(value)?,
238 "email_change_hours" => next.email_change_hours = number(value)?,
239 other => return Err(Error::Invalid(format!("{other} is not a policy setting"))),
240 }
241 next.validate().map_err(|e| Error::Invalid(e.to_string()))?;
242 Ok(next)
243 }
244}
245
246/// The whole file. Field names are the TOML keys.
247#[derive(Debug, Clone, Deserialize)]
248#[serde(deny_unknown_fields)]
249pub struct Config {
250 /// Path of the SQLite-format database file.
251 pub database: PathBuf,
252 /// Directory for the instance key, photos, backups and other files beside the database.
253 pub data_dir: PathBuf,
254 /// Address the HTTP server binds to.
255 pub listen: SocketAddr,
256 /// Public origin of this instance, such as `https://id.example.com`. No trailing slash. Used
257 /// for links in mail and for the OpenID issuer.
258 pub base_url: String,
259 /// Peers whose `X-Forwarded-For` header is believed. Entries are addresses or CIDR networks.
260 /// Empty by default, so the TCP peer is always the client.
261 #[serde(default, deserialize_with = "deserialize_trusted_proxies")]
262 pub trusted_proxies: Vec<IpNet>,
263 /// Mail settings without secrets.
264 #[serde(default)]
265 pub mail: MailConfig,
266 /// The SMTP sender.
267 #[serde(default)]
268 pub smtp: SmtpConfig,
269 /// Scheduled backups.
270 #[serde(default)]
271 pub backup: BackupConfig,
272 /// Sign-in policy.
273 #[serde(default)]
274 pub policy: PolicyConfig,
275 /// The policy keys that the file sets explicitly, so the admin page can say "file" rather than
276 /// "default". Not read from TOML: [`Config::parse`] fills it.
277 #[serde(skip)]
278 pub explicit_policy: Vec<String>,
279}
280
281impl Config {
282 /// Reads and validates the file at `path`.
283 ///
284 /// When the file does not exist, the example file is written there first (creating its parent
285 /// directory), so a fresh checkout runs with development defaults.
286 pub fn load(path: &Path) -> Result<Config> {
287 let text = match std::fs::read_to_string(path) {
288 Ok(text) => text,
289 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
290 if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
291 std::fs::create_dir_all(parent)?;
292 }
293 std::fs::write(path, EXAMPLE)?;
294 EXAMPLE.to_owned()
295 }
296 Err(e) => return Err(e.into()),
297 };
298 Self::parse(&text).map_err(|e| Error::Config(format!("{}: {e}", path.display())))
299 }
300
301 /// Parses and validates TOML text. Used by [`Config::load`] and by tests.
302 pub fn parse(text: &str) -> Result<Config> {
303 let mut config: Config = toml::from_str(text).map_err(|e| Error::Config(format!("{e}")))?;
304 config.validate()?;
305 // A second, loose read of the same text: which [policy] keys the file names.
306 if let Ok(table) = text.parse::<toml::Table>()
307 && let Some(toml::Value::Table(policy)) = table.get("policy")
308 {
309 config.explicit_policy = policy.keys().cloned().collect();
310 }
311 Ok(config)
312 }
313
314 /// The cross-field rules that cannot be expressed per field. Run after parsing.
315 pub fn validate(&self) -> Result<()> {
316 if self.database.as_os_str().is_empty() {
317 return Err(Error::Config("database must not be empty".into()));
318 }
319 if self.data_dir.as_os_str().is_empty() {
320 return Err(Error::Config("data_dir must not be empty".into()));
321 }
322 validate_base_url(&self.base_url)?;
323 if self.backup.enabled() {
324 if self.backup.interval_hours == 0 {
325 return Err(Error::Config(
326 "[backup] interval_hours must be at least 1".into(),
327 ));
328 }
329 if self.backup.keep == 0 {
330 return Err(Error::Config("[backup] keep must be at least 1".into()));
331 }
332 }
333 self.policy.validate()?;
334 self.validate_smtp()?;
335 let hc = &self.backup.healthcheck_url;
336 if !hc.is_empty() && !(hc.starts_with("https://") || hc.starts_with("http://")) {
337 return Err(Error::Config(
338 "[backup] healthcheck_url must be an http or https URL".into(),
339 ));
340 }
341 Ok(())
342 }
343}
344
345impl Config {
346 /// The SMTP rules: plaintext only on localhost, a valid sender address, and a password file when
347 /// there is a login. Checked only when a sender is configured.
348 fn validate_smtp(&self) -> Result<()> {
349 let smtp = &self.smtp;
350 if !smtp.enabled() {
351 return Ok(());
352 }
353 if smtp.port == 0 {
354 return Err(Error::Config(
355 "[smtp] port must be between 1 and 65535".into(),
356 ));
357 }
358 if smtp.tls == SmtpTls::None && !is_localhost(&smtp.host) {
359 return Err(Error::Config(
360 "[smtp] tls = \"none\" is allowed only for a localhost host".into(),
361 ));
362 }
363 if !smtp.username.is_empty() && smtp.password_file.as_os_str().is_empty() {
364 return Err(Error::Config(
365 "[smtp] a username needs a password_file".into(),
366 ));
367 }
368 crate::names::parse_email(&smtp.from)
369 .map_err(|_| Error::Config("[smtp] from must be an email address".into()))?;
370 crate::names::parse_display_name(&smtp.from_name)
371 .map_err(|_| Error::Config("[smtp] from_name is not a valid name".into()))?;
372 Ok(())
373 }
374}
375
376/// Checks that `base_url` is an origin with a path of at most `/`. It must be https, except for a localhost
377/// or loopback host, where plain http never leaves the machine (the same rule as the SMTP `tls = "none"`).
378fn validate_base_url(url: &str) -> Result<()> {
379 let (secure, rest) = match url.strip_prefix("https://") {
380 Some(rest) => (true, rest),
381 None => (
382 false,
383 url.strip_prefix("http://").ok_or_else(|| {
384 Error::Config("base_url must start with http:// or https://".into())
385 })?,
386 ),
387 };
388 if rest.is_empty() || rest.ends_with('/') || url.chars().any(char::is_whitespace) {
389 return Err(Error::Config(
390 "base_url must be an origin with no trailing slash or spaces".into(),
391 ));
392 }
393 let authority = rest.split('/').next().unwrap_or(rest);
394 let host = match authority.strip_prefix('[') {
395 Some(bracketed) => bracketed.split(']').next().unwrap_or(bracketed),
396 None => authority.split(':').next().unwrap_or(authority),
397 };
398 if !secure && !is_localhost(host) {
399 return Err(Error::Config(
400 "base_url must use https:// unless its host is localhost or a loopback address".into(),
401 ));
402 }
403 Ok(())
404}
405
406#[cfg(test)]
407mod tests {
408 use super::*;
409
410 #[test]
411 fn example_file_parses_and_rejects_unknown_keys() {
412 Config::parse(EXAMPLE).expect("the example must be valid");
413 let typo = format!("{EXAMPLE}\nlisen = \"0.0.0.0:1\"\n");
414 assert!(Config::parse(&typo).is_err());
415 }
416
417 #[test]
418 fn plaintext_smtp_is_refused_unless_the_host_is_localhost() {
419 let base = "database = \"d\"\ndata_dir = \"x\"\nlisten = \"127.0.0.1:1\"\nbase_url = \"https://a\"\n";
420 let remote = format!(
421 "{base}[smtp]\nhost = \"mail.example.com\"\ntls = \"none\"\nfrom = \"im@example.com\"\n"
422 );
423 assert!(Config::parse(&remote).is_err());
424 let local = format!(
425 "{base}[smtp]\nhost = \"127.0.0.1\"\nport = 2525\ntls = \"none\"\nfrom = \"im@example.com\"\n"
426 );
427 Config::parse(&local).expect("localhost may be plain");
428 let no_from = format!("{base}[smtp]\nhost = \"mail.example.com\"\n");
429 assert!(Config::parse(&no_from).is_err());
430 }
431
432 #[test]
433 fn plain_http_base_url_is_refused_unless_the_host_is_loopback() {
434 let base_url = |url: &str| {
435 format!(
436 "database = \"d\"\ndata_dir = \"x\"\nlisten = \"127.0.0.1:1\"\nbase_url = \"{url}\"\n"
437 )
438 };
439 assert!(Config::parse(&base_url("http://id.example.com")).is_err());
440 assert!(Config::parse(&base_url("http://127.0.0.1:7650")).is_ok());
441 assert!(Config::parse(&base_url("http://[::1]:7650")).is_ok());
442 assert!(Config::parse(&base_url("https://id.example.com")).is_ok());
443 }
444}