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