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#[derive(Clone, Debug, Default, Deserialize, Serialize)]
11pub struct AppConfig {
12 #[serde(default)]
14 pub storage: crate::StorageSettings,
15 #[serde(default)]
17 pub mail: crate::MailSettings,
18 #[serde(default)]
20 pub jobs: crate::JobsSettings,
21 #[serde(default)]
23 pub auth: crate::AuthSettings,
24 pub app: AppSettings,
26 pub database: DatabaseSettings,
28 pub server: ServerSettings,
30 pub http: HttpSettings,
32 pub api: ApiSettings,
34}
35
36#[derive(Clone, Debug, Deserialize, Serialize)]
38#[serde(default, deny_unknown_fields)]
39pub struct ApiSettings {
40 pub require_documented_routes: bool,
42 pub title: Option<String>,
44 pub version: String,
46 pub openapi: bool,
48 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#[derive(Clone, Debug, Deserialize, Serialize)]
66#[serde(default, deny_unknown_fields)]
67pub struct ServerSettings {
68 pub host: Option<String>,
70 pub port: Option<u16>,
72 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#[derive(Clone, Debug, Deserialize, Serialize)]
88#[serde(default, deny_unknown_fields)]
89pub struct HttpSettings {
90 pub client_ip: crate::ClientIpSettings,
92 pub request_timeout_seconds: u64,
94 pub readiness_timeout_seconds: u64,
96 pub max_body_bytes: usize,
98 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#[derive(Clone, Debug, Deserialize, Serialize)]
116#[serde(default, deny_unknown_fields)]
117pub struct AppSettings {
118 pub url: Option<String>,
120 pub name: String,
122 pub environment: String,
124 pub host: String,
126 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#[derive(Clone, Deserialize, Serialize)]
144#[serde(default, deny_unknown_fields)]
145pub struct DatabaseSettings {
146 pub url: String,
148 pub max_connections: u32,
150 pub connect_timeout_seconds: u64,
152 pub min_connections: u32,
154 pub acquire_timeout_seconds: u64,
156 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 pub fn load() -> Result<Self> {
189 Self::load_from(".")
190 }
191
192 pub fn load_from(root: impl AsRef<Path>) -> Result<Self> {
195 Self::load_sections(root.as_ref(), true, false)
196 }
197
198 pub fn load_for_contracts() -> Result<Self> {
201 Self::load_sections(Path::new("."), false, false)
202 }
203
204 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 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 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 pub fn host(&self) -> &str {
518 self.server.host.as_deref().unwrap_or(&self.app.host)
519 }
520
521 pub fn port(&self) -> u16 {
523 self.server.port.unwrap_or(self.app.port)
524 }
525}
526
527impl DatabaseSettings {
528 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}