steid

@jamesgill /

Rust6.9 KBCode·Blame·History·Raw
1use std::{fmt, path::PathBuf};
2
3use 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)]
9pub 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 /// A setup token supplied by the operator instead of one generated at boot.
51 ///
52 /// Only ever consulted while the instance is unclaimed — a claimed instance holds
53 /// no token at all, so this is inert the moment an owner exists. It exists so a
54 /// scripted install can claim an instance without racing `journalctl` for the
55 /// generated token, and it is validated by `SetupToken::from_operator` before it
56 /// is used: a weak value fails startup rather than being accepted.
57 ///
58 /// This does not reopen `plans/decisions/0002`. What that decision refused to put
59 /// in configuration is the owner's *password* — a long-lived credential that goes
60 /// stale the moment it is changed in the app. This is the one-time claim secret,
61 /// which is dead as soon as it has been used once and which the operator was
62 /// already reading out of the log by hand.
63 ///
64 /// [`Secret`] keeps it out of any `Debug` rendering of the config, and `main`
65 /// takes it before the config reaches the app context.
66 #[serde(default)]
67 pub setup_token: Option<Secret>,
68}
69
70/// A configured value that must not reach a log line.
71///
72/// `AppConfig` is `Debug`, lives in the app context, and is one `dbg!` away from
73/// standard error; the redacted `Debug` is what makes that safe.
74#[derive(Clone, Deserialize)]
75pub struct Secret(String);
76
77impl Secret {
78 /// The value itself, at the one place that needs it.
79 #[must_use]
80 pub fn expose(&self) -> &str {
81 &self.0
82 }
83}
84
85impl fmt::Debug for Secret {
86 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87 f.write_str("Secret(redacted)")
88 }
89}
90
91fn default_database_url() -> String {
92 "sqlite:steid.db?mode=rwc".to_owned()
93}
94
95fn default_data_dir() -> PathBuf {
96 PathBuf::from("./data")
97}
98
99impl AppConfig {
100 /// Loads configuration from the environment, applying defaults for anything unset.
101 pub fn from_env() -> Result<Self, envy::Error> {
102 envy::prefixed("STEID_").from_env()
103 }
104}
105
106#[cfg(test)]
107mod tests {
108 use super::*;
109
110 /// Builds a config from an explicit iterator rather than the process environment,
111 /// so tests don't race on shared global state.
112 fn from_pairs(pairs: &[(&str, &str)]) -> Result<AppConfig, envy::Error> {
113 envy::prefixed("STEID_").from_iter(
114 pairs
115 .iter()
116 .map(|(k, v)| ((*k).to_owned(), (*v).to_owned())),
117 )
118 }
119
120 #[test]
121 fn applies_defaults_when_environment_is_empty() {
122 let config = from_pairs(&[]).expect("defaults should satisfy every field");
123
124 assert_eq!(config.database_url, "sqlite:steid.db?mode=rwc");
125 assert_eq!(config.data_dir, PathBuf::from("./data"));
126 }
127
128 #[test]
129 fn reads_prefixed_variables() {
130 let config = from_pairs(&[
131 ("STEID_DATABASE_URL", "sqlite:custom.db?mode=rwc"),
132 ("STEID_DATA_DIR", "/srv/steid/repos"),
133 ])
134 .expect("explicit values should parse");
135
136 assert_eq!(config.database_url, "sqlite:custom.db?mode=rwc");
137 assert_eq!(config.data_dir, PathBuf::from("/srv/steid/repos"));
138 }
139
140 #[test]
141 fn private_webhook_targets_are_refused_unless_asked_for() {
142 let config = from_pairs(&[]).expect("defaults should satisfy every field");
143
144 assert!(!config.allow_private_webhooks);
145 assert!(
146 from_pairs(&[("STEID_ALLOW_PRIVATE_WEBHOOKS", "true")])
147 .expect("an explicit value should parse")
148 .allow_private_webhooks
149 );
150 }
151
152 #[test]
153 fn a_setup_token_is_absent_unless_configured() {
154 let config = from_pairs(&[]).expect("defaults should satisfy every field");
155
156 assert!(config.setup_token.is_none());
157 }
158
159 #[test]
160 fn reads_the_setup_token_from_the_environment() {
161 let config = from_pairs(&[("STEID_SETUP_TOKEN", "b2a9c17e4d5f80316a7c9e2b4d8f0135")])
162 .expect("an explicit token should parse");
163
164 assert_eq!(
165 config.setup_token.as_ref().map(Secret::expose),
166 Some("b2a9c17e4d5f80316a7c9e2b4d8f0135")
167 );
168 }
169
170 #[test]
171 fn a_configured_setup_token_is_redacted_in_debug_output() {
172 let secret = "b2a9c17e4d5f80316a7c9e2b4d8f0135";
173 let config = from_pairs(&[("STEID_SETUP_TOKEN", secret)]).expect("an explicit token");
174
175 let rendered = format!("{config:?}");
176
177 assert!(!rendered.contains(secret), "{rendered}");
178 assert!(rendered.contains("Secret(redacted)"), "{rendered}");
179 }
180
181 #[test]
182 fn ignores_unprefixed_variables() {
183 let config = from_pairs(&[("DATA_DIR", "/should/be/ignored")])
184 .expect("unprefixed keys should not interfere");
185
186 assert_eq!(config.data_dir, PathBuf::from("./data"));
187 }
188}