steid

@jamesgill /

Rust18.6 KBCode·Blame·History·Raw
1use std::{fmt, path::PathBuf};
2
3use serde::Deserialize;
4
5use crate::domain::DomainError;
6
7use super::claim::OwnerSeed;
8
9/// Application configuration, read from `STEID_`-prefixed environment variables.
10///
11/// The bind address is deliberately absent: Topcoat owns it via `HOST` and `PORT`.
12#[derive(Debug, Clone, Deserialize)]
13pub struct AppConfig {
14 /// SQLite connection string. Needs `mode=rwc` to create the file on first boot.
15 #[serde(default = "default_database_url")]
16 pub database_url: String,
17
18 /// Root directory for bare git repositories, laid out as
19 /// `{data_dir}/{handle}/{name}.git`.
20 ///
21 /// Keyed by handle rather than `OrgId` so the directory is legible to anyone
22 /// debugging it; the cost is that renaming a handle becomes a directory move.
23 #[serde(default = "default_data_dir")]
24 pub data_dir: PathBuf,
25
26 /// Drops `Secure` and the `__Host-` prefix from the session cookie so it survives
27 /// plain-HTTP `localhost`.
28 ///
29 /// Development only. With this on, the session cookie travels unencrypted and
30 /// anyone on the path can lift it.
31 #[serde(default)]
32 pub insecure_cookies: bool,
33
34 /// Lets a webhook point at this machine or its own private network.
35 ///
36 /// Development only, and the reason it exists is narrow: **the end-to-end webhook
37 /// check cannot be run without it.** Proving that a real push signs and delivers a
38 /// real payload needs a receiver, the obvious receiver is a script on
39 /// `127.0.0.1`, and the SSRF rule in
40 /// [`WebhookUrl`](crate::domain::WebhookUrl) refuses exactly that. Before this
41 /// existed the check needed a temporary patch to the source, which is worse: a patch
42 /// is invisible and easy to leave in, a flag is neither.
43 ///
44 /// With this on, anyone who can add a hook can make the server dial its own network
45 /// and read the response body back off the deliveries page. **Never deploy it** — see
46 /// `plans/runbook.md`, beside [`insecure_cookies`](Self::insecure_cookies).
47 ///
48 /// It relaxes the address rules only. The scheme, credentials in the authority, the
49 /// port and the packed spellings of an address are refused with it on exactly as
50 /// without.
51 #[serde(default)]
52 pub allow_private_webhooks: bool,
53
54 /// Whether a proxy in front of this instance is trusted to have written
55 /// `X-Forwarded-For` / `X-Real-IP`.
56 ///
57 /// Off by default, and the default is the safe one. The rate limiters key on those
58 /// headers because **Topcoat 0.5 discards the peer address at accept time** and a
59 /// handler sees headers and nothing else. Behind a proxy that is fine — the proxy
60 /// appends the address it accepted the connection from, and the rightmost entry is
61 /// the one a client cannot forge. Exposed **directly**, nothing appends anything, so
62 /// a caller can invent a fresh header per request and buy itself a fresh per-client
63 /// budget every time; only the global cap is left.
64 ///
65 /// With this off the limiters key every caller together, so only the global caps
66 /// apply and a spoofed header buys nothing. That is stricter, not laxer: the cost is
67 /// that one flood can exhaust everyone's shared window, which is a recoverable denial
68 /// of the login form rather than an unlimited guessing budget.
69 ///
70 /// `install.sh` sets it true, because that install puts Caddy in front. Anything
71 /// serving Steid straight to the internet must leave it off.
72 #[serde(default)]
73 pub trusted_proxy: bool,
74
75 /// A bearer token for the operator surface — `/metrics`, the detailed
76 /// `/api/instance`, and anything else a control plane drives rather than a person.
77 ///
78 /// Absent means the surface does not exist: those routes answer 404, not 401, so an
79 /// instance that was never given a token advertises nothing. Compared in constant
80 /// time. Never a session: an operator is not a user of the site.
81 ///
82 /// A [`Secret`] for the same reason [`setup_token`](Self::setup_token) is, and it
83 /// was the one credential on this struct that was not: unlike the setup token this
84 /// one is long-lived and stays in the app context for the life of the process, so
85 /// a `Debug` rendering of the config would put a live bearer token in the log.
86 #[serde(default)]
87 pub operator_token: Option<Secret>,
88
89 /// A setup token supplied by the operator instead of one generated at boot.
90 ///
91 /// Only ever consulted while the instance is unclaimed — a claimed instance holds
92 /// no token at all, so this is inert the moment an owner exists. It exists so a
93 /// scripted install can claim an instance without racing `journalctl` for the
94 /// generated token, and it is validated by `SetupToken::from_operator` before it
95 /// is used: a weak value fails startup rather than being accepted.
96 ///
97 /// This does not reopen `plans/decisions/0002`. What that decision refused to put
98 /// in configuration is the owner's *password* — a long-lived credential that goes
99 /// stale the moment it is changed in the app. This is the one-time claim secret,
100 /// which is dead as soon as it has been used once and which the operator was
101 /// already reading out of the log by hand.
102 ///
103 /// [`Secret`] keeps it out of any `Debug` rendering of the config, and `main`
104 /// takes it before the config reaches the app context.
105 #[serde(default)]
106 pub setup_token: Option<Secret>,
107
108 /// A file the scheduled-backup timer touches after each successful run.
109 ///
110 /// Absent means no schedule is configured, which is what the settings page says —
111 /// and it is absent by default, because `install.sh` only writes it when asked for
112 /// `--backups daily`. Steid never writes this file and never reads its contents:
113 /// **the modification time is the whole of the signal**, so the timer can be a
114 /// two-line shell script and the two halves cannot drift into disagreeing about a
115 /// format.
116 ///
117 /// The file's *contents* are for whoever is reading the directory by hand; nothing
118 /// in Steid parses them.
119 #[serde(default)]
120 pub backup_marker: Option<PathBuf>,
121
122 /// Where to submit outgoing mail, e.g. `smtps://steid:password@smtp.example.com:465`.
123 ///
124 /// Absent, or absent alongside [`mail_from`](Self::mail_from), means **this instance
125 /// cannot send email** — a designed state, not an error. Password reset then happens
126 /// through `steid reset-password <handle>` on the box, and the forgot page says so
127 /// instead of offering a form.
128 ///
129 /// `smtps://` wraps the connection in TLS on port 465; `smtp://host:port` is
130 /// plaintext and is for a local sink during development; `smtp://host?tls=required`
131 /// is STARTTLS on 587. The trust anchors are the operating system's, so an internal
132 /// relay with a private CA works if the CA is installed and a container without
133 /// `ca-certificates` cannot send at all.
134 ///
135 /// A [`Secret`] because the URL carries the submission password — it would otherwise
136 /// reach a log line through any `Debug` rendering of the config.
137 #[serde(default)]
138 pub smtp_url: Option<Secret>,
139
140 /// The address mail is sent from, e.g. `Steid <steid@example.com>` or
141 /// `steid@example.com`.
142 ///
143 /// Separate from [`smtp_url`](Self::smtp_url) because they are separate facts: a
144 /// relay's login is rarely the address a recipient should see, and a submission
145 /// service usually refuses a from-address it has not verified.
146 #[serde(default)]
147 pub mail_from: Option<String>,
148
149 /// The email address of an owner to create at boot, on an unclaimed instance.
150 ///
151 /// Read together with [`owner_handle`](Self::owner_handle) — see
152 /// [`owner_seed`](Self::owner_seed). Absent, Steid behaves exactly as it always
153 /// has: it prints a setup token and waits for a person.
154 #[serde(default)]
155 pub owner_email: Option<String>,
156
157 /// The handle of an owner to create at boot, on an unclaimed instance.
158 ///
159 /// A plain `String` rather than an `OrgName`: configuration is untrusted input like
160 /// any other, and the rules — the reserved list among them — belong to the use case
161 /// that refuses. See [`owner_seed`](Self::owner_seed).
162 #[serde(default)]
163 pub owner_handle: Option<String>,
164
165 /// The address this instance is reached on, e.g. `https://git.example.com`.
166 ///
167 /// **Only the command line reads this.** A request knows its own origin — see
168 /// `web::context::public_origin` — so every link built while serving is derived
169 /// rather than configured, and an instance stays deployable anywhere without being
170 /// told its own address. `steid reset-password` has no request to derive it from,
171 /// so with this unset it prints the link's path and leaves the operator to put
172 /// their own address in front of it.
173 #[serde(default)]
174 pub public_url: Option<String>,
175}
176
177/// A configured value that must not reach a log line.
178///
179/// `AppConfig` is `Debug`, lives in the app context, and is one `dbg!` away from
180/// standard error; the redacted `Debug` is what makes that safe.
181#[derive(Clone, Deserialize)]
182pub struct Secret(String);
183
184impl Secret {
185 /// The value itself, at the one place that needs it.
186 #[must_use]
187 pub fn expose(&self) -> &str {
188 &self.0
189 }
190}
191
192impl fmt::Debug for Secret {
193 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
194 f.write_str("Secret(redacted)")
195 }
196}
197
198fn default_database_url() -> String {
199 "sqlite:steid.db?mode=rwc".to_owned()
200}
201
202fn default_data_dir() -> PathBuf {
203 PathBuf::from("./data")
204}
205
206impl AppConfig {
207 /// Loads configuration from the environment, applying defaults for anything unset.
208 pub fn from_env() -> Result<Self, envy::Error> {
209 envy::prefixed("STEID_").from_env()
210 }
211
212 /// The owner to create at boot, if the operator asked for one.
213 ///
214 /// **Both variables or neither.** One without the other is a refusal rather than a
215 /// half-configured instance: an operator who wrote only `STEID_OWNER_HANDLE` meant
216 /// to have a claimed instance, and silently serving an unclaimed one — with a setup
217 /// page on the public internet — is the failure they were trying to avoid. The error
218 /// names the missing variable, and `main` exits 4 on it, like the mail check.
219 ///
220 /// It lives here, next to the two fields, rather than in `main`: this is a decision
221 /// a test can make assertions about, and `main` is the one place in the tree that
222 /// nothing can. The values are **not** validated here — `seed_owner` does that,
223 /// because the rules belong to the domain and the reserved list is one of them.
224 ///
225 /// # Errors
226 ///
227 /// [`DomainError::Validation`] when exactly one of the two is set.
228 pub fn owner_seed(&self) -> Result<Option<OwnerSeed>, DomainError> {
229 match (self.owner_email.as_deref(), self.owner_handle.as_deref()) {
230 (Some(email), Some(handle)) => Ok(Some(OwnerSeed {
231 handle: handle.to_owned(),
232 email: email.to_owned(),
233 })),
234 (Some(_), None) => Err(missing("STEID_OWNER_HANDLE", "STEID_OWNER_EMAIL")),
235 (None, Some(_)) => Err(missing("STEID_OWNER_EMAIL", "STEID_OWNER_HANDLE")),
236 (None, None) => Ok(None),
237 }
238 }
239}
240
241/// The one sentence an operator sees when they set half of the owner.
242fn missing(absent: &str, present: &str) -> DomainError {
243 DomainError::validation(
244 "owner",
245 format!("{absent} is not set, and {present} is. Set both or neither."),
246 )
247}
248
249#[cfg(test)]
250mod tests {
251 use super::*;
252
253 /// Builds a config from an explicit iterator rather than the process environment,
254 /// so tests don't race on shared global state.
255 fn from_pairs(pairs: &[(&str, &str)]) -> Result<AppConfig, envy::Error> {
256 envy::prefixed("STEID_").from_iter(
257 pairs
258 .iter()
259 .map(|(k, v)| ((*k).to_owned(), (*v).to_owned())),
260 )
261 }
262
263 #[test]
264 fn applies_defaults_when_environment_is_empty() {
265 let config = from_pairs(&[]).expect("defaults should satisfy every field");
266
267 assert_eq!(config.database_url, "sqlite:steid.db?mode=rwc");
268 assert_eq!(config.data_dir, PathBuf::from("./data"));
269 }
270
271 #[test]
272 fn reads_prefixed_variables() {
273 let config = from_pairs(&[
274 ("STEID_DATABASE_URL", "sqlite:custom.db?mode=rwc"),
275 ("STEID_DATA_DIR", "/srv/steid/repos"),
276 ])
277 .expect("explicit values should parse");
278
279 assert_eq!(config.database_url, "sqlite:custom.db?mode=rwc");
280 assert_eq!(config.data_dir, PathBuf::from("/srv/steid/repos"));
281 }
282
283 #[test]
284 fn private_webhook_targets_are_refused_unless_asked_for() {
285 let config = from_pairs(&[]).expect("defaults should satisfy every field");
286
287 assert!(!config.allow_private_webhooks);
288 assert!(
289 from_pairs(&[("STEID_ALLOW_PRIVATE_WEBHOOKS", "true")])
290 .expect("an explicit value should parse")
291 .allow_private_webhooks
292 );
293 }
294
295 #[test]
296 fn forwarded_headers_are_distrusted_unless_asked_for() {
297 let config = from_pairs(&[]).expect("defaults should satisfy every field");
298
299 assert!(
300 !config.trusted_proxy,
301 "the default has to be the safe one: an instance nobody configured is the \
302 one most likely to be exposed directly"
303 );
304 assert!(
305 from_pairs(&[("STEID_TRUSTED_PROXY", "true")])
306 .expect("an explicit value should parse")
307 .trusted_proxy
308 );
309 }
310
311 #[test]
312 fn a_setup_token_is_absent_unless_configured() {
313 let config = from_pairs(&[]).expect("defaults should satisfy every field");
314
315 assert!(config.setup_token.is_none());
316 }
317
318 #[test]
319 fn reads_the_setup_token_from_the_environment() {
320 let config = from_pairs(&[("STEID_SETUP_TOKEN", "b2a9c17e4d5f80316a7c9e2b4d8f0135")])
321 .expect("an explicit token should parse");
322
323 assert_eq!(
324 config.setup_token.as_ref().map(Secret::expose),
325 Some("b2a9c17e4d5f80316a7c9e2b4d8f0135")
326 );
327 }
328
329 #[test]
330 fn a_configured_setup_token_is_redacted_in_debug_output() {
331 let secret = "b2a9c17e4d5f80316a7c9e2b4d8f0135";
332 let config = from_pairs(&[("STEID_SETUP_TOKEN", secret)]).expect("an explicit token");
333
334 let rendered = format!("{config:?}");
335
336 assert!(!rendered.contains(secret), "{rendered}");
337 assert!(rendered.contains("Secret(redacted)"), "{rendered}");
338 }
339
340 /// The operator token is the one long-lived credential on this struct: unlike the
341 /// setup token it stays in the app context for the life of the process, so a
342 /// `Debug` rendering of the config is exactly where it would otherwise surface.
343 #[test]
344 fn a_configured_operator_token_is_redacted_in_debug_output() {
345 let secret = "3f1c8a5d90b47e26c1a8f0d3b95e7c42";
346 let config = from_pairs(&[("STEID_OPERATOR_TOKEN", secret)]).expect("an explicit token");
347
348 assert_eq!(
349 config.operator_token.as_ref().map(Secret::expose),
350 Some(secret)
351 );
352
353 let rendered = format!("{config:?}");
354
355 assert!(!rendered.contains(secret), "{rendered}");
356 }
357
358 #[test]
359 fn no_backup_schedule_is_configured_unless_asked_for() {
360 assert!(
361 from_pairs(&[])
362 .expect("defaults should satisfy every field")
363 .backup_marker
364 .is_none()
365 );
366 assert_eq!(
367 from_pairs(&[("STEID_BACKUP_MARKER", "/var/lib/steid/backups/.last")])
368 .expect("an explicit path should parse")
369 .backup_marker,
370 Some(PathBuf::from("/var/lib/steid/backups/.last"))
371 );
372 }
373
374 #[test]
375 fn an_instance_cannot_send_mail_unless_both_halves_are_configured() {
376 let config = from_pairs(&[]).expect("defaults should satisfy every field");
377
378 assert!(config.smtp_url.is_none());
379 assert!(config.mail_from.is_none());
380 assert!(config.public_url.is_none());
381 }
382
383 #[test]
384 fn a_configured_smtp_url_is_redacted_in_debug_output() {
385 // It carries the submission password.
386 let url = "smtps://steid:hunter2@smtp.example.com:465";
387 let config = from_pairs(&[
388 ("STEID_SMTP_URL", url),
389 ("STEID_MAIL_FROM", "Steid <steid@example.com>"),
390 ])
391 .expect("explicit values should parse");
392
393 let rendered = format!("{config:?}");
394
395 assert_eq!(config.smtp_url.as_ref().map(Secret::expose), Some(url));
396 assert_eq!(
397 config.mail_from.as_deref(),
398 Some("Steid <steid@example.com>")
399 );
400 assert!(!rendered.contains("hunter2"), "{rendered}");
401 }
402
403 #[test]
404 fn no_owner_is_seeded_unless_both_halves_are_configured() {
405 let config = from_pairs(&[]).expect("defaults should satisfy every field");
406
407 assert_eq!(config.owner_seed().expect("neither is not an error"), None);
408 }
409
410 #[test]
411 fn both_halves_together_are_the_owner_to_create_at_boot() {
412 let config = from_pairs(&[
413 ("STEID_OWNER_EMAIL", "ada@example.com"),
414 ("STEID_OWNER_HANDLE", "ada"),
415 ])
416 .expect("explicit values should parse");
417
418 assert_eq!(
419 config.owner_seed().expect("both is the configured case"),
420 Some(OwnerSeed {
421 handle: "ada".to_owned(),
422 email: "ada@example.com".to_owned(),
423 })
424 );
425 }
426
427 #[test]
428 fn half_an_owner_refuses_and_names_the_missing_variable() {
429 // The refusal matters more than the pair: an operator who set one of them wanted
430 // a claimed instance, and the alternative is a setup page on the public internet.
431 let without_handle = from_pairs(&[("STEID_OWNER_EMAIL", "ada@example.com")])
432 .expect("one value should parse")
433 .owner_seed()
434 .expect_err("half an owner is refused");
435 assert!(
436 without_handle.to_string().contains("STEID_OWNER_HANDLE"),
437 "{without_handle}"
438 );
439
440 let without_email = from_pairs(&[("STEID_OWNER_HANDLE", "ada")])
441 .expect("one value should parse")
442 .owner_seed()
443 .expect_err("half an owner is refused");
444 assert!(
445 without_email.to_string().contains("STEID_OWNER_EMAIL"),
446 "{without_email}"
447 );
448 }
449
450 #[test]
451 fn ignores_unprefixed_variables() {
452 let config = from_pairs(&[("DATA_DIR", "/should/be/ignored")])
453 .expect("unprefixed keys should not interfere");
454
455 assert_eq!(config.data_dir, PathBuf::from("./data"));
456 }
457}