| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | use std::net::SocketAddr; |
| 9 | use std::path::{Path, PathBuf}; |
| 10 | |
| 11 | use ipnet::IpNet; |
| 12 | use serde::{Deserialize, Deserializer}; |
| 13 | |
| 14 | use crate::error::{Error, Result}; |
| 15 | |
| 16 | |
| 17 | const EXAMPLE: &str = include_str!("../../../config/im.example.toml"); |
| 18 | |
| 19 | |
| 20 | fn 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 | |
| 36 | #[derive(Debug, Clone, Default, Deserialize)] |
| 37 | #[serde(deny_unknown_fields, default)] |
| 38 | pub struct MailConfig { |
| 39 | |
| 40 | |
| 41 | pub log_only: bool, |
| 42 | } |
| 43 | |
| 44 | |
| 45 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)] |
| 46 | #[serde(rename_all = "lowercase")] |
| 47 | pub enum SmtpTls { |
| 48 | |
| 49 | #[default] |
| 50 | Implicit, |
| 51 | |
| 52 | Starttls, |
| 53 | |
| 54 | None, |
| 55 | } |
| 56 | |
| 57 | |
| 58 | |
| 59 | |
| 60 | #[derive(Debug, Clone, Deserialize)] |
| 61 | #[serde(deny_unknown_fields, default)] |
| 62 | pub struct SmtpConfig { |
| 63 | |
| 64 | pub host: String, |
| 65 | |
| 66 | pub port: u16, |
| 67 | |
| 68 | pub tls: SmtpTls, |
| 69 | |
| 70 | pub username: String, |
| 71 | |
| 72 | pub password_file: PathBuf, |
| 73 | |
| 74 | pub from: String, |
| 75 | |
| 76 | pub from_name: String, |
| 77 | } |
| 78 | |
| 79 | impl 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 | |
| 93 | impl SmtpConfig { |
| 94 | |
| 95 | pub fn enabled(&self) -> bool { |
| 96 | !self.host.is_empty() |
| 97 | } |
| 98 | } |
| 99 | |
| 100 | |
| 101 | pub 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 | |
| 109 | #[derive(Debug, Clone, Deserialize)] |
| 110 | #[serde(deny_unknown_fields, default)] |
| 111 | pub struct BackupConfig { |
| 112 | |
| 113 | pub dir: PathBuf, |
| 114 | |
| 115 | pub interval_hours: u64, |
| 116 | |
| 117 | pub keep: u32, |
| 118 | |
| 119 | pub healthcheck_url: String, |
| 120 | } |
| 121 | |
| 122 | impl 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 | |
| 133 | impl BackupConfig { |
| 134 | |
| 135 | pub fn enabled(&self) -> bool { |
| 136 | !self.dir.as_os_str().is_empty() |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | |
| 141 | |
| 142 | |
| 143 | #[derive(Debug, Clone, PartialEq, Eq, Deserialize)] |
| 144 | #[serde(deny_unknown_fields, default)] |
| 145 | pub struct PolicyConfig { |
| 146 | |
| 147 | |
| 148 | pub require_2fa_for_admins: bool, |
| 149 | |
| 150 | |
| 151 | pub max_sessions: u32, |
| 152 | |
| 153 | |
| 154 | pub session_max_days: u32, |
| 155 | |
| 156 | pub invite_days: u32, |
| 157 | |
| 158 | pub reset_minutes: u32, |
| 159 | |
| 160 | pub email_change_hours: u32, |
| 161 | } |
| 162 | |
| 163 | |
| 164 | pub 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 | |
| 173 | impl 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 | |
| 186 | impl PolicyConfig { |
| 187 | |
| 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 | |
| 218 | |
| 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 | |
| 247 | #[derive(Debug, Clone, Deserialize)] |
| 248 | #[serde(deny_unknown_fields)] |
| 249 | pub struct Config { |
| 250 | |
| 251 | pub database: PathBuf, |
| 252 | |
| 253 | pub data_dir: PathBuf, |
| 254 | |
| 255 | pub listen: SocketAddr, |
| 256 | |
| 257 | |
| 258 | pub base_url: String, |
| 259 | |
| 260 | |
| 261 | #[serde(default, deserialize_with = "deserialize_trusted_proxies")] |
| 262 | pub trusted_proxies: Vec<IpNet>, |
| 263 | |
| 264 | #[serde(default)] |
| 265 | pub mail: MailConfig, |
| 266 | |
| 267 | #[serde(default)] |
| 268 | pub smtp: SmtpConfig, |
| 269 | |
| 270 | #[serde(default)] |
| 271 | pub backup: BackupConfig, |
| 272 | |
| 273 | #[serde(default)] |
| 274 | pub policy: PolicyConfig, |
| 275 | |
| 276 | |
| 277 | #[serde(skip)] |
| 278 | pub explicit_policy: Vec<String>, |
| 279 | } |
| 280 | |
| 281 | impl Config { |
| 282 | |
| 283 | |
| 284 | |
| 285 | |
| 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 | |
| 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 | |
| 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 | |
| 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 | |
| 345 | impl Config { |
| 346 | |
| 347 | |
| 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 | |
| 377 | |
| 378 | fn 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)] |
| 407 | mod 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 | } |