Skip to main content

capy_core/
config.rs

1use crate::{AppError, Result};
2use figment::{
3    providers::{Env, Format, Serialized, Toml},
4    Figment,
5};
6use serde::{Deserialize, Serialize};
7use std::{collections::BTreeMap, path::Path};
8
9/// Application and database settings, resolved before startup.
10#[derive(Clone, Debug, Default, Deserialize, Serialize)]
11pub struct AppConfig {
12    /// Optional outbound communication settings (`MAIL_*`).
13    #[serde(default)]
14    pub mail: crate::MailSettings,
15    /// Optional durable worker settings (`JOBS_*`).
16    #[serde(default)]
17    pub jobs: crate::JobsSettings,
18    /// Optional identity subsystem settings (`AUTH_*`); activated by `App::auth`.
19    #[serde(default)]
20    pub auth: crate::AuthSettings,
21    /// HTTP server settings.
22    pub app: AppSettings,
23    /// Database connection settings.
24    pub database: DatabaseSettings,
25    /// Listener overrides and bounded graceful shutdown (`SERVER_*`).
26    pub server: ServerSettings,
27    /// Request and readiness bounds (`HTTP_*`).
28    pub http: HttpSettings,
29    /// API document metadata and explicit documentation exposure (`API_*`).
30    pub api: ApiSettings,
31}
32
33/// Small application-owned API metadata. Documentation is disabled by default.
34#[derive(Clone, Debug, Deserialize, Serialize)]
35#[serde(default, deny_unknown_fields)]
36pub struct ApiSettings {
37    /// Document title; defaults to the application name when omitted.
38    pub title: Option<String>,
39    /// Public API contract version, independent of the Capy package version.
40    pub version: String,
41    /// Explicitly expose GET /openapi.json, including in production.
42    pub openapi: bool,
43    /// Expose Scalar at /docs/api in development/test only; also enables the schema there.
44    pub docs: bool,
45}
46
47impl Default for ApiSettings {
48    fn default() -> Self {
49        Self {
50            title: None,
51            version: "1.0.0".into(),
52            openapi: false,
53            docs: false,
54        }
55    }
56}
57
58/// Listener settings. Unspecified host/port retain legacy `APP_HOST`/`APP_PORT`.
59#[derive(Clone, Debug, Deserialize, Serialize)]
60#[serde(default, deny_unknown_fields)]
61pub struct ServerSettings {
62    /// Explicit listener interface or hostname; overrides `app.host`.
63    pub host: Option<String>,
64    /// Explicit listener port; overrides `app.port`.
65    pub port: Option<u16>,
66    /// Maximum graceful drain time in seconds (1..=3600).
67    pub shutdown_timeout_seconds: u64,
68}
69
70impl Default for ServerSettings {
71    fn default() -> Self {
72        Self {
73            host: None,
74            port: None,
75            shutdown_timeout_seconds: 10,
76        }
77    }
78}
79
80/// Small HTTP policy surface, expressed in seconds and bytes to avoid ambiguous units.
81#[derive(Clone, Debug, Deserialize, Serialize)]
82#[serde(default, deny_unknown_fields)]
83pub struct HttpSettings {
84    /// Explicit socket/trusted proxy client identity policy.
85    pub client_ip: crate::ClientIpSettings,
86    /// Deadline until response headers (0 disables it, otherwise at most 86400).
87    pub request_timeout_seconds: u64,
88    /// Independent readiness database probe timeout (1..=30 seconds).
89    pub readiness_timeout_seconds: u64,
90    /// Default body limit in bytes (1..=1073741824); native route overrides remain possible.
91    pub max_body_bytes: usize,
92    /// Enable negotiated gzip response compression with Tower's default predicate.
93    pub compression: bool,
94}
95
96impl Default for HttpSettings {
97    fn default() -> Self {
98        Self {
99            client_ip: crate::ClientIpSettings::default(),
100            request_timeout_seconds: 30,
101            readiness_timeout_seconds: 2,
102            max_body_bytes: 2 * 1024 * 1024,
103            compression: true,
104        }
105    }
106}
107
108/// HTTP server and logging settings. Environment variables use `APP_`.
109#[derive(Clone, Debug, Deserialize, Serialize)]
110#[serde(default, deny_unknown_fields)]
111pub struct AppSettings {
112    /// Explicit public application URL, never inferred from request headers.
113    pub url: Option<String>,
114    /// Display name of this application.
115    pub name: String,
116    /// `development`, `test`, or `production`.
117    pub environment: String,
118    /// Interface or hostname to bind.
119    pub host: String,
120    /// TCP port to bind (zero allows the OS to choose).
121    pub port: u16,
122}
123
124impl Default for AppSettings {
125    fn default() -> Self {
126        Self {
127            url: None,
128            name: "Capy".into(),
129            environment: "development".into(),
130            host: "127.0.0.1".into(),
131            port: 8000,
132        }
133    }
134}
135
136/// SeaORM connection settings. Environment variables use `DATABASE_`.
137#[derive(Clone, Deserialize, Serialize)]
138#[serde(default, deny_unknown_fields)]
139pub struct DatabaseSettings {
140    /// PostgreSQL or SQLite connection URL. Debug output redacts this value.
141    pub url: String,
142    /// Maximum pool size; SQLite in-memory databases always use one connection.
143    pub max_connections: u32,
144    /// Maximum time to initialize the connection pool, in seconds.
145    pub connect_timeout_seconds: u64,
146    /// Minimum idle connections; cannot exceed the configured maximum.
147    pub min_connections: u32,
148    /// Maximum wait for an available connection, in seconds.
149    pub acquire_timeout_seconds: u64,
150    /// Maximum idle lifetime in seconds (1..=86400).
151    pub idle_timeout_seconds: u64,
152}
153
154impl std::fmt::Debug for DatabaseSettings {
155    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
156        f.debug_struct("DatabaseSettings")
157            .field("url", &"[redacted]")
158            .field("max_connections", &self.max_connections)
159            .field("connect_timeout_seconds", &self.connect_timeout_seconds)
160            .field("min_connections", &self.min_connections)
161            .field("acquire_timeout_seconds", &self.acquire_timeout_seconds)
162            .field("idle_timeout_seconds", &self.idle_timeout_seconds)
163            .finish()
164    }
165}
166
167impl Default for DatabaseSettings {
168    fn default() -> Self {
169        Self {
170            url: String::new(),
171            max_connections: 10,
172            connect_timeout_seconds: 10,
173            min_connections: 0,
174            acquire_timeout_seconds: 10,
175            idle_timeout_seconds: 600,
176        }
177    }
178}
179
180impl AppConfig {
181    /// Load from the current project directory.
182    pub fn load() -> Result<Self> {
183        Self::load_from(".")
184    }
185
186    /// Resolve defaults < TOML files < `.env` < process environment.
187    /// Reading `.env` never mutates the process environment.
188    pub fn load_from(root: impl AsRef<Path>) -> Result<Self> {
189        Self::load_sections(root.as_ref(), true)
190    }
191
192    /// Load metadata for offline contract export. A database URL is not required.
193    /// All supplied configuration is parsed, but no connection is ever opened.
194    pub fn load_for_contracts() -> Result<Self> {
195        Self::load_sections(Path::new("."), false)
196    }
197
198    fn load_sections(root: &Path, require_database: bool) -> Result<Self> {
199        let mut app_env = BTreeMap::new();
200        let mut db_env = BTreeMap::new();
201        let mut server_env = BTreeMap::new();
202        let mut http_env = serde_json::Map::new();
203        let mut client_ip_env = serde_json::Map::new();
204        let mut api_env = BTreeMap::new();
205        let mut auth_env = serde_json::Map::new();
206        let mut password_env = serde_json::Map::new();
207        let mut throttle_env = serde_json::Map::new();
208        let mut throttle_ip_env = serde_json::Map::new();
209        let mut throttle_account_env = serde_json::Map::new();
210        let mut jobs_env = BTreeMap::new();
211        let mut mail_env = serde_json::Map::new();
212        let mut smtp_env = serde_json::Map::new();
213        match dotenvy::from_path_iter(root.join(".env")) {
214            Ok(entries) => {
215                for entry in entries {
216                    let (key, value) = entry.map_err(|_| {
217                        AppError::Configuration("Could not parse .env. Check its syntax.".into())
218                    })?;
219                    let value =
220                        if matches!(key.as_str(), "MAIL_SMTP_USERNAME" | "MAIL_SMTP_PASSWORD") {
221                            serde_json::Value::String(value)
222                        } else {
223                            serde_json::from_str::<serde_json::Value>(&value)
224                                .unwrap_or(serde_json::Value::String(value))
225                        };
226                    if let Some(key) = key.strip_prefix("MAIL_SMTP_") {
227                        smtp_env.insert(key.to_lowercase(), value);
228                    } else if let Some(key) = key.strip_prefix("MAIL_") {
229                        mail_env.insert(key.to_lowercase(), value);
230                    } else if let Some(key) = key.strip_prefix("JOBS_") {
231                        jobs_env.insert(key.to_lowercase(), value);
232                    } else if key.starts_with("AUTH_PASSWORD_")
233                        && key != "AUTH_PASSWORD_RESET_LIFETIME_SECONDS"
234                    {
235                        password_env.insert(key[14..].to_lowercase(), value);
236                    } else if let Some(key) = key.strip_prefix("AUTH_THROTTLE_IP_") {
237                        throttle_ip_env.insert(key.to_lowercase(), value);
238                    } else if let Some(key) = key.strip_prefix("AUTH_THROTTLE_ACCOUNT_") {
239                        throttle_account_env.insert(key.to_lowercase(), value);
240                    } else if let Some(key) = key.strip_prefix("AUTH_THROTTLE_") {
241                        throttle_env.insert(key.to_lowercase(), value);
242                    } else if let Some(key) = key.strip_prefix("AUTH_") {
243                        auth_env.insert(key.to_lowercase(), value);
244                    } else if let Some(key) = key.strip_prefix("APP_") {
245                        app_env.insert(key.to_lowercase(), value);
246                    } else if let Some(key) = key.strip_prefix("DATABASE_") {
247                        db_env.insert(key.to_lowercase(), value);
248                    } else if let Some(key) = key.strip_prefix("SERVER_") {
249                        server_env.insert(key.to_lowercase(), value);
250                    } else if let Some(key) = key.strip_prefix("HTTP_CLIENT_IP_") {
251                        client_ip_env.insert(key.to_lowercase(), value);
252                    } else if let Some(key) = key.strip_prefix("HTTP_") {
253                        http_env.insert(key.to_lowercase(), value);
254                    } else if let Some(key) = key.strip_prefix("API_") {
255                        api_env.insert(key.to_lowercase(), value);
256                    }
257                }
258            }
259            Err(dotenvy::Error::Io(e)) if e.kind() == std::io::ErrorKind::NotFound => {}
260            Err(_) => return Err(AppError::Configuration("Could not read .env.".into())),
261        }
262        let app = Figment::from(Serialized::defaults(AppSettings::default()))
263            .merge(Toml::file(root.join("config/app.toml")))
264            .merge(Serialized::defaults(app_env))
265            .merge(Env::prefixed("APP_"))
266            .extract()
267            .map_err(|_| {
268                AppError::Configuration(
269                    "Invalid application settings. Check config/app.toml and APP_* variables."
270                        .into(),
271                )
272            })?;
273        let database = Figment::from(Serialized::defaults(DatabaseSettings::default()))
274            .merge(Toml::file(root.join("config/database.toml")))
275            .merge(Serialized::defaults(db_env))
276            .merge(Env::prefixed("DATABASE_"))
277            .extract()
278            .map_err(|_| AppError::Configuration(
279                "Invalid database settings. Check config/database.toml and DATABASE_* variables.".into(),
280            ))?;
281        let server = Figment::from(Serialized::defaults(ServerSettings::default()))
282            .merge(Toml::file(root.join("config/server.toml")))
283            .merge(Serialized::defaults(server_env))
284            .merge(Env::prefixed("SERVER_"))
285            .extract()
286            .map_err(|_| AppError::Configuration(
287                "Invalid server settings. Check config/server.toml and SERVER_* variables; ports must be 0..=65535 and deadlines integer seconds.".into()))?;
288        http_env.insert("client_ip".into(), serde_json::Value::Object(client_ip_env));
289        let http = Figment::from(Serialized::defaults(HttpSettings::default()))
290            .merge(Toml::file(root.join("config/http.toml")))
291            .merge(Serialized::defaults(http_env))
292            .merge(Env::prefixed("HTTP_").map(|key| key.as_str().to_lowercase().replacen("client_ip_", "client_ip.", 1).into()))
293            .extract()
294            .map_err(|_| AppError::Configuration(
295                "Invalid HTTP settings. Check config/http.toml and HTTP_* variables: deadlines use integer seconds, body limits integer bytes; client_ip.strategy must be direct/forwarded/x-forwarded-for/x-real-ip, trusted_proxies a CIDR array, and require_proxy a boolean.".into()))?;
296        let api = Figment::from(Serialized::defaults(ApiSettings::default()))
297            .merge(Toml::file(root.join("config/api.toml")))
298            .merge(Serialized::defaults(api_env))
299            .merge(Env::prefixed("API_"))
300            .extract()
301            .map_err(|_| {
302                AppError::Configuration(
303                    "Invalid API settings. Check config/api.toml and API_* variables.".into(),
304                )
305            })?;
306        throttle_env.insert("ip".into(), serde_json::Value::Object(throttle_ip_env));
307        throttle_env.insert(
308            "account".into(),
309            serde_json::Value::Object(throttle_account_env),
310        );
311        auth_env.insert("throttle".into(), serde_json::Value::Object(throttle_env));
312        auth_env.insert("password".into(), serde_json::Value::Object(password_env));
313        let auth = Figment::from(Serialized::defaults(crate::AuthSettings::default()))
314            .merge(Toml::file(root.join("config/auth.toml")))
315            .merge(Serialized::defaults(auth_env))
316            .merge(Env::prefixed("AUTH_").map(|key| {
317                let key = key.as_str().to_lowercase();
318                if let Some(setting) = key.strip_prefix("throttle_") {
319                    return format!("throttle.{}", setting.replacen("ip_", "ip.", 1).replacen("account_", "account.", 1)).into();
320                }
321                match key.strip_prefix("password_") {
322                    Some(setting) if setting != "reset_lifetime_seconds" => {
323                        format!("password.{setting}").into()
324                    }
325                    _ => key.into(),
326                }
327            }))
328            .extract()
329            .map_err(|_| {
330                AppError::Configuration(
331                    "Invalid auth settings. Check config/auth.toml and AUTH_* variables; use [password] hash_concurrency = \"auto\" or an integer, integer cost/queue limits, and AUTH_PASSWORD_* environment overrides.".into(),
332                )
333            })?;
334        let jobs = Figment::from(Serialized::defaults(crate::JobsSettings::default()))
335            .merge(Toml::file(root.join("config/jobs.toml")))
336            .merge(Serialized::defaults(jobs_env))
337            .merge(Env::prefixed("JOBS_"))
338            .extract()
339            .map_err(|_| {
340                AppError::Configuration(
341                    "Invalid jobs settings. Check config/jobs.toml and JOBS_* variables.".into(),
342                )
343            })?;
344        // Credentials are literal text, even when they resemble numbers, booleans
345        // or JSON. Preserve their bytes instead of applying environment coercion.
346        for (key, variable) in [
347            ("username", "MAIL_SMTP_USERNAME"),
348            ("password", "MAIL_SMTP_PASSWORD"),
349        ] {
350            match std::env::var(variable) {
351                Ok(value) => {
352                    smtp_env.insert(key.into(), serde_json::Value::String(value));
353                }
354                Err(std::env::VarError::NotPresent) => {}
355                Err(_) => {
356                    return Err(AppError::Configuration(
357                        "SMTP credentials must be valid UTF-8 (values redacted).".into(),
358                    ));
359                }
360            }
361        }
362        mail_env.insert("smtp".into(), serde_json::Value::Object(smtp_env));
363        let mail = Figment::from(Serialized::defaults(crate::MailSettings::default()))
364            .merge(Toml::file(root.join("config/mail.toml")))
365            .merge(Serialized::defaults(mail_env))
366            .merge(Env::prefixed("MAIL_").ignore(&["smtp_username", "smtp_password"]).map(|key| key.as_str().to_lowercase().replacen("smtp_", "smtp.", 1).into()))
367            .extract()
368            .map_err(|_| AppError::Configuration("Invalid mail settings. Check config/mail.toml and MAIL_* variables (credentials redacted).".into()))?;
369        let config = Self {
370            mail,
371            jobs,
372            auth,
373            app,
374            database,
375            server,
376            http,
377            api,
378        };
379        config.validate_application()?;
380        if require_database {
381            config.database.validate()?;
382        }
383        Ok(config)
384    }
385
386    /// Validate manually constructed configuration as well as loaded settings.
387    pub fn validate(&self) -> Result<()> {
388        self.validate_application()?;
389        self.database.validate()
390    }
391
392    fn validate_application(&self) -> Result<()> {
393        self.http.client_ip.validate()?;
394        self.auth.password.concurrency()?;
395        self.auth.throttle.validate()?;
396        self.jobs.validate()?;
397        self.mail.validate()?;
398        if self
399            .api
400            .title
401            .as_ref()
402            .is_some_and(|title| title.trim().is_empty())
403            || self.api.version.trim().is_empty()
404        {
405            return Err(AppError::Configuration(
406                "API_TITLE (when set) and API_VERSION must not be empty.".into(),
407            ));
408        }
409        if self.app.name.trim().is_empty() || self.app.host.trim().is_empty() {
410            return Err(AppError::Configuration(
411                "APP_NAME and APP_HOST cannot be empty.".into(),
412            ));
413        }
414        if !matches!(
415            self.app.environment.as_str(),
416            "development" | "test" | "production"
417        ) {
418            return Err(AppError::Configuration(
419                "APP_ENVIRONMENT must be development, test, or production.".into(),
420            ));
421        }
422        if self.host().trim().is_empty() || self.host().chars().any(char::is_whitespace) {
423            return Err(AppError::Configuration(
424                "SERVER_HOST must be a hostname or IP address without whitespace.".into(),
425            ));
426        }
427        if self.app.environment == "production" && self.port() == 0 {
428            return Err(AppError::Configuration(
429                "The production server port must be 1..=65535.".into(),
430            ));
431        }
432        if !(1..=3600).contains(&self.server.shutdown_timeout_seconds) {
433            return Err(AppError::Configuration(
434                "SERVER_SHUTDOWN_TIMEOUT_SECONDS must be 1..=3600.".into(),
435            ));
436        }
437        if self.http.request_timeout_seconds > 86400 {
438            return Err(AppError::Configuration("HTTP_REQUEST_TIMEOUT_SECONDS must be 0..=86400 (0 intentionally disables the deadline).".into()));
439        }
440        if !(1..=30).contains(&self.http.readiness_timeout_seconds) {
441            return Err(AppError::Configuration(
442                "HTTP_READINESS_TIMEOUT_SECONDS must be 1..=30.".into(),
443            ));
444        }
445        if !(1..=1024 * 1024 * 1024).contains(&self.http.max_body_bytes) {
446            return Err(AppError::Configuration(
447                "HTTP_MAX_BODY_BYTES must be 1..=1073741824.".into(),
448            ));
449        }
450        Ok(())
451    }
452
453    /// Effective listener host, including explicit server overrides.
454    pub fn host(&self) -> &str {
455        self.server.host.as_deref().unwrap_or(&self.app.host)
456    }
457
458    /// Effective listener port, including explicit server overrides.
459    pub fn port(&self) -> u16 {
460        self.server.port.unwrap_or(self.app.port)
461    }
462}
463
464impl DatabaseSettings {
465    /// Validate supported backends and pool limits without exposing credentials.
466    pub fn validate(&self) -> Result<()> {
467        if self.url.trim().is_empty() {
468            return Err(AppError::Configuration(
469                "Database configuration error: DATABASE_URL is missing.".into(),
470            ));
471        }
472        if !(self.url.starts_with("postgres://")
473            || self.url.starts_with("postgresql://")
474            || self.url.starts_with("sqlite:"))
475        {
476            return Err(AppError::Configuration(
477                "DATABASE_URL must use PostgreSQL or SQLite.".into(),
478            ));
479        }
480        if self.max_connections == 0
481            || self.max_connections > 10_000
482            || self.min_connections > self.max_connections
483            || !(1..=3600).contains(&self.connect_timeout_seconds)
484            || !(1..=3600).contains(&self.acquire_timeout_seconds)
485            || !(1..=86400).contains(&self.idle_timeout_seconds)
486        {
487            return Err(AppError::Configuration(
488                "Invalid database pool: max_connections must be 1..=10000, min_connections <= max_connections, connect/acquire timeouts 1..=3600 seconds, idle timeout 1..=86400 seconds.".into(),
489            ));
490        }
491        Ok(())
492    }
493}