Skip to main content

phoenix_config/
lib.rs

1//! Layered and validated configuration for Phoenix applications.
2//!
3//! Values are merged in this order: optional `.env`, process environment,
4//! then explicit builder overrides. Production-only requirements are checked
5//! before the HTTP server or a management command starts.
6
7use std::{
8    collections::BTreeMap, error::Error, fmt, net::IpAddr, str::FromStr, sync::Arc, time::Duration,
9};
10
11use zeroize::Zeroizing;
12
13mod builder;
14mod files;
15mod validation;
16
17pub use builder::AppConfigBuilder;
18
19const DEFAULT_ADDRESS: &str = "127.0.0.1:3000";
20const DEFAULT_DATABASE_URL: &str = "sqlite:storage/app.sqlite";
21const DEFAULT_VITE_DEV_URL: &str = "http://127.0.0.1:5173";
22const DEFAULT_RATE_LIMIT_REQUESTS: u64 = 60;
23const DEFAULT_RATE_LIMIT_WINDOW_SECONDS: u64 = 60;
24const KNOWN_KEYS: &[&str] = &[
25    "ALLOWED_HOSTS",
26    "APP_ADDR",
27    "APP_ENV",
28    "APP_NAME",
29    "APP_URL",
30    "DATABASE_URL",
31    "DB_CONNECTION",
32    "DB_PASSWORD",
33    "RATE_LIMIT_REQUESTS",
34    "RATE_LIMIT_WINDOW_SECONDS",
35    "TRUSTED_PROXIES",
36    "VITE_DEV_URL",
37];
38
39/// Runtime mode controlling local defaults and production validation.
40#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
41pub enum Environment {
42    #[default]
43    Development,
44    Test,
45    Production,
46}
47
48impl Environment {
49    #[must_use]
50    pub const fn is_production(self) -> bool {
51        matches!(self, Self::Production)
52    }
53}
54
55impl FromStr for Environment {
56    type Err = ConfigError;
57
58    fn from_str(value: &str) -> Result<Self, Self::Err> {
59        match value.trim().to_ascii_lowercase().as_str() {
60            "development" | "dev" | "local" => Ok(Self::Development),
61            "test" | "testing" => Ok(Self::Test),
62            "production" | "prod" => Ok(Self::Production),
63            _ => Err(ConfigError::invalid(
64                "APP_ENV",
65                "expected development, test, or production",
66            )),
67        }
68    }
69}
70
71/// Secret configuration whose debug representation never exposes its value.
72#[derive(Clone)]
73pub struct SecretValue(Arc<Zeroizing<String>>);
74
75impl SecretValue {
76    #[must_use]
77    pub fn expose(&self) -> &str {
78        self.0.as_str()
79    }
80}
81
82impl fmt::Debug for SecretValue {
83    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
84        formatter.write_str("SecretValue([REDACTED])")
85    }
86}
87
88/// Validated application settings loaded once during process startup.
89#[derive(Clone)]
90pub struct AppConfig {
91    environment: Environment,
92    address: String,
93    public_url: String,
94    database_url: String,
95    vite_dev_url: Option<String>,
96    trusted_proxies: Arc<[IpAddr]>,
97    allowed_hosts: Arc<[String]>,
98    rate_limit_requests: u64,
99    rate_limit_window: Duration,
100    secrets: Arc<BTreeMap<String, SecretValue>>,
101}
102
103impl AppConfig {
104    #[must_use]
105    pub const fn environment(&self) -> Environment {
106        self.environment
107    }
108
109    #[must_use]
110    pub fn address(&self) -> &str {
111        &self.address
112    }
113
114    #[must_use]
115    pub fn public_url(&self) -> &str {
116        &self.public_url
117    }
118
119    #[must_use]
120    pub fn database_url(&self) -> &str {
121        &self.database_url
122    }
123
124    #[must_use]
125    pub fn vite_dev_url(&self) -> Option<&str> {
126        self.vite_dev_url.as_deref()
127    }
128
129    #[must_use]
130    pub fn trusted_proxies(&self) -> &[IpAddr] {
131        &self.trusted_proxies
132    }
133
134    #[must_use]
135    pub fn allowed_hosts(&self) -> &[String] {
136        &self.allowed_hosts
137    }
138
139    #[must_use]
140    pub const fn rate_limit_requests(&self) -> u64 {
141        self.rate_limit_requests
142    }
143
144    #[must_use]
145    pub const fn rate_limit_window(&self) -> Duration {
146        self.rate_limit_window
147    }
148
149    #[must_use]
150    pub fn secret(&self, key: &str) -> Option<&SecretValue> {
151        self.secrets.get(key)
152    }
153}
154
155impl fmt::Debug for AppConfig {
156    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
157        formatter
158            .debug_struct("AppConfig")
159            .field("environment", &self.environment)
160            .field("address", &self.address)
161            .field("public_url", &self.public_url)
162            .field("database_url", &"[REDACTED]")
163            .field("vite_dev_url", &self.vite_dev_url)
164            .field("trusted_proxies", &self.trusted_proxies)
165            .field("allowed_hosts", &self.allowed_hosts)
166            .field("rate_limit_requests", &self.rate_limit_requests)
167            .field("rate_limit_window", &self.rate_limit_window)
168            .field("secret_keys", &self.secrets.keys().collect::<Vec<_>>())
169            .finish()
170    }
171}
172
173/// Stable application configuration failure categories.
174#[derive(Debug)]
175pub enum ConfigError {
176    Dotenv(dotenvy::Error),
177    NonUnicode(String),
178    MissingProduction(&'static str),
179    Invalid {
180        key: &'static str,
181        reason: &'static str,
182    },
183    InvalidOwned {
184        key: String,
185        reason: String,
186    },
187    InvalidSecretRequirement(String),
188    MissingRequiredSecret(String),
189    SecretTooShort {
190        key: String,
191        minimum_bytes: usize,
192    },
193}
194
195impl ConfigError {
196    const fn invalid(key: &'static str, reason: &'static str) -> Self {
197        Self::Invalid { key, reason }
198    }
199
200    fn invalid_owned(key: impl Into<String>, reason: impl Into<String>) -> Self {
201        Self::InvalidOwned {
202            key: key.into(),
203            reason: reason.into(),
204        }
205    }
206}
207
208impl fmt::Display for ConfigError {
209    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
210        match self {
211            Self::Dotenv(error) => {
212                write!(formatter, "failed to load dotenv configuration: {error}")
213            }
214            Self::NonUnicode(key) => write!(formatter, "{key} must be valid Unicode"),
215            Self::MissingProduction(key) => {
216                write!(formatter, "production requires an explicit {key} value")
217            }
218            Self::Invalid { key, reason } => write!(formatter, "invalid {key}: {reason}"),
219            Self::InvalidOwned { key, reason } => write!(formatter, "invalid {key}: {reason}"),
220            Self::InvalidSecretRequirement(key) => {
221                write!(
222                    formatter,
223                    "invalid or duplicate required secret name `{key}`"
224                )
225            }
226            Self::MissingRequiredSecret(key) => {
227                write!(
228                    formatter,
229                    "production requires the application secret {key}"
230                )
231            }
232            Self::SecretTooShort { key, minimum_bytes } => {
233                write!(
234                    formatter,
235                    "{key} must contain at least {minimum_bytes} bytes"
236                )
237            }
238        }
239    }
240}
241
242impl Error for ConfigError {
243    fn source(&self) -> Option<&(dyn Error + 'static)> {
244        match self {
245            Self::Dotenv(error) => Some(error),
246            Self::NonUnicode(_)
247            | Self::MissingProduction(_)
248            | Self::Invalid { .. }
249            | Self::InvalidOwned { .. }
250            | Self::InvalidSecretRequirement(_)
251            | Self::MissingRequiredSecret(_)
252            | Self::SecretTooShort { .. } => None,
253        }
254    }
255}