Skip to main content

glacier/
config.rs

1//! Configuration and environments.
2//!
3//! `Config::load()` merges, in increasing priority:
4//!
5//! 1. `config/default.toml`
6//! 2. `config/<env>.toml` (`development`, `test` or `production`)
7//! 3. environment variables: `GLACIER__SERVER__PORT=8080` sets `server.port`.
8//!    `PORT`, which hosting platforms set, also sets it (the `GLACIER__`
9//!    variable wins if both are set).
10//!
11//! Keys Glacier itself reads:
12//!
13//! | key | default | |
14//! | --- | --- | --- |
15//! | `server.host` | `127.0.0.1` | |
16//! | `server.port` | `4000` | or `PORT` |
17//! | `server.max_body_size` | 2 MiB | bytes |
18//! | `secret_key_base` | random per boot | at least 32 bytes; signs and encrypts cookies. Required in production. |
19//! | `name` | `Glacier app` | the app's name, as people see it: an authenticator app's label for its two-factor codes |
20//! | `url` | `http://` + `server.host:port` | the app's public address, for absolute links (`url_for`, links in mail). Required in production for them. |
21
22use std::fmt;
23use std::path::Path;
24
25use serde::de::DeserializeOwned;
26use toml::{Table, Value};
27
28use crate::error::{Error, Result};
29
30const ENV_PREFIX: &str = "GLACIER__";
31
32/// The environment the app runs in, from `GLACIER_ENV`.
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
34pub enum Env {
35    Development,
36    Test,
37    Production,
38}
39
40impl Env {
41    /// Reads `GLACIER_ENV`, defaulting to development when unset.
42    ///
43    /// # Panics
44    ///
45    /// On an unrecognized value. A typo like `producton` must not silently
46    /// boot in development mode with debug pages switched on.
47    pub fn current() -> Env {
48        match std::env::var("GLACIER_ENV") {
49            Err(_) => Env::Development,
50            Ok(value) => value.parse().unwrap_or_else(|_| {
51                panic!("GLACIER_ENV=`{value}` is not one of development, test, production")
52            }),
53        }
54    }
55
56    pub fn as_str(self) -> &'static str {
57        match self {
58            Env::Development => "development",
59            Env::Test => "test",
60            Env::Production => "production",
61        }
62    }
63
64    pub fn is_development(self) -> bool {
65        self == Env::Development
66    }
67
68    pub fn is_production(self) -> bool {
69        self == Env::Production
70    }
71}
72
73impl std::str::FromStr for Env {
74    type Err = ();
75
76    fn from_str(s: &str) -> std::result::Result<Self, ()> {
77        match s {
78            "development" | "dev" => Ok(Env::Development),
79            "test" => Ok(Env::Test),
80            "production" | "prod" => Ok(Env::Production),
81            _ => Err(()),
82        }
83    }
84}
85
86impl fmt::Display for Env {
87    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88        f.write_str(self.as_str())
89    }
90}
91
92/// Merged configuration for one environment.
93#[derive(Debug, Clone)]
94pub struct Config {
95    env: Env,
96    table: Table,
97}
98
99static CURRENT: std::sync::RwLock<Option<Config>> = std::sync::RwLock::new(None);
100
101/// The running app's name (`name` in its config), "Glacier app" if unset:
102/// `glacier::config::app_name()`.
103pub fn app_name() -> String {
104    Config::current().map_or_else(|_| "Glacier app".to_owned(), |config| config.app_name())
105}
106
107impl Config {
108    /// The app's config, as `App::config` was given it: for code that
109    /// builds what the app builds from it outside a request, as a webhook
110    /// handler building a client does (`Stripe.new()?`).
111    ///
112    /// # Errors
113    ///
114    /// Before the app is configured.
115    pub fn current() -> Result<Config> {
116        CURRENT
117            .read()
118            .unwrap_or_else(|e| e.into_inner())
119            .clone()
120            .ok_or_else(|| {
121                crate::Error::internal("the app's config isn't loaded yet (App::config)")
122            })
123    }
124
125    /// Makes this the config [`Config::current`] gives. `App::config` calls it.
126    pub fn make_current(&self) {
127        *CURRENT.write().unwrap_or_else(|e| e.into_inner()) = Some(self.clone());
128    }
129
130    /// Loads `./config` for the current environment.
131    pub fn load() -> Result<Self> {
132        Self::load_from("config", Env::current())
133    }
134
135    pub fn load_from(dir: impl AsRef<Path>, env: Env) -> Result<Self> {
136        let mut table = Table::new();
137        for name in ["default", env.as_str()] {
138            let path = dir.as_ref().join(format!("{name}.toml"));
139            let source = match std::fs::read_to_string(&path) {
140                Ok(source) => source,
141                Err(err) if err.kind() == std::io::ErrorKind::NotFound => continue,
142                Err(err) => return Err(err.into()),
143            };
144            merge_toml(&mut table, &source, &path.display().to_string())?;
145        }
146        apply_env_overrides(&mut table, std::env::vars());
147        Ok(Self { env, table })
148    }
149
150    /// Like [`Config::load`], from files compiled into the binary:
151    /// `(name, contents)` pairs such as `("production", "…")`, as
152    /// `glacier::config!()` passes them in release builds. Environment
153    /// variables still override them.
154    pub fn load_embedded(files: &[(&str, &str)]) -> Result<Self> {
155        Self::load_embedded_as(files, Env::current())
156    }
157
158    /// [`Config::load_embedded`] for a given environment.
159    pub fn load_embedded_as(files: &[(&str, &str)], env: Env) -> Result<Self> {
160        let mut table = Table::new();
161        for name in ["default", env.as_str()] {
162            if let Some((_, source)) = files.iter().find(|(file, _)| *file == name) {
163                merge_toml(&mut table, source, &format!("config/{name}.toml"))?;
164            }
165        }
166        apply_env_overrides(&mut table, std::env::vars());
167        Ok(Self { env, table })
168    }
169
170    /// Builds a config from a TOML string, without touching the filesystem
171    /// or environment. Handy in tests.
172    pub fn from_toml(env: Env, source: &str) -> Result<Self> {
173        let table = toml::from_str(source).map_err(|e| Error::internal(e.to_string()))?;
174        Ok(Self { env, table })
175    }
176
177    pub fn env(&self) -> Env {
178        self.env
179    }
180
181    /// Reads a dotted key such as `"database.pool_size"`.
182    pub fn get<T: DeserializeOwned>(&self, key: &str) -> Result<T> {
183        self.get_opt(key)?
184            .ok_or_else(|| Error::internal(format!("missing config key `{key}`")))
185    }
186
187    /// Like `get`, but a missing key is `Ok(None)`.
188    pub fn get_opt<T: DeserializeOwned>(&self, key: &str) -> Result<Option<T>> {
189        let Some(value) = lookup(&self.table, key) else {
190            return Ok(None);
191        };
192        value.clone().try_into().map(Some).or_else(|e| {
193            // An environment variable that looks like a number or a
194            // boolean (`GLACIER__MAIL__SMTP__PASSWORD=12345`) is read as
195            // one; where text is wanted, it's still text.
196            match value {
197                Value::Integer(_) | Value::Float(_) | Value::Boolean(_) => {
198                    Value::String(value.to_string()).try_into().map(Some)
199                }
200                _ => Err(e.clone()),
201            }
202            .map_err(|_| Error::internal(format!("config key `{key}`: {e}")))
203        })
204    }
205
206    /// A secret, such as an API key: the config's `key` (which an
207    /// environment variable overrides as usual: `stripe.api_key` from
208    /// `GLACIER__STRIPE__API_KEY`), or else the service's own variable,
209    /// `env_var` (`STRIPE_API_KEY`), as other tools set it. `None` when
210    /// neither is set; an empty value counts as unset.
211    ///
212    /// Tests read only the config (and `GLACIER__…` variables): a real key
213    /// left in a developer's shell never reaches them.
214    ///
215    /// ```ignore
216    /// let key = config.secret("stripe.api_key", "STRIPE_API_KEY")?;
217    /// ```
218    pub fn secret(&self, key: &str, env_var: &str) -> Result<Option<String>> {
219        let configured = self
220            .get_opt::<String>(key)?
221            .filter(|value| !value.is_empty());
222        if configured.is_some() || self.env == Env::Test {
223            return Ok(configured);
224        }
225        Ok(std::env::var(env_var)
226            .ok()
227            .filter(|value| !value.is_empty()))
228    }
229
230    /// Deserializes the whole config into an app-defined struct.
231    pub fn deserialize<T: DeserializeOwned>(&self) -> Result<T> {
232        Value::Table(self.table.clone())
233            .try_into()
234            .map_err(|e| Error::internal(format!("config: {e}")))
235    }
236
237    /// The app's public address, `https://example.com`, for absolute links
238    /// such as a reset link in a mail: `url` from the config, or outside
239    /// production the address the server listens on. Never the request's
240    /// `Host` header, which whoever sends the request chooses.
241    ///
242    /// # Errors
243    ///
244    /// In production without a `url`.
245    pub fn url(&self) -> Result<String> {
246        if let Some(url) = self.get_opt::<String>("url")? {
247            return Ok(url.trim_end_matches('/').to_owned());
248        }
249        if self.env() == Env::Production {
250            return Err(Error::internal(
251                "set `url` in the config (GLACIER__URL), the app's public address, for absolute links",
252            ));
253        }
254        let addr = self
255            .addr()?
256            .replace("0.0.0.0", "localhost")
257            .replace("127.0.0.1", "localhost");
258        Ok(format!("http://{addr}"))
259    }
260
261    /// The app's name as people see it (`name` in the config): "My Shop".
262    pub fn app_name(&self) -> String {
263        self.get_opt::<String>("name")
264            .ok()
265            .flatten()
266            .unwrap_or_else(|| "Glacier app".to_owned())
267    }
268
269    /// `server.host:server.port`, defaulting to `127.0.0.1:4000`.
270    pub fn addr(&self) -> Result<String> {
271        let host: String = self
272            .get_opt("server.host")?
273            .unwrap_or_else(|| "127.0.0.1".into());
274        let port: u16 = self.get_opt("server.port")?.unwrap_or(4000);
275        Ok(format!("{host}:{port}"))
276    }
277}
278
279fn merge_toml(table: &mut Table, source: &str, name: &str) -> Result<()> {
280    let parsed: Table =
281        toml::from_str(source).map_err(|e| Error::internal(format!("{name}: {e}")))?;
282    merge(table, parsed);
283    Ok(())
284}
285
286fn lookup<'t>(table: &'t Table, key: &str) -> Option<&'t Value> {
287    let mut parts = key.split('.');
288    let mut value = table.get(parts.next()?)?;
289    for part in parts {
290        value = value.as_table()?.get(part)?;
291    }
292    Some(value)
293}
294
295/// Deep-merges `overlay` into `base`; tables merge, everything else replaces.
296fn merge(base: &mut Table, overlay: Table) {
297    for (key, value) in overlay {
298        match (base.get_mut(&key), value) {
299            (Some(Value::Table(existing)), Value::Table(incoming)) => merge(existing, incoming),
300            (_, value) => {
301                base.insert(key, value);
302            }
303        }
304    }
305}
306
307fn apply_env_overrides(table: &mut Table, vars: impl Iterator<Item = (String, String)>) {
308    let vars: Vec<(String, String)> = vars.collect();
309    // `PORT`, as hosting platforms set it, is `server.port`; applied first,
310    // so `GLACIER__SERVER__PORT` still wins.
311    let port = vars
312        .iter()
313        .find(|(name, _)| name == "PORT")
314        .map(|(_, raw)| (format!("{ENV_PREFIX}SERVER__PORT"), raw.clone()));
315    for (name, raw) in port.into_iter().chain(vars) {
316        let Some(path) = name.strip_prefix(ENV_PREFIX) else {
317            continue;
318        };
319        let keys: Vec<String> = path.split("__").map(str::to_lowercase).collect();
320        if keys.iter().any(String::is_empty) {
321            continue;
322        }
323
324        let mut current = &mut *table;
325        for key in &keys[..keys.len() - 1] {
326            let entry = current
327                .entry(key.clone())
328                .or_insert_with(|| Value::Table(Table::new()));
329            if !entry.is_table() {
330                *entry = Value::Table(Table::new());
331            }
332            current = entry.as_table_mut().expect("just ensured a table");
333        }
334        current.insert(keys[keys.len() - 1].clone(), parse_env_value(&raw));
335    }
336}
337
338/// Env values are typed loosely: integers, floats and booleans are
339/// recognized, everything else is a string.
340fn parse_env_value(raw: &str) -> Value {
341    if let Ok(i) = raw.parse::<i64>() {
342        Value::Integer(i)
343    } else if let Ok(f) = raw.parse::<f64>() {
344        Value::Float(f)
345    } else if let Ok(b) = raw.parse::<bool>() {
346        Value::Boolean(b)
347    } else {
348        Value::String(raw.to_owned())
349    }
350}
351
352#[cfg(test)]
353mod tests {
354    #[test]
355    fn the_apps_url_is_configured_never_guessed() {
356        let config = Config::from_toml(Env::Development, "[server]\nport = 4100\n").unwrap();
357        assert_eq!(config.url().unwrap(), "http://localhost:4100");
358        let config =
359            Config::from_toml(Env::Production, "url = \"https://shop.example/\"\n").unwrap();
360        assert_eq!(config.url().unwrap(), "https://shop.example");
361        let config = Config::from_toml(Env::Production, "").unwrap();
362        assert!(config.url().is_err(), "production says where it lives");
363    }
364
365    use super::*;
366
367    #[test]
368    fn merges_files_and_env() {
369        let dir = std::env::temp_dir().join(format!("glacier-config-{}", std::process::id()));
370        std::fs::create_dir_all(&dir).unwrap();
371        std::fs::write(
372            dir.join("default.toml"),
373            "[server]\nport = 4000\nhost = \"0.0.0.0\"\n[db]\npool = 5\n",
374        )
375        .unwrap();
376        std::fs::write(dir.join("production.toml"), "[server]\nport = 80\n").unwrap();
377
378        let config = Config::load_from(&dir, Env::Production).unwrap();
379        assert_eq!(config.addr().unwrap(), "0.0.0.0:80");
380        assert_eq!(config.get::<u32>("db.pool").unwrap(), 5);
381        assert!(config.get_opt::<String>("nope.nothing").unwrap().is_none());
382        assert!(config.get::<bool>("db.pool").is_err());
383
384        let dev = Config::load_from(&dir, Env::Development).unwrap();
385        assert_eq!(dev.addr().unwrap(), "0.0.0.0:4000");
386        std::fs::remove_dir_all(dir).unwrap();
387    }
388
389    #[test]
390    fn env_vars_override_nested_keys() {
391        let mut table: Table = toml::from_str("[server]\nport = 4000\nhost = \"x\"").unwrap();
392        apply_env_overrides(
393            &mut table,
394            [
395                ("GLACIER__SERVER__PORT".into(), "8080".into()),
396                ("GLACIER__SECRET_KEY_BASE".into(), "abc".into()),
397                ("GLACIER__FEATURES__SIGNUP".into(), "true".into()),
398                ("OTHER".into(), "ignored".into()),
399            ]
400            .into_iter(),
401        );
402        let config = Config {
403            env: Env::Test,
404            table,
405        };
406        assert_eq!(config.get::<u16>("server.port").unwrap(), 8080);
407        assert_eq!(config.get::<String>("server.host").unwrap(), "x");
408        assert_eq!(config.get::<String>("secret_key_base").unwrap(), "abc");
409        assert!(config.get::<bool>("features.signup").unwrap());
410        // A secret from the config, or the service's own variable.
411        assert_eq!(
412            config
413                .secret("secret_key_base", "GLACIER_TEST_UNSET")
414                .unwrap()
415                .as_deref(),
416            Some("abc")
417        );
418        assert_eq!(
419            config.secret("missing.key", "GLACIER_TEST_UNSET").unwrap(),
420            None
421        );
422        // Text that looks like a number is still text where text is wanted.
423        assert_eq!(config.get::<String>("server.port").unwrap(), "8080");
424        assert_eq!(config.get::<String>("features.signup").unwrap(), "true");
425    }
426
427    #[test]
428    fn loads_embedded_files_for_the_environment() {
429        let files = [
430            ("default", "[server]\nport = 4000\nhost = \"127.0.0.1\""),
431            ("production", "[server]\nhost = \"0.0.0.0\""),
432            ("development", "[server]\nport = 3000"),
433        ];
434        let prod = Config::load_embedded_as(&files, Env::Production).unwrap();
435        assert_eq!(prod.get::<String>("server.host").unwrap(), "0.0.0.0");
436        assert_eq!(prod.get::<u16>("server.port").unwrap(), 4000);
437        let test = Config::load_embedded_as(&files, Env::Test).unwrap();
438        assert_eq!(test.get::<String>("server.host").unwrap(), "127.0.0.1");
439        let err = Config::load_embedded_as(&[("default", "port = ")], Env::Test).unwrap_err();
440        assert!(err.to_string().contains("config/default.toml"), "{err}");
441    }
442
443    #[test]
444    fn port_from_the_platform() {
445        let port = |vars: &[(&str, &str)]| {
446            let mut table: Table = toml::from_str("[server]\nport = 4000").unwrap();
447            apply_env_overrides(
448                &mut table,
449                vars.iter().map(|(k, v)| (k.to_string(), v.to_string())),
450            );
451            Config {
452                env: Env::Production,
453                table,
454            }
455            .get::<u16>("server.port")
456            .unwrap()
457        };
458        assert_eq!(port(&[]), 4000);
459        assert_eq!(
460            port(&[("PORT", "8080")]),
461            8080,
462            "PORT beats the config files"
463        );
464        assert_eq!(
465            port(&[("GLACIER__SERVER__PORT", "9000"), ("PORT", "8080")]),
466            9000,
467            "the GLACIER__ variable beats PORT, in any order"
468        );
469    }
470
471    #[test]
472    fn deserializes_into_app_structs() {
473        #[derive(serde::Deserialize)]
474        struct AppConfig {
475            mailer: Mailer,
476        }
477        #[derive(serde::Deserialize)]
478        struct Mailer {
479            from: String,
480        }
481
482        let config = Config::from_toml(Env::Test, "[mailer]\nfrom = \"hi@example.com\"").unwrap();
483        let app: AppConfig = config.deserialize().unwrap();
484        assert_eq!(app.mailer.from, "hi@example.com");
485    }
486
487    #[test]
488    fn parses_env_names() {
489        assert_eq!("prod".parse::<Env>(), Ok(Env::Production));
490        assert_eq!("development".parse::<Env>(), Ok(Env::Development));
491        assert!("producton".parse::<Env>().is_err());
492    }
493}