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