Skip to main content

auth_framework/config/
mod.rs

1//! Configuration types for the authentication framework.
2
3pub mod app_config;
4pub mod config_manager;
5
6// Re-export for easy access
7pub use config_manager::{
8    AuthFrameworkSettings, ConfigBuilder, ConfigIntegration, ConfigManager, SessionCookieSettings,
9    SessionSettings,
10};
11
12use crate::errors::{AuthError, Result};
13use serde::{Deserialize, Serialize};
14use std::collections::HashMap;
15use std::time::Duration;
16
17/// Main configuration for the authentication framework.
18#[derive(Debug, Clone, Serialize, Deserialize)]
19pub struct AuthConfig {
20    /// Default token lifetime
21    pub token_lifetime: Duration,
22
23    /// Refresh token lifetime
24    pub refresh_token_lifetime: Duration,
25
26    /// Whether multi-factor authentication is enabled
27    pub enable_multi_factor: bool,
28
29    /// JWT issuer for token validation
30    pub issuer: String,
31
32    /// JWT audience for token validation
33    pub audience: String,
34
35    /// JWT secret key (optional - can be set via environment)
36    pub secret: Option<String>,
37
38    /// Storage configuration
39    pub storage: StorageConfig,
40
41    /// Rate limiting configuration
42    pub rate_limiting: RateLimitConfig,
43
44    /// Security configuration
45    pub security: SecurityConfig,
46
47    /// Audit logging configuration
48    pub audit: AuditConfig,
49
50    /// Custom settings for different auth methods
51    pub method_configs: HashMap<String, serde_json::Value>,
52}
53
54/// Storage configuration options.
55#[derive(Debug, Clone, Serialize, Deserialize)]
56pub enum StorageConfig {
57    /// In-memory storage (not recommended for production)
58    Memory,
59
60    /// Redis storage
61    #[cfg(feature = "redis-storage")]
62    Redis { url: String, key_prefix: String },
63
64    /// PostgreSQL storage
65    #[cfg(feature = "postgres-storage")]
66    Postgres {
67        connection_string: String,
68        table_prefix: String,
69    },
70
71    /// Custom storage backend
72    Custom(String),
73}
74
75/// Rate limiting configuration.
76#[derive(Debug, Clone, Serialize, Deserialize)]
77pub struct RateLimitConfig {
78    /// Enable rate limiting
79    pub enabled: bool,
80
81    /// Maximum requests per window
82    pub max_requests: u32,
83
84    /// Time window for rate limiting
85    pub window: Duration,
86
87    /// Burst allowance
88    pub burst: u32,
89}
90
91/// Security configuration options.
92#[derive(Debug, Clone, Serialize, Deserialize)]
93pub struct SecurityConfig {
94    /// Minimum password length
95    pub min_password_length: usize,
96
97    /// Require password complexity
98    pub require_password_complexity: bool,
99
100    /// Password hash algorithm
101    pub password_hash_algorithm: PasswordHashAlgorithm,
102
103    /// JWT signing algorithm
104    pub jwt_algorithm: JwtAlgorithm,
105
106    /// Secret key for signing (should be loaded from environment)
107    pub secret_key: Option<String>,
108
109    /// Enable secure cookies
110    pub secure_cookies: bool,
111
112    /// Cookie SameSite policy
113    pub cookie_same_site: CookieSameSite,
114
115    /// CSRF protection
116    pub csrf_protection: bool,
117
118    /// Session timeout
119    pub session_timeout: Duration,
120}
121
122/// Password hashing algorithms.
123#[derive(Debug, Clone, Serialize, Deserialize)]
124pub enum PasswordHashAlgorithm {
125    Argon2,
126    Bcrypt,
127    Scrypt,
128}
129
130/// JWT signing algorithms.
131#[derive(Debug, Clone, Serialize, Deserialize)]
132pub enum JwtAlgorithm {
133    HS256,
134    HS384,
135    HS512,
136    RS256,
137    RS384,
138    RS512,
139    ES256,
140    ES384,
141}
142
143/// Cookie SameSite policies.
144#[derive(Debug, Clone, Serialize, Deserialize)]
145pub enum CookieSameSite {
146    Strict,
147    Lax,
148    None,
149}
150
151/// Audit logging configuration.
152#[derive(Debug, Clone, Serialize, Deserialize)]
153pub struct AuditConfig {
154    /// Enable audit logging
155    pub enabled: bool,
156
157    /// Log successful authentications
158    pub log_success: bool,
159
160    /// Log failed authentications
161    pub log_failures: bool,
162
163    /// Log permission checks
164    pub log_permissions: bool,
165
166    /// Log token operations
167    pub log_tokens: bool,
168
169    /// Audit log storage
170    pub storage: AuditStorage,
171}
172
173/// Audit log storage options.
174#[derive(Debug, Clone, Serialize, Deserialize)]
175pub enum AuditStorage {
176    /// Standard logging (via tracing)
177    Tracing,
178
179    /// File-based storage
180    File { path: String },
181
182    /// Database storage
183    Database { connection_string: String },
184
185    /// External service
186    External { endpoint: String, api_key: String },
187}
188
189impl Default for AuthConfig {
190    fn default() -> Self {
191        Self {
192            token_lifetime: Duration::from_secs(3600), // 1 hour
193            refresh_token_lifetime: Duration::from_secs(86400 * 7), // 7 days
194            enable_multi_factor: false,
195            issuer: "auth-framework".to_string(),
196            audience: "api".to_string(),
197            secret: None,
198            storage: StorageConfig::Memory,
199            rate_limiting: RateLimitConfig::default(),
200            security: SecurityConfig::default(),
201            audit: AuditConfig::default(),
202            method_configs: HashMap::new(),
203        }
204    }
205}
206
207impl Default for RateLimitConfig {
208    fn default() -> Self {
209        Self {
210            enabled: true,
211            max_requests: 100,
212            window: Duration::from_secs(60), // 1 minute
213            burst: 10,
214        }
215    }
216}
217
218impl Default for SecurityConfig {
219    fn default() -> Self {
220        Self {
221            min_password_length: 8,
222            require_password_complexity: true,
223            password_hash_algorithm: PasswordHashAlgorithm::Argon2,
224            jwt_algorithm: JwtAlgorithm::HS256,
225            secret_key: None,
226            secure_cookies: true,
227            cookie_same_site: CookieSameSite::Lax,
228            csrf_protection: true,
229            session_timeout: Duration::from_secs(3600 * 24), // 24 hours
230        }
231    }
232}
233
234impl Default for AuditConfig {
235    fn default() -> Self {
236        Self {
237            enabled: true,
238            log_success: true,
239            log_failures: true,
240            log_permissions: true,
241            log_tokens: false, // Tokens can be sensitive
242            storage: AuditStorage::Tracing,
243        }
244    }
245}
246
247impl AuthConfig {
248    /// Create a new configuration with default values.
249    pub fn new() -> Self {
250        Self::default()
251    }
252
253    /// Set the token lifetime.
254    pub fn token_lifetime(mut self, lifetime: Duration) -> Self {
255        self.token_lifetime = lifetime;
256        self
257    }
258
259    /// Set the refresh token lifetime.
260    pub fn refresh_token_lifetime(mut self, lifetime: Duration) -> Self {
261        self.refresh_token_lifetime = lifetime;
262        self
263    }
264
265    /// Enable or disable multi-factor authentication.
266    pub fn enable_multi_factor(mut self, enabled: bool) -> Self {
267        self.enable_multi_factor = enabled;
268        self
269    }
270
271    /// Set the JWT issuer.
272    pub fn issuer(mut self, issuer: impl Into<String>) -> Self {
273        self.issuer = issuer.into();
274        self
275    }
276
277    /// Set the JWT audience.
278    pub fn audience(mut self, audience: impl Into<String>) -> Self {
279        self.audience = audience.into();
280        self
281    }
282
283    /// Set the JWT secret key.
284    pub fn secret(mut self, secret: impl Into<String>) -> Self {
285        self.secret = Some(secret.into());
286        self
287    }
288
289    /// Require MFA for all users.
290    pub fn require_mfa(mut self, required: bool) -> Self {
291        self.enable_multi_factor = required;
292        self
293    }
294
295    /// Enable caching.
296    pub fn enable_caching(self, _enabled: bool) -> Self {
297        // This would set a caching flag in a real implementation
298        self
299    }
300
301    /// Set maximum failed attempts.
302    pub fn max_failed_attempts(self, _max: u32) -> Self {
303        // This would set max failed attempts in security config
304        self
305    }
306
307    /// Enable RBAC.
308    pub fn enable_rbac(self, _enabled: bool) -> Self {
309        // This would enable role-based access control
310        self
311    }
312
313    /// Enable security audit.
314    pub fn enable_security_audit(self, _enabled: bool) -> Self {
315        // This would enable security auditing
316        self
317    }
318
319    /// Enable middleware.
320    pub fn enable_middleware(self, _enabled: bool) -> Self {
321        // This would enable middleware support
322        self
323    }
324
325    /// Set the storage configuration.
326    pub fn storage(mut self, storage: StorageConfig) -> Self {
327        self.storage = storage;
328        self
329    }
330
331    /// Configure Redis storage.
332    #[cfg(feature = "redis-storage")]
333    pub fn redis_storage(mut self, url: impl Into<String>) -> Self {
334        self.storage = StorageConfig::Redis {
335            url: url.into(),
336            key_prefix: "auth:".to_string(),
337        };
338        self
339    }
340
341    /// Set rate limiting configuration.
342    pub fn rate_limiting(mut self, config: RateLimitConfig) -> Self {
343        self.rate_limiting = config;
344        self
345    }
346
347    /// Set security configuration.
348    pub fn security(mut self, config: SecurityConfig) -> Self {
349        self.security = config;
350        self
351    }
352
353    /// Set audit configuration.
354    pub fn audit(mut self, config: AuditConfig) -> Self {
355        self.audit = config;
356        self
357    }
358
359    /// Add configuration for a specific auth method.
360    pub fn method_config(
361        mut self,
362        method_name: impl Into<String>,
363        config: impl Serialize,
364    ) -> Result<Self> {
365        let value = serde_json::to_value(config)
366            .map_err(|e| AuthError::config(format!("Failed to serialize method config: {e}")))?;
367
368        self.method_configs.insert(method_name.into(), value);
369        Ok(self)
370    }
371
372    /// Get configuration for a specific auth method.
373    pub fn get_method_config<T>(&self, method_name: &str) -> Result<Option<T>>
374    where
375        T: for<'de> Deserialize<'de>,
376    {
377        if let Some(value) = self.method_configs.get(method_name) {
378            let config = serde_json::from_value(value.clone()).map_err(|e| {
379                AuthError::config(format!("Failed to deserialize method config: {e}"))
380            })?;
381            Ok(Some(config))
382        } else {
383            Ok(None)
384        }
385    }
386
387    /// Validate the configuration.
388    pub fn validate(&self) -> Result<()> {
389        // Validate token lifetimes
390        if self.token_lifetime.as_secs() == 0 {
391            return Err(AuthError::config("Token lifetime must be greater than 0"));
392        }
393
394        if self.refresh_token_lifetime.as_secs() == 0 {
395            return Err(AuthError::config(
396                "Refresh token lifetime must be greater than 0",
397            ));
398        }
399
400        if self.refresh_token_lifetime <= self.token_lifetime {
401            return Err(AuthError::config(
402                "Refresh token lifetime must be greater than token lifetime",
403            ));
404        }
405
406        // Validate JWT secret configuration
407        self.validate_jwt_secret()?;
408
409        // Validate security settings
410        if self.security.min_password_length < 4 {
411            return Err(AuthError::config(
412                "Minimum password length must be at least 4 characters",
413            ));
414        }
415
416        // Enhanced security validation for production
417        if self.is_production_environment() && !self.is_test_environment() {
418            self.validate_production_security()?;
419        }
420
421        // Validate rate limiting
422        if self.rate_limiting.enabled && self.rate_limiting.max_requests == 0 {
423            return Err(AuthError::config(
424                "Rate limit max requests must be greater than 0 when enabled",
425            ));
426        }
427
428        // Validate storage configuration
429        self.validate_storage_config()?;
430
431        Ok(())
432    }
433
434    /// Validate JWT secret configuration for security
435    fn validate_jwt_secret(&self) -> Result<()> {
436        // Check multiple sources for JWT secret
437        let env_secret = std::env::var("JWT_SECRET").ok();
438        let jwt_secret = self
439            .security
440            .secret_key
441            .as_ref()
442            .or(self.secret.as_ref())
443            .or(env_secret.as_ref());
444
445        if let Some(secret) = jwt_secret {
446            if secret.len() < 32 {
447                return Err(AuthError::config(
448                    "JWT secret must be at least 32 characters for security. \
449                     Generate with: openssl rand -base64 32",
450                ));
451            }
452
453            // Check for common insecure patterns (but allow in test environments)
454            if !self.is_test_environment()
455                && (secret.contains("secret")
456                    || secret.contains("password")
457                    || secret.contains("123"))
458            {
459                return Err(AuthError::config(
460                    "JWT secret appears to contain common words or patterns. \
461                     Use a cryptographically secure random string.",
462                ));
463            }
464
465            // Warn if secret looks like it might be base64 but too short
466            if secret.len() < 44
467                && secret
468                    .chars()
469                    .all(|c| c.is_alphanumeric() || c == '+' || c == '/' || c == '=')
470            {
471                tracing::warn!(
472                    "JWT secret may be too short for optimal security. \
473                     Consider using at least 44 characters (32 bytes base64-encoded)."
474                );
475            }
476        } else if self.is_production_environment() {
477            return Err(AuthError::config(
478                "JWT secret is required for production environments. \
479                 Set JWT_SECRET environment variable or configure security.secret_key",
480            ));
481        }
482
483        Ok(())
484    }
485
486    /// Validate production-specific security requirements
487    fn validate_production_security(&self) -> Result<()> {
488        // Require strong password policies in production
489        if self.security.min_password_length < 8 {
490            return Err(AuthError::config(
491                "Production environments require minimum password length of 8 characters",
492            ));
493        }
494
495        if !self.security.require_password_complexity {
496            tracing::warn!("Production deployment should enable password complexity requirements");
497        }
498
499        // Require secure cookies in production
500        if !self.security.secure_cookies {
501            return Err(AuthError::config(
502                "Production environments must use secure cookies (HTTPS required)",
503            ));
504        }
505
506        // Ensure rate limiting is enabled
507        if !self.rate_limiting.enabled {
508            tracing::warn!("Production deployment should enable rate limiting for security");
509        }
510
511        // Validate audit configuration for compliance
512        if !self.audit.enabled {
513            return Err(AuthError::config(
514                "Production environments require audit logging for compliance",
515            ));
516        }
517
518        Ok(())
519    }
520
521    /// Validate storage configuration
522    fn validate_storage_config(&self) -> Result<()> {
523        match &self.storage {
524            StorageConfig::Memory
525                if self.is_production_environment() && !self.is_test_environment() =>
526            {
527                return Err(AuthError::config(
528                    "Memory storage is not suitable for production environments. \
529                         Use PostgreSQL or Redis storage.",
530                ));
531            }
532            _ => {} // PostgreSQL and Redis are production-ready
533        }
534
535        Ok(())
536    }
537
538    /// Detect production environment
539    fn is_production_environment(&self) -> bool {
540        // Check common production environment indicators
541        if let Ok(env) = std::env::var("ENVIRONMENT")
542            && (env.to_lowercase() == "production" || env.to_lowercase() == "prod")
543        {
544            return true;
545        }
546
547        if let Ok(env) = std::env::var("ENV")
548            && (env.to_lowercase() == "production" || env.to_lowercase() == "prod")
549        {
550            return true;
551        }
552
553        if let Ok(env) = std::env::var("NODE_ENV")
554            && env.to_lowercase() == "production"
555        {
556            return true;
557        }
558
559        if let Ok(env) = std::env::var("RUST_ENV")
560            && env.to_lowercase() == "production"
561        {
562            return true;
563        }
564
565        // Check for containerized environments
566        if std::env::var("KUBERNETES_SERVICE_HOST").is_ok() {
567            return true;
568        }
569
570        if std::env::var("DOCKER_CONTAINER").is_ok() {
571            return true;
572        }
573
574        false
575    }
576
577    /// Detect test environment
578    fn is_test_environment(&self) -> bool {
579        // Check if we're running in a test environment
580        cfg!(test)
581            || std::thread::current()
582                .name()
583                .is_some_and(|name| name.contains("test"))
584            || std::env::var("RUST_TEST").is_ok()
585            || std::env::var("ENVIRONMENT").as_deref() == Ok("test")
586            || std::env::var("ENV").as_deref() == Ok("test")
587            || std::env::args().any(|arg| arg.contains("test"))
588    }
589}
590
591impl RateLimitConfig {
592    /// Create a new rate limit configuration.
593    pub fn new(max_requests: u32, window: Duration) -> Self {
594        Self {
595            enabled: true,
596            max_requests,
597            window,
598            burst: max_requests / 10, // 10% of max as burst
599        }
600    }
601
602    /// Disable rate limiting.
603    pub fn disabled() -> Self {
604        Self {
605            enabled: false,
606            ..Default::default()
607        }
608    }
609}
610
611impl SecurityConfig {
612    /// Create a new security configuration with secure defaults.
613    pub fn secure() -> Self {
614        Self {
615            min_password_length: 12,
616            require_password_complexity: true,
617            password_hash_algorithm: PasswordHashAlgorithm::Argon2,
618            jwt_algorithm: JwtAlgorithm::RS256,
619            secret_key: None,
620            secure_cookies: true,
621            cookie_same_site: CookieSameSite::Strict,
622            csrf_protection: true,
623            session_timeout: Duration::from_secs(3600 * 8), // 8 hours
624        }
625    }
626
627    /// Create a development-friendly configuration.
628    /// WARNING: You MUST set a secret key before using this configuration!
629    /// Use either config.security.secret_key or JWT_SECRET environment variable.
630    pub fn development() -> Self {
631        Self {
632            min_password_length: 6,
633            require_password_complexity: false,
634            password_hash_algorithm: PasswordHashAlgorithm::Bcrypt,
635            jwt_algorithm: JwtAlgorithm::HS256,
636            secret_key: None, // Must be set by developer for security
637            secure_cookies: false,
638            cookie_same_site: CookieSameSite::Lax,
639            csrf_protection: false,
640            session_timeout: Duration::from_secs(3600 * 24), // 24 hours
641        }
642    }
643}