forge
Explore
Log in

Don't you dare go Hollow

in

Clone
★ 0

0 watching0 forksRustAGPL-3.0528.7 KiB9215377Tahinli27 days ago37 commits

config.rs376 lines, 13.3 KiBHistoryRawDownload
1//! File configuration (`config/in.toml`). Secrets never live here: the OIDC client secret and the
2//! S3 keys are read from files or entered in the admin UI. Every struct rejects unknown keys, so a
3//! typo fails at boot instead of being silently ignored.
4
5use std::fmt;
6use std::net::{IpAddr, SocketAddr};
7use std::path::{Path, PathBuf};
8use std::str::FromStr;
9
10use ipnet::IpNet;
11use serde::{Deserialize, Deserializer};
12use url::{Host, Url};
13
14use crate::error::{Error, Result};
15use crate::secret::Redacted;
16
17/// The example file. It is committed, and it is written to `config/in.toml` when that file is missing.
18pub const EXAMPLE: &str = include_str!("../../../config/in.example.toml");
19
20/// The whole file configuration.
21#[derive(Debug, Clone, PartialEq, Deserialize)]
22#[serde(deny_unknown_fields, default)]
23pub struct Config {
24 /// Path of the database file. Relative paths are relative to the working directory.
25 pub database: PathBuf,
26 /// Directory for blobs, staging files, the instance key and caches. Created at boot with mode 0700.
27 pub data_dir: PathBuf,
28 /// Address the HTTP server binds to.
29 pub listen: SocketAddr,
30 /// Public URL of the instance, with scheme and no trailing slash. Decides cookie `Secure` and HSTS.
31 pub base_url: String,
32 /// Proxies whose `X-Forwarded-For` is believed. Each entry is a CIDR range or a bare address.
33 #[serde(deserialize_with = "deserialize_trusted_proxies")]
34 pub trusted_proxies: Vec<IpNet>,
35 /// Sign-in through `im`. Without it the instance cannot sign anyone in.
36 pub oidc: Option<Oidc>,
37 /// Where blobs are kept.
38 pub storage: Storage,
39 /// Scheduled backups. Absent means no scheduled backups.
40 pub backup: Option<Backup>,
41 /// Defaults the admin page may override at run time. See `settings.rs` for the precedence rule.
42 pub limits: Limits,
43}
44
45impl 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/// The `[oidc]` table: where `im` lives and which client id `in` uses. The secret is not here.
62#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
63#[serde(deny_unknown_fields)]
64pub struct Oidc {
65 /// Issuer URL of `im`, as published in its discovery document.
66 pub issuer: String,
67 /// The OAuth client id registered for `in` in `im`.
68 pub client_id: String,
69 /// File holding the client secret, readable only by the service user. Read at boot.
70 pub client_secret_file: PathBuf,
71}
72
73/// The `[limits]` table: file-level values of the settings the admin page can override. A value that is
74/// absent here falls back to the built-in default. Each one is checked by `settings::check_file`.
75#[derive(Debug, Clone, PartialEq, Eq, Default, Deserialize)]
76#[serde(deny_unknown_fields, default)]
77pub struct Limits {
78 /// Quota of a person who first appears, in bytes.
79 pub default_quota_bytes: Option<i64>,
80 /// Quota of a service namespace that makes its first call, in bytes.
81 pub default_service_quota_bytes: Option<i64>,
82 /// Days a trashed item waits before it is purged.
83 pub purge_after_days: Option<i64>,
84 /// Largest upload accepted, in bytes.
85 pub max_upload_bytes: Option<i64>,
86 /// Longest a share link may last, in days.
87 pub link_max_days: Option<i64>,
88}
89
90/// The `[storage]` table.
91#[derive(Debug, Clone, PartialEq, Eq, Default, Deserialize)]
92#[serde(deny_unknown_fields, default)]
93pub struct Storage {
94 /// Which blob backend to use.
95 pub backend: Backend,
96 /// S3 settings. Required when `backend` is `s3`, and an error when `backend` is `local`.
97 pub s3: Option<S3>,
98}
99
100/// Blob backends.
101#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
102#[serde(rename_all = "lowercase")]
103pub enum Backend {
104 /// Files in `data_dir/blobs`.
105 #[default]
106 Local,
107 /// An S3-compatible bucket (AWS, R2, Hetzner Object Storage, ...).
108 S3,
109}
110
111/// The `[storage.s3]` table. Credentials are files readable only by the service user.
112#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
113#[serde(deny_unknown_fields)]
114pub struct S3 {
115 /// Endpoint URL for a non-AWS service. Absent means AWS.
116 #[serde(default)]
117 pub endpoint: Option<String>,
118 /// Region name the service expects (`auto` for R2).
119 pub region: String,
120 /// Bucket that holds the blob tree.
121 pub bucket: String,
122 /// File holding the access key id.
123 pub access_key_id_file: PathBuf,
124 /// File holding the secret access key.
125 pub secret_access_key_file: PathBuf,
126}
127
128/// The `[backup]` table.
129#[derive(Clone, PartialEq, Eq, Deserialize)]
130#[serde(deny_unknown_fields)]
131pub struct Backup {
132 /// Directory that receives one snapshot set per run.
133 pub dir: PathBuf,
134 /// Hours between backup runs. Must be at least 1.
135 #[serde(default = "default_interval_hours")]
136 pub interval_hours: u32,
137 /// Snapshot sets kept; older ones are removed after a successful run. Must be at least 1.
138 #[serde(default = "default_keep")]
139 pub keep: u32,
140 /// Dead-man URL pinged after each successful run. Absent means no pings.
141 #[serde(default)]
142 pub healthcheck_url: Option<String>,
143}
144
145impl 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
159fn default_interval_hours() -> u32 {
160 24
161}
162
163fn default_keep() -> u32 {
164 7
165}
166
167impl Config {
168 /// Reads and validates the file at `path`. A missing file is first created from [`EXAMPLE`], so a
169 /// first run starts with working development defaults.
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 /// Checks the rules that span fields. Called by [`Config::load`] and again whenever a setting
189 /// is changed from the admin UI.
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
218impl 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
233impl 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
255impl 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
273fn config_err(message: &str) -> Error {
274 Error::Config(message.to_string())
275}
276
277/// Parses `url` and returns it only when `in` may connect to it: `https` always, and `http` only for a
278/// loopback host with no userinfo, so plain text never leaves the machine. Every URL `in` is given
279/// goes through here, the configuration and the family switcher alike.
280pub 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/// Whether the host of `url` is `localhost`, an IPv4 address in 127.0.0.0/8, or `::1`.
290fn 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/// A URL that [`parse_endpoint`] accepts, with no trailing slash and no whitespace. The rest is left to
300/// the component that uses the URL, which reports its own error.
301fn 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/// Accepts `10.0.0.1`, `fd00::1` (a single address, which becomes a host range) or a CIDR range.
316fn deserialize_trusted_proxies<'de, D>(deserializer: D) -> std::result::Result<Vec<IpNet>, D::Error>
317where
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/// Parses one trusted-proxy entry. A bare address becomes a single-host range.
328pub 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)]
339mod 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}