Skip to main content

phoenix_config/
builder.rs

1use std::{
2    collections::{BTreeMap, BTreeSet},
3    env,
4    path::PathBuf,
5    sync::Arc,
6    time::Duration,
7};
8
9use zeroize::Zeroizing;
10
11use crate::{
12    AppConfig, ConfigError, DEFAULT_ADDRESS, DEFAULT_DATABASE_URL, DEFAULT_RATE_LIMIT_REQUESTS,
13    DEFAULT_RATE_LIMIT_WINDOW_SECONDS, DEFAULT_VITE_DEV_URL, Environment, KNOWN_KEYS, SecretValue,
14    files::{self, TomlDirectory},
15    validation::{
16        default_allowed_hosts, parse_allowed_hosts, parse_positive_u64, parse_trusted_proxies,
17        validate_database_url, validate_origin,
18    },
19};
20
21#[derive(Clone, Debug)]
22enum ConfigFile {
23    Discover,
24    Exact(PathBuf),
25    Disabled,
26}
27
28#[derive(Clone, Debug)]
29struct SecretRequirement {
30    key: String,
31    minimum_bytes: usize,
32}
33
34/// Controls configuration-file selection, application secrets, and test overrides.
35#[derive(Clone, Debug)]
36pub struct AppConfigBuilder {
37    config_file: ConfigFile,
38    toml_directory: TomlDirectory,
39    required_secrets: Vec<SecretRequirement>,
40    overrides: BTreeMap<String, String>,
41}
42
43impl Default for AppConfigBuilder {
44    fn default() -> Self {
45        Self::new()
46    }
47}
48
49impl AppConfigBuilder {
50    #[must_use]
51    pub fn new() -> Self {
52        Self {
53            config_file: ConfigFile::Discover,
54            toml_directory: TomlDirectory::Discover,
55            required_secrets: Vec::new(),
56            overrides: BTreeMap::new(),
57        }
58    }
59
60    /// Load exactly this dotenv file. Unlike conventional discovery, a missing
61    /// explicit file is an error.
62    #[must_use]
63    pub fn config_file(mut self, path: impl Into<PathBuf>) -> Self {
64        self.config_file = ConfigFile::Exact(path.into());
65        self
66    }
67
68    /// Load Laravel-style TOML files from this `config/` directory.
69    #[must_use]
70    pub fn config_directory(mut self, path: impl Into<PathBuf>) -> Self {
71        self.toml_directory = TomlDirectory::Exact(path.into());
72        self
73    }
74
75    /// Disable dotenv and `config/*.toml` loading while retaining process
76    /// variables and overrides.
77    #[must_use]
78    pub fn without_config_file(mut self) -> Self {
79        self.config_file = ConfigFile::Disabled;
80        self.toml_directory = TomlDirectory::Disabled;
81        self
82    }
83
84    /// Require a named secret in production and enforce its minimum byte length
85    /// whenever supplied. The framework does not infer or reuse keys between
86    /// JWT, encryption, blind-index, or other application purposes.
87    #[must_use]
88    pub fn required_secret(mut self, key: impl Into<String>, minimum_bytes: usize) -> Self {
89        self.required_secrets.push(SecretRequirement {
90            key: key.into(),
91            minimum_bytes,
92        });
93        self
94    }
95
96    /// Add the highest-precedence value, intended for tests and explicit process
97    /// bootstrap code.
98    #[must_use]
99    pub fn override_value(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
100        self.overrides.insert(key.into(), value.into());
101        self
102    }
103
104    /// Merge and validate all configured sources.
105    ///
106    /// Precedence (low → high): `config/*.toml` → `.env` → process environment →
107    /// builder overrides. `DATABASE_URL` from `.env`/process wins over TOML; otherwise
108    /// the URL is built from `config/database.toml` + `DB_CONNECTION` / `DB_PASSWORD`.
109    ///
110    /// # Errors
111    ///
112    /// Returns a source, validation, or production-requirement error.
113    pub fn load(self) -> Result<AppConfig, ConfigError> {
114        validate_secret_requirements(&self.required_secrets)?;
115        let mut values = files::load_toml_defaults(&self.toml_directory)?;
116        let mut explicit_keys = BTreeSet::new();
117
118        match &self.config_file {
119            ConfigFile::Discover => match dotenvy::dotenv_iter() {
120                Ok(iter) => extend_dotenv(&mut values, &mut explicit_keys, iter)?,
121                Err(error) if error.not_found() => {}
122                Err(error) => return Err(ConfigError::Dotenv(error)),
123            },
124            ConfigFile::Exact(path) => {
125                let iter = dotenvy::from_path_iter(path).map_err(ConfigError::Dotenv)?;
126                extend_dotenv(&mut values, &mut explicit_keys, iter)?;
127            }
128            ConfigFile::Disabled => {}
129        }
130
131        let mut environment_keys = KNOWN_KEYS
132            .iter()
133            .map(|key| (*key).to_owned())
134            .collect::<BTreeSet<_>>();
135        environment_keys.extend(
136            self.required_secrets
137                .iter()
138                .map(|requirement| requirement.key.clone()),
139        );
140        for key in environment_keys {
141            match env::var(&key) {
142                Ok(value) => {
143                    values.insert(key.clone(), value);
144                    explicit_keys.insert(key);
145                }
146                Err(env::VarError::NotPresent) => {}
147                Err(env::VarError::NotUnicode(_)) => {
148                    return Err(ConfigError::NonUnicode(key));
149                }
150            }
151        }
152        for key in self.overrides.keys() {
153            explicit_keys.insert(key.clone());
154        }
155        values.extend(self.overrides);
156        files::apply_database_overrides(&mut values, &self.toml_directory, &explicit_keys)?;
157        AppConfig::from_values(&values, &self.required_secrets)
158    }
159}
160
161impl AppConfig {
162    /// Load the conventional optional `.env` and process environment.
163    ///
164    /// # Errors
165    ///
166    /// Returns an error for malformed files, invalid values, or missing
167    /// production requirements.
168    pub fn load() -> Result<Self, ConfigError> {
169        AppConfigBuilder::new().load()
170    }
171
172    #[must_use]
173    pub fn builder() -> AppConfigBuilder {
174        AppConfigBuilder::new()
175    }
176
177    fn from_values(
178        values: &BTreeMap<String, String>,
179        required_secrets: &[SecretRequirement],
180    ) -> Result<Self, ConfigError> {
181        let environment = setting(values, "APP_ENV")
182            .as_deref()
183            .unwrap_or("development")
184            .parse()?;
185        let address = setting(values, "APP_ADDR").unwrap_or_else(|| DEFAULT_ADDRESS.to_owned());
186        if address.is_empty() || address.bytes().any(|byte| byte.is_ascii_whitespace()) {
187            return Err(ConfigError::invalid(
188                "APP_ADDR",
189                "expected a non-empty host:port value",
190            ));
191        }
192
193        let public_url =
194            required_in_production(environment, "APP_URL", setting(values, "APP_URL"), || {
195                format!("http://{address}")
196            })?;
197        let public_host = validate_origin("APP_URL", &public_url)?;
198
199        let database_url = required_in_production(
200            environment,
201            "DATABASE_URL",
202            setting(values, "DATABASE_URL"),
203            || DEFAULT_DATABASE_URL.to_owned(),
204        )?;
205        validate_database_url(&database_url)?;
206
207        let vite_dev_url = if environment.is_production() {
208            None
209        } else {
210            let value =
211                setting(values, "VITE_DEV_URL").unwrap_or_else(|| DEFAULT_VITE_DEV_URL.to_owned());
212            validate_origin("VITE_DEV_URL", &value)?;
213            Some(value)
214        };
215
216        let proxies = if environment.is_production() {
217            setting(values, "TRUSTED_PROXIES")
218                .ok_or(ConfigError::MissingProduction("TRUSTED_PROXIES"))?
219        } else {
220            setting(values, "TRUSTED_PROXIES").unwrap_or_else(|| "none".to_owned())
221        };
222        let trusted_proxies = parse_trusted_proxies(&proxies)?;
223
224        let allowed_hosts = match setting(values, "ALLOWED_HOSTS") {
225            Some(value) => parse_allowed_hosts(&value)?,
226            None if environment.is_production() => {
227                return Err(ConfigError::MissingProduction("ALLOWED_HOSTS"));
228            }
229            None => default_allowed_hosts(&public_host),
230        };
231        if !allowed_hosts.contains(&public_host) {
232            return Err(ConfigError::invalid(
233                "ALLOWED_HOSTS",
234                "must include the host from APP_URL",
235            ));
236        }
237
238        let rate_limit_requests = parse_positive_u64(
239            "RATE_LIMIT_REQUESTS",
240            setting(values, "RATE_LIMIT_REQUESTS"),
241            DEFAULT_RATE_LIMIT_REQUESTS,
242        )?;
243        let rate_limit_window = Duration::from_secs(parse_positive_u64(
244            "RATE_LIMIT_WINDOW_SECONDS",
245            setting(values, "RATE_LIMIT_WINDOW_SECONDS"),
246            DEFAULT_RATE_LIMIT_WINDOW_SECONDS,
247        )?);
248        let secrets = load_secrets(values, environment, required_secrets)?;
249
250        Ok(Self {
251            environment,
252            address,
253            public_url,
254            database_url,
255            vite_dev_url,
256            trusted_proxies: trusted_proxies.into(),
257            allowed_hosts: allowed_hosts.into(),
258            rate_limit_requests,
259            rate_limit_window,
260            secrets: Arc::new(secrets),
261        })
262    }
263}
264
265fn extend_dotenv(
266    values: &mut BTreeMap<String, String>,
267    explicit_keys: &mut BTreeSet<String>,
268    entries: impl IntoIterator<Item = dotenvy::Result<(String, String)>>,
269) -> Result<(), ConfigError> {
270    for entry in entries {
271        let (key, value) = entry.map_err(ConfigError::Dotenv)?;
272        values.insert(key.clone(), value);
273        explicit_keys.insert(key);
274    }
275    Ok(())
276}
277
278fn setting(values: &BTreeMap<String, String>, key: &str) -> Option<String> {
279    values
280        .get(key)
281        .filter(|value| !value.trim().is_empty())
282        .cloned()
283}
284
285fn required_in_production(
286    environment: Environment,
287    key: &'static str,
288    value: Option<String>,
289    default: impl FnOnce() -> String,
290) -> Result<String, ConfigError> {
291    match value {
292        Some(value) => Ok(value),
293        None if environment.is_production() => Err(ConfigError::MissingProduction(key)),
294        None => Ok(default()),
295    }
296}
297
298fn validate_secret_requirements(requirements: &[SecretRequirement]) -> Result<(), ConfigError> {
299    let mut keys = BTreeSet::new();
300    for requirement in requirements {
301        let valid_key = !requirement.key.is_empty()
302            && requirement
303                .key
304                .bytes()
305                .all(|byte| byte.is_ascii_uppercase() || byte.is_ascii_digit() || byte == b'_');
306        if !valid_key || requirement.minimum_bytes == 0 || !keys.insert(&requirement.key) {
307            return Err(ConfigError::InvalidSecretRequirement(
308                requirement.key.clone(),
309            ));
310        }
311    }
312    Ok(())
313}
314
315fn load_secrets(
316    values: &BTreeMap<String, String>,
317    environment: Environment,
318    requirements: &[SecretRequirement],
319) -> Result<BTreeMap<String, SecretValue>, ConfigError> {
320    let mut secrets = BTreeMap::new();
321    for requirement in requirements {
322        match setting(values, &requirement.key) {
323            Some(value) if value.len() >= requirement.minimum_bytes => {
324                secrets.insert(
325                    requirement.key.clone(),
326                    SecretValue(Arc::new(Zeroizing::new(value))),
327                );
328            }
329            Some(_) => {
330                return Err(ConfigError::SecretTooShort {
331                    key: requirement.key.clone(),
332                    minimum_bytes: requirement.minimum_bytes,
333                });
334            }
335            None if environment.is_production() => {
336                return Err(ConfigError::MissingRequiredSecret(requirement.key.clone()));
337            }
338            None => {}
339        }
340    }
341    Ok(secrets)
342}
343
344#[cfg(test)]
345mod tests {
346    use std::{fs, time::SystemTime};
347
348    use super::*;
349
350    fn config(values: &[(&str, &str)]) -> Result<AppConfig, ConfigError> {
351        values
352            .iter()
353            .fold(
354                AppConfig::builder().without_config_file(),
355                |builder, (key, value)| builder.override_value(*key, *value),
356            )
357            .load()
358    }
359
360    #[test]
361    fn development_has_working_local_defaults() {
362        let config = config(&[]).unwrap();
363
364        assert_eq!(config.environment(), Environment::Development);
365        assert_eq!(config.address(), DEFAULT_ADDRESS);
366        assert_eq!(config.database_url(), DEFAULT_DATABASE_URL);
367        assert_eq!(config.vite_dev_url(), Some(DEFAULT_VITE_DEV_URL));
368        assert!(config.trusted_proxies().is_empty());
369        assert!(
370            config
371                .allowed_hosts()
372                .iter()
373                .any(|host| host == "localhost")
374        );
375        assert_eq!(config.rate_limit_requests(), 60);
376        assert_eq!(config.rate_limit_window(), Duration::from_mins(1));
377    }
378
379    #[test]
380    fn production_requires_explicit_network_and_database_boundaries() {
381        let missing = config(&[("APP_ENV", "production")]).unwrap_err();
382        assert!(matches!(missing, ConfigError::MissingProduction("APP_URL")));
383
384        let config = config(&[
385            ("APP_ENV", "production"),
386            ("APP_URL", "https://app.example.test"),
387            ("DATABASE_URL", "postgresql://database/app"),
388            ("TRUSTED_PROXIES", "127.0.0.1,::1"),
389            ("ALLOWED_HOSTS", "app.example.test"),
390        ])
391        .unwrap();
392        assert!(config.environment().is_production());
393        assert_eq!(config.trusted_proxies().len(), 2);
394        assert_eq!(config.allowed_hosts(), ["app.example.test"]);
395    }
396
397    #[test]
398    fn application_declared_secrets_are_required_and_redacted() {
399        let builder = AppConfig::builder()
400            .without_config_file()
401            .required_secret("JWT_SECRET", 32)
402            .override_value("APP_ENV", "production")
403            .override_value("APP_URL", "https://app.example.test")
404            .override_value("DATABASE_URL", "postgresql://database/app")
405            .override_value("TRUSTED_PROXIES", "none")
406            .override_value("ALLOWED_HOSTS", "app.example.test");
407        assert!(matches!(
408            builder.clone().load(),
409            Err(ConfigError::MissingRequiredSecret(key)) if key == "JWT_SECRET"
410        ));
411
412        let config = builder
413            .override_value("JWT_SECRET", "0123456789abcdef0123456789abcdef")
414            .load()
415            .unwrap();
416        assert_eq!(
417            config.secret("JWT_SECRET").unwrap().expose(),
418            "0123456789abcdef0123456789abcdef"
419        );
420        assert!(!format!("{config:?}").contains("0123456789abcdef"));
421    }
422
423    #[test]
424    fn toml_database_connection_selects_pgsql() {
425        let id = SystemTime::now()
426            .duration_since(std::time::UNIX_EPOCH)
427            .unwrap()
428            .as_nanos();
429        let root = env::temp_dir().join(format!("phoenix-config-dir-{}-{id}", std::process::id()));
430        let config_dir = root.join("config");
431        fs::create_dir_all(&config_dir).unwrap();
432        fs::write(
433            config_dir.join("database.toml"),
434            r#"
435default = "sqlite"
436
437[connections.sqlite]
438driver = "sqlite"
439database = "storage/app.sqlite"
440
441[connections.pgsql]
442driver = "pgsql"
443host = "127.0.0.1"
444port = 5432
445database = "phoenix"
446username = "phoenix"
447password = ""
448"#,
449        )
450        .unwrap();
451
452        let config = AppConfig::builder()
453            .without_config_file()
454            .config_directory(&config_dir)
455            .override_value("DB_CONNECTION", "pgsql")
456            .override_value("DB_PASSWORD", "s3cret")
457            .load()
458            .unwrap();
459        assert_eq!(
460            config.database_url(),
461            "postgresql://phoenix:s3cret@127.0.0.1:5432/phoenix"
462        );
463        fs::remove_dir_all(root).unwrap();
464    }
465
466    #[test]
467    fn explicit_database_url_wins_over_toml() {
468        let id = SystemTime::now()
469            .duration_since(std::time::UNIX_EPOCH)
470            .unwrap()
471            .as_nanos();
472        let root = env::temp_dir().join(format!("phoenix-config-url-{}-{id}", std::process::id()));
473        let config_dir = root.join("config");
474        fs::create_dir_all(&config_dir).unwrap();
475        fs::write(
476            config_dir.join("database.toml"),
477            r#"
478default = "pgsql"
479[connections.pgsql]
480driver = "pgsql"
481host = "127.0.0.1"
482database = "from-toml"
483username = "phoenix"
484"#,
485        )
486        .unwrap();
487
488        let config = AppConfig::builder()
489            .without_config_file()
490            .config_directory(&config_dir)
491            .override_value("DATABASE_URL", "sqlite:storage/override.sqlite")
492            .load()
493            .unwrap();
494        assert_eq!(config.database_url(), "sqlite:storage/override.sqlite");
495        fs::remove_dir_all(root).unwrap();
496    }
497}