1use serde::{Deserialize, Serialize};
5use std::collections::HashMap;
6use std::fs;
7use std::path::{Path, PathBuf};
8use thiserror::Error;
9use zeroize::Zeroizing;
10
11#[derive(Debug, Error)]
12pub enum ConfigError {
13 #[error("Configuration file not found: {0}")]
14 FileNotFound(String),
15 #[error("Invalid configuration format: {0}")]
16 InvalidFormat(String),
17 #[error("Configuration validation error: {0}")]
18 Validation(String),
19 #[error("Environment variable error: {0}")]
20 Environment(String),
21 #[error("IO error: {0}")]
22 Io(#[from] std::io::Error),
23 #[error("Serialization error: {0}")]
24 Serialization(#[from] serde_json::Error),
25 #[error("TOML parsing error: {0}")]
26 Toml(#[from] toml::de::Error),
27 #[error("YAML parsing error: {0}")]
28 Yaml(#[from] serde_saphyr::Error),
29}
30
31#[derive(Debug, Clone)]
33pub enum ConfigFormat {
34 Json,
35 Toml,
36 Yaml,
37 Environment,
38}
39
40#[derive(Clone, Serialize, Deserialize)]
42pub struct EnvironmentConfig {
43 pub name: String,
44 pub variables: HashMap<String, String>,
45 pub overrides: HashMap<String, serde_json::Value>,
46 pub secrets: Vec<String>,
47 pub required_vars: Vec<String>,
48}
49
50impl std::fmt::Debug for EnvironmentConfig {
51 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52 let mut d = f.debug_struct("EnvironmentConfig");
53 d.field("name", &self.name);
54 d.field(
55 "variables",
56 &crate::utils::redact::redacted(&self.variables),
57 );
58 d.field(
59 "overrides",
60 &crate::utils::redact::redacted(&self.overrides),
61 );
62 d.field("secrets", &crate::utils::redact::redacted(&self.secrets));
63 d.field("required_vars", &self.required_vars);
64 d.finish()
65 }
66}
67
68#[derive(Clone, Serialize, Deserialize)]
70pub struct DatabaseConfig {
71 pub host: String,
72 pub port: u16,
73 pub database: String,
74 pub username: String,
75 pub password: String,
76 pub ssl_mode: String,
77 pub pool_size: u32,
78 pub timeout: u64,
79}
80
81impl std::fmt::Debug for DatabaseConfig {
82 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
83 let mut d = f.debug_struct("DatabaseConfig");
84 d.field("host", &self.host);
85 d.field("port", &self.port);
86 d.field("database", &self.database);
87 d.field("username", &self.username);
88 d.field("password", &crate::utils::redact::redacted(&self.password));
89 d.field("ssl_mode", &self.ssl_mode);
90 d.field("pool_size", &self.pool_size);
91 d.field("timeout", &self.timeout);
92 d.finish()
93 }
94}
95
96#[derive(Clone, Serialize, Deserialize)]
98pub struct ServerConfig {
99 pub host: String,
100 pub port: u16,
101 pub workers: u32,
102 pub max_connections: u32,
103 pub timeout: u64,
104 pub tls_cert: Option<String>,
105 pub tls_key: Option<String>,
106}
107
108impl std::fmt::Debug for ServerConfig {
109 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
110 let mut d = f.debug_struct("ServerConfig");
111 d.field("host", &self.host);
112 d.field("port", &self.port);
113 d.field("workers", &self.workers);
114 d.field("max_connections", &self.max_connections);
115 d.field("timeout", &self.timeout);
116 d.field("tls_cert", &self.tls_cert);
117 d.field("tls_key", &crate::utils::redact::redacted(&self.tls_key));
118 d.finish()
119 }
120}
121
122#[derive(Debug, Clone, Serialize, Deserialize)]
124pub struct LoggingConfig {
125 pub level: String,
126 pub format: String,
127 pub output: Vec<String>,
128 pub rotation: Option<LogRotationConfig>,
129 pub structured: bool,
130}
131
132#[derive(Debug, Clone, Serialize, Deserialize)]
133pub struct LogRotationConfig {
134 pub size: String,
135 pub keep: u32,
136 pub compress: bool,
137}
138
139#[derive(Debug, Clone, Serialize, Deserialize)]
141pub struct SecurityConfig {
142 pub jwt_secret: Zeroizing<String>,
143 pub session_timeout: u64,
144 pub bcrypt_cost: u32,
145 pub rate_limiting: RateLimitConfig,
146 pub cors: CorsConfig,
147}
148
149#[derive(Debug, Clone, Serialize, Deserialize)]
150pub struct RateLimitConfig {
151 pub enabled: bool,
152 pub requests_per_minute: u32,
153 pub burst_size: u32,
154 pub whitelist: Vec<String>,
155}
156
157#[derive(Debug, Clone, Serialize, Deserialize)]
158pub struct CorsConfig {
159 pub enabled: bool,
160 pub allowed_origins: Vec<String>,
161 pub allowed_methods: Vec<String>,
162 pub allowed_headers: Vec<String>,
163 pub max_age: u32,
164}
165
166#[derive(Clone, Serialize, Deserialize)]
168pub struct AppConfig {
169 pub environment: String,
170 pub debug: bool,
171 pub server: ServerConfig,
172 pub database: DatabaseConfig,
173 pub logging: LoggingConfig,
174 pub security: SecurityConfig,
175 pub features: HashMap<String, bool>,
176 pub custom: HashMap<String, serde_json::Value>,
177}
178
179impl std::fmt::Debug for AppConfig {
180 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
181 let mut d = f.debug_struct("AppConfig");
182 d.field("environment", &self.environment);
183 d.field("debug", &self.debug);
184 d.field("server", &self.server);
185 d.field("database", &self.database);
186 d.field("logging", &self.logging);
187 d.field("security", &self.security);
188 d.field("features", &self.features);
189 d.field("custom", &crate::utils::redact::redacted(&self.custom));
190 d.finish()
191 }
192}
193
194pub struct ConfigManager {
196 config: AppConfig,
197 config_path: PathBuf,
198 format: ConfigFormat,
199 environments: HashMap<String, EnvironmentConfig>,
200 watchers: Vec<Box<dyn ConfigWatcher>>,
201}
202
203pub trait ConfigWatcher: Send + Sync {
205 fn on_config_changed(&self, config: &AppConfig) -> Result<(), ConfigError>;
206}
207
208impl Default for ConfigManager {
209 fn default() -> Self {
210 Self::new()
211 }
212}
213
214impl ConfigManager {
215 pub fn new() -> Self {
217 Self {
218 config: AppConfig::default(),
219 config_path: PathBuf::from("config.toml"),
220 format: ConfigFormat::Toml,
221 environments: HashMap::new(),
222 watchers: Vec::new(),
223 }
224 }
225
226 pub fn load_from_file<P: AsRef<Path>>(&mut self, path: P) -> Result<(), ConfigError> {
228 let path = path.as_ref();
229 self.config_path = path.to_path_buf();
230
231 self.format = match path.extension().and_then(|ext| ext.to_str()) {
233 Some("json") => ConfigFormat::Json,
234 Some("toml") => ConfigFormat::Toml,
235 Some("yaml") | Some("yml") => ConfigFormat::Yaml,
236 _ => ConfigFormat::Toml,
237 };
238
239 let content = fs::read_to_string(path)
240 .map_err(|_| ConfigError::FileNotFound(path.display().to_string()))?;
241
242 self.config = self.parse_config(&content)?;
243 self.validate_config()?;
244
245 Ok(())
246 }
247
248 pub fn load_from_env(&mut self) -> Result<(), ConfigError> {
250 self.format = ConfigFormat::Environment;
251
252 let mut config = AppConfig::default();
253
254 if let Ok(host) = std::env::var("SERVER_HOST") {
256 config.server.host = host;
257 }
258 if let Ok(port) = std::env::var("SERVER_PORT") {
259 config.server.port = port
260 .parse()
261 .map_err(|_| ConfigError::Environment("Invalid SERVER_PORT".to_string()))?;
262 }
263
264 if let Ok(host) = std::env::var("DATABASE_HOST") {
266 config.database.host = host;
267 }
268 if let Ok(port) = std::env::var("DATABASE_PORT") {
269 config.database.port = port
270 .parse()
271 .map_err(|_| ConfigError::Environment("Invalid DATABASE_PORT".to_string()))?;
272 }
273 if let Ok(database) = std::env::var("DATABASE_NAME") {
274 config.database.database = database;
275 }
276 if let Ok(username) = std::env::var("DATABASE_USER") {
277 config.database.username = username;
278 }
279 if let Ok(password) = std::env::var("DATABASE_PASSWORD") {
280 config.database.password = password;
281 }
282
283 if let Ok(jwt_secret) = std::env::var("JWT_SECRET") {
285 config.security.jwt_secret = jwt_secret.into();
286 }
287
288 if let Ok(env) = std::env::var("ENVIRONMENT") {
290 config.environment = env;
291 }
292
293 self.config = config;
294 self.validate_config()?;
295
296 Ok(())
297 }
298
299 fn parse_config(&self, content: &str) -> Result<AppConfig, ConfigError> {
301 match self.format {
302 ConfigFormat::Json => {
303 serde_json::from_str(content).map_err(|e| ConfigError::InvalidFormat(e.to_string()))
304 }
305 ConfigFormat::Toml => {
306 toml::from_str(content).map_err(|e| ConfigError::InvalidFormat(e.to_string()))
307 }
308 ConfigFormat::Yaml => serde_saphyr::from_str(content)
309 .map_err(|e| ConfigError::InvalidFormat(e.to_string())),
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_saphyr::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 use ring::rand::{SecureRandom, SystemRandom};
526 let rng = SystemRandom::new();
529 let mut bytes = [0u8; 32];
530 rng.fill(&mut bytes)
531 .expect("AuthFramework fatal: system CSPRNG unavailable — the operating system cannot provide cryptographic randomness");
532 let jwt_secret = bytes.iter().fold(String::with_capacity(64), |mut s, b| {
533 s.push_str(&format!("{b:02x}"));
534 s
535 });
536
537 Self {
538 environment: "development".to_string(),
539 debug: false,
540 server: ServerConfig {
541 host: "127.0.0.1".to_string(),
542 port: 8080,
543 workers: 4,
544 max_connections: 1000,
545 timeout: 30,
546 tls_cert: None,
547 tls_key: None,
548 },
549 database: DatabaseConfig {
550 host: "localhost".to_string(),
551 port: 5432,
552 database: "authframework".to_string(),
553 username: "postgres".to_string(),
554 password: "".to_string(),
555 ssl_mode: "require".to_string(),
556 pool_size: 10,
557 timeout: 30,
558 },
559 logging: LoggingConfig {
560 level: "info".to_string(),
561 format: "json".to_string(),
562 output: vec!["stdout".to_string()],
563 rotation: Some(LogRotationConfig {
564 size: "10MB".to_string(),
565 keep: 7,
566 compress: true,
567 }),
568 structured: true,
569 },
570 security: SecurityConfig {
571 jwt_secret: jwt_secret.into(),
575 session_timeout: 3600,
576 bcrypt_cost: 12,
577 rate_limiting: RateLimitConfig {
578 enabled: true,
579 requests_per_minute: 100,
580 burst_size: 20,
581 whitelist: vec!["127.0.0.1".to_string()],
582 },
583 cors: CorsConfig {
584 enabled: true,
585 allowed_origins: vec![], allowed_methods: vec![
587 "GET".to_string(),
588 "POST".to_string(),
589 "PUT".to_string(),
590 "DELETE".to_string(),
591 ],
592 allowed_headers: vec!["Content-Type".to_string(), "Authorization".to_string()],
593 max_age: 3600,
594 },
595 },
596 features: HashMap::new(),
597 custom: HashMap::new(),
598 }
599 }
600}
601
602pub struct SimpleConfigWatcher {
604 name: String,
605}
606
607impl SimpleConfigWatcher {
608 pub fn new(name: String) -> Self {
609 Self { name }
610 }
611}
612
613impl ConfigWatcher for SimpleConfigWatcher {
614 fn on_config_changed(&self, _config: &AppConfig) -> Result<(), ConfigError> {
615 tracing::info!(watcher = %self.name, "Configuration changed");
616 Ok(())
617 }
618}
619
620#[cfg(test)]
621mod tests {
622 use super::*;
623 use std::fs::write;
624 use tempfile::tempdir;
625
626 #[test]
627 fn test_config_manager_creation() {
628 let manager = ConfigManager::new();
629 assert_eq!(manager.config.environment, "development");
630 }
631
632 #[test]
633 fn test_load_from_env() {
634 unsafe {
637 std::env::set_var("SERVER_HOST", "0.0.0.0");
638 std::env::set_var("SERVER_PORT", "9090");
639 std::env::set_var("JWT_SECRET", "test-jwt-secret-key-minimum-32-chars-ok");
641 }
642
643 let mut manager = ConfigManager::new();
644 let result = manager.load_from_env();
645
646 assert!(result.is_ok());
647 assert_eq!(manager.config.server.host, "0.0.0.0");
648 assert_eq!(manager.config.server.port, 9090);
649
650 unsafe {
652 std::env::remove_var("SERVER_PORT");
653 std::env::remove_var("JWT_SECRET");
654 }
655 }
656
657 #[test]
658 fn test_load_from_toml_file() {
659 let dir = tempdir().unwrap();
660 let file_path = dir.path().join("config.toml");
661
662 let toml_content = r#"
663environment = "test"
664debug = false
665
666[server]
667host = "0.0.0.0"
668port = 9000
669workers = 8
670max_connections = 2000
671timeout = 60
672
673[database]
674host = "db.example.com"
675port = 5432
676database = "test_db"
677username = "test_user"
678password = "test_pass"
679ssl_mode = "require"
680pool_size = 20
681timeout = 60
682
683[logging]
684level = "debug"
685format = "text"
686output = ["stdout", "file"]
687structured = false
688
689[security]
690jwt_secret = "test-secret-key-that-is-long-enough-for-validation"
691session_timeout = 7200
692bcrypt_cost = 10
693
694[security.rate_limiting]
695enabled = true
696requests_per_minute = 200
697burst_size = 40
698whitelist = ["192.168.1.1"]
699
700[security.cors]
701enabled = true
702allowed_origins = ["https://example.com"]
703allowed_methods = ["GET", "POST"]
704allowed_headers = ["Content-Type"]
705max_age = 1800
706
707[features]
708# Add some example features
709mfa = true
710oauth = false
711
712[custom]
713# Custom configuration values
714app_version = "1.0.0"
715 "#;
716
717 write(&file_path, toml_content).unwrap();
718
719 let mut manager = ConfigManager::new();
720 let result = manager.load_from_file(&file_path);
721
722 if let Err(ref e) = result {
723 eprintln!("Config load error: {:?}", e);
724 }
725 assert!(
726 result.is_ok(),
727 "Failed to load config: {:?}",
728 result.unwrap_err()
729 );
730 assert_eq!(manager.config.environment, "test");
731 assert_eq!(manager.config.server.host, "0.0.0.0");
732 assert_eq!(manager.config.server.port, 9000);
733 assert_eq!(manager.config.database.host, "db.example.com");
734 assert_eq!(manager.config.security.bcrypt_cost, 10);
735 }
736
737 #[test]
738 fn test_config_validation() {
739 let mut config = AppConfig::default();
740 config.security.jwt_secret = "short".to_string().into(); let manager = ConfigManager {
743 config,
744 config_path: PathBuf::new(),
745 format: ConfigFormat::Toml,
746 environments: HashMap::new(),
747 watchers: Vec::new(),
748 };
749
750 let result = manager.validate_config();
751 assert!(result.is_err());
752 assert!(matches!(result.unwrap_err(), ConfigError::Validation(_)));
753 }
754
755 #[test]
756 fn test_set_value() {
757 let mut manager = ConfigManager::new();
758 manager.config.security.jwt_secret = "test-jwt-secret-minimum-32-characters-long"
760 .to_string()
761 .into();
762
763 let result = manager.set_value(
764 "server.port",
765 serde_json::Value::Number(serde_json::Number::from(9999)),
766 );
767 assert!(result.is_ok());
768 assert_eq!(manager.config.server.port, 9999);
769 }
770
771 #[test]
772 fn test_config_watcher() {
773 let mut manager = ConfigManager::new();
774 manager.config.security.jwt_secret = "test-jwt-secret-minimum-32-characters-long"
776 .to_string()
777 .into();
778 let watcher = Box::new(SimpleConfigWatcher::new("test".to_string()));
779 manager.add_watcher(watcher);
780
781 let result = manager.set_value(
782 "server.port",
783 serde_json::Value::Number(serde_json::Number::from(8888)),
784 );
785 assert!(result.is_ok());
786 }
787}