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