Skip to main content

auth_framework/config/
app_config.rs

1/// Configuration management with environment variable support.
2///
3/// This module provides easy configuration loading from environment
4/// variables, config files, and other sources.
5use super::SecurityConfig;
6use serde::{Deserialize, Serialize};
7use std::{env, time::Duration};
8use zeroize::Zeroizing;
9
10impl Default for ConfigBuilder {
11    fn default() -> Self {
12        Self::new()
13    }
14}
15
16/// Complete application configuration
17#[derive(Debug, Clone, Serialize, Deserialize)]
18pub struct AppConfig {
19    /// Database configuration
20    pub database: DatabaseConfig,
21    /// Redis configuration
22    pub redis: Option<RedisConfig>,
23    /// JWT configuration
24    pub jwt: JwtConfig,
25    /// OAuth providers
26    pub oauth: OAuthConfig,
27    /// Security settings
28    pub security: SecuritySettings,
29    /// Logging configuration
30    pub logging: LoggingConfig,
31}
32
33/// Database connection settings.
34#[derive(Debug, Clone, Serialize, Deserialize)]
35pub struct DatabaseConfig {
36    /// Database connection URL (PostgreSQL, SQLite, etc.)
37    pub url: String,
38    /// Maximum number of concurrent database connections
39    pub max_connections: u32,
40    /// Minimum number of idle connections to maintain
41    pub min_connections: u32,
42    /// Connection timeout in seconds
43    pub connect_timeout_seconds: u64,
44}
45
46/// Redis cache and session storage settings.
47#[derive(Debug, Clone, Serialize, Deserialize)]
48pub struct RedisConfig {
49    /// Redis connection URL
50    pub url: String,
51    /// Number of connections in the Redis connection pool
52    pub pool_size: u32,
53}
54
55/// JWT authentication settings.
56#[derive(Debug, Clone, Serialize, Deserialize)]
57pub struct JwtConfig {
58    /// Cryptographic secret key used to sign and verify JWTs
59    pub secret_key: Zeroizing<String>,
60    /// The 'iss' (issuer) claim to embed in generated tokens
61    pub issuer: String,
62    /// The 'aud' (audience) claim to embed in generated tokens
63    pub audience: String,
64    /// Primary access token lifetime in seconds
65    pub access_token_ttl_seconds: u64,
66    /// Refresh token lifetime in seconds
67    pub refresh_token_ttl_seconds: u64,
68}
69
70/// Supported OAuth provider identities.
71#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, std::hash::Hash)]
72#[serde(rename_all = "lowercase")]
73pub enum OAuthProvider {
74    /// Google OAuth identity provider
75    Google,
76    /// GitHub OAuth identity provider
77    GitHub,
78    /// Microsoft OAuth identity provider
79    Microsoft,
80    /// Other custom OAuth provider
81    Custom(String),
82}
83
84/// OAuth 2.0 configuration settings.
85#[derive(Debug, Clone, Serialize, Deserialize)]
86pub struct OAuthConfig {
87    /// OAuth provider configurations, keyed by provider
88    pub providers: std::collections::HashMap<String, OAuthProviderConfig>,
89}
90
91/// Individual OAuth provider settings.
92#[derive(Debug, Clone, Serialize, Deserialize)]
93pub struct OAuthProviderConfig {
94    /// OAuth client ID provided by the Identity Provider
95    pub client_id: String,
96    /// OAuth client secret provided by the Identity Provider
97    pub client_secret: Zeroizing<String>,
98    /// The redirect URI where the IDP will send the user post-authentication
99    pub redirect_uri: String,
100    /// List of scopes to request during authentication
101    pub scopes: Vec<String>,
102}
103
104/// Application-wide security policies.
105#[derive(Debug, Clone, Serialize, Deserialize)]
106pub struct SecuritySettings {
107    /// Minimum character length for new passwords
108    pub password_min_length: usize,
109    /// Whether to require at least one special character in new passwords
110    pub password_require_special_chars: bool,
111    /// Maximum number of requests allowed per minute per IP
112    pub rate_limit_requests_per_minute: u32,
113    /// Maximum hours a session token remains valid without activity
114    pub session_timeout_hours: u64,
115    /// Maximum number of simultaneous active sessions a user can have
116    pub max_concurrent_sessions: u32,
117    /// Whether Multi-Factor Authentication is globally required
118    pub require_mfa: bool,
119}
120
121/// System logging and auditing settings.
122#[derive(Debug, Clone, Serialize, Deserialize)]
123pub struct LoggingConfig {
124    /// Log level filter (e.g., "info", "debug", "warn")
125    pub level: String,
126    /// True if audit logging for security events is enabled
127    pub audit_enabled: bool,
128    /// Location to store audit events ("database", "file", "syslog")
129    pub audit_storage: String,
130}
131
132impl AppConfig {
133    /// Load configuration from environment variables
134    pub fn from_env() -> Result<Self, ConfigError> {
135        Ok(Self {
136            database: DatabaseConfig {
137                url: env::var("DATABASE_URL")
138                    .map_err(|_| ConfigError::MissingEnvVar("DATABASE_URL"))?,
139                max_connections: env::var("DB_MAX_CONNECTIONS")
140                    .unwrap_or_else(|_| "10".to_string())
141                    .parse()
142                    .map_err(|_| ConfigError::InvalidValue("DB_MAX_CONNECTIONS"))?,
143                min_connections: 1,
144                connect_timeout_seconds: 30,
145            },
146            redis: if let Ok(redis_url) = env::var("REDIS_URL") {
147                Some(RedisConfig {
148                    url: redis_url,
149                    pool_size: 10,
150                })
151            } else {
152                None
153            },
154            jwt: JwtConfig {
155                secret_key: env::var("JWT_SECRET")
156                    .map_err(|_| ConfigError::MissingEnvVar("JWT_SECRET"))?
157                    .into(),
158                issuer: env::var("JWT_ISSUER").unwrap_or_else(|_| "auth-framework".to_string()),
159                audience: env::var("JWT_AUDIENCE").unwrap_or_else(|_| "api".to_string()),
160                access_token_ttl_seconds: 3600,
161                refresh_token_ttl_seconds: 86400 * 7,
162            },
163            oauth: OAuthConfig {
164                providers: {
165                    let mut map = std::collections::HashMap::new();
166                    if let Some(cfg) = Self::load_oauth_provider("GOOGLE") {
167                        map.insert("google".to_string(), cfg);
168                    }
169                    if let Some(cfg) = Self::load_oauth_provider("GITHUB") {
170                        map.insert("github".to_string(), cfg);
171                    }
172                    if let Some(cfg) = Self::load_oauth_provider("MICROSOFT") {
173                        map.insert("microsoft".to_string(), cfg);
174                    }
175                    map
176                },
177            },
178            security: SecuritySettings {
179                password_min_length: 8,
180                password_require_special_chars: true,
181                rate_limit_requests_per_minute: 60,
182                session_timeout_hours: 24,
183                max_concurrent_sessions: 5,
184                require_mfa: env::var("REQUIRE_MFA").unwrap_or_default() == "true",
185            },
186            logging: LoggingConfig {
187                level: env::var("LOG_LEVEL").unwrap_or_else(|_| "info".to_string()),
188                audit_enabled: true,
189                audit_storage: env::var("AUDIT_STORAGE").unwrap_or_else(|_| "database".to_string()),
190            },
191        })
192    }
193
194    fn load_oauth_provider(provider: &str) -> Option<OAuthProviderConfig> {
195        let client_id = env::var(format!("{}_CLIENT_ID", provider)).ok()?;
196        let client_secret = env::var(format!("{}_CLIENT_SECRET", provider)).ok()?;
197
198        Some(OAuthProviderConfig {
199            client_id,
200            client_secret: client_secret.into(),
201            redirect_uri: env::var(format!("{}_REDIRECT_URI", provider))
202                .unwrap_or_else(|_| format!("/auth/{}/callback", provider.to_lowercase())),
203            scopes: env::var(format!("{}_SCOPES", provider))
204                .unwrap_or_default()
205                .split(',')
206                .map(|s| s.trim().to_string())
207                .filter(|s| !s.is_empty())
208                .collect(),
209        })
210    }
211
212    /// Convert to AuthConfig
213    pub fn to_auth_config(&self) -> super::AuthConfig {
214        let mut config = super::AuthConfig::new()
215            .token_lifetime(Duration::from_secs(self.jwt.access_token_ttl_seconds))
216            .refresh_token_lifetime(Duration::from_secs(self.jwt.refresh_token_ttl_seconds))
217            .issuer(&self.jwt.issuer)
218            .audience(&self.jwt.audience)
219            .secret(&*self.jwt.secret_key)
220            .security(self.to_security_config());
221
222        config.storage = self.primary_storage_config();
223        config.enable_multi_factor = self.security.require_mfa;
224        config.rate_limiting = super::RateLimitConfig {
225            enabled: self.security.rate_limit_requests_per_minute > 0,
226            max_requests: self.security.rate_limit_requests_per_minute,
227            window: Duration::from_secs(60),
228            burst: (self.security.rate_limit_requests_per_minute / 10).max(1),
229        };
230        config.audit.enabled = self.logging.audit_enabled;
231        config
232    }
233
234    /// Convert to SecurityConfig
235    pub fn to_security_config(&self) -> SecurityConfig {
236        SecurityConfig {
237            min_password_length: self.security.password_min_length,
238            require_password_complexity: self.security.password_require_special_chars,
239            secret_key: Some(self.jwt.secret_key.clone()),
240            session_timeout: Duration::from_secs(self.security.session_timeout_hours * 3600),
241            ..Default::default()
242        }
243    }
244
245    /// Build an initialized AuthFramework using the configured storage backend.
246    pub async fn build_auth_framework(&self) -> crate::errors::Result<crate::AuthFramework> {
247        let auth_config = self.to_auth_config();
248        let pool_size = self.primary_storage_pool_size();
249
250        let mut framework = crate::AuthFramework::new(auth_config.clone());
251        let storage = crate::storage::factory::build_storage_backend_with_encryption(
252            &auth_config.storage,
253            pool_size,
254            &auth_config.storage_encryption,
255        )
256        .await?;
257        framework.replace_storage_from_factory(storage);
258        framework.initialize().await?;
259        Ok(framework)
260    }
261
262    pub(crate) fn primary_storage_config(&self) -> super::StorageConfig {
263        let database_url = self.database.url.trim();
264
265        if database_url.starts_with("postgres://") || database_url.starts_with("postgresql://") {
266            #[cfg(feature = "postgres-storage")]
267            {
268                return super::StorageConfig::Postgres {
269                    connection_string: database_url.to_string(),
270                    table_prefix: "auth_".to_string(),
271                };
272            }
273
274            #[cfg(not(feature = "postgres-storage"))]
275            {
276                return super::StorageConfig::Custom(
277                    "postgres-storage feature is required for PostgreSQL DATABASE_URL".to_string(),
278                );
279            }
280        }
281
282        if database_url.starts_with("mysql://") {
283            return super::StorageConfig::Custom(
284                "MySQL storage support has been removed; use postgres-storage, \
285                 sqlite-storage, or redis-storage instead"
286                    .to_string(),
287            );
288        }
289
290        if database_url.starts_with("sqlite:") {
291            #[cfg(feature = "sqlite-storage")]
292            {
293                return super::StorageConfig::Sqlite {
294                    connection_string: database_url.to_string(),
295                };
296            }
297
298            #[cfg(not(feature = "sqlite-storage"))]
299            {
300                return super::StorageConfig::Custom(
301                    "sqlite-storage feature is required for SQLite DATABASE_URL".to_string(),
302                );
303            }
304        }
305
306        super::StorageConfig::Memory
307    }
308
309    fn primary_storage_pool_size(&self) -> Option<u32> {
310        let database_url = self.database.url.trim();
311        if database_url.starts_with("postgres://")
312            || database_url.starts_with("postgresql://")
313            || database_url.starts_with("mysql://")
314            || database_url.starts_with("sqlite:")
315        {
316            return Some(self.database.max_connections);
317        }
318
319        None
320    }
321}
322
323#[derive(Debug, thiserror::Error)]
324pub enum ConfigError {
325    #[error("Missing environment variable: {0}")]
326    MissingEnvVar(&'static str),
327    #[error("Invalid value for: {0}")]
328    InvalidValue(&'static str),
329    #[error("Configuration validation error: {0}")]
330    Validation(String),
331}
332
333/// Configuration builder for easy setup
334pub struct ConfigBuilder {
335    config: AppConfig,
336}
337
338impl ConfigBuilder {
339    pub fn new() -> Self {
340        Self {
341            config: AppConfig::from_env().unwrap_or_else(|_| AppConfig::default()),
342        }
343    }
344
345    pub fn with_database_url(mut self, url: impl Into<String>) -> Self {
346        self.config.database.url = url.into();
347        self
348    }
349
350    pub fn with_database_max_connections(mut self, max_connections: u32) -> Self {
351        self.config.database.max_connections = max_connections;
352        self
353    }
354
355    pub fn with_database_min_connections(mut self, min_connections: u32) -> Self {
356        self.config.database.min_connections = min_connections;
357        self
358    }
359
360    pub fn with_database_connect_timeout(mut self, seconds: u64) -> Self {
361        self.config.database.connect_timeout_seconds = seconds;
362        self
363    }
364
365    pub fn with_jwt_secret(mut self, secret: impl Into<String>) -> Self {
366        self.config.jwt.secret_key = Zeroizing::new(secret.into());
367        self
368    }
369
370    pub fn with_jwt_issuer(mut self, issuer: impl Into<String>) -> Self {
371        self.config.jwt.issuer = issuer.into();
372        self
373    }
374
375    pub fn with_jwt_audience(mut self, audience: impl Into<String>) -> Self {
376        self.config.jwt.audience = audience.into();
377        self
378    }
379
380    pub fn with_access_token_ttl_seconds(mut self, ttl_seconds: u64) -> Self {
381        self.config.jwt.access_token_ttl_seconds = ttl_seconds;
382        self
383    }
384
385    pub fn with_refresh_token_ttl_seconds(mut self, ttl_seconds: u64) -> Self {
386        self.config.jwt.refresh_token_ttl_seconds = ttl_seconds;
387        self
388    }
389
390    pub fn with_redis_url(mut self, url: impl Into<String>) -> Self {
391        self.config.redis = Some(RedisConfig {
392            url: url.into(),
393            pool_size: 10,
394        });
395        self
396    }
397
398    pub fn with_redis_pool_size(mut self, pool_size: u32) -> Self {
399        let redis = self.config.redis.get_or_insert(RedisConfig {
400            url: "redis://127.0.0.1:6379".to_string(),
401            pool_size: 10,
402        });
403        redis.pool_size = pool_size;
404        self
405    }
406
407    /// Set password policy constraints.
408    ///
409    /// # Arguments
410    /// * `min_length` - minimum password length (typically 8+)
411    /// * `require_special` - require at least one special character (!@#$%^&* etc.)
412    pub fn with_password_policy(mut self, min_length: usize, require_special: bool) -> Self {
413        self.config.security.password_min_length = min_length;
414        self.config.security.password_require_special_chars = require_special;
415        self
416    }
417
418    pub fn with_rate_limit_requests_per_minute(mut self, requests: u32) -> Self {
419        self.config.security.rate_limit_requests_per_minute = requests;
420        self
421    }
422
423    pub fn with_session_timeout_hours(mut self, hours: u64) -> Self {
424        self.config.security.session_timeout_hours = hours;
425        self
426    }
427
428    pub fn with_require_mfa(mut self, require_mfa: bool) -> Self {
429        self.config.security.require_mfa = require_mfa;
430        self
431    }
432
433    pub fn with_log_level(mut self, level: impl Into<String>) -> Self {
434        self.config.logging.level = level.into();
435        self
436    }
437
438    pub fn build(self) -> AppConfig {
439        self.config
440    }
441}
442
443impl Default for AppConfig {
444    fn default() -> Self {
445        Self {
446            database: DatabaseConfig {
447                url: "postgresql://localhost/auth_framework".to_string(),
448                max_connections: 10,
449                min_connections: 1,
450                connect_timeout_seconds: 30,
451            },
452            redis: None,
453            jwt: JwtConfig {
454                secret_key: "development-only-secret-change-in-production"
455                    .to_string()
456                    .into(),
457                issuer: "auth-framework".to_string(),
458                audience: "api".to_string(),
459                access_token_ttl_seconds: 3600,
460                refresh_token_ttl_seconds: 86400 * 7,
461            },
462            oauth: OAuthConfig {
463                providers: std::collections::HashMap::new(),
464            },
465            security: SecuritySettings {
466                password_min_length: 8,
467                password_require_special_chars: true,
468                rate_limit_requests_per_minute: 60,
469                session_timeout_hours: 24,
470                max_concurrent_sessions: 5,
471                require_mfa: false,
472            },
473            logging: LoggingConfig {
474                level: "info".to_string(),
475                audit_enabled: true,
476                audit_storage: "database".to_string(),
477            },
478        }
479    }
480}
481
482#[cfg(test)]
483mod tests {
484    use super::*;
485
486    #[test]
487    fn test_config_builder() {
488        let config = ConfigBuilder::new()
489            .with_database_url("postgresql://test")
490            .with_database_max_connections(25)
491            .with_jwt_secret("test-secret")
492            .with_jwt_issuer("issuer")
493            .with_jwt_audience("audience")
494            .with_rate_limit_requests_per_minute(120)
495            .build();
496
497        assert_eq!(config.database.url, "postgresql://test");
498        assert_eq!(config.database.max_connections, 25);
499        assert_eq!(config.jwt.secret_key.as_str(), "test-secret");
500        assert_eq!(config.jwt.issuer, "issuer");
501        assert_eq!(config.jwt.audience, "audience");
502        assert_eq!(config.security.rate_limit_requests_per_minute, 120);
503    }
504}