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(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 => serde_saphyr::from_str(content)
247                .map_err(|e| ConfigError::InvalidFormat(e.to_string())),
248            ConfigFormat::Environment => Err(ConfigError::InvalidFormat(
249                "Environment loading not supported here".to_string(),
250            )),
251        }
252    }
253
254    /// Validate configuration
255    fn validate_config(&self) -> Result<(), ConfigError> {
256        // Validate server configuration
257        if self.config.server.host.is_empty() {
258            return Err(ConfigError::Validation(
259                "Server host cannot be empty".to_string(),
260            ));
261        }
262        if self.config.server.port == 0 {
263            return Err(ConfigError::Validation(
264                "Server port must be greater than 0".to_string(),
265            ));
266        }
267        if self.config.server.workers == 0 {
268            return Err(ConfigError::Validation(
269                "Server workers must be greater than 0".to_string(),
270            ));
271        }
272
273        // Validate database configuration
274        if self.config.database.host.is_empty() {
275            return Err(ConfigError::Validation(
276                "Database host cannot be empty".to_string(),
277            ));
278        }
279        if self.config.database.port == 0 {
280            return Err(ConfigError::Validation(
281                "Database port must be greater than 0".to_string(),
282            ));
283        }
284        if self.config.database.database.is_empty() {
285            return Err(ConfigError::Validation(
286                "Database name cannot be empty".to_string(),
287            ));
288        }
289
290        // Validate security configuration
291        if self.config.security.jwt_secret.is_empty() {
292            return Err(ConfigError::Validation(
293                "JWT secret cannot be empty".to_string(),
294            ));
295        }
296        if self.config.security.jwt_secret.len() < 32 {
297            return Err(ConfigError::Validation(
298                "JWT secret must be at least 32 characters".to_string(),
299            ));
300        }
301        if self.config.security.bcrypt_cost < 4 || self.config.security.bcrypt_cost > 31 {
302            return Err(ConfigError::Validation(
303                "Bcrypt cost must be between 4 and 31".to_string(),
304            ));
305        }
306
307        // Validate logging configuration
308        let valid_levels = ["trace", "debug", "info", "warn", "error"];
309        if !valid_levels.contains(&self.config.logging.level.as_str()) {
310            return Err(ConfigError::Validation("Invalid logging level".to_string()));
311        }
312
313        Ok(())
314    }
315
316    /// Get current configuration
317    pub fn get_config(&self) -> &AppConfig {
318        &self.config
319    }
320
321    /// Update configuration value
322    pub fn set_value(&mut self, key: &str, value: serde_json::Value) -> Result<(), ConfigError> {
323        // Parse key path (e.g., "server.port" or "database.host")
324        let parts: Vec<&str> = key.split('.').collect();
325
326        match parts.as_slice() {
327            ["server", "host"] => {
328                if let Some(host) = value.as_str() {
329                    self.config.server.host = host.to_string();
330                } else {
331                    return Err(ConfigError::Validation(
332                        "Server host must be a string".to_string(),
333                    ));
334                }
335            }
336            ["server", "port"] => {
337                if let Some(port) = value.as_u64() {
338                    self.config.server.port = port as u16;
339                } else {
340                    return Err(ConfigError::Validation(
341                        "Server port must be a number".to_string(),
342                    ));
343                }
344            }
345            ["database", "host"] => {
346                if let Some(host) = value.as_str() {
347                    self.config.database.host = host.to_string();
348                } else {
349                    return Err(ConfigError::Validation(
350                        "Database host must be a string".to_string(),
351                    ));
352                }
353            }
354            ["database", "port"] => {
355                if let Some(port) = value.as_u64() {
356                    self.config.database.port = port as u16;
357                } else {
358                    return Err(ConfigError::Validation(
359                        "Database port must be a number".to_string(),
360                    ));
361                }
362            }
363            ["features", feature] => {
364                if let Some(feature_value) = value.as_bool() {
365                    self.config
366                        .features
367                        .insert(feature.to_string(), feature_value);
368                } else {
369                    return Err(ConfigError::Validation(
370                        "Feature value must be boolean".to_string(),
371                    ));
372                }
373            }
374            ["custom", custom_key] => {
375                self.config.custom.insert(custom_key.to_string(), value);
376            }
377            _ => {
378                return Err(ConfigError::Validation(format!(
379                    "Unknown configuration key: {}",
380                    key
381                )));
382            }
383        }
384
385        self.validate_config()?;
386        self.notify_watchers()?;
387
388        Ok(())
389    }
390
391    /// Add environment configuration
392    pub fn add_environment(&mut self, name: String, env_config: EnvironmentConfig) {
393        self.environments.insert(name, env_config);
394    }
395
396    /// Switch to specific environment
397    pub fn switch_environment(&mut self, env_name: &str) -> Result<(), ConfigError> {
398        let overrides = if let Some(env_config) = self.environments.get(env_name) {
399            env_config.overrides.clone()
400        } else {
401            return Err(ConfigError::Validation(format!(
402                "Environment not found: {}",
403                env_name
404            )));
405        };
406
407        // Apply environment overrides
408        for (key, value) in &overrides {
409            self.set_value(key, value.clone())?;
410        }
411
412        self.config.environment = env_name.to_string();
413        self.notify_watchers()?;
414
415        Ok(())
416    }
417
418    /// Add configuration watcher
419    pub fn add_watcher(&mut self, watcher: Box<dyn ConfigWatcher>) {
420        self.watchers.push(watcher);
421    }
422
423    /// Notify all watchers of configuration changes
424    fn notify_watchers(&self) -> Result<(), ConfigError> {
425        for watcher in &self.watchers {
426            watcher.on_config_changed(&self.config)?;
427        }
428        Ok(())
429    }
430
431    /// Save current configuration to file
432    pub fn save_to_file<P: AsRef<Path>>(&self, path: P) -> Result<(), ConfigError> {
433        let content = match self.format {
434            ConfigFormat::Json => serde_json::to_string_pretty(&self.config)?,
435            ConfigFormat::Toml => toml::to_string(&self.config)
436                .map_err(|e| ConfigError::InvalidFormat(e.to_string()))?,
437            ConfigFormat::Yaml => serde_saphyr::to_string(&self.config)
438                .map_err(|e| ConfigError::InvalidFormat(e.to_string()))?,
439            ConfigFormat::Environment => {
440                return Err(ConfigError::InvalidFormat(
441                    "Cannot save environment config to file".to_string(),
442                ));
443            }
444        };
445
446        fs::write(path, content)?;
447        Ok(())
448    }
449
450    /// Reload configuration from file
451    pub fn reload(&mut self) -> Result<(), ConfigError> {
452        let config_path = self.config_path.clone();
453        if config_path.exists() {
454            self.load_from_file(&config_path)?;
455            self.notify_watchers()?;
456        }
457        Ok(())
458    }
459}
460
461impl Default for AppConfig {
462    fn default() -> Self {
463        use ring::rand::{SecureRandom, SystemRandom};
464        // SAFETY: CSPRNG failure at initialization is terminal; the framework
465        // cannot operate without entropy.
466        let rng = SystemRandom::new();
467        let mut bytes = [0u8; 32];
468        rng.fill(&mut bytes)
469            .expect("AuthFramework fatal: system CSPRNG unavailable — the operating system cannot provide cryptographic randomness");
470        let jwt_secret = bytes.iter().fold(String::with_capacity(64), |mut s, b| {
471            s.push_str(&format!("{b:02x}"));
472            s
473        });
474
475        Self {
476            environment: "development".to_string(),
477            debug: false,
478            server: ServerConfig {
479                host: "127.0.0.1".to_string(),
480                port: 8080,
481                workers: 4,
482                max_connections: 1000,
483                timeout: 30,
484                tls_cert: None,
485                tls_key: None,
486            },
487            database: DatabaseConfig {
488                host: "localhost".to_string(),
489                port: 5432,
490                database: "authframework".to_string(),
491                username: "postgres".to_string(),
492                password: "".to_string(),
493                ssl_mode: "require".to_string(),
494                pool_size: 10,
495                timeout: 30,
496            },
497            logging: LoggingConfig {
498                level: "info".to_string(),
499                format: "json".to_string(),
500                output: vec!["stdout".to_string()],
501                rotation: Some(LogRotationConfig {
502                    size: "10MB".to_string(),
503                    keep: 7,
504                    compress: true,
505                }),
506                structured: true,
507            },
508            security: SecurityConfig {
509                // Randomly generated at startup. Override with the JWT_SECRET env var (or an
510                // explicit config value) in production to ensure tokens remain verifiable
511                // across process restarts.
512                jwt_secret: jwt_secret.into(),
513                session_timeout: 3600,
514                bcrypt_cost: 12,
515                rate_limiting: RateLimitConfig {
516                    enabled: true,
517                    requests_per_minute: 100,
518                    burst_size: 20,
519                    whitelist: vec!["127.0.0.1".to_string()],
520                },
521                cors: CorsConfig {
522                    enabled: true,
523                    allowed_origins: vec![], // Must be configured explicitly; wildcard CORS is rejected by default.
524                    allowed_methods: vec![
525                        "GET".to_string(),
526                        "POST".to_string(),
527                        "PUT".to_string(),
528                        "DELETE".to_string(),
529                    ],
530                    allowed_headers: vec!["Content-Type".to_string(), "Authorization".to_string()],
531                    max_age: 3600,
532                },
533            },
534            features: HashMap::new(),
535            custom: HashMap::new(),
536        }
537    }
538}
539
540/// Simple configuration watcher implementation
541pub struct SimpleConfigWatcher {
542    name: String,
543}
544
545impl SimpleConfigWatcher {
546    pub fn new(name: String) -> Self {
547        Self { name }
548    }
549}
550
551impl ConfigWatcher for SimpleConfigWatcher {
552    fn on_config_changed(&self, _config: &AppConfig) -> Result<(), ConfigError> {
553        tracing::info!(watcher = %self.name, "Configuration changed");
554        Ok(())
555    }
556}
557
558#[cfg(test)]
559mod tests {
560    use super::*;
561    use std::fs::write;
562    use tempfile::tempdir;
563
564    #[test]
565    fn test_config_manager_creation() {
566        let manager = ConfigManager::new();
567        assert_eq!(manager.config.environment, "development");
568    }
569
570    #[test]
571    fn test_load_from_env() {
572        // SAFETY: This test is not run concurrently with other env-var tests;
573        // env mutations are restored at the end of the test.
574        unsafe {
575            std::env::set_var("SERVER_HOST", "0.0.0.0");
576            std::env::set_var("SERVER_PORT", "9090");
577            // JWT_SECRET is required by validate_config; must be at least 32 chars.
578            std::env::set_var("JWT_SECRET", "test-jwt-secret-key-minimum-32-chars-ok");
579        }
580
581        let mut manager = ConfigManager::new();
582        let result = manager.load_from_env();
583
584        assert!(result.is_ok());
585        assert_eq!(manager.config.server.host, "0.0.0.0");
586        assert_eq!(manager.config.server.port, 9090);
587
588        // SAFETY: Restoring env vars set above; same serialization guarantees.
589        unsafe {
590            std::env::remove_var("SERVER_PORT");
591            std::env::remove_var("JWT_SECRET");
592        }
593    }
594
595    #[test]
596    fn test_load_from_toml_file() {
597        let dir = tempdir().unwrap();
598        let file_path = dir.path().join("config.toml");
599
600        let toml_content = r#"
601environment = "test"
602debug = false
603
604[server]
605host = "0.0.0.0"
606port = 9000
607workers = 8
608max_connections = 2000
609timeout = 60
610
611[database]
612host = "db.example.com"
613port = 5432
614database = "test_db"
615username = "test_user"
616password = "test_pass"
617ssl_mode = "require"
618pool_size = 20
619timeout = 60
620
621[logging]
622level = "debug"
623format = "text"
624output = ["stdout", "file"]
625structured = false
626
627[security]
628jwt_secret = "test-secret-key-that-is-long-enough-for-validation"
629session_timeout = 7200
630bcrypt_cost = 10
631
632[security.rate_limiting]
633enabled = true
634requests_per_minute = 200
635burst_size = 40
636whitelist = ["192.168.1.1"]
637
638[security.cors]
639enabled = true
640allowed_origins = ["https://example.com"]
641allowed_methods = ["GET", "POST"]
642allowed_headers = ["Content-Type"]
643max_age = 1800
644
645[features]
646# Add some example features
647mfa = true
648oauth = false
649
650[custom]
651# Custom configuration values
652app_version = "1.0.0"
653        "#;
654
655        write(&file_path, toml_content).unwrap();
656
657        let mut manager = ConfigManager::new();
658        let result = manager.load_from_file(&file_path);
659
660        if let Err(ref e) = result {
661            eprintln!("Config load error: {:?}", e);
662        }
663        assert!(
664            result.is_ok(),
665            "Failed to load config: {:?}",
666            result.unwrap_err()
667        );
668        assert_eq!(manager.config.environment, "test");
669        assert_eq!(manager.config.server.host, "0.0.0.0");
670        assert_eq!(manager.config.server.port, 9000);
671        assert_eq!(manager.config.database.host, "db.example.com");
672        assert_eq!(manager.config.security.bcrypt_cost, 10);
673    }
674
675    #[test]
676    fn test_config_validation() {
677        let mut config = AppConfig::default();
678        config.security.jwt_secret = "short".to_string().into(); // Too short
679
680        let manager = ConfigManager {
681            config,
682            config_path: PathBuf::new(),
683            format: ConfigFormat::Toml,
684            environments: HashMap::new(),
685            watchers: Vec::new(),
686        };
687
688        let result = manager.validate_config();
689        assert!(result.is_err());
690        assert!(matches!(result.unwrap_err(), ConfigError::Validation(_)));
691    }
692
693    #[test]
694    fn test_set_value() {
695        let mut manager = ConfigManager::new();
696        // set_value calls validate_config; provide a valid JWT secret first.
697        manager.config.security.jwt_secret = "test-jwt-secret-minimum-32-characters-long"
698            .to_string()
699            .into();
700
701        let result = manager.set_value(
702            "server.port",
703            serde_json::Value::Number(serde_json::Number::from(9999)),
704        );
705        assert!(result.is_ok());
706        assert_eq!(manager.config.server.port, 9999);
707    }
708
709    #[test]
710    fn test_config_watcher() {
711        let mut manager = ConfigManager::new();
712        // set_value calls validate_config; provide a valid JWT secret first.
713        manager.config.security.jwt_secret = "test-jwt-secret-minimum-32-characters-long"
714            .to_string()
715            .into();
716        let watcher = Box::new(SimpleConfigWatcher::new("test".to_string()));
717        manager.add_watcher(watcher);
718
719        let result = manager.set_value(
720            "server.port",
721            serde_json::Value::Number(serde_json::Number::from(8888)),
722        );
723        assert!(result.is_ok());
724    }
725}