| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | use std::fmt; |
| 6 | use std::net::{IpAddr, SocketAddr}; |
| 7 | use std::path::{Path, PathBuf}; |
| 8 | use std::str::FromStr; |
| 9 | |
| 10 | use ipnet::IpNet; |
| 11 | use serde::{Deserialize, Deserializer}; |
| 12 | use url::{Host, Url}; |
| 13 | |
| 14 | use crate::error::{Error, Result}; |
| 15 | use crate::secret::Redacted; |
| 16 | |
| 17 | |
| 18 | pub const EXAMPLE: &str = include_str!("../../../config/in.example.toml"); |
| 19 | |
| 20 | |
| 21 | #[derive(Debug, Clone, PartialEq, Deserialize)] |
| 22 | #[serde(deny_unknown_fields, default)] |
| 23 | pub struct Config { |
| 24 | |
| 25 | pub database: PathBuf, |
| 26 | |
| 27 | pub data_dir: PathBuf, |
| 28 | |
| 29 | pub listen: SocketAddr, |
| 30 | |
| 31 | pub base_url: String, |
| 32 | |
| 33 | #[serde(deserialize_with = "deserialize_trusted_proxies")] |
| 34 | pub trusted_proxies: Vec<IpNet>, |
| 35 | |
| 36 | pub oidc: Option<Oidc>, |
| 37 | |
| 38 | pub storage: Storage, |
| 39 | |
| 40 | pub backup: Option<Backup>, |
| 41 | |
| 42 | pub limits: Limits, |
| 43 | } |
| 44 | |
| 45 | impl Default for Config { |
| 46 | fn default() -> Self { |
| 47 | Self { |
| 48 | database: PathBuf::from("data/in.db"), |
| 49 | data_dir: PathBuf::from("data"), |
| 50 | listen: SocketAddr::from(([127, 0, 0, 1], 7655)), |
| 51 | base_url: "http://127.0.0.1:7655".into(), |
| 52 | trusted_proxies: Vec::new(), |
| 53 | oidc: None, |
| 54 | storage: Storage::default(), |
| 55 | backup: None, |
| 56 | limits: Limits::default(), |
| 57 | } |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | |
| 62 | #[derive(Debug, Clone, PartialEq, Eq, Deserialize)] |
| 63 | #[serde(deny_unknown_fields)] |
| 64 | pub struct Oidc { |
| 65 | |
| 66 | pub issuer: String, |
| 67 | |
| 68 | pub client_id: String, |
| 69 | |
| 70 | pub client_secret_file: PathBuf, |
| 71 | } |
| 72 | |
| 73 | |
| 74 | |
| 75 | #[derive(Debug, Clone, PartialEq, Eq, Default, Deserialize)] |
| 76 | #[serde(deny_unknown_fields, default)] |
| 77 | pub struct Limits { |
| 78 | |
| 79 | pub default_quota_bytes: Option<i64>, |
| 80 | |
| 81 | pub default_service_quota_bytes: Option<i64>, |
| 82 | |
| 83 | pub purge_after_days: Option<i64>, |
| 84 | |
| 85 | pub max_upload_bytes: Option<i64>, |
| 86 | |
| 87 | pub link_max_days: Option<i64>, |
| 88 | } |
| 89 | |
| 90 | |
| 91 | #[derive(Debug, Clone, PartialEq, Eq, Default, Deserialize)] |
| 92 | #[serde(deny_unknown_fields, default)] |
| 93 | pub struct Storage { |
| 94 | |
| 95 | pub backend: Backend, |
| 96 | |
| 97 | pub s3: Option<S3>, |
| 98 | } |
| 99 | |
| 100 | |
| 101 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)] |
| 102 | #[serde(rename_all = "lowercase")] |
| 103 | pub enum Backend { |
| 104 | |
| 105 | #[default] |
| 106 | Local, |
| 107 | |
| 108 | S3, |
| 109 | } |
| 110 | |
| 111 | |
| 112 | #[derive(Debug, Clone, PartialEq, Eq, Deserialize)] |
| 113 | #[serde(deny_unknown_fields)] |
| 114 | pub struct S3 { |
| 115 | |
| 116 | #[serde(default)] |
| 117 | pub endpoint: Option<String>, |
| 118 | |
| 119 | pub region: String, |
| 120 | |
| 121 | pub bucket: String, |
| 122 | |
| 123 | pub access_key_id_file: PathBuf, |
| 124 | |
| 125 | pub secret_access_key_file: PathBuf, |
| 126 | } |
| 127 | |
| 128 | |
| 129 | #[derive(Clone, PartialEq, Eq, Deserialize)] |
| 130 | #[serde(deny_unknown_fields)] |
| 131 | pub struct Backup { |
| 132 | |
| 133 | pub dir: PathBuf, |
| 134 | |
| 135 | #[serde(default = "default_interval_hours")] |
| 136 | pub interval_hours: u32, |
| 137 | |
| 138 | #[serde(default = "default_keep")] |
| 139 | pub keep: u32, |
| 140 | |
| 141 | #[serde(default)] |
| 142 | pub healthcheck_url: Option<String>, |
| 143 | } |
| 144 | |
| 145 | impl fmt::Debug for Backup { |
| 146 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 147 | f.debug_struct("Backup") |
| 148 | .field("dir", &self.dir) |
| 149 | .field("interval_hours", &self.interval_hours) |
| 150 | .field("keep", &self.keep) |
| 151 | .field( |
| 152 | "healthcheck_url", |
| 153 | &self.healthcheck_url.as_ref().map(|_| Redacted), |
| 154 | ) |
| 155 | .finish() |
| 156 | } |
| 157 | } |
| 158 | |
| 159 | fn default_interval_hours() -> u32 { |
| 160 | 24 |
| 161 | } |
| 162 | |
| 163 | fn default_keep() -> u32 { |
| 164 | 7 |
| 165 | } |
| 166 | |
| 167 | impl Config { |
| 168 | |
| 169 | |
| 170 | pub fn load(path: &Path) -> Result<Config> { |
| 171 | let text = match std::fs::read_to_string(path) { |
| 172 | Ok(text) => text, |
| 173 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => { |
| 174 | if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) { |
| 175 | std::fs::create_dir_all(parent)?; |
| 176 | } |
| 177 | std::fs::write(path, EXAMPLE)?; |
| 178 | EXAMPLE.to_owned() |
| 179 | } |
| 180 | Err(e) => return Err(e.into()), |
| 181 | }; |
| 182 | let config: Config = |
| 183 | toml::from_str(&text).map_err(|e| Error::Config(format!("{}: {e}", path.display())))?; |
| 184 | config.validate()?; |
| 185 | Ok(config) |
| 186 | } |
| 187 | |
| 188 | |
| 189 | |
| 190 | pub fn validate(&self) -> Result<()> { |
| 191 | if self.data_dir.as_os_str().is_empty() { |
| 192 | return Err(config_err("data_dir must not be empty")); |
| 193 | } |
| 194 | if self.database.as_os_str().is_empty() { |
| 195 | return Err(config_err("database must not be empty")); |
| 196 | } |
| 197 | validate_base_url("base_url", &self.base_url)?; |
| 198 | if let Some(oidc) = &self.oidc { |
| 199 | validate_base_url("oidc.issuer", &oidc.issuer)?; |
| 200 | if oidc.client_id.trim().is_empty() || oidc.client_id.chars().any(char::is_control) { |
| 201 | return Err(config_err( |
| 202 | "oidc.client_id must be a non-empty plain string", |
| 203 | )); |
| 204 | } |
| 205 | if oidc.client_secret_file.as_os_str().is_empty() { |
| 206 | return Err(config_err("oidc.client_secret_file must not be empty")); |
| 207 | } |
| 208 | } |
| 209 | self.storage.validate()?; |
| 210 | crate::settings::check_file(&self.limits)?; |
| 211 | if let Some(backup) = &self.backup { |
| 212 | backup.validate()?; |
| 213 | } |
| 214 | Ok(()) |
| 215 | } |
| 216 | } |
| 217 | |
| 218 | impl Storage { |
| 219 | fn validate(&self) -> Result<()> { |
| 220 | match (self.backend, &self.s3) { |
| 221 | (Backend::Local, Some(_)) => Err(config_err( |
| 222 | "storage.s3 is set but storage.backend is \"local\"", |
| 223 | )), |
| 224 | (Backend::Local, None) => Ok(()), |
| 225 | (Backend::S3, None) => Err(config_err( |
| 226 | "storage.backend is \"s3\" but [storage.s3] is missing", |
| 227 | )), |
| 228 | (Backend::S3, Some(s3)) => s3.validate(), |
| 229 | } |
| 230 | } |
| 231 | } |
| 232 | |
| 233 | impl S3 { |
| 234 | fn validate(&self) -> Result<()> { |
| 235 | if let Some(endpoint) = &self.endpoint { |
| 236 | validate_base_url("storage.s3.endpoint", endpoint)?; |
| 237 | } |
| 238 | if self.region.trim().is_empty() { |
| 239 | return Err(config_err("storage.s3.region must not be empty")); |
| 240 | } |
| 241 | if self.bucket.trim().is_empty() { |
| 242 | return Err(config_err("storage.s3.bucket must not be empty")); |
| 243 | } |
| 244 | if self.access_key_id_file.as_os_str().is_empty() |
| 245 | || self.secret_access_key_file.as_os_str().is_empty() |
| 246 | { |
| 247 | return Err(config_err( |
| 248 | "storage.s3 credential file paths must not be empty", |
| 249 | )); |
| 250 | } |
| 251 | Ok(()) |
| 252 | } |
| 253 | } |
| 254 | |
| 255 | impl Backup { |
| 256 | fn validate(&self) -> Result<()> { |
| 257 | if self.dir.as_os_str().is_empty() { |
| 258 | return Err(config_err("backup.dir must not be empty")); |
| 259 | } |
| 260 | if self.interval_hours == 0 { |
| 261 | return Err(config_err("backup.interval_hours must be at least 1")); |
| 262 | } |
| 263 | if self.keep == 0 { |
| 264 | return Err(config_err("backup.keep must be at least 1")); |
| 265 | } |
| 266 | if let Some(url) = &self.healthcheck_url { |
| 267 | validate_base_url("backup.healthcheck_url", url)?; |
| 268 | } |
| 269 | Ok(()) |
| 270 | } |
| 271 | } |
| 272 | |
| 273 | fn config_err(message: &str) -> Error { |
| 274 | Error::Config(message.to_string()) |
| 275 | } |
| 276 | |
| 277 | |
| 278 | |
| 279 | |
| 280 | pub fn parse_endpoint(url: &str) -> Option<Url> { |
| 281 | let parsed = Url::parse(url).ok()?; |
| 282 | let plain_ok = parsed.scheme() == "http" |
| 283 | && parsed.username().is_empty() |
| 284 | && parsed.password().is_none() |
| 285 | && is_loopback(&parsed); |
| 286 | (parsed.scheme() == "https" || plain_ok).then_some(parsed) |
| 287 | } |
| 288 | |
| 289 | |
| 290 | fn is_loopback(url: &Url) -> bool { |
| 291 | match url.host() { |
| 292 | Some(Host::Domain(name)) => name == "localhost", |
| 293 | Some(Host::Ipv4(ip)) => ip.is_loopback(), |
| 294 | Some(Host::Ipv6(ip)) => ip.is_loopback(), |
| 295 | None => false, |
| 296 | } |
| 297 | } |
| 298 | |
| 299 | |
| 300 | |
| 301 | fn validate_base_url(field: &str, url: &str) -> Result<()> { |
| 302 | if parse_endpoint(url).is_none() { |
| 303 | return Err(config_err(&format!( |
| 304 | "{field} must be an https:// URL, or an http:// URL for a loopback host" |
| 305 | ))); |
| 306 | } |
| 307 | if url.ends_with('/') || url.chars().any(char::is_whitespace) { |
| 308 | return Err(config_err(&format!( |
| 309 | "{field} must have no trailing slash and no whitespace" |
| 310 | ))); |
| 311 | } |
| 312 | Ok(()) |
| 313 | } |
| 314 | |
| 315 | |
| 316 | fn deserialize_trusted_proxies<'de, D>(deserializer: D) -> std::result::Result<Vec<IpNet>, D::Error> |
| 317 | where |
| 318 | D: Deserializer<'de>, |
| 319 | { |
| 320 | let items = Vec::<String>::deserialize(deserializer)?; |
| 321 | items |
| 322 | .iter() |
| 323 | .map(|item| parse_proxy(item).map_err(serde::de::Error::custom)) |
| 324 | .collect() |
| 325 | } |
| 326 | |
| 327 | |
| 328 | pub fn parse_proxy(text: &str) -> std::result::Result<IpNet, String> { |
| 329 | let text = text.trim(); |
| 330 | if text.contains('/') { |
| 331 | return IpNet::from_str(text).map_err(|e| format!("trusted proxy {text:?}: {e}")); |
| 332 | } |
| 333 | let ip = IpAddr::from_str(text).map_err(|e| format!("trusted proxy {text:?}: {e}"))?; |
| 334 | let host_len = if ip.is_ipv4() { 32 } else { 128 }; |
| 335 | IpNet::new(ip, host_len).map_err(|e| format!("trusted proxy {text:?}: {e}")) |
| 336 | } |
| 337 | |
| 338 | #[cfg(test)] |
| 339 | mod tests { |
| 340 | use super::*; |
| 341 | |
| 342 | #[test] |
| 343 | fn plain_http_is_allowed_only_for_loopback_hosts() { |
| 344 | for url in [ |
| 345 | "http://127.0.0.1:7655", |
| 346 | "http://127.4.5.6", |
| 347 | "http://localhost:7650", |
| 348 | "http://[::1]:7650", |
| 349 | "https://im.example.com", |
| 350 | ] { |
| 351 | assert!(parse_endpoint(url).is_some(), "{url}"); |
| 352 | } |
| 353 | for url in [ |
| 354 | "http://localhost.evil.example", |
| 355 | "http://localhost@evil.example", |
| 356 | "http://192.168.1.5", |
| 357 | "http://evil.example", |
| 358 | "ftp://127.0.0.1", |
| 359 | ] { |
| 360 | assert!(parse_endpoint(url).is_none(), "{url}"); |
| 361 | } |
| 362 | } |
| 363 | |
| 364 | #[test] |
| 365 | fn example_is_valid_and_bare_proxy_addresses_are_accepted() { |
| 366 | let config: Config = toml::from_str(EXAMPLE).unwrap(); |
| 367 | config.validate().unwrap(); |
| 368 | |
| 369 | let text = "trusted_proxies = [\"10.0.0.1\", \"fd00::/8\"]"; |
| 370 | let config: Config = toml::from_str(text).unwrap(); |
| 371 | assert_eq!(config.trusted_proxies.len(), 2); |
| 372 | assert_eq!(config.trusted_proxies[0].prefix_len(), 32); |
| 373 | |
| 374 | assert!(toml::from_str::<Config>("databse = \"typo.db\"").is_err()); |
| 375 | } |
| 376 | } |