Skip to main content

auth_framework/deployment/
config.rs

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