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