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