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