Skip to main content

seiva_config/
lib.rs

1//! Typed, 12-factor configuration for the Delonix Seiva framework.
2//!
3//! The twelve-factor "config" principle is that configuration lives in the
4//! *environment*, not in the code or in a checked-in file. This crate reads
5//! configuration only from process environment variables, decodes it into
6//! typed values, and — crucially — **validates it at startup**. A service that
7//! is missing a required variable or was handed an unparseable value should
8//! refuse to boot, not surface the problem on the first request that happens to
9//! touch the bad value.
10//!
11//! # The three pieces
12//!
13//! - [`AppEnv`] — the runtime environment ([`Development`](AppEnv::Development),
14//!   [`Staging`](AppEnv::Staging), [`Production`](AppEnv::Production)), read
15//!   from `APP_ENV` (defaulting to development). It carries the
16//!   [production-safety guard](AppEnv::reject_dev_shortcut).
17//! - [`EnvReader`] — a small typed reader with [`require_var`](EnvReader::require_var),
18//!   [`optional_var`](EnvReader::optional_var) and
19//!   [`var_parsed`](EnvReader::var_parsed). It **collects every problem** it
20//!   meets instead of stopping at the first, so a misconfigured deployment
21//!   learns about all its mistakes in one boot.
22//! - [`ConfigError`] — a compact error (a `Vec<String>` of named problems behind
23//!   one small struct) that reports all collected problems together.
24//!
25//! # Ergonomics
26//!
27//! A config struct implements [`FromEnv`] by reading *every* field up front
28//! (so each missing or bad variable is recorded) and only then assembling
29//! itself. [`load`] drives the whole thing and turns the accumulated problems
30//! into a single [`ConfigError`].
31//!
32//! ```
33//! use seiva_config::{AppEnv, ConfigError, EnvReader, FromEnv, load_from};
34//! use std::collections::HashMap;
35//!
36//! #[derive(Debug)]
37//! struct ServerConfig {
38//!     env: AppEnv,
39//!     bind_port: u16,
40//!     database_url: String,
41//!     allow_insecure_tls: bool,
42//! }
43//!
44//! impl FromEnv for ServerConfig {
45//!     fn from_env(r: &mut EnvReader) -> Option<Self> {
46//!         // Read every field FIRST so each problem is collected, not just the
47//!         // first one. The `?`s below only decide whether to assemble.
48//!         let env = r.app_env();
49//!         let bind_port = r.var_parsed::<u16>("BIND_PORT");
50//!         let database_url = r.require_var("DATABASE_URL");
51//!         let allow_insecure_tls = r.optional_bool("ALLOW_INSECURE_TLS", false);
52//!
53//!         let config = Self {
54//!             env,
55//!             bind_port: bind_port?,
56//!             database_url: database_url?,
57//!             allow_insecure_tls: allow_insecure_tls?,
58//!         };
59//!
60//!         // Production-safety guard: a dev-only shortcut left on in production
61//!         // is a startup error, not a silent risk.
62//!         r.guard(config.env.reject_dev_shortcut(
63//!             "ALLOW_INSECURE_TLS",
64//!             config.allow_insecure_tls,
65//!         ));
66//!
67//!         Some(config)
68//!     }
69//! }
70//!
71//! // `load_from` takes an explicit map (tests use it; `load` reads the process
72//! // environment). A valid development configuration boots:
73//! let vars = HashMap::from([
74//!     ("APP_ENV".to_string(), "development".to_string()),
75//!     ("BIND_PORT".to_string(), "8080".to_string()),
76//!     ("DATABASE_URL".to_string(), "postgres://localhost/app".to_string()),
77//! ]);
78//! let config: ServerConfig = load_from(vars).expect("valid config");
79//! assert_eq!(config.bind_port, 8080);
80//! assert!(config.env.is_development());
81//!
82//! // A missing required variable AND a bad port are reported together:
83//! let bad = HashMap::from([("BIND_PORT".to_string(), "not-a-port".to_string())]);
84//! let err: ConfigError = load_from::<ServerConfig>(bad).unwrap_err();
85//! assert_eq!(err.problems().len(), 2);
86//! ```
87
88#![forbid(unsafe_code)]
89#![deny(missing_docs)]
90
91use std::collections::HashMap;
92use std::fmt;
93use std::str::FromStr;
94
95/// The runtime environment a service runs in, read from the `APP_ENV`
96/// environment variable.
97///
98/// Parsing is case-insensitive and accepts the common short aliases a
99/// deployment platform might set: `dev`, `stage`/`stg`, `prod`. An unset
100/// `APP_ENV` means [`Development`](AppEnv::Development) — the safe default for
101/// a workstation, and the one that *permits* the development shortcuts the
102/// [production guard](AppEnv::reject_dev_shortcut) later refuses.
103#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
104pub enum AppEnv {
105    /// A developer workstation or a local test. The default when `APP_ENV` is
106    /// unset. Development shortcuts are permitted here.
107    #[default]
108    Development,
109    /// A pre-production environment that mirrors production. Shortcuts are
110    /// permitted (staging is not the guarded environment) but should be rare.
111    Staging,
112    /// Real production traffic. The [guard](AppEnv::reject_dev_shortcut)
113    /// refuses development shortcuts here.
114    Production,
115}
116
117impl AppEnv {
118    /// The environment variable this type is read from.
119    pub const VAR: &'static str = "APP_ENV";
120
121    /// Reads [`AppEnv`] from the process environment's `APP_ENV`, defaulting to
122    /// [`Development`](AppEnv::Development) when unset.
123    ///
124    /// Returns a [`ConfigError`] naming `APP_ENV` when the value is set but
125    /// unrecognised, so a typo (`APP_ENV=prod_uction`) fails at startup rather
126    /// than silently downgrading to development.
127    pub fn from_process_env() -> Result<Self, ConfigError> {
128        match std::env::var(Self::VAR) {
129            Ok(raw) => raw
130                .parse()
131                .map_err(|e: ParseAppEnvError| ConfigError::single(e.into_problem(Self::VAR))),
132            Err(std::env::VarError::NotPresent) => Ok(Self::default()),
133            Err(std::env::VarError::NotUnicode(_)) => Err(ConfigError::single(format!(
134                "environment variable `{}` is not valid UTF-8",
135                Self::VAR
136            ))),
137        }
138    }
139
140    /// True for [`Development`](AppEnv::Development).
141    #[must_use]
142    pub fn is_development(self) -> bool {
143        matches!(self, Self::Development)
144    }
145
146    /// True for [`Staging`](AppEnv::Staging).
147    #[must_use]
148    pub fn is_staging(self) -> bool {
149        matches!(self, Self::Staging)
150    }
151
152    /// True for [`Production`](AppEnv::Production).
153    #[must_use]
154    pub fn is_production(self) -> bool {
155        matches!(self, Self::Production)
156    }
157
158    /// The canonical lowercase name of this environment (`"development"`,
159    /// `"staging"`, `"production"`).
160    #[must_use]
161    pub fn as_str(self) -> &'static str {
162        match self {
163            Self::Development => "development",
164            Self::Staging => "staging",
165            Self::Production => "production",
166        }
167    }
168
169    /// The production-safety guard: refuses a development shortcut when running
170    /// in production.
171    ///
172    /// Call this for any flag that is convenient in development but dangerous
173    /// in production — allowing insecure TLS, seeding test data, exposing
174    /// internal error details to clients, disabling auth. When
175    /// `self.is_production() && enabled`, it returns a [`ConfigError`] naming
176    /// the offending flag; otherwise it is `Ok`.
177    ///
178    /// ```
179    /// use seiva_config::AppEnv;
180    ///
181    /// // A dev-only flag left on in production is rejected...
182    /// let prod = AppEnv::Production;
183    /// assert!(prod.reject_dev_shortcut("ALLOW_INSECURE_TLS", true).is_err());
184    /// assert!(prod.reject_dev_shortcut("ALLOW_INSECURE_TLS", false).is_ok());
185    ///
186    /// // ...but the same flag is fine in development.
187    /// let dev = AppEnv::Development;
188    /// assert!(dev.reject_dev_shortcut("ALLOW_INSECURE_TLS", true).is_ok());
189    /// ```
190    pub fn reject_dev_shortcut(self, name: &str, enabled: bool) -> Result<(), ConfigError> {
191        if self.is_production() && enabled {
192            Err(ConfigError::single(format!(
193                "development-only shortcut `{name}` must not be enabled in production \
194                 (APP_ENV=production); unset it or set it to a non-truthy value"
195            )))
196        } else {
197            Ok(())
198        }
199    }
200}
201
202impl fmt::Display for AppEnv {
203    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
204        f.write_str(self.as_str())
205    }
206}
207
208/// Error returned when `APP_ENV` holds an unrecognised value.
209#[derive(Debug, Clone, PartialEq, Eq)]
210pub struct ParseAppEnvError {
211    raw: String,
212}
213
214impl ParseAppEnvError {
215    fn into_problem(self, var: &str) -> String {
216        format!(
217            "environment variable `{}` has unrecognised value `{}` \
218             (expected one of: development, staging, production)",
219            var, self.raw
220        )
221    }
222}
223
224impl fmt::Display for ParseAppEnvError {
225    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
226        write!(
227            f,
228            "unrecognised APP_ENV value `{}` (expected development, staging or production)",
229            self.raw
230        )
231    }
232}
233
234impl std::error::Error for ParseAppEnvError {}
235
236impl FromStr for AppEnv {
237    type Err = ParseAppEnvError;
238
239    fn from_str(s: &str) -> Result<Self, Self::Err> {
240        match s.trim().to_ascii_lowercase().as_str() {
241            "development" | "dev" | "develop" | "local" => Ok(Self::Development),
242            "staging" | "stage" | "stg" => Ok(Self::Staging),
243            "production" | "prod" | "prd" | "live" => Ok(Self::Production),
244            _ => Err(ParseAppEnvError { raw: s.to_string() }),
245        }
246    }
247}
248
249/// A compact startup-configuration error.
250///
251/// It holds a `Vec<String>` of human-readable problems, each naming the
252/// variable at fault, so the whole struct is pointer-sized and cheap to return
253/// by value (it does not trip clippy's `result_large_err`). Multiple problems
254/// discovered during a single [`load`] are reported together.
255#[derive(Debug, Clone, PartialEq, Eq)]
256pub struct ConfigError {
257    problems: Vec<String>,
258}
259
260impl ConfigError {
261    /// Builds an error from a single problem.
262    #[must_use]
263    pub fn single(problem: impl Into<String>) -> Self {
264        Self {
265            problems: vec![problem.into()],
266        }
267    }
268
269    /// Builds an error from a collection of problems.
270    ///
271    /// Returns `None` when `problems` is empty — there is no error to report.
272    #[must_use]
273    pub fn from_problems(problems: Vec<String>) -> Option<Self> {
274        if problems.is_empty() {
275            None
276        } else {
277            Some(Self { problems })
278        }
279    }
280
281    /// The collected problems, each a message naming the offending variable.
282    #[must_use]
283    pub fn problems(&self) -> &[String] {
284        &self.problems
285    }
286}
287
288impl fmt::Display for ConfigError {
289    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
290        if self.problems.len() == 1 {
291            write!(f, "configuration error: {}", self.problems[0])
292        } else {
293            write!(
294                f,
295                "configuration invalid ({} problems):",
296                self.problems.len()
297            )?;
298            for problem in &self.problems {
299                write!(f, "\n  - {problem}")?;
300            }
301            Ok(())
302        }
303    }
304}
305
306impl std::error::Error for ConfigError {}
307
308/// Where an [`EnvReader`] reads variables from.
309enum EnvSource {
310    /// The live process environment (`std::env::var`). The production path.
311    Process,
312    /// An explicit map. Used by tests so reads never touch — and never race on
313    /// — the process-global environment.
314    Explicit(HashMap<String, String>),
315}
316
317/// A typed reader over a set of environment variables that **accumulates
318/// problems** rather than stopping at the first.
319///
320/// Construct one with [`EnvReader::from_process`] (the real 12-factor path) or
321/// [`EnvReader::from_map`] (deterministic, race-free tests). Read each field
322/// with [`require_var`](Self::require_var), [`optional_var`](Self::optional_var),
323/// [`var_parsed`](Self::var_parsed) or [`optional_bool`](Self::optional_bool);
324/// a missing required variable or an unparseable value records a problem and
325/// yields `None`, but reading *continues*. Feed cross-field checks (such as the
326/// [production guard](AppEnv::reject_dev_shortcut)) back in with
327/// [`guard`](Self::guard). Finish with [`into_result`](Self::into_result), or
328/// let [`load`]/[`load_from`] do it for you.
329pub struct EnvReader {
330    source: EnvSource,
331    problems: Vec<String>,
332}
333
334impl EnvReader {
335    /// A reader over the live process environment.
336    #[must_use]
337    pub fn from_process() -> Self {
338        Self {
339            source: EnvSource::Process,
340            problems: Vec::new(),
341        }
342    }
343
344    /// A reader over an explicit variable map. Nothing it does touches the
345    /// process environment, so tests using it are immune to env races.
346    #[must_use]
347    pub fn from_map(vars: HashMap<String, String>) -> Self {
348        Self {
349            source: EnvSource::Explicit(vars),
350            problems: Vec::new(),
351        }
352    }
353
354    fn lookup(&self, name: &str) -> Option<String> {
355        match &self.source {
356            EnvSource::Process => std::env::var(name).ok(),
357            EnvSource::Explicit(map) => map.get(name).cloned(),
358        }
359    }
360
361    /// Reads a required string variable. Records a "missing" problem and returns
362    /// `None` when it is absent (or empty).
363    pub fn require_var(&mut self, name: &str) -> Option<String> {
364        match self.lookup(name) {
365            Some(value) if !value.is_empty() => Some(value),
366            _ => {
367                self.problems
368                    .push(format!("required environment variable `{name}` is not set"));
369                None
370            }
371        }
372    }
373
374    /// Reads an optional string variable. Never records a problem; returns
375    /// `None` when absent or empty.
376    #[must_use]
377    pub fn optional_var(&self, name: &str) -> Option<String> {
378        self.lookup(name).filter(|v| !v.is_empty())
379    }
380
381    /// Reads a required variable and parses it into `T`. Records a problem (and
382    /// returns `None`) when the variable is missing or fails to parse, naming
383    /// the variable and the parse error either way.
384    pub fn var_parsed<T>(&mut self, name: &str) -> Option<T>
385    where
386        T: FromStr,
387        T::Err: fmt::Display,
388    {
389        let raw = self.require_var(name)?;
390        match raw.parse::<T>() {
391            Ok(value) => Some(value),
392            Err(e) => {
393                self.problems.push(format!(
394                    "environment variable `{name}` has invalid value `{raw}`: {e}"
395                ));
396                None
397            }
398        }
399    }
400
401    /// Reads an optional variable, parsing it into `T` when present and falling
402    /// back to `default` when absent. A present-but-unparseable value is a
403    /// problem (and yields `None`): a typo must not silently become the default.
404    pub fn optional_parsed<T>(&mut self, name: &str, default: T) -> Option<T>
405    where
406        T: FromStr,
407        T::Err: fmt::Display,
408    {
409        match self.optional_var(name) {
410            None => Some(default),
411            Some(raw) => match raw.parse::<T>() {
412                Ok(value) => Some(value),
413                Err(e) => {
414                    self.problems.push(format!(
415                        "environment variable `{name}` has invalid value `{raw}`: {e}"
416                    ));
417                    None
418                }
419            },
420        }
421    }
422
423    /// Reads an optional boolean flag with common truthy/falsy spellings
424    /// (`true`/`false`, `1`/`0`, `yes`/`no`, `on`/`off`), falling back to
425    /// `default` when absent. An unrecognised value is a problem.
426    pub fn optional_bool(&mut self, name: &str, default: bool) -> Option<bool> {
427        match self.optional_var(name) {
428            None => Some(default),
429            Some(raw) => match raw.trim().to_ascii_lowercase().as_str() {
430                "true" | "1" | "yes" | "y" | "on" => Some(true),
431                "false" | "0" | "no" | "n" | "off" => Some(false),
432                _ => {
433                    self.problems.push(format!(
434                        "environment variable `{name}` has invalid boolean value `{raw}` \
435                         (expected true/false, 1/0, yes/no, on/off)"
436                    ));
437                    None
438                }
439            },
440        }
441    }
442
443    /// Reads [`AppEnv`] from this reader's source, recording a problem for an
444    /// unrecognised value and defaulting to [`Development`](AppEnv::Development)
445    /// when unset.
446    pub fn app_env(&mut self) -> AppEnv {
447        match self.optional_var(AppEnv::VAR) {
448            None => AppEnv::default(),
449            Some(raw) => match raw.parse::<AppEnv>() {
450                Ok(env) => env,
451                Err(e) => {
452                    self.problems.push(e.into_problem(AppEnv::VAR));
453                    AppEnv::default()
454                }
455            },
456        }
457    }
458
459    /// Folds the result of a cross-field check (typically
460    /// [`AppEnv::reject_dev_shortcut`]) into the accumulated problems, so it is
461    /// reported alongside any missing or invalid variables.
462    pub fn guard(&mut self, result: Result<(), ConfigError>) {
463        if let Err(e) = result {
464            self.problems.extend(e.problems);
465        }
466    }
467
468    /// True once at least one problem has been recorded.
469    #[must_use]
470    pub fn has_problems(&self) -> bool {
471        !self.problems.is_empty()
472    }
473
474    /// Consumes the reader, turning accumulated problems into a single
475    /// [`ConfigError`].
476    ///
477    /// `value` is the assembled configuration (`None` when a required field was
478    /// missing). When there are no problems the value is returned; otherwise the
479    /// collected problems are. A `None` value with no recorded problems is
480    /// itself reported as a problem, since a correct [`FromEnv`] impl only
481    /// returns `None` after recording why.
482    pub fn into_result<T>(self, value: Option<T>) -> Result<T, ConfigError> {
483        match ConfigError::from_problems(self.problems) {
484            Some(err) => Err(err),
485            None => value.ok_or_else(|| {
486                ConfigError::single(
487                    "configuration could not be assembled but no problem was recorded \
488                     (bug in a FromEnv implementation)",
489                )
490            }),
491        }
492    }
493}
494
495/// A configuration type that can be built from environment variables.
496///
497/// Implementations read **every** field up front — each read records any
498/// problem into the [`EnvReader`] — and only then assemble `Self`, so a single
499/// [`load`] reports all problems at once instead of stopping at the first. See
500/// the [crate-level example](crate#ergonomics) for the shape.
501pub trait FromEnv: Sized {
502    /// Reads and validates this type from the given reader, returning `None`
503    /// (after recording problems) when it cannot be assembled.
504    fn from_env(reader: &mut EnvReader) -> Option<Self>;
505}
506
507/// Loads a [`FromEnv`] configuration from the live process environment,
508/// validating it at startup.
509///
510/// This is the entrypoint a `main` calls: on success it has a fully typed,
511/// fully validated configuration; on failure it has a [`ConfigError`] listing
512/// every problem, suitable for logging and a non-zero exit.
513///
514/// # Errors
515///
516/// Returns a [`ConfigError`] when any required variable is missing, any value
517/// fails to parse, or any [guard](AppEnv::reject_dev_shortcut) fails.
518pub fn load<T: FromEnv>() -> Result<T, ConfigError> {
519    let mut reader = EnvReader::from_process();
520    let value = T::from_env(&mut reader);
521    reader.into_result(value)
522}
523
524/// Loads a [`FromEnv`] configuration from an explicit variable map.
525///
526/// Identical to [`load`] but reads from `vars` instead of the process
527/// environment, so tests are deterministic and never race on the process-global
528/// environment.
529///
530/// # Errors
531///
532/// Returns a [`ConfigError`] on the same conditions as [`load`].
533pub fn load_from<T: FromEnv>(vars: HashMap<String, String>) -> Result<T, ConfigError> {
534    let mut reader = EnvReader::from_map(vars);
535    let value = T::from_env(&mut reader);
536    reader.into_result(value)
537}
538
539#[cfg(test)]
540mod tests {
541    use super::*;
542    use std::sync::Mutex;
543
544    // A single serializing guard for the FEW tests that must touch the
545    // process-global `APP_ENV`. Map-based tests below need no lock at all.
546    static ENV_LOCK: Mutex<()> = Mutex::new(());
547
548    fn map(pairs: &[(&str, &str)]) -> HashMap<String, String> {
549        pairs
550            .iter()
551            .map(|(k, v)| ((*k).to_string(), (*v).to_string()))
552            .collect()
553    }
554
555    // --- AppEnv parsing -----------------------------------------------------
556
557    #[test]
558    fn app_env_parses_canonical_and_aliases() {
559        assert_eq!("development".parse(), Ok(AppEnv::Development));
560        assert_eq!("DEV".parse(), Ok(AppEnv::Development));
561        assert_eq!("  Staging ".parse(), Ok(AppEnv::Staging));
562        assert_eq!("prod".parse(), Ok(AppEnv::Production));
563        assert_eq!("PRODUCTION".parse(), Ok(AppEnv::Production));
564    }
565
566    #[test]
567    fn app_env_default_is_development() {
568        assert_eq!(AppEnv::default(), AppEnv::Development);
569        assert!(AppEnv::default().is_development());
570    }
571
572    #[test]
573    fn app_env_rejects_unknown_value() {
574        let err = "prod_uction".parse::<AppEnv>().unwrap_err();
575        assert!(err.to_string().contains("prod_uction"));
576    }
577
578    #[test]
579    fn app_env_from_process_env_reads_the_var() {
580        let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
581        // SAFETY of correctness, not memory: serialized by ENV_LOCK so no other
582        // test reads/writes APP_ENV concurrently.
583        std::env::set_var(AppEnv::VAR, "production");
584        assert_eq!(AppEnv::from_process_env().unwrap(), AppEnv::Production);
585        std::env::remove_var(AppEnv::VAR);
586        assert_eq!(AppEnv::from_process_env().unwrap(), AppEnv::Development);
587    }
588
589    #[test]
590    fn app_env_from_process_env_rejects_bad_var() {
591        let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
592        std::env::set_var(AppEnv::VAR, "banana");
593        let err = AppEnv::from_process_env().unwrap_err();
594        std::env::remove_var(AppEnv::VAR);
595        assert_eq!(err.problems().len(), 1);
596        assert!(err.problems()[0].contains("APP_ENV"));
597        assert!(err.problems()[0].contains("banana"));
598    }
599
600    // --- Example config, loaded from a map (no env races) -------------------
601
602    #[derive(Debug)]
603    struct ServerConfig {
604        env: AppEnv,
605        bind_port: u16,
606        database_url: String,
607        allow_insecure_tls: bool,
608    }
609
610    impl FromEnv for ServerConfig {
611        fn from_env(r: &mut EnvReader) -> Option<Self> {
612            let env = r.app_env();
613            let bind_port = r.var_parsed::<u16>("BIND_PORT");
614            let database_url = r.require_var("DATABASE_URL");
615            let allow_insecure_tls = r.optional_bool("ALLOW_INSECURE_TLS", false);
616
617            let config = Self {
618                env,
619                bind_port: bind_port?,
620                database_url: database_url?,
621                allow_insecure_tls: allow_insecure_tls?,
622            };
623            r.guard(
624                config
625                    .env
626                    .reject_dev_shortcut("ALLOW_INSECURE_TLS", config.allow_insecure_tls),
627            );
628            Some(config)
629        }
630    }
631
632    #[test]
633    fn loads_valid_config_from_map() {
634        let cfg: ServerConfig = load_from(map(&[
635            ("APP_ENV", "staging"),
636            ("BIND_PORT", "8080"),
637            ("DATABASE_URL", "postgres://localhost/app"),
638        ]))
639        .expect("valid config");
640        assert_eq!(cfg.env, AppEnv::Staging);
641        assert_eq!(cfg.bind_port, 8080);
642        assert_eq!(cfg.database_url, "postgres://localhost/app");
643        assert!(!cfg.allow_insecure_tls);
644    }
645
646    #[test]
647    fn missing_required_var_is_a_startup_error_naming_the_var() {
648        let err = load_from::<ServerConfig>(map(&[("BIND_PORT", "8080")])).unwrap_err();
649        assert_eq!(err.problems().len(), 1);
650        assert!(err.problems()[0].contains("DATABASE_URL"));
651        assert!(err.to_string().contains("DATABASE_URL"));
652    }
653
654    #[test]
655    fn multiple_problems_are_reported_together() {
656        // DATABASE_URL missing AND BIND_PORT unparseable: both must surface.
657        let err = load_from::<ServerConfig>(map(&[("BIND_PORT", "not-a-number")])).unwrap_err();
658        assert_eq!(err.problems().len(), 2);
659        let joined = err.problems().join("\n");
660        assert!(joined.contains("BIND_PORT"));
661        assert!(joined.contains("DATABASE_URL"));
662    }
663
664    #[test]
665    fn production_guard_rejects_dev_shortcut() {
666        let err = load_from::<ServerConfig>(map(&[
667            ("APP_ENV", "production"),
668            ("BIND_PORT", "443"),
669            ("DATABASE_URL", "postgres://db/app"),
670            ("ALLOW_INSECURE_TLS", "true"),
671        ]))
672        .unwrap_err();
673        assert_eq!(err.problems().len(), 1);
674        assert!(err.problems()[0].contains("ALLOW_INSECURE_TLS"));
675        assert!(err.problems()[0].contains("production"));
676    }
677
678    #[test]
679    fn development_allows_the_same_dev_shortcut() {
680        let cfg: ServerConfig = load_from(map(&[
681            ("APP_ENV", "development"),
682            ("BIND_PORT", "8080"),
683            ("DATABASE_URL", "postgres://localhost/app"),
684            ("ALLOW_INSECURE_TLS", "true"),
685        ]))
686        .expect("dev permits the shortcut");
687        assert!(cfg.allow_insecure_tls);
688        assert!(cfg.env.is_development());
689    }
690
691    #[test]
692    fn invalid_bool_is_reported() {
693        let err = load_from::<ServerConfig>(map(&[
694            ("BIND_PORT", "8080"),
695            ("DATABASE_URL", "postgres://localhost/app"),
696            ("ALLOW_INSECURE_TLS", "maybe"),
697        ]))
698        .unwrap_err();
699        assert!(err.problems()[0].contains("ALLOW_INSECURE_TLS"));
700    }
701
702    #[test]
703    fn optional_parsed_falls_back_and_catches_typos() {
704        let mut r = EnvReader::from_map(map(&[("A", "7")]));
705        assert_eq!(r.optional_parsed::<u32>("A", 1), Some(7));
706        assert_eq!(r.optional_parsed::<u32>("MISSING", 42), Some(42));
707        assert_eq!(r.optional_parsed::<u32>("MISSING", 42), Some(42));
708        assert!(!r.has_problems());
709        let mut r2 = EnvReader::from_map(map(&[("A", "x")]));
710        assert_eq!(r2.optional_parsed::<u32>("A", 1), None);
711        assert!(r2.has_problems());
712    }
713}