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