1use serde::{Deserialize, Serialize};
5use std::collections::HashMap;
6use std::fs;
7use std::path::{Path, PathBuf};
8use thiserror::Error;
9
10#[derive(Debug, Error)]
11pub enum ConfigError {
12 #[error("Configuration file not found: {0}")]
13 FileNotFound(String),
14 #[error("Invalid configuration format: {0}")]
15 InvalidFormat(String),
16 #[error("Configuration validation error: {0}")]
17 Validation(String),
18 #[error("Environment variable error: {0}")]
19 Environment(String),
20 #[error("IO error: {0}")]
21 Io(#[from] std::io::Error),
22 #[error("Serialization error: {0}")]
23 Serialization(#[from] serde_json::Error),
24 #[error("TOML parsing error: {0}")]
25 Toml(#[from] toml::de::Error),
26 #[error("YAML parsing error: {0}")]
27 Yaml(#[from] serde_yaml::Error),
28}
29
30#[derive(Debug, Clone)]
32pub enum ConfigFormat {
33 Json,
34 Toml,
35 Yaml,
36 Environment,
37}
38
39#[derive(Clone, Serialize, Deserialize)]
41pub struct EnvironmentConfig {
42 pub name: String,
43 pub variables: HashMap<String, String>,
44 pub overrides: HashMap<String, serde_json::Value>,
45 pub secrets: Vec<String>,
46 pub required_vars: Vec<String>,
47}
48
49impl std::fmt::Debug for EnvironmentConfig {
50 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
51 let mut d = f.debug_struct("EnvironmentConfig");
52 d.field("name", &self.name);
53 d.field(
54 "variables",
55 &crate::utils::redact::redacted(&self.variables),
56 );
57 d.field(
58 "overrides",
59 &crate::utils::redact::redacted(&self.overrides),
60 );
61 d.field("secrets", &crate::utils::redact::redacted(&self.secrets));
62 d.field("required_vars", &self.required_vars);
63 d.finish()
64 }
65}
66
67#[derive(Clone, Serialize, Deserialize)]
69pub struct DatabaseConfig {
70 pub host: String,
71 pub port: u16,
72 pub database: String,
73 pub username: String,
74 pub password: String,
75 pub ssl_mode: String,
76 pub pool_size: u32,
77 pub timeout: u64,
78}
79
80impl std::fmt::Debug for DatabaseConfig {
81 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
82 let mut d = f.debug_struct("DatabaseConfig");
83 d.field("host", &self.host);
84 d.field("port", &self.port);
85 d.field("database", &self.database);
86 d.field("username", &self.username);
87 d.field("password", &crate::utils::redact::redacted(&self.password));
88 d.field("ssl_mode", &self.ssl_mode);
89 d.field("pool_size", &self.pool_size);
90 d.field("timeout", &self.timeout);
91 d.finish()
92 }
93}
94
95#[derive(Clone, Serialize, Deserialize)]
97pub struct ServerConfig {
98 pub host: String,
99 pub port: u16,
100 pub workers: u32,
101 pub max_connections: u32,
102 pub timeout: u64,
103 pub tls_cert: Option<String>,
104 pub tls_key: Option<String>,
105}
106
107impl std::fmt::Debug for ServerConfig {
108 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
109 let mut d = f.debug_struct("ServerConfig");
110 d.field("host", &self.host);
111 d.field("port", &self.port);
112 d.field("workers", &self.workers);
113 d.field("max_connections", &self.max_connections);
114 d.field("timeout", &self.timeout);
115 d.field("tls_cert", &self.tls_cert);
116 d.field("tls_key", &crate::utils::redact::redacted(&self.tls_key));
117 d.finish()
118 }
119}
120
121#[derive(Debug, Clone, Serialize, Deserialize)]
123pub struct LoggingConfig {
124 pub level: String,
125 pub format: String,
126 pub output: Vec<String>,
127 pub rotation: Option<LogRotationConfig>,
128 pub structured: bool,
129}
130
131#[derive(Debug, Clone, Serialize, Deserialize)]
132pub struct LogRotationConfig {
133 pub size: String,
134 pub keep: u32,
135 pub compress: bool,
136}
137
138#[derive(Clone, Serialize, Deserialize)]
140pub struct SecurityConfig {
141 pub jwt_secret: String,
142 pub session_timeout: u64,
143 pub bcrypt_cost: u32,
144 pub rate_limiting: RateLimitConfig,
145 pub cors: CorsConfig,
146}
147
148impl std::fmt::Debug for SecurityConfig {
149 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
150 let mut d = f.debug_struct("SecurityConfig");
151 d.field(
152 "jwt_secret",
153 &crate::utils::redact::redacted(&self.jwt_secret),
154 );
155 d.field("session_timeout", &self.session_timeout);
156 d.field("bcrypt_cost", &self.bcrypt_cost);
157 d.field("rate_limiting", &self.rate_limiting);
158 d.field("cors", &self.cors);
159 d.finish()
160 }
161}
162
163#[derive(Debug, Clone, Serialize, Deserialize)]
164pub struct RateLimitConfig {
165 pub enabled: bool,
166 pub requests_per_minute: u32,
167 pub burst_size: u32,
168 pub whitelist: Vec<String>,
169}
170
171#[derive(Debug, Clone, Serialize, Deserialize)]
172pub struct CorsConfig {
173 pub enabled: bool,
174 pub allowed_origins: Vec<String>,
175 pub allowed_methods: Vec<String>,
176 pub allowed_headers: Vec<String>,
177 pub max_age: u32,
178}
179
180#[derive(Debug, Clone, Serialize, Deserialize)]
182pub struct AppConfig {
183 pub environment: String,
184 pub debug: bool,
185 pub server: ServerConfig,
186 pub database: DatabaseConfig,
187 pub logging: LoggingConfig,
188 pub security: SecurityConfig,
189 pub features: HashMap<String, bool>,
190 pub custom: HashMap<String, serde_json::Value>,
191}
192
193pub struct ConfigManager {
195 config: AppConfig,
196 config_path: PathBuf,
197 format: ConfigFormat,
198 environments: HashMap<String, EnvironmentConfig>,
199 watchers: Vec<Box<dyn ConfigWatcher>>,
200}
201
202pub trait ConfigWatcher: Send + Sync {
204 fn on_config_changed(&self, config: &AppConfig) -> Result<(), ConfigError>;
205}
206
207impl Default for ConfigManager {
208 fn default() -> Self {
209 Self::new()
210 }
211}
212
213impl ConfigManager {
214 pub fn new() -> Self {
216 Self {
217 config: AppConfig::default(),
218 config_path: PathBuf::from("config.toml"),
219 format: ConfigFormat::Toml,
220 environments: HashMap::new(),
221 watchers: Vec::new(),
222 }
223 }
224
225 pub fn load_from_file<P: AsRef<Path>>(&mut self, path: P) -> Result<(), ConfigError> {
227 let path = path.as_ref();
228 self.config_path = path.to_path_buf();
229
230 self.format = match path.extension().and_then(|ext| ext.to_str()) {
232 Some("json") => ConfigFormat::Json,
233 Some("toml") => ConfigFormat::Toml,
234 Some("yaml") | Some("yml") => ConfigFormat::Yaml,
235 _ => ConfigFormat::Toml,
236 };
237
238 let content = fs::read_to_string(path)
239 .map_err(|_| ConfigError::FileNotFound(path.display().to_string()))?;
240
241 self.config = self.parse_config(&content)?;
242 self.validate_config()?;
243
244 Ok(())
245 }
246
247 pub fn load_from_env(&mut self) -> Result<(), ConfigError> {
249 self.format = ConfigFormat::Environment;
250
251 let mut config = AppConfig::default();
252
253 if let Ok(host) = std::env::var("SERVER_HOST") {
255 config.server.host = host;
256 }
257 if let Ok(port) = std::env::var("SERVER_PORT") {
258 config.server.port = port
259 .parse()
260 .map_err(|_| ConfigError::Environment("Invalid SERVER_PORT".to_string()))?;
261 }
262
263 if let Ok(host) = std::env::var("DATABASE_HOST") {
265 config.database.host = host;
266 }
267 if let Ok(port) = std::env::var("DATABASE_PORT") {
268 config.database.port = port
269 .parse()
270 .map_err(|_| ConfigError::Environment("Invalid DATABASE_PORT".to_string()))?;
271 }
272 if let Ok(database) = std::env::var("DATABASE_NAME") {
273 config.database.database = database;
274 }
275 if let Ok(username) = std::env::var("DATABASE_USER") {
276 config.database.username = username;
277 }
278 if let Ok(password) = std::env::var("DATABASE_PASSWORD") {
279 config.database.password = password;
280 }
281
282 if let Ok(jwt_secret) = std::env::var("JWT_SECRET") {
284 config.security.jwt_secret = jwt_secret;
285 }
286
287 if let Ok(env) = std::env::var("ENVIRONMENT") {
289 config.environment = env;
290 }
291
292 self.config = config;
293 self.validate_config()?;
294
295 Ok(())
296 }
297
298 fn parse_config(&self, content: &str) -> Result<AppConfig, ConfigError> {
300 match self.format {
301 ConfigFormat::Json => {
302 serde_json::from_str(content).map_err(|e| ConfigError::InvalidFormat(e.to_string()))
303 }
304 ConfigFormat::Toml => {
305 toml::from_str(content).map_err(|e| ConfigError::InvalidFormat(e.to_string()))
306 }
307 ConfigFormat::Yaml => {
308 serde_yaml::from_str(content).map_err(|e| ConfigError::InvalidFormat(e.to_string()))
309 }
310 ConfigFormat::Environment => Err(ConfigError::InvalidFormat(
311 "Environment loading not supported here".to_string(),
312 )),
313 }
314 }
315
316 fn validate_config(&self) -> Result<(), ConfigError> {
318 if self.config.server.host.is_empty() {
320 return Err(ConfigError::Validation(
321 "Server host cannot be empty".to_string(),
322 ));
323 }
324 if self.config.server.port == 0 {
325 return Err(ConfigError::Validation(
326 "Server port must be greater than 0".to_string(),
327 ));
328 }
329 if self.config.server.workers == 0 {
330 return Err(ConfigError::Validation(
331 "Server workers must be greater than 0".to_string(),
332 ));
333 }
334
335 if self.config.database.host.is_empty() {
337 return Err(ConfigError::Validation(
338 "Database host cannot be empty".to_string(),
339 ));
340 }
341 if self.config.database.port == 0 {
342 return Err(ConfigError::Validation(
343 "Database port must be greater than 0".to_string(),
344 ));
345 }
346 if self.config.database.database.is_empty() {
347 return Err(ConfigError::Validation(
348 "Database name cannot be empty".to_string(),
349 ));
350 }
351
352 if self.config.security.jwt_secret.is_empty() {
354 return Err(ConfigError::Validation(
355 "JWT secret cannot be empty".to_string(),
356 ));
357 }
358 if self.config.security.jwt_secret.len() < 32 {
359 return Err(ConfigError::Validation(
360 "JWT secret must be at least 32 characters".to_string(),
361 ));
362 }
363 if self.config.security.bcrypt_cost < 4 || self.config.security.bcrypt_cost > 31 {
364 return Err(ConfigError::Validation(
365 "Bcrypt cost must be between 4 and 31".to_string(),
366 ));
367 }
368
369 let valid_levels = ["trace", "debug", "info", "warn", "error"];
371 if !valid_levels.contains(&self.config.logging.level.as_str()) {
372 return Err(ConfigError::Validation("Invalid logging level".to_string()));
373 }
374
375 Ok(())
376 }
377
378 pub fn get_config(&self) -> &AppConfig {
380 &self.config
381 }
382
383 pub fn set_value(&mut self, key: &str, value: serde_json::Value) -> Result<(), ConfigError> {
385 let parts: Vec<&str> = key.split('.').collect();
387
388 match parts.as_slice() {
389 ["server", "host"] => {
390 if let Some(host) = value.as_str() {
391 self.config.server.host = host.to_string();
392 } else {
393 return Err(ConfigError::Validation(
394 "Server host must be a string".to_string(),
395 ));
396 }
397 }
398 ["server", "port"] => {
399 if let Some(port) = value.as_u64() {
400 self.config.server.port = port as u16;
401 } else {
402 return Err(ConfigError::Validation(
403 "Server port must be a number".to_string(),
404 ));
405 }
406 }
407 ["database", "host"] => {
408 if let Some(host) = value.as_str() {
409 self.config.database.host = host.to_string();
410 } else {
411 return Err(ConfigError::Validation(
412 "Database host must be a string".to_string(),
413 ));
414 }
415 }
416 ["database", "port"] => {
417 if let Some(port) = value.as_u64() {
418 self.config.database.port = port as u16;
419 } else {
420 return Err(ConfigError::Validation(
421 "Database port must be a number".to_string(),
422 ));
423 }
424 }
425 ["features", feature] => {
426 if let Some(feature_value) = value.as_bool() {
427 self.config
428 .features
429 .insert(feature.to_string(), feature_value);
430 } else {
431 return Err(ConfigError::Validation(
432 "Feature value must be boolean".to_string(),
433 ));
434 }
435 }
436 ["custom", custom_key] => {
437 self.config.custom.insert(custom_key.to_string(), value);
438 }
439 _ => {
440 return Err(ConfigError::Validation(format!(
441 "Unknown configuration key: {}",
442 key
443 )));
444 }
445 }
446
447 self.validate_config()?;
448 self.notify_watchers()?;
449
450 Ok(())
451 }
452
453 pub fn add_environment(&mut self, name: String, env_config: EnvironmentConfig) {
455 self.environments.insert(name, env_config);
456 }
457
458 pub fn switch_environment(&mut self, env_name: &str) -> Result<(), ConfigError> {
460 let overrides = if let Some(env_config) = self.environments.get(env_name) {
461 env_config.overrides.clone()
462 } else {
463 return Err(ConfigError::Validation(format!(
464 "Environment not found: {}",
465 env_name
466 )));
467 };
468
469 for (key, value) in &overrides {
471 self.set_value(key, value.clone())?;
472 }
473
474 self.config.environment = env_name.to_string();
475 self.notify_watchers()?;
476
477 Ok(())
478 }
479
480 pub fn add_watcher(&mut self, watcher: Box<dyn ConfigWatcher>) {
482 self.watchers.push(watcher);
483 }
484
485 fn notify_watchers(&self) -> Result<(), ConfigError> {
487 for watcher in &self.watchers {
488 watcher.on_config_changed(&self.config)?;
489 }
490 Ok(())
491 }
492
493 pub fn save_to_file<P: AsRef<Path>>(&self, path: P) -> Result<(), ConfigError> {
495 let content = match self.format {
496 ConfigFormat::Json => serde_json::to_string_pretty(&self.config)?,
497 ConfigFormat::Toml => toml::to_string(&self.config)
498 .map_err(|e| ConfigError::InvalidFormat(e.to_string()))?,
499 ConfigFormat::Yaml => serde_yaml::to_string(&self.config)
500 .map_err(|e| ConfigError::InvalidFormat(e.to_string()))?,
501 ConfigFormat::Environment => {
502 return Err(ConfigError::InvalidFormat(
503 "Cannot save environment config to file".to_string(),
504 ));
505 }
506 };
507
508 fs::write(path, content)?;
509 Ok(())
510 }
511
512 pub fn reload(&mut self) -> Result<(), ConfigError> {
514 let config_path = self.config_path.clone();
515 if config_path.exists() {
516 self.load_from_file(&config_path)?;
517 self.notify_watchers()?;
518 }
519 Ok(())
520 }
521}
522
523impl Default for AppConfig {
524 fn default() -> Self {
525 Self {
526 environment: "development".to_string(),
527 debug: true,
528 server: ServerConfig {
529 host: "127.0.0.1".to_string(),
530 port: 8080,
531 workers: 4,
532 max_connections: 1000,
533 timeout: 30,
534 tls_cert: None,
535 tls_key: None,
536 },
537 database: DatabaseConfig {
538 host: "localhost".to_string(),
539 port: 5432,
540 database: "authframework".to_string(),
541 username: "postgres".to_string(),
542 password: "password".to_string(),
543 ssl_mode: "prefer".to_string(),
544 pool_size: 10,
545 timeout: 30,
546 },
547 logging: LoggingConfig {
548 level: "info".to_string(),
549 format: "json".to_string(),
550 output: vec!["stdout".to_string()],
551 rotation: Some(LogRotationConfig {
552 size: "10MB".to_string(),
553 keep: 7,
554 compress: true,
555 }),
556 structured: true,
557 },
558 security: SecurityConfig {
559 jwt_secret: "your-super-secret-jwt-key-change-this-in-production".to_string(),
560 session_timeout: 3600,
561 bcrypt_cost: 12,
562 rate_limiting: RateLimitConfig {
563 enabled: true,
564 requests_per_minute: 100,
565 burst_size: 20,
566 whitelist: vec!["127.0.0.1".to_string()],
567 },
568 cors: CorsConfig {
569 enabled: true,
570 allowed_origins: vec!["*".to_string()],
571 allowed_methods: vec![
572 "GET".to_string(),
573 "POST".to_string(),
574 "PUT".to_string(),
575 "DELETE".to_string(),
576 ],
577 allowed_headers: vec!["Content-Type".to_string(), "Authorization".to_string()],
578 max_age: 3600,
579 },
580 },
581 features: HashMap::new(),
582 custom: HashMap::new(),
583 }
584 }
585}
586
587pub struct SimpleConfigWatcher {
589 name: String,
590}
591
592impl SimpleConfigWatcher {
593 pub fn new(name: String) -> Self {
594 Self { name }
595 }
596}
597
598impl ConfigWatcher for SimpleConfigWatcher {
599 fn on_config_changed(&self, _config: &AppConfig) -> Result<(), ConfigError> {
600 println!("Configuration changed for watcher: {}", self.name);
601 Ok(())
602 }
603}
604
605#[cfg(test)]
606mod tests {
607 use super::*;
608 use std::fs::write;
609 use tempfile::tempdir;
610
611 #[test]
612 fn test_config_manager_creation() {
613 let manager = ConfigManager::new();
614 assert_eq!(manager.config.environment, "development");
615 }
616
617 #[test]
618 fn test_load_from_env() {
619 unsafe {
620 std::env::set_var("SERVER_HOST", "0.0.0.0");
621 std::env::set_var("SERVER_PORT", "9090");
622 }
623
624 let mut manager = ConfigManager::new();
625 let result = manager.load_from_env();
626
627 assert!(result.is_ok());
628 assert_eq!(manager.config.server.host, "0.0.0.0");
629 assert_eq!(manager.config.server.port, 9090);
630
631 unsafe {
632 std::env::remove_var("SERVER_HOST");
633 std::env::remove_var("SERVER_PORT");
634 }
635 }
636
637 #[test]
638 fn test_load_from_toml_file() {
639 let dir = tempdir().unwrap();
640 let file_path = dir.path().join("config.toml");
641
642 let toml_content = r#"
643environment = "test"
644debug = false
645
646[server]
647host = "0.0.0.0"
648port = 9000
649workers = 8
650max_connections = 2000
651timeout = 60
652
653[database]
654host = "db.example.com"
655port = 5432
656database = "test_db"
657username = "test_user"
658password = "test_pass"
659ssl_mode = "require"
660pool_size = 20
661timeout = 60
662
663[logging]
664level = "debug"
665format = "text"
666output = ["stdout", "file"]
667structured = false
668
669[security]
670jwt_secret = "test-secret-key-that-is-long-enough-for-validation"
671session_timeout = 7200
672bcrypt_cost = 10
673
674[security.rate_limiting]
675enabled = true
676requests_per_minute = 200
677burst_size = 40
678whitelist = ["192.168.1.1"]
679
680[security.cors]
681enabled = true
682allowed_origins = ["https://example.com"]
683allowed_methods = ["GET", "POST"]
684allowed_headers = ["Content-Type"]
685max_age = 1800
686
687[features]
688# Add some example features
689mfa = true
690oauth = false
691
692[custom]
693# Custom configuration values
694app_version = "1.0.0"
695 "#;
696
697 write(&file_path, toml_content).unwrap();
698
699 let mut manager = ConfigManager::new();
700 let result = manager.load_from_file(&file_path);
701
702 if let Err(ref e) = result {
703 eprintln!("Config load error: {:?}", e);
704 }
705 assert!(
706 result.is_ok(),
707 "Failed to load config: {:?}",
708 result.unwrap_err()
709 );
710 assert_eq!(manager.config.environment, "test");
711 assert_eq!(manager.config.server.host, "0.0.0.0");
712 assert_eq!(manager.config.server.port, 9000);
713 assert_eq!(manager.config.database.host, "db.example.com");
714 assert_eq!(manager.config.security.bcrypt_cost, 10);
715 }
716
717 #[test]
718 fn test_config_validation() {
719 let mut config = AppConfig::default();
720 config.security.jwt_secret = "short".to_string(); let manager = ConfigManager {
723 config,
724 config_path: PathBuf::new(),
725 format: ConfigFormat::Toml,
726 environments: HashMap::new(),
727 watchers: Vec::new(),
728 };
729
730 let result = manager.validate_config();
731 assert!(result.is_err());
732 assert!(matches!(result.unwrap_err(), ConfigError::Validation(_)));
733 }
734
735 #[test]
736 fn test_set_value() {
737 let mut manager = ConfigManager::new();
738
739 let result = manager.set_value(
740 "server.port",
741 serde_json::Value::Number(serde_json::Number::from(9999)),
742 );
743 assert!(result.is_ok());
744 assert_eq!(manager.config.server.port, 9999);
745 }
746
747 #[test]
748 fn test_config_watcher() {
749 let mut manager = ConfigManager::new();
750 let watcher = Box::new(SimpleConfigWatcher::new("test".to_string()));
751 manager.add_watcher(watcher);
752
753 let result = manager.set_value(
754 "server.port",
755 serde_json::Value::Number(serde_json::Number::from(8888)),
756 );
757 assert!(result.is_ok());
758 }
759}