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(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
193impl std::fmt::Debug for AppConfig {
194 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
195 let mut d = f.debug_struct("AppConfig");
196 d.field("environment", &self.environment);
197 d.field("debug", &self.debug);
198 d.field("server", &self.server);
199 d.field("database", &self.database);
200 d.field("logging", &self.logging);
201 d.field("security", &self.security);
202 d.field("features", &self.features);
203 d.field("custom", &crate::utils::redact::redacted(&self.custom));
204 d.finish()
205 }
206}
207
208pub struct ConfigManager {
210 config: AppConfig,
211 config_path: PathBuf,
212 format: ConfigFormat,
213 environments: HashMap<String, EnvironmentConfig>,
214 watchers: Vec<Box<dyn ConfigWatcher>>,
215}
216
217pub trait ConfigWatcher: Send + Sync {
219 fn on_config_changed(&self, config: &AppConfig) -> Result<(), ConfigError>;
220}
221
222impl Default for ConfigManager {
223 fn default() -> Self {
224 Self::new()
225 }
226}
227
228impl ConfigManager {
229 pub fn new() -> Self {
231 Self {
232 config: AppConfig::default(),
233 config_path: PathBuf::from("config.toml"),
234 format: ConfigFormat::Toml,
235 environments: HashMap::new(),
236 watchers: Vec::new(),
237 }
238 }
239
240 pub fn load_from_file<P: AsRef<Path>>(&mut self, path: P) -> Result<(), ConfigError> {
242 let path = path.as_ref();
243 self.config_path = path.to_path_buf();
244
245 self.format = match path.extension().and_then(|ext| ext.to_str()) {
247 Some("json") => ConfigFormat::Json,
248 Some("toml") => ConfigFormat::Toml,
249 Some("yaml") | Some("yml") => ConfigFormat::Yaml,
250 _ => ConfigFormat::Toml,
251 };
252
253 let content = fs::read_to_string(path)
254 .map_err(|_| ConfigError::FileNotFound(path.display().to_string()))?;
255
256 self.config = self.parse_config(&content)?;
257 self.validate_config()?;
258
259 Ok(())
260 }
261
262 pub fn load_from_env(&mut self) -> Result<(), ConfigError> {
264 self.format = ConfigFormat::Environment;
265
266 let mut config = AppConfig::default();
267
268 if let Ok(host) = std::env::var("SERVER_HOST") {
270 config.server.host = host;
271 }
272 if let Ok(port) = std::env::var("SERVER_PORT") {
273 config.server.port = port
274 .parse()
275 .map_err(|_| ConfigError::Environment("Invalid SERVER_PORT".to_string()))?;
276 }
277
278 if let Ok(host) = std::env::var("DATABASE_HOST") {
280 config.database.host = host;
281 }
282 if let Ok(port) = std::env::var("DATABASE_PORT") {
283 config.database.port = port
284 .parse()
285 .map_err(|_| ConfigError::Environment("Invalid DATABASE_PORT".to_string()))?;
286 }
287 if let Ok(database) = std::env::var("DATABASE_NAME") {
288 config.database.database = database;
289 }
290 if let Ok(username) = std::env::var("DATABASE_USER") {
291 config.database.username = username;
292 }
293 if let Ok(password) = std::env::var("DATABASE_PASSWORD") {
294 config.database.password = password;
295 }
296
297 if let Ok(jwt_secret) = std::env::var("JWT_SECRET") {
299 config.security.jwt_secret = jwt_secret;
300 }
301
302 if let Ok(env) = std::env::var("ENVIRONMENT") {
304 config.environment = env;
305 }
306
307 self.config = config;
308 self.validate_config()?;
309
310 Ok(())
311 }
312
313 fn parse_config(&self, content: &str) -> Result<AppConfig, ConfigError> {
315 match self.format {
316 ConfigFormat::Json => {
317 serde_json::from_str(content).map_err(|e| ConfigError::InvalidFormat(e.to_string()))
318 }
319 ConfigFormat::Toml => {
320 toml::from_str(content).map_err(|e| ConfigError::InvalidFormat(e.to_string()))
321 }
322 ConfigFormat::Yaml => {
323 serde_yaml::from_str(content).map_err(|e| ConfigError::InvalidFormat(e.to_string()))
324 }
325 ConfigFormat::Environment => Err(ConfigError::InvalidFormat(
326 "Environment loading not supported here".to_string(),
327 )),
328 }
329 }
330
331 fn validate_config(&self) -> Result<(), ConfigError> {
333 if self.config.server.host.is_empty() {
335 return Err(ConfigError::Validation(
336 "Server host cannot be empty".to_string(),
337 ));
338 }
339 if self.config.server.port == 0 {
340 return Err(ConfigError::Validation(
341 "Server port must be greater than 0".to_string(),
342 ));
343 }
344 if self.config.server.workers == 0 {
345 return Err(ConfigError::Validation(
346 "Server workers must be greater than 0".to_string(),
347 ));
348 }
349
350 if self.config.database.host.is_empty() {
352 return Err(ConfigError::Validation(
353 "Database host cannot be empty".to_string(),
354 ));
355 }
356 if self.config.database.port == 0 {
357 return Err(ConfigError::Validation(
358 "Database port must be greater than 0".to_string(),
359 ));
360 }
361 if self.config.database.database.is_empty() {
362 return Err(ConfigError::Validation(
363 "Database name cannot be empty".to_string(),
364 ));
365 }
366
367 if self.config.security.jwt_secret.is_empty() {
369 return Err(ConfigError::Validation(
370 "JWT secret cannot be empty".to_string(),
371 ));
372 }
373 if self.config.security.jwt_secret.len() < 32 {
374 return Err(ConfigError::Validation(
375 "JWT secret must be at least 32 characters".to_string(),
376 ));
377 }
378 if self.config.security.bcrypt_cost < 4 || self.config.security.bcrypt_cost > 31 {
379 return Err(ConfigError::Validation(
380 "Bcrypt cost must be between 4 and 31".to_string(),
381 ));
382 }
383
384 let valid_levels = ["trace", "debug", "info", "warn", "error"];
386 if !valid_levels.contains(&self.config.logging.level.as_str()) {
387 return Err(ConfigError::Validation("Invalid logging level".to_string()));
388 }
389
390 Ok(())
391 }
392
393 pub fn get_config(&self) -> &AppConfig {
395 &self.config
396 }
397
398 pub fn set_value(&mut self, key: &str, value: serde_json::Value) -> Result<(), ConfigError> {
400 let parts: Vec<&str> = key.split('.').collect();
402
403 match parts.as_slice() {
404 ["server", "host"] => {
405 if let Some(host) = value.as_str() {
406 self.config.server.host = host.to_string();
407 } else {
408 return Err(ConfigError::Validation(
409 "Server host must be a string".to_string(),
410 ));
411 }
412 }
413 ["server", "port"] => {
414 if let Some(port) = value.as_u64() {
415 self.config.server.port = port as u16;
416 } else {
417 return Err(ConfigError::Validation(
418 "Server port must be a number".to_string(),
419 ));
420 }
421 }
422 ["database", "host"] => {
423 if let Some(host) = value.as_str() {
424 self.config.database.host = host.to_string();
425 } else {
426 return Err(ConfigError::Validation(
427 "Database host must be a string".to_string(),
428 ));
429 }
430 }
431 ["database", "port"] => {
432 if let Some(port) = value.as_u64() {
433 self.config.database.port = port as u16;
434 } else {
435 return Err(ConfigError::Validation(
436 "Database port must be a number".to_string(),
437 ));
438 }
439 }
440 ["features", feature] => {
441 if let Some(feature_value) = value.as_bool() {
442 self.config
443 .features
444 .insert(feature.to_string(), feature_value);
445 } else {
446 return Err(ConfigError::Validation(
447 "Feature value must be boolean".to_string(),
448 ));
449 }
450 }
451 ["custom", custom_key] => {
452 self.config.custom.insert(custom_key.to_string(), value);
453 }
454 _ => {
455 return Err(ConfigError::Validation(format!(
456 "Unknown configuration key: {}",
457 key
458 )));
459 }
460 }
461
462 self.validate_config()?;
463 self.notify_watchers()?;
464
465 Ok(())
466 }
467
468 pub fn add_environment(&mut self, name: String, env_config: EnvironmentConfig) {
470 self.environments.insert(name, env_config);
471 }
472
473 pub fn switch_environment(&mut self, env_name: &str) -> Result<(), ConfigError> {
475 let overrides = if let Some(env_config) = self.environments.get(env_name) {
476 env_config.overrides.clone()
477 } else {
478 return Err(ConfigError::Validation(format!(
479 "Environment not found: {}",
480 env_name
481 )));
482 };
483
484 for (key, value) in &overrides {
486 self.set_value(key, value.clone())?;
487 }
488
489 self.config.environment = env_name.to_string();
490 self.notify_watchers()?;
491
492 Ok(())
493 }
494
495 pub fn add_watcher(&mut self, watcher: Box<dyn ConfigWatcher>) {
497 self.watchers.push(watcher);
498 }
499
500 fn notify_watchers(&self) -> Result<(), ConfigError> {
502 for watcher in &self.watchers {
503 watcher.on_config_changed(&self.config)?;
504 }
505 Ok(())
506 }
507
508 pub fn save_to_file<P: AsRef<Path>>(&self, path: P) -> Result<(), ConfigError> {
510 let content = match self.format {
511 ConfigFormat::Json => serde_json::to_string_pretty(&self.config)?,
512 ConfigFormat::Toml => toml::to_string(&self.config)
513 .map_err(|e| ConfigError::InvalidFormat(e.to_string()))?,
514 ConfigFormat::Yaml => serde_yaml::to_string(&self.config)
515 .map_err(|e| ConfigError::InvalidFormat(e.to_string()))?,
516 ConfigFormat::Environment => {
517 return Err(ConfigError::InvalidFormat(
518 "Cannot save environment config to file".to_string(),
519 ));
520 }
521 };
522
523 fs::write(path, content)?;
524 Ok(())
525 }
526
527 pub fn reload(&mut self) -> Result<(), ConfigError> {
529 let config_path = self.config_path.clone();
530 if config_path.exists() {
531 self.load_from_file(&config_path)?;
532 self.notify_watchers()?;
533 }
534 Ok(())
535 }
536}
537
538impl Default for AppConfig {
539 fn default() -> Self {
540 use ring::rand::{SecureRandom, SystemRandom};
541 let rng = SystemRandom::new();
544 let mut bytes = [0u8; 32];
545 rng.fill(&mut bytes)
546 .expect("AuthFramework fatal: system CSPRNG unavailable — the operating system cannot provide cryptographic randomness");
547 let jwt_secret = bytes.iter().fold(String::with_capacity(64), |mut s, b| {
548 s.push_str(&format!("{b:02x}"));
549 s
550 });
551
552 Self {
553 environment: "development".to_string(),
554 debug: false,
555 server: ServerConfig {
556 host: "127.0.0.1".to_string(),
557 port: 8080,
558 workers: 4,
559 max_connections: 1000,
560 timeout: 30,
561 tls_cert: None,
562 tls_key: None,
563 },
564 database: DatabaseConfig {
565 host: "localhost".to_string(),
566 port: 5432,
567 database: "authframework".to_string(),
568 username: "postgres".to_string(),
569 password: "".to_string(),
570 ssl_mode: "require".to_string(),
571 pool_size: 10,
572 timeout: 30,
573 },
574 logging: LoggingConfig {
575 level: "info".to_string(),
576 format: "json".to_string(),
577 output: vec!["stdout".to_string()],
578 rotation: Some(LogRotationConfig {
579 size: "10MB".to_string(),
580 keep: 7,
581 compress: true,
582 }),
583 structured: true,
584 },
585 security: SecurityConfig {
586 jwt_secret,
590 session_timeout: 3600,
591 bcrypt_cost: 12,
592 rate_limiting: RateLimitConfig {
593 enabled: true,
594 requests_per_minute: 100,
595 burst_size: 20,
596 whitelist: vec!["127.0.0.1".to_string()],
597 },
598 cors: CorsConfig {
599 enabled: true,
600 allowed_origins: vec![], allowed_methods: vec![
602 "GET".to_string(),
603 "POST".to_string(),
604 "PUT".to_string(),
605 "DELETE".to_string(),
606 ],
607 allowed_headers: vec!["Content-Type".to_string(), "Authorization".to_string()],
608 max_age: 3600,
609 },
610 },
611 features: HashMap::new(),
612 custom: HashMap::new(),
613 }
614 }
615}
616
617pub struct SimpleConfigWatcher {
619 name: String,
620}
621
622impl SimpleConfigWatcher {
623 pub fn new(name: String) -> Self {
624 Self { name }
625 }
626}
627
628impl ConfigWatcher for SimpleConfigWatcher {
629 fn on_config_changed(&self, _config: &AppConfig) -> Result<(), ConfigError> {
630 tracing::info!(watcher = %self.name, "Configuration changed");
631 Ok(())
632 }
633}
634
635#[cfg(test)]
636mod tests {
637 use super::*;
638 use std::fs::write;
639 use tempfile::tempdir;
640
641 #[test]
642 fn test_config_manager_creation() {
643 let manager = ConfigManager::new();
644 assert_eq!(manager.config.environment, "development");
645 }
646
647 #[test]
648 fn test_load_from_env() {
649 unsafe {
652 std::env::set_var("SERVER_HOST", "0.0.0.0");
653 std::env::set_var("SERVER_PORT", "9090");
654 std::env::set_var("JWT_SECRET", "test-jwt-secret-key-minimum-32-chars-ok");
656 }
657
658 let mut manager = ConfigManager::new();
659 let result = manager.load_from_env();
660
661 assert!(result.is_ok());
662 assert_eq!(manager.config.server.host, "0.0.0.0");
663 assert_eq!(manager.config.server.port, 9090);
664
665 unsafe {
667 std::env::remove_var("SERVER_PORT");
668 std::env::remove_var("JWT_SECRET");
669 }
670 }
671
672 #[test]
673 fn test_load_from_toml_file() {
674 let dir = tempdir().unwrap();
675 let file_path = dir.path().join("config.toml");
676
677 let toml_content = r#"
678environment = "test"
679debug = false
680
681[server]
682host = "0.0.0.0"
683port = 9000
684workers = 8
685max_connections = 2000
686timeout = 60
687
688[database]
689host = "db.example.com"
690port = 5432
691database = "test_db"
692username = "test_user"
693password = "test_pass"
694ssl_mode = "require"
695pool_size = 20
696timeout = 60
697
698[logging]
699level = "debug"
700format = "text"
701output = ["stdout", "file"]
702structured = false
703
704[security]
705jwt_secret = "test-secret-key-that-is-long-enough-for-validation"
706session_timeout = 7200
707bcrypt_cost = 10
708
709[security.rate_limiting]
710enabled = true
711requests_per_minute = 200
712burst_size = 40
713whitelist = ["192.168.1.1"]
714
715[security.cors]
716enabled = true
717allowed_origins = ["https://example.com"]
718allowed_methods = ["GET", "POST"]
719allowed_headers = ["Content-Type"]
720max_age = 1800
721
722[features]
723# Add some example features
724mfa = true
725oauth = false
726
727[custom]
728# Custom configuration values
729app_version = "1.0.0"
730 "#;
731
732 write(&file_path, toml_content).unwrap();
733
734 let mut manager = ConfigManager::new();
735 let result = manager.load_from_file(&file_path);
736
737 if let Err(ref e) = result {
738 eprintln!("Config load error: {:?}", e);
739 }
740 assert!(
741 result.is_ok(),
742 "Failed to load config: {:?}",
743 result.unwrap_err()
744 );
745 assert_eq!(manager.config.environment, "test");
746 assert_eq!(manager.config.server.host, "0.0.0.0");
747 assert_eq!(manager.config.server.port, 9000);
748 assert_eq!(manager.config.database.host, "db.example.com");
749 assert_eq!(manager.config.security.bcrypt_cost, 10);
750 }
751
752 #[test]
753 fn test_config_validation() {
754 let mut config = AppConfig::default();
755 config.security.jwt_secret = "short".to_string(); let manager = ConfigManager {
758 config,
759 config_path: PathBuf::new(),
760 format: ConfigFormat::Toml,
761 environments: HashMap::new(),
762 watchers: Vec::new(),
763 };
764
765 let result = manager.validate_config();
766 assert!(result.is_err());
767 assert!(matches!(result.unwrap_err(), ConfigError::Validation(_)));
768 }
769
770 #[test]
771 fn test_set_value() {
772 let mut manager = ConfigManager::new();
773 manager.config.security.jwt_secret =
775 "test-jwt-secret-minimum-32-characters-long".to_string();
776
777 let result = manager.set_value(
778 "server.port",
779 serde_json::Value::Number(serde_json::Number::from(9999)),
780 );
781 assert!(result.is_ok());
782 assert_eq!(manager.config.server.port, 9999);
783 }
784
785 #[test]
786 fn test_config_watcher() {
787 let mut manager = ConfigManager::new();
788 manager.config.security.jwt_secret =
790 "test-jwt-secret-minimum-32-characters-long".to_string();
791 let watcher = Box::new(SimpleConfigWatcher::new("test".to_string()));
792 manager.add_watcher(watcher);
793
794 let result = manager.set_value(
795 "server.port",
796 serde_json::Value::Number(serde_json::Number::from(8888)),
797 );
798 assert!(result.is_ok());
799 }
800}