Skip to main content

laterite_core/
config.rs

1//! Layered configuration loading.
2
3use std::path::Path;
4
5use config::{Config, Environment, File};
6use serde::de::DeserializeOwned;
7use serde::Deserialize;
8
9use crate::error::{CoreError, CoreResult};
10
11/// Database connection settings.
12#[derive(Debug, Clone, Deserialize)]
13pub struct DatabaseConfig {
14    pub url: String,
15    #[serde(default = "default_max_connections")]
16    pub max_connections: u32,
17    #[serde(default = "default_acquire_timeout_secs")]
18    pub acquire_timeout_secs: u64,
19}
20
21/// HTTP listener settings.
22#[derive(Debug, Clone, Deserialize)]
23pub struct ServerConfig {
24    #[serde(default = "default_listen")]
25    pub listen: String,
26}
27
28/// Application-level metadata. The `name` is the human-readable application
29/// name, the baseline for the admin brand: a `BrandSetting` in the admin can
30/// override it, but this is the default when none is set.
31///
32/// Non-exhaustive: build one with [`Default`] and set fields, so a field added
33/// in a later release is additive.
34#[derive(Debug, Clone, Deserialize)]
35#[serde(default)]
36#[non_exhaustive]
37pub struct AppMeta {
38    /// The display name of the application (e.g. `"Acme Blog"`). Shown as the
39    /// admin brand unless overridden by a brand setting.
40    pub name: String,
41    /// The application's public base URL (scheme and host, with any port), such
42    /// as `https://acme.example`. It is the canonical origin absolute links build
43    /// on, distinct from the server bind address (they differ behind a proxy or a
44    /// local `.test` domain). When unset, [`base_url`] derives it from the bind
45    /// address.
46    pub url: Option<String>,
47    /// The application's default locale (BCP 47, e.g. `"en"`): the deployment
48    /// default for UI-string translation, the last stop in a request's locale
49    /// chain before the English source when neither the operator's preference nor
50    /// the request's `Accept-Language` resolves.
51    pub locale: String,
52    /// Debug mode: error pages include the internal cause. Off by default;
53    /// enable only in development. Read via [`debug`] where request context is
54    /// not available (error rendering).
55    pub debug: bool,
56    /// The prefix of the environment variables that override this configuration
57    /// (`<PREFIX>__SECTION__KEY`). Declared here so the application and the `lat`
58    /// command agree on it; unset means the framework default. Read from the files
59    /// alone by [`declared_env_prefix`], since it selects the environment layer.
60    pub env_prefix: Option<String>,
61    /// The application key, `id:<base64 of 32 bytes>` (`lat key generate`
62    /// writes one; `LAT__APP__KEY` overrides). Everything the framework
63    /// encrypts or signs uses it. Unset, a key derived from `backend.secret` or
64    /// the key stored at the first boot is used, so a deployment without one
65    /// keeps working; a production deployment sets it.
66    pub key: Option<String>,
67    /// Keys retired by a rotation, each `id:<base64>`, still read; see
68    /// [`crate::crypt`].
69    pub previous_keys: Vec<String>,
70}
71
72impl Default for AppMeta {
73    fn default() -> Self {
74        Self {
75            name: "Laterite".to_string(),
76            url: None,
77            locale: "en".to_string(),
78            debug: false,
79            env_prefix: None,
80            key: None,
81            previous_keys: Vec::new(),
82        }
83    }
84}
85
86/// Records whether the deployment is in debug mode, once, at boot from the loaded
87/// config. Later calls are ignored (the first wins), so error rendering has a
88/// stable answer without threading config through every handler.
89pub fn set_debug(on: bool) {
90    let _ = DEBUG.set(on);
91}
92
93/// Whether the deployment is in debug mode (default `false` until [`set_debug`]).
94pub fn debug() -> bool {
95    *DEBUG.get().unwrap_or(&false)
96}
97
98static DEBUG: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
99
100/// The application's public base URL, without a trailing slash: the configured
101/// `url` when set and non-empty, otherwise derived from the server bind address
102/// as `http://<listen>`. A wildcard bind host (`0.0.0.0` or `[::]`) is shown via
103/// loopback so the result is browsable. Absolute links (the admin URL in the
104/// startup banner, and later notifications and share cards) build on this.
105pub fn base_url(url: Option<&str>, listen: &str) -> String {
106    match url.map(str::trim).filter(|u| !u.is_empty()) {
107        Some(url) => url.trim_end_matches('/').to_string(),
108        None => format!("http://{}", browsable_host(listen)),
109    }
110}
111
112/// Rewrites a wildcard bind host to a loopback address so a bind string like
113/// `0.0.0.0:8080` yields a URL a browser can actually open.
114fn browsable_host(listen: &str) -> String {
115    if let Some(port) = listen.strip_prefix("0.0.0.0") {
116        format!("127.0.0.1{port}")
117    } else if let Some(port) = listen.strip_prefix("[::]") {
118        format!("[::1]{port}")
119    } else {
120        listen.to_string()
121    }
122}
123
124/// Deployment-level backend settings. Per-install brand and per-operator preferences
125/// live in the settings and preferences stores, not here.
126///
127/// Non-exhaustive: build one with [`Default`] and set fields, so a field added
128/// in a later release is additive.
129#[derive(Debug, Clone, Deserialize)]
130#[serde(default)]
131#[non_exhaustive]
132pub struct BackendConfig {
133    /// Set the `Secure` attribute on the admin session cookie. Enable behind HTTPS
134    /// in production; leave off for plain-HTTP local development.
135    pub secure_cookie: bool,
136    /// The key the admin signs its tokens with (a private file's URL). Unset,
137    /// a key is generated at the first boot and kept in the settings table, so
138    /// set it when several instances share a database behind one hostname.
139    pub secret: Option<String>,
140    /// The default display timezone for the admin (an IANA name like
141    /// `Asia/Kolkata`). Storage is always UTC; this only affects how dates render.
142    /// An operator's own preference overrides it (later); it falls back to UTC.
143    pub timezone: String,
144    /// Admin path overrides, keyed by module id (`"rainmill.location"`) or by a
145    /// module id and one contribution's declared path
146    /// (`"rainmill.location/nodes"`), the more specific winning. Values are
147    /// absolute under the admin mount, so they survive a relocated panel. Lets a
148    /// deployment move a plugin's screens without forking it.
149    pub paths: std::collections::BTreeMap<String, String>,
150    /// Arrangement overrides, keyed by hierarchy (`"backend.nav"`,
151    /// `"backend.settings"`, a plugin's own): the keys in the wanted order.
152    /// Keys left out keep their arrangement after the listed ones; a fixed
153    /// hierarchy ignores its entry.
154    pub order: std::collections::BTreeMap<String, Vec<String>>,
155    /// Entries moved from the home their author gave them, keyed by the
156    /// entry (`"backend.access_log"`, `"resource:/orders"`); see
157    /// [`crate::arrange::Move`].
158    pub menu: std::collections::BTreeMap<String, crate::arrange::Move>,
159    /// The URL path the admin panel is mounted under, without a trailing slash
160    /// (default `/admin`). Change it to move or obscure the panel (`/manage`,
161    /// `/backend`). A leading slash is added if missing and a trailing slash is
162    /// stripped; an empty value falls back to `/admin`.
163    pub path: String,
164    /// Networks whose `X-Forwarded-For` header may be believed, as CIDR ranges
165    /// (`"10.0.0.0/8"`). The header is caller-controlled, so it is read only when
166    /// the connecting peer falls inside one of these; the client is then the
167    /// rightmost address in the chain that is not itself a trusted proxy.
168    ///
169    /// Empty (the default) trusts nothing and records the peer address, which is
170    /// right for a directly bound server. Set it to the load balancer's network
171    /// when there is one: leaving it empty behind a proxy records the proxy on
172    /// every row, and filling it in for a network that is not a proxy lets anyone
173    /// on it forge the address in the audit log.
174    pub trusted_proxies: Vec<String>,
175    /// The directory files the admin keeps are stored under (default
176    /// `storage`), relative to the working directory unless absolute. Uploaded
177    /// import files go to `private` beneath it.
178    pub storage: String,
179    /// The admin skin by code: `standard` (the default), `compact`, or one a
180    /// module registered. An unknown code aborts the boot.
181    pub skin: String,
182    /// The file extensions an upload may carry (`["jpg", "png", "pdf"]`).
183    /// Empty, the admin's default list applies: images, documents, audio,
184    /// video, fonts and archives, with no scripts, markup or stylesheets.
185    pub upload_extensions: Vec<String>,
186}
187
188impl Default for BackendConfig {
189    fn default() -> Self {
190        Self {
191            secure_cookie: false,
192            secret: None,
193            timezone: "UTC".to_string(),
194            paths: std::collections::BTreeMap::new(),
195            order: std::collections::BTreeMap::new(),
196            menu: std::collections::BTreeMap::new(),
197            path: "/admin".to_string(),
198            trusted_proxies: Vec::new(),
199            storage: "storage".to_string(),
200            skin: "standard".to_string(),
201            upload_extensions: Vec::new(),
202        }
203    }
204}
205
206fn default_max_connections() -> u32 {
207    10
208}
209
210fn default_acquire_timeout_secs() -> u64 {
211    5
212}
213
214fn default_listen() -> String {
215    "127.0.0.1:8080".to_string()
216}
217
218/// Loads a layered configuration into any deserializable type.
219///
220/// Layers, later overriding earlier:
221/// 1. `<dir>/default.toml` (required)
222/// 2. `<dir>/<APP_ENV>.toml` (optional; `APP_ENV` defaults to `development`)
223/// 3. `<dir>/local.toml` (optional, git-ignored developer overrides)
224/// 4. Environment variables `<PREFIX>__SECTION__KEY` (e.g. `LAT__DATABASE__URL`);
225///    the prefix an application declares as `app.env_prefix` is read with
226///    [`declared_env_prefix`] and passed here.
227pub fn load<T: DeserializeOwned>(dir: &Path, env_prefix: &str) -> CoreResult<T> {
228    file_layers(dir)
229        .add_source(
230            Environment::with_prefix(env_prefix)
231                .prefix_separator("__")
232                .separator("__"),
233        )
234        .build()
235        .and_then(Config::try_deserialize)
236        .map_err(|e| CoreError::Config(e.to_string()))
237}
238
239/// The environment-variable prefix a configuration declares as `app.env_prefix`,
240/// read from the files alone: it selects the environment layer, so it cannot come
241/// from there. `None` when undeclared or blank, meaning the framework default.
242pub fn declared_env_prefix(dir: &Path) -> CoreResult<Option<String>> {
243    #[derive(Deserialize)]
244    struct Declared {
245        #[serde(default)]
246        app: DeclaredApp,
247    }
248    #[derive(Deserialize, Default)]
249    struct DeclaredApp {
250        env_prefix: Option<String>,
251    }
252    let declared: Declared = file_layers(dir)
253        .build()
254        .and_then(Config::try_deserialize)
255        .map_err(|e| CoreError::Config(e.to_string()))?;
256    Ok(declared
257        .app
258        .env_prefix
259        .map(|prefix| prefix.trim().to_string())
260        .filter(|prefix| !prefix.is_empty()))
261}
262
263/// The file layers of a config directory, in override order: `default.toml`
264/// (required), `<APP_ENV>.toml`, then `local.toml`.
265fn file_layers(dir: &Path) -> config::ConfigBuilder<config::builder::DefaultState> {
266    let app_env = std::env::var("APP_ENV").unwrap_or_else(|_| "development".into());
267    Config::builder()
268        .add_source(File::from(dir.join("default.toml")).required(true))
269        .add_source(File::from(dir.join(format!("{app_env}.toml"))).required(false))
270        .add_source(File::from(dir.join("local.toml")).required(false))
271}
272
273#[cfg(test)]
274mod tests {
275    use super::*;
276
277    #[derive(Deserialize)]
278    struct TestConfig {
279        server: ServerConfig,
280        database: DatabaseConfig,
281    }
282
283    #[test]
284    fn loads_defaults_env_overrides_and_serde_defaults() {
285        let dir = tempfile::tempdir().unwrap();
286        std::fs::write(
287            dir.path().join("default.toml"),
288            "[server]\nlisten = \"0.0.0.0:9999\"\n\n[database]\nurl = \"postgres://from-file\"\n",
289        )
290        .unwrap();
291        std::env::set_var("LATERITE_TEST__DATABASE__URL", "postgres://from-env");
292        let cfg: TestConfig = load(dir.path(), "LATERITE_TEST").unwrap();
293        std::env::remove_var("LATERITE_TEST__DATABASE__URL");
294        assert_eq!(cfg.server.listen, "0.0.0.0:9999");
295        assert_eq!(cfg.database.url, "postgres://from-env");
296        assert_eq!(cfg.database.max_connections, 10);
297        assert_eq!(cfg.database.acquire_timeout_secs, 5);
298    }
299
300    #[test]
301    fn backend_config_defaults_and_loads() {
302        #[derive(Deserialize)]
303        struct C {
304            #[serde(default)]
305            backend: BackendConfig,
306        }
307        let dir = tempfile::tempdir().unwrap();
308        std::fs::write(dir.path().join("default.toml"), "").unwrap();
309        let c: C = load(dir.path(), "LATERITE_BE_NONE").unwrap();
310        assert!(!c.backend.secure_cookie);
311        assert_eq!(c.backend.timezone, "UTC");
312
313        std::fs::write(
314            dir.path().join("default.toml"),
315            "[backend]\nsecure_cookie = true\ntimezone = \"Asia/Kolkata\"\n",
316        )
317        .unwrap();
318        let c: C = load(dir.path(), "LATERITE_BE_SET").unwrap();
319        assert!(c.backend.secure_cookie);
320        assert_eq!(c.backend.timezone, "Asia/Kolkata");
321    }
322
323    #[test]
324    fn declared_env_prefix_comes_from_the_files_alone() {
325        let dir = tempfile::tempdir().unwrap();
326        std::fs::write(dir.path().join("default.toml"), "[app]\nname = \"Acme\"\n").unwrap();
327        assert_eq!(declared_env_prefix(dir.path()).unwrap(), None);
328        std::fs::write(
329            dir.path().join("default.toml"),
330            "[app]\nenv_prefix = \"ACME\"\n",
331        )
332        .unwrap();
333        assert_eq!(
334            declared_env_prefix(dir.path()).unwrap().as_deref(),
335            Some("ACME")
336        );
337        // local.toml overrides it, and a blank value counts as undeclared.
338        std::fs::write(
339            dir.path().join("local.toml"),
340            "[app]\nenv_prefix = \"  \"\n",
341        )
342        .unwrap();
343        assert_eq!(declared_env_prefix(dir.path()).unwrap(), None);
344    }
345
346    #[test]
347    fn base_url_prefers_config_then_derives_from_listen() {
348        // Configured URL wins and loses any trailing slash.
349        assert_eq!(
350            base_url(Some("https://acme.example/"), "127.0.0.1:8080"),
351            "https://acme.example"
352        );
353        // Blank configured URL falls through to the derived form.
354        assert_eq!(
355            base_url(Some("  "), "127.0.0.1:9000"),
356            "http://127.0.0.1:9000"
357        );
358        // No URL: derive from the bind address.
359        assert_eq!(base_url(None, "127.0.0.1:8080"), "http://127.0.0.1:8080");
360        // A wildcard bind host is shown via loopback so the URL is browsable.
361        assert_eq!(base_url(None, "0.0.0.0:8080"), "http://127.0.0.1:8080");
362        assert_eq!(base_url(None, "[::]:8080"), "http://[::1]:8080");
363    }
364
365    #[test]
366    fn missing_default_file_is_a_config_error() {
367        let dir = tempfile::tempdir().unwrap();
368        let result: CoreResult<TestConfig> = load(dir.path(), "LATERITE_TEST_MISSING");
369        assert!(matches!(result, Err(CoreError::Config(_))));
370    }
371}