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