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