Skip to main content

auth_framework/auth_modular/
mod.rs

1//! Modular authentication framework with component-based architecture.
2//!
3//! This module provides a modular approach to authentication and authorization,
4//! allowing fine-grained control over individual components while maintaining
5//! the same high-level API as the main `AuthFramework`.
6//!
7//! # Architecture
8//!
9//! The modular framework separates concerns into distinct managers:
10//! - **MFA Manager**: Multi-factor authentication coordination
11//! - **Session Manager**: Session lifecycle and security
12//! - **User Manager**: User account and profile management
13//! - **Token Manager**: JWT token creation and validation
14//! - **Permission Checker**: Authorization and access control
15//!
16//! # Benefits of Modular Design
17//!
18//! - **Composability**: Use only the components you need
19//! - **Testability**: Test individual components in isolation
20//! - **Extensibility**: Replace or extend specific managers
21//! - **Memory Efficiency**: Reduced memory footprint for specialized use cases
22//! - **Performance**: Optimized component interactions
23//!
24//! # Component Independence
25//!
26//! Each manager can operate independently while sharing common storage
27//! and configuration. This allows for:
28//! - Microservice deployment patterns
29//! - Custom authentication flows
30//! - Progressive feature adoption
31//! - A/B testing of authentication methods
32//!
33//! # Example
34//!
35//! ```rust,no_run
36//! use auth_framework::auth_modular::AuthFramework;
37//! use auth_framework::config::AuthConfig;
38//!
39//! // Create modular framework
40//! let config = AuthConfig::default();
41//! let auth = AuthFramework::new(config).expect("valid modular auth framework config");
42//!
43//! // Access individual managers
44//! let mfa_manager = auth.mfa_manager();
45//! let session_manager = auth.session_manager();
46//! let user_manager = auth.user_manager();
47//! ```
48//!
49//! # Migration from Monolithic Framework
50//!
51//! The modular framework maintains API compatibility with the main framework,
52//! making migration straightforward while providing additional flexibility.
53//!
54//! # When To Use This Module
55//!
56//! Prefer [`crate::AuthFramework`] for most applications.
57//! Reach for [`crate::ModularAuthFramework`] only when you need direct access
58//! to manager-level composition such as `session_manager()` or `user_manager()`.
59
60pub mod authorization_manager;
61pub mod mfa;
62pub mod session_manager;
63pub mod user_manager;
64
65use crate::authentication::credentials::{Credential, CredentialMetadata};
66use crate::config::AuthConfig;
67use crate::errors::{AuthError, MfaError, Result};
68use crate::methods::{AuthMethod, AuthMethodEnum, MethodResult, MfaChallenge};
69use crate::permissions::{Permission, PermissionChecker};
70use crate::storage::{AuthStorage, MemoryStorage};
71use crate::tokens::{AuthToken, TokenManager};
72use crate::utils::rate_limit::RateLimiter;
73use std::collections::HashMap;
74use std::sync::Arc;
75use tokio::sync::RwLock;
76use tracing::{debug, error, info, warn};
77
78pub use authorization_manager::AuthorizationManager;
79pub use mfa::MfaManager;
80pub use session_manager::SessionManager;
81pub use user_manager::{UserInfo, UserManager};
82
83/// Result of an authentication attempt — alias for the canonical [`crate::auth::AuthResult`].
84pub use crate::auth::AuthResult;
85
86/// Main authentication framework - now focused and modular
87pub struct AuthFramework {
88    /// Configuration
89    config: AuthConfig,
90
91    /// Registered authentication methods
92    methods: HashMap<String, AuthMethodEnum>,
93
94    /// Token manager
95    token_manager: TokenManager,
96
97    /// Storage backend
98    storage: Arc<dyn AuthStorage>,
99
100    /// Permission checker
101    permission_checker: Arc<RwLock<PermissionChecker>>,
102
103    /// Rate limiter
104    rate_limiter: Option<RateLimiter>,
105
106    /// MFA manager
107    mfa_manager: MfaManager,
108
109    /// Session manager
110    session_manager: SessionManager,
111
112    /// User manager
113    user_manager: UserManager,
114
115    /// Framework initialization state
116    initialized: bool,
117}
118
119impl AuthFramework {
120    /// Create a new authentication framework.
121    ///
122    /// Returns a descriptive error if the configuration is invalid rather than
123    /// panicking, so callers can decide how to handle startup failures.
124    ///
125    /// Equivalent to [`AuthFramework::try_new`].
126    ///
127    /// # Example
128    /// ```rust,ignore
129    /// use auth_framework::{AuthFramework, config::AuthConfig};
130    ///
131    /// let fw = AuthFramework::new(AuthConfig::default())?;
132    /// ```
133    pub fn new(config: AuthConfig) -> crate::errors::Result<Self> {
134        Self::try_new(config)
135    }
136
137    /// Create a new authentication framework, returning an error instead of panicking.
138    ///
139    /// This is the preferred constructor for library callers and server startup code where
140    /// configuration errors should be handled gracefully rather than aborting the process.
141    ///
142    /// # Example
143    /// ```rust,ignore
144    /// let fw = AuthFramework::try_new(AuthConfig::default())?;
145    /// ```
146    pub fn try_new(config: AuthConfig) -> crate::errors::Result<Self> {
147        // Validate configuration
148        config.validate().map_err(|e| {
149            crate::errors::AuthError::configuration(format!("Invalid configuration: {e}"))
150        })?;
151
152        // Create token manager
153        let token_manager = if let Some(secret) = &config.security.secret_key {
154            if secret.len() < 32 {
155                tracing::warn!(
156                    "JWT secret is shorter than 32 characters. Consider using a longer secret for better security."
157                );
158            }
159            TokenManager::new_hmac(secret.as_bytes(), "auth-framework", "auth-framework")
160        } else if let Some(secret) = &config.secret {
161            if secret.len() < 32 {
162                tracing::warn!(
163                    "JWT secret is shorter than 32 characters. Consider using a longer secret for better security."
164                );
165            }
166            TokenManager::new_hmac(secret.as_bytes(), "auth-framework", "auth-framework")
167        } else if let Ok(jwt_secret) = std::env::var("JWT_SECRET") {
168            if jwt_secret.len() < 32 {
169                tracing::warn!(
170                    "JWT_SECRET is shorter than 32 characters. Consider using a longer secret for better security."
171                );
172            }
173            TokenManager::new_hmac(jwt_secret.as_bytes(), "auth-framework", "auth-framework")
174        } else {
175            return Err(crate::errors::AuthError::configuration(
176                "JWT secret not set! Please set JWT_SECRET env variable or provide in config.\n\
177                   For security reasons, no default secret is provided.\n\
178                   Generate a secure secret with: openssl rand -base64 32",
179            ));
180        };
181
182        // Create storage backend. NOTE: unlike the main `AuthFramework`
183        // (src/auth.rs), this modular framework only supports Redis and
184        // Memory here -- any other `StorageConfig` (Postgres, SQLite,
185        // Custom) silently falls back to Memory. That gap predates this
186        // encryption work and is out of its scope, but the encryption
187        // wrapping itself must not be skipped just because this path
188        // builds storage differently from `storage::factory` --
189        // `wrap_with_encryption_if_enabled` is reused here for parity.
190        let storage: Arc<dyn AuthStorage> = match &config.storage {
191            #[cfg(feature = "redis-storage")]
192            crate::config::StorageConfig::Redis { url, key_prefix } => {
193                let redis: Arc<dyn AuthStorage> = Arc::new(
194                    crate::storage::RedisStorage::new(url, key_prefix).map_err(|e| {
195                        crate::errors::AuthError::configuration(format!(
196                            "Failed to create Redis storage: {e}"
197                        ))
198                    })?,
199                );
200                crate::storage::factory::wrap_with_encryption_if_enabled(
201                    redis,
202                    &config.storage_encryption,
203                )?
204            }
205            _ => Arc::new(MemoryStorage::new()),
206        };
207
208        // Create rate limiter if enabled
209        let rate_limiter = if config.rate_limiting.enabled {
210            Some(RateLimiter::new(
211                config.rate_limiting.max_requests,
212                config.rate_limiting.window,
213            ))
214        } else {
215            None
216        };
217
218        // Create specialized managers
219        let mfa_manager = MfaManager::new(storage.clone());
220        let session_manager = SessionManager::new(storage.clone());
221        let user_manager = UserManager::new(
222            storage.clone(),
223            config.security.password_hash_algorithm.clone(),
224        );
225
226        Ok(Self {
227            config,
228            methods: HashMap::new(),
229            token_manager,
230            storage,
231            permission_checker: Arc::new(RwLock::new(PermissionChecker::new())),
232            rate_limiter,
233            mfa_manager,
234            session_manager,
235            user_manager,
236            initialized: false,
237        })
238    }
239
240    /// Replace the storage backend with a custom implementation.
241    ///
242    /// This will swap the internal storage Arc and recreate dependent managers so
243    /// they use the provided storage instance.
244    pub fn replace_storage(&mut self, storage: Arc<dyn AuthStorage>) {
245        // Replace storage
246        self.storage = storage.clone();
247
248        // Recreate managers that depend on storage
249        self.mfa_manager = MfaManager::new(self.storage.clone());
250        self.session_manager = SessionManager::new(self.storage.clone());
251        self.user_manager = UserManager::new(
252            self.storage.clone(),
253            self.config.security.password_hash_algorithm.clone(),
254        );
255    }
256
257    /// Convenience constructor that creates a framework with a custom storage instance.
258    ///
259    /// # Example
260    /// ```rust,ignore
261    /// let fw = AuthFramework::new_with_storage(config, Arc::new(MyStorage::new()))?;
262    /// ```
263    pub fn new_with_storage(
264        config: AuthConfig,
265        storage: Arc<dyn AuthStorage>,
266    ) -> crate::errors::Result<Self> {
267        crate::storage::factory::check_overridden_storage(&storage, &config.storage_encryption)?;
268        let mut framework = Self::new(config)?;
269        framework.replace_storage(storage);
270        Ok(framework)
271    }
272
273    /// Create a new framework with SMSKit configuration.
274    ///
275    /// # Example
276    /// ```rust,ignore
277    /// let fw = AuthFramework::new_with_smskit_config(config, smskit_cfg)?;
278    /// ```
279    #[cfg(feature = "smskit")]
280    pub fn new_with_smskit_config(
281        config: AuthConfig,
282        smskit_config: crate::auth_modular::mfa::SmsKitConfig,
283    ) -> Result<Self> {
284        // First create the framework normally
285        let mut framework = Self::new(config)?;
286
287        // Then replace the MFA manager with one configured for SMSKit
288        framework.mfa_manager = crate::auth_modular::mfa::MfaManager::new_with_smskit_config(
289            framework.storage.clone(),
290            smskit_config,
291        )?;
292
293        Ok(framework)
294    }
295
296    /// Register an authentication method.
297    ///
298    /// # Example
299    /// ```rust,ignore
300    /// fw.register_method("password", AuthMethodEnum::Password(PasswordAuth::default()));
301    /// ```
302    pub fn register_method(&mut self, name: impl Into<String>, method: AuthMethodEnum) {
303        let name = name.into();
304        info!("Registering authentication method: {}", name);
305
306        // Validate method configuration
307        if let Err(e) = method.validate_config() {
308            error!("Method '{}' configuration validation failed: {}", name, e);
309            return;
310        }
311
312        self.methods.insert(name, method);
313    }
314
315    /// Initialize the authentication framework.
316    ///
317    /// Sets up default roles and marks the framework as ready. Must be called
318    /// before `authenticate` or `validate_token`.
319    ///
320    /// # Example
321    /// ```rust,ignore
322    /// fw.initialize().await?;
323    /// ```
324    pub async fn initialize(&mut self) -> Result<()> {
325        if self.initialized {
326            return Ok(());
327        }
328
329        info!("Initializing authentication framework");
330
331        // Initialize permission checker with default roles
332        {
333            let mut checker = self.permission_checker.write().await;
334            checker.create_default_roles();
335        }
336
337        // Perform any necessary cleanup
338        self.cleanup_expired_data().await?;
339
340        self.initialized = true;
341        info!("Authentication framework initialized successfully");
342
343        Ok(())
344    }
345
346    /// Authenticate a user with the specified method.
347    ///
348    /// Delegates to [`authenticate_with_metadata`](Self::authenticate_with_metadata)
349    /// with empty metadata.
350    ///
351    /// # Example
352    /// ```rust,ignore
353    /// let result = fw.authenticate("jwt", Credential::jwt(token)).await?;
354    /// match result {
355    ///     AuthResult::Success(token) => println!("authenticated"),
356    ///     AuthResult::MfaRequired(challenge) => println!("MFA needed"),
357    ///     AuthResult::Failure(msg) => eprintln!("failed: {msg}"),
358    /// }
359    /// ```
360    pub async fn authenticate(
361        &self,
362        method_name: &str,
363        credential: Credential,
364    ) -> Result<AuthResult> {
365        self.authenticate_with_metadata(method_name, credential, CredentialMetadata::new())
366            .await
367    }
368
369    /// Authenticate a user with the specified method and additional metadata.
370    ///
371    /// Metadata can carry client IP, user-agent, and other contextual information
372    /// for adaptive risk scoring and audit logging.
373    ///
374    /// # Example
375    /// ```rust,ignore
376    /// let mut meta = CredentialMetadata::new();
377    /// meta.client_ip = Some("203.0.113.1".to_string());
378    /// let result = fw.authenticate_with_metadata("jwt", credential, meta).await?;
379    /// ```
380    pub async fn authenticate_with_metadata(
381        &self,
382        method_name: &str,
383        credential: Credential,
384        metadata: CredentialMetadata,
385    ) -> Result<AuthResult> {
386        use std::time::Instant;
387        use tokio::time::{Duration as TokioDuration, sleep};
388
389        let start_time = Instant::now();
390
391        if !self.initialized {
392            return Err(AuthError::internal("Framework not initialized"));
393        }
394
395        // Perform the authentication logic
396        let result = self
397            .authenticate_internal(method_name, credential, metadata)
398            .await;
399
400        // Ensure minimum response time to prevent timing attacks
401        let min_duration = TokioDuration::from_millis(100);
402        let elapsed = start_time.elapsed();
403        if elapsed < min_duration {
404            sleep(min_duration - elapsed).await;
405        }
406
407        result
408    }
409
410    /// Internal authentication logic without timing protection
411    async fn authenticate_internal(
412        &self,
413        method_name: &str,
414        credential: Credential,
415        metadata: CredentialMetadata,
416    ) -> Result<AuthResult> {
417        // Check rate limiting
418        if let Some(ref rate_limiter) = self.rate_limiter {
419            let rate_key = format!(
420                "auth:{}:{}",
421                method_name,
422                metadata.client_ip.as_deref().unwrap_or("unknown")
423            );
424
425            if !rate_limiter.is_allowed(&rate_key) {
426                warn!(
427                    "Rate limit exceeded for method '{}' from IP {:?}",
428                    method_name, metadata.client_ip
429                );
430                return Err(AuthError::rate_limit("Too many authentication attempts"));
431            }
432        }
433
434        if method_name == "jwt" {
435            return match credential {
436                Credential::Jwt { token } | Credential::Bearer { token } => {
437                    self.authenticate_jwt_builtin(&token, &metadata, "jwt")
438                        .await
439                }
440                _ => Ok(AuthResult::Failure(
441                    "JWT authentication expects Credential::jwt or Credential::bearer".to_string(),
442                )),
443            };
444        }
445
446        if matches!(method_name, "api_key" | "api-key") {
447            return match credential {
448                Credential::ApiKey { key } => {
449                    self.authenticate_api_key_builtin(&key, &metadata, "api_key")
450                        .await
451                }
452                _ => Ok(AuthResult::Failure(
453                    "API key authentication expects Credential::api_key".to_string(),
454                )),
455            };
456        }
457
458        if method_name == "oauth2" {
459            return self
460                .authenticate_oauth2_builtin(credential, &metadata)
461                .await;
462        }
463
464        // Get the authentication method
465        let method = self.methods.get(method_name).ok_or_else(|| {
466            AuthError::auth_method(method_name, "Authentication method not found".to_string())
467        })?;
468
469        // Log authentication attempt
470        debug!(
471            "Authentication attempt with method '{}' for credential: {}",
472            method_name,
473            credential.safe_display()
474        );
475
476        // Perform authentication
477        let result = method.authenticate(credential, metadata.clone()).await?;
478
479        // Handle the result
480        match &result {
481            MethodResult::Success(token) => {
482                info!(
483                    "Authentication successful for user '{}' with method '{}'",
484                    token.user_id, method_name
485                );
486
487                // Store token
488                self.storage.store_token(token).await?;
489
490                // Log audit event
491                self.log_audit_event("auth_success", &token.user_id, method_name, &metadata)
492                    .await;
493
494                Ok(AuthResult::Success(token.clone()))
495            }
496
497            MethodResult::MfaRequired(challenge) => {
498                info!(
499                    "MFA required for user '{}' with method '{}'",
500                    challenge.user_id, method_name
501                );
502
503                // Store MFA challenge
504                self.mfa_manager
505                    .store_challenge((**challenge).clone())
506                    .await?;
507
508                // Log audit event
509                self.log_audit_event("mfa_required", &challenge.user_id, method_name, &metadata)
510                    .await;
511
512                Ok(AuthResult::MfaRequired(challenge.clone()))
513            }
514
515            MethodResult::Failure { reason } => {
516                warn!(
517                    "Authentication failed for method '{}': {}",
518                    method_name, reason
519                );
520
521                // Log audit event
522                self.log_audit_event("auth_failure", "unknown", method_name, &metadata)
523                    .await;
524
525                Ok(AuthResult::Failure(reason.clone()))
526            }
527        }
528    }
529
530    async fn authenticate_jwt_builtin(
531        &self,
532        token: &str,
533        metadata: &CredentialMetadata,
534        auth_method: &str,
535    ) -> Result<AuthResult> {
536        if token.is_empty() {
537            return Ok(AuthResult::Failure("JWT token cannot be empty".to_string()));
538        }
539
540        match self.token_manager.validate_jwt_token(token) {
541            Ok(claims) => {
542                let token =
543                    Self::build_validated_jwt_auth_token(token, claims, metadata, auth_method);
544                Ok(AuthResult::Success(Box::new(token)))
545            }
546            Err(error) => {
547                if let Some(reason) = Self::credential_failure_reason(&error) {
548                    Ok(AuthResult::Failure(reason))
549                } else {
550                    Err(error)
551                }
552            }
553        }
554    }
555
556    async fn authenticate_api_key_builtin(
557        &self,
558        api_key: &str,
559        metadata: &CredentialMetadata,
560        auth_method: &str,
561    ) -> Result<AuthResult> {
562        if api_key.is_empty() {
563            return Ok(AuthResult::Failure("API key cannot be empty".to_string()));
564        }
565
566        match self.user_manager.validate_api_key(api_key).await {
567            Ok(user) => {
568                let scopes: Vec<String> = if user.roles.is_empty() {
569                    vec!["api_user".to_string()]
570                } else {
571                    user.roles.to_vec()
572                };
573                let mut token = self
574                    .token_manager
575                    .create_auth_token(&user.id, scopes.clone(), auth_method, None)?
576                    .with_roles(user.roles)
577                    .with_scopes(scopes);
578                token.metadata.issued_ip = metadata.client_ip.clone();
579                token.metadata.user_agent = metadata.user_agent.clone();
580                Ok(AuthResult::Success(Box::new(token)))
581            }
582            Err(error) => {
583                if let Some(reason) = Self::credential_failure_reason(&error) {
584                    Ok(AuthResult::Failure(reason))
585                } else {
586                    Err(error)
587                }
588            }
589        }
590    }
591
592    async fn authenticate_oauth2_builtin(
593        &self,
594        credential: Credential,
595        metadata: &CredentialMetadata,
596    ) -> Result<AuthResult> {
597        match credential {
598            Credential::OAuth {
599                authorization_code, ..
600            } => {
601                if authorization_code.is_empty() {
602                    return Ok(AuthResult::Failure(
603                        "OAuth authorization code cannot be empty".to_string(),
604                    ));
605                }
606                Ok(AuthResult::Failure(
607                    "OAuth 2.0 authorization codes must be exchanged through an OAuth provider or server endpoint before authentication completes"
608                        .to_string(),
609                ))
610            }
611            Credential::OAuthRefresh { refresh_token } => {
612                if refresh_token.is_empty() {
613                    return Ok(AuthResult::Failure(
614                        "OAuth refresh token cannot be empty".to_string(),
615                    ));
616                }
617                Ok(AuthResult::Failure(
618                    "OAuth 2.0 refresh tokens must be exchanged through an OAuth provider or server endpoint before authentication completes"
619                        .to_string(),
620                ))
621            }
622            Credential::Jwt { token }
623            | Credential::Bearer { token }
624            | Credential::OpenIdConnect { id_token: token, .. } => {
625                self.authenticate_jwt_builtin(&token, metadata, "oauth2").await
626            }
627            _ => Ok(AuthResult::Failure(
628                "OAuth2 authentication expects Credential::oauth_code, Credential::oauth_refresh, Credential::jwt, Credential::bearer, or Credential::openid_connect"
629                    .to_string(),
630            )),
631        }
632    }
633
634    fn build_validated_jwt_auth_token(
635        raw_token: &str,
636        claims: crate::tokens::JwtClaims,
637        metadata: &CredentialMetadata,
638        auth_method: &str,
639    ) -> AuthToken {
640        let crate::tokens::JwtClaims {
641            sub,
642            iss,
643            exp,
644            iat,
645            jti,
646            scope,
647            permissions,
648            roles,
649            client_id,
650            ..
651        } = claims;
652
653        let now = chrono::Utc::now();
654        let issued_at = chrono::DateTime::<chrono::Utc>::from_timestamp(iat, 0).unwrap_or(now);
655        let expires_at = chrono::DateTime::<chrono::Utc>::from_timestamp(exp, 0)
656            .unwrap_or(now + chrono::Duration::hours(1));
657        let lifetime = (expires_at - now)
658            .to_std()
659            .unwrap_or_else(|_| std::time::Duration::from_secs(1));
660        let scopes = if scope.trim().is_empty() {
661            Vec::new()
662        } else {
663            scope.split_whitespace().map(str::to_string).collect()
664        };
665
666        let mut token = AuthToken::new(sub.clone(), raw_token.to_string(), lifetime, auth_method)
667            .with_scopes(scopes)
668            .with_permissions(permissions.unwrap_or_default())
669            .with_roles(roles.unwrap_or_default());
670        token.token_id = jti;
671        token.subject = Some(sub);
672        token.issuer = Some(iss);
673        token.issued_at = issued_at;
674        token.expires_at = expires_at;
675        token.metadata.issued_ip = metadata.client_ip.clone();
676        token.metadata.user_agent = metadata.user_agent.clone();
677        if let Some(client_id) = client_id {
678            token.client_id = Some(client_id);
679        }
680        token
681    }
682
683    fn credential_failure_reason(error: &AuthError) -> Option<String> {
684        match error {
685            AuthError::Token(_) | AuthError::Jwt(_) => Some(error.to_string()),
686            AuthError::Validation { message } => Some(message.clone()),
687            AuthError::UserNotFound => Some("User not found".to_string()),
688            _ => None,
689        }
690    }
691
692    /// Complete multi-factor authentication.
693    ///
694    /// # Example
695    /// ```rust,ignore
696    /// let token = fw.complete_mfa(challenge, "123456").await?;
697    /// ```
698    pub async fn complete_mfa(&self, challenge: MfaChallenge, mfa_code: &str) -> Result<AuthToken> {
699        debug!("Completing MFA for challenge '{}'", challenge.id);
700
701        // Check if challenge exists and is valid
702        let stored_challenge = self
703            .mfa_manager
704            .get_challenge(&challenge.id)
705            .await?
706            .ok_or(MfaError::ChallengeExpired)?;
707
708        if stored_challenge.is_expired() {
709            self.mfa_manager.remove_challenge(&challenge.id).await?;
710            return Err(MfaError::ChallengeExpired.into());
711        }
712
713        // Verify MFA code based on challenge type
714        let is_valid = match &stored_challenge.mfa_type {
715            crate::methods::MfaType::Totp => {
716                self.mfa_manager
717                    .totp
718                    .verify_code(&stored_challenge.user_id, mfa_code)
719                    .await?
720            }
721            crate::methods::MfaType::Sms { .. } => {
722                self.mfa_manager
723                    .sms
724                    .verify_code(&challenge.id, mfa_code)
725                    .await?
726            }
727            crate::methods::MfaType::Email { .. } => {
728                self.mfa_manager
729                    .email
730                    .verify_code(&challenge.id, mfa_code)
731                    .await?
732            }
733            crate::methods::MfaType::BackupCode => {
734                self.mfa_manager
735                    .backup_codes
736                    .verify_code(&stored_challenge.user_id, mfa_code)
737                    .await?
738            }
739            _ => false,
740        };
741
742        if !is_valid {
743            return Err(MfaError::InvalidCode.into());
744        }
745
746        // Remove the challenge
747        self.mfa_manager.remove_challenge(&challenge.id).await?;
748
749        // Look up user roles from storage
750        let user_key = format!("user:{}", challenge.user_id);
751        let scopes = if let Ok(Some(data)) = self.storage.get_kv(&user_key).await {
752            serde_json::from_slice::<serde_json::Value>(&data)
753                .ok()
754                .and_then(|v| {
755                    v.get("roles").and_then(|r| {
756                        r.as_array().map(|arr| {
757                            arr.iter()
758                                .filter_map(|v| v.as_str().map(String::from))
759                                .collect::<Vec<_>>()
760                        })
761                    })
762                })
763                .unwrap_or_else(|| vec!["user".to_string()])
764        } else {
765            vec!["user".to_string()]
766        };
767
768        // Create authentication token
769        let token =
770            self.token_manager
771                .create_auth_token(&challenge.user_id, scopes, "mfa", None)?;
772
773        // Store the token
774        self.storage.store_token(&token).await?;
775
776        info!(
777            "MFA completed successfully for user '{}'",
778            challenge.user_id
779        );
780
781        Ok(token)
782    }
783
784    /// Validate a token.
785    ///
786    /// # Example
787    /// ```rust,ignore
788    /// let valid = fw.validate_token(&token).await?;
789    /// ```
790    pub async fn validate_token(&self, token: &AuthToken) -> Result<bool> {
791        if !self.initialized {
792            return Err(AuthError::internal("Framework not initialized"));
793        }
794
795        // Check basic token validity
796        if !token.is_valid() {
797            return Ok(false);
798        }
799
800        // Validate with token manager
801        self.token_manager.validate_auth_token(token)?;
802
803        // Check if token exists in storage
804        if let Some(stored_token) = self.storage.get_token(&token.token_id).await? {
805            // Update last used time
806            let mut updated_token = stored_token;
807            updated_token.mark_used();
808            self.storage.update_token(&updated_token).await?;
809
810            Ok(true)
811        } else {
812            Ok(false)
813        }
814    }
815
816    /// Get user information from a token.
817    ///
818    /// # Example
819    /// ```rust,ignore
820    /// let info = fw.get_user_info(&token).await?;
821    /// println!("username: {}", info.username);
822    /// ```
823    pub async fn get_user_info(&self, token: &AuthToken) -> Result<UserInfo> {
824        if !self.validate_token(token).await? {
825            return Err(AuthError::auth_method("token", "Invalid token".to_string()));
826        }
827
828        self.user_manager.get_user_info(&token.user_id).await
829    }
830
831    /// Check if a token has a specific permission.
832    ///
833    /// # Example
834    /// ```rust,ignore
835    /// let allowed = fw.check_permission(&token, "read", "users").await?;
836    /// ```
837    pub async fn check_permission(
838        &self,
839        token: &AuthToken,
840        action: &str,
841        resource: &str,
842    ) -> Result<bool> {
843        if !self.validate_token(token).await? {
844            return Ok(false);
845        }
846
847        let permission = Permission::new(action, resource);
848        let mut checker = self.permission_checker.write().await;
849        checker.check_token_permission(token, &permission)
850    }
851
852    /// Get the token manager.
853    ///
854    /// # Example
855    /// ```rust,ignore
856    /// let tm = fw.token_manager();
857    /// ```
858    pub fn token_manager(&self) -> &TokenManager {
859        &self.token_manager
860    }
861
862    /// Get the MFA manager.
863    ///
864    /// # Example
865    /// ```rust,ignore
866    /// let mfa = fw.mfa_manager();
867    /// ```
868    pub fn mfa_manager(&self) -> &MfaManager {
869        &self.mfa_manager
870    }
871
872    /// Get the session manager.
873    ///
874    /// # Example
875    /// ```rust,ignore
876    /// let sm = fw.session_manager();
877    /// ```
878    pub fn session_manager(&self) -> &SessionManager {
879        &self.session_manager
880    }
881
882    /// Get the user manager.
883    ///
884    /// # Example
885    /// ```rust,ignore
886    /// let um = fw.user_manager();
887    /// ```
888    pub fn user_manager(&self) -> &UserManager {
889        &self.user_manager
890    }
891
892    /// Initiate SMS challenge (uses SMSKit).
893    ///
894    /// # Example
895    /// ```rust,ignore
896    /// let challenge_id = fw.initiate_sms_challenge("user-1").await?;
897    /// ```
898    pub async fn initiate_sms_challenge(&self, user_id: &str) -> Result<String> {
899        self.mfa_manager.sms.initiate_challenge(user_id).await
900    }
901
902    /// Send SMS code (uses SMSKit).
903    ///
904    /// # Example
905    /// ```rust,ignore
906    /// fw.send_sms_code(&challenge_id, "+1234567890").await?;
907    /// ```
908    pub async fn send_sms_code(&self, challenge_id: &str, phone_number: &str) -> Result<()> {
909        self.mfa_manager
910            .sms
911            .send_code(challenge_id, phone_number)
912            .await
913    }
914
915    /// Generate SMS code (uses SMSKit).
916    ///
917    /// # Example
918    /// ```rust,ignore
919    /// let code = fw.generate_sms_code(&challenge_id).await?;
920    /// ```
921    pub async fn generate_sms_code(&self, challenge_id: &str) -> Result<String> {
922        self.mfa_manager.sms.generate_code(challenge_id).await
923    }
924
925    /// Verify SMS code (uses SMSKit).
926    ///
927    /// # Example
928    /// ```rust,ignore
929    /// let ok = fw.verify_sms_code(&challenge_id, "123456").await?;
930    /// ```
931    pub async fn verify_sms_code(&self, challenge_id: &str, code: &str) -> Result<bool> {
932        self.mfa_manager.sms.verify_code(challenge_id, code).await
933    }
934
935    /// Clean up expired data (sessions, MFA challenges, rate limiter entries).
936    ///
937    /// # Example
938    /// ```rust,ignore
939    /// fw.cleanup_expired_data().await?;
940    /// ```
941    pub async fn cleanup_expired_data(&self) -> Result<()> {
942        debug!("Cleaning up expired data");
943
944        // Clean up storage
945        self.storage.cleanup_expired().await?;
946
947        // Clean up MFA challenges
948        self.mfa_manager.cleanup_expired_challenges().await?;
949
950        // Clean up sessions
951        self.session_manager.cleanup_expired_sessions().await?;
952
953        // Clean up rate limiter
954        if let Some(ref rate_limiter) = self.rate_limiter {
955            let _ = rate_limiter.cleanup().ok();
956        }
957
958        Ok(())
959    }
960
961    /// Get authentication framework statistics.
962    ///
963    /// # Example
964    /// ```rust,ignore
965    /// let stats = fw.get_stats().await?;
966    /// println!("methods: {:?}", stats.registered_methods);
967    /// ```
968    pub async fn get_stats(&self) -> Result<AuthStats> {
969        let mut stats = AuthStats::default();
970
971        for method in self.methods.keys() {
972            stats.registered_methods.push(method.clone());
973        }
974
975        stats.active_mfa_challenges = self.mfa_manager.get_active_challenge_count().await as u64;
976
977        // Count tokens from storage as a proxy for tokens_issued
978        stats.tokens_issued = self.storage.count_active_sessions().await.unwrap_or(0) as u64;
979
980        Ok(stats)
981    }
982
983    /// Log an audit event
984    async fn log_audit_event(
985        &self,
986        event_type: &str,
987        user_id: &str,
988        method: &str,
989        metadata: &CredentialMetadata,
990    ) {
991        if self.config.audit.enabled {
992            let should_log = match event_type {
993                "auth_success" => self.config.audit.log_success,
994                "auth_failure" => self.config.audit.log_failures,
995                "mfa_required" => self.config.audit.log_success,
996                _ => true,
997            };
998
999            if should_log {
1000                info!(
1001                    target: "auth_audit",
1002                    event_type = event_type,
1003                    user_id = user_id,
1004                    method = method,
1005                    client_ip = metadata.client_ip.as_deref().unwrap_or("unknown"),
1006                    user_agent = metadata.user_agent.as_deref().unwrap_or("unknown"),
1007                    timestamp = chrono::Utc::now().to_rfc3339(),
1008                    "Authentication event"
1009                );
1010            }
1011        }
1012    }
1013}
1014
1015/// Authentication framework statistics
1016#[derive(Debug, Clone, Default)]
1017pub struct AuthStats {
1018    /// Number of registered authentication methods
1019    pub registered_methods: Vec<String>,
1020
1021    /// Number of active MFA challenges
1022    pub active_mfa_challenges: u64,
1023
1024    /// Number of tokens issued (this would need proper tracking)
1025    pub tokens_issued: u64,
1026
1027    /// Number of authentication attempts (this would need proper tracking)
1028    pub auth_attempts: u64,
1029}
1030
1031#[cfg(test)]
1032mod tests {
1033    use super::*;
1034    use crate::authentication::credentials::Credential;
1035    use crate::config::{AuthConfig, SecurityConfig};
1036    use std::time::Duration;
1037
1038    async fn initialized_framework(config: AuthConfig) -> AuthFramework {
1039        let mut framework = AuthFramework::new(config).expect("test config should be valid");
1040        framework
1041            .initialize()
1042            .await
1043            .expect("framework initialization should succeed");
1044        framework
1045    }
1046
1047    fn test_config() -> AuthConfig {
1048        AuthConfig::new().secret("test_secret_key_32_bytes_long!!!!")
1049    }
1050
1051    #[tokio::test]
1052    async fn test_modular_framework_initialization() {
1053        let config = AuthConfig::new().security(SecurityConfig {
1054            min_password_length: 8,
1055            require_password_complexity: false,
1056            password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
1057            jwt_algorithm: crate::config::JwtAlgorithm::HS256,
1058            secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string().into()),
1059            secure_cookies: false,
1060            cookie_same_site: crate::config::CookieSameSite::Lax,
1061            csrf_protection: false,
1062            session_timeout: Duration::from_secs(3600),
1063            previous_secret_key: None,
1064        });
1065        let mut framework = AuthFramework::new(config).expect("test config should be valid");
1066
1067        assert!(framework.initialize().await.is_ok());
1068        assert!(framework.initialized);
1069    }
1070
1071    #[tokio::test]
1072    async fn test_mfa_manager_access() {
1073        let config = AuthConfig::new().security(SecurityConfig {
1074            min_password_length: 8,
1075            require_password_complexity: false,
1076            password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
1077            jwt_algorithm: crate::config::JwtAlgorithm::HS256,
1078            secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string().into()),
1079            secure_cookies: false,
1080            cookie_same_site: crate::config::CookieSameSite::Lax,
1081            csrf_protection: false,
1082            session_timeout: Duration::from_secs(3600),
1083            previous_secret_key: None,
1084        });
1085        let framework = AuthFramework::new(config).expect("test config should be valid");
1086
1087        // Test that we can access specialized managers
1088        let _mfa_manager = framework.mfa_manager();
1089        let _session_manager = framework.session_manager();
1090        let _user_manager = framework.user_manager();
1091    }
1092
1093    #[tokio::test]
1094    async fn test_authenticate_with_metadata_enforces_minimum_duration() {
1095        let framework = initialized_framework(test_config()).await;
1096        let start = std::time::Instant::now();
1097
1098        let result = framework
1099            .authenticate_with_metadata(
1100                "oauth2",
1101                Credential::oauth_refresh(""),
1102                CredentialMetadata::new(),
1103            )
1104            .await
1105            .expect("empty refresh token should return failure, not error");
1106
1107        assert!(
1108            start.elapsed() >= std::time::Duration::from_millis(90),
1109            "timing floor should add a noticeable delay"
1110        );
1111        assert!(matches!(result, AuthResult::Failure(_)));
1112    }
1113
1114    #[tokio::test]
1115    async fn test_authenticate_oauth2_refresh_empty_returns_failure() {
1116        let framework = initialized_framework(test_config()).await;
1117
1118        let result = framework
1119            .authenticate("oauth2", Credential::oauth_refresh(""))
1120            .await
1121            .expect("empty refresh token should return failure, not error");
1122
1123        match result {
1124            AuthResult::Failure(reason) => {
1125                assert!(reason.contains("refresh token cannot be empty"));
1126            }
1127            _ => panic!("expected failure result for empty OAuth refresh token"),
1128        }
1129    }
1130
1131    #[tokio::test]
1132    async fn test_authenticate_oauth2_openid_connect_routes_to_jwt_validation() {
1133        let framework = initialized_framework(test_config()).await;
1134        let jwt = framework
1135            .token_manager()
1136            .create_jwt_token("oidc-user", vec!["openid".to_string()], None)
1137            .expect("jwt creation should succeed");
1138
1139        let result = framework
1140            .authenticate("oauth2", Credential::openid_connect(jwt))
1141            .await
1142            .expect("valid OIDC credential should authenticate");
1143
1144        match result {
1145            AuthResult::Success(token) => {
1146                assert_eq!(token.user_id, "oidc-user");
1147                assert_eq!(token.auth_method, "oauth2");
1148            }
1149            _ => panic!("expected success result for OpenID Connect credential"),
1150        }
1151    }
1152
1153    #[tokio::test]
1154    async fn test_authenticate_oauth2_unsupported_credential_returns_failure() {
1155        let framework = initialized_framework(test_config()).await;
1156
1157        let result = framework
1158            .authenticate("oauth2", Credential::password("alice", "secret"))
1159            .await
1160            .expect("unsupported credential should return failure, not error");
1161
1162        match result {
1163            AuthResult::Failure(reason) => {
1164                assert!(reason.contains("OAuth2 authentication expects"));
1165            }
1166            _ => panic!("expected failure result for unsupported OAuth2 credential"),
1167        }
1168    }
1169
1170    #[tokio::test]
1171    async fn test_rate_limiting_without_client_ip_uses_shared_unknown_bucket() {
1172        let config = AuthConfig::new()
1173            .secret("test_secret_key_32_bytes_long!!!!")
1174            .rate_limiting(crate::config::RateLimitConfig {
1175                enabled: true,
1176                max_requests: 1,
1177                window: Duration::from_secs(60),
1178                burst: 0,
1179            });
1180        let framework = initialized_framework(config).await;
1181
1182        let first = framework
1183            .authenticate_with_metadata(
1184                "oauth2",
1185                Credential::oauth_code("first-code"),
1186                CredentialMetadata::new(),
1187            )
1188            .await
1189            .expect("first request should pass rate limiting");
1190        assert!(matches!(first, AuthResult::Failure(_)));
1191
1192        let second = framework
1193            .authenticate_with_metadata(
1194                "oauth2",
1195                Credential::oauth_code("second-code"),
1196                CredentialMetadata::new(),
1197            )
1198            .await;
1199        assert!(second.is_err(), "second request should be rate limited");
1200        assert!(
1201            second
1202                .unwrap_err()
1203                .to_string()
1204                .contains("Too many authentication attempts")
1205        );
1206    }
1207
1208    #[tokio::test]
1209    async fn test_complete_mfa_missing_challenge_returns_expired_error() {
1210        let framework = initialized_framework(test_config()).await;
1211        let challenge = MfaChallenge::new(
1212            crate::methods::MfaType::BackupCode,
1213            "user-123",
1214            Duration::from_secs(60),
1215        );
1216
1217        let result = framework.complete_mfa(challenge, "123456").await;
1218        assert!(result.is_err());
1219        assert!(result.unwrap_err().to_string().contains("expired"));
1220    }
1221
1222    #[tokio::test]
1223    async fn test_complete_mfa_expired_challenge_is_removed() {
1224        let framework = initialized_framework(test_config()).await;
1225        let mut challenge = MfaChallenge::new(
1226            crate::methods::MfaType::BackupCode,
1227            "user-123",
1228            Duration::from_secs(60),
1229        );
1230        challenge.expires_at = chrono::Utc::now() - chrono::Duration::seconds(1);
1231        framework
1232            .mfa_manager
1233            .store_challenge(challenge.clone())
1234            .await
1235            .expect("storing challenge should succeed");
1236
1237        let result = framework.complete_mfa(challenge.clone(), "123456").await;
1238        assert!(result.is_err());
1239        assert!(result.unwrap_err().to_string().contains("expired"));
1240        assert!(
1241            framework
1242                .mfa_manager
1243                .get_challenge(&challenge.id)
1244                .await
1245                .expect("challenge lookup should succeed")
1246                .is_none()
1247        );
1248    }
1249
1250    #[tokio::test]
1251    async fn test_validate_token_returns_false_for_expired_token() {
1252        let framework = initialized_framework(test_config()).await;
1253        let mut token = framework
1254            .token_manager()
1255            .create_auth_token("user-123", vec!["read".to_string()], "jwt", None)
1256            .expect("token creation should succeed");
1257        token.expires_at = chrono::Utc::now() - chrono::Duration::seconds(1);
1258
1259        let valid = framework
1260            .validate_token(&token)
1261            .await
1262            .expect("expired token should return false, not error");
1263        assert!(!valid);
1264    }
1265
1266    #[tokio::test]
1267    async fn test_validate_token_returns_false_when_not_in_storage() {
1268        let framework = initialized_framework(test_config()).await;
1269        let token = framework
1270            .token_manager()
1271            .create_auth_token("user-123", vec!["read".to_string()], "jwt", None)
1272            .expect("token creation should succeed");
1273
1274        let valid = framework
1275            .validate_token(&token)
1276            .await
1277            .expect("missing stored token should return false, not error");
1278        assert!(!valid);
1279    }
1280
1281    /// Regression test for a past review finding: this module's Redis
1282    /// construction path used to build `RedisStorage` directly with no
1283    /// encryption wrapping at all. If the `wrap_with_encryption_if_enabled`
1284    /// call this fix added is ever removed again, construction would
1285    /// SUCCEED here instead of failing closed (no key is configured),
1286    /// silently reintroducing the gap. `RedisStorage::new` only parses the
1287    /// URL -- it doesn't connect -- so this doesn't need a live server.
1288    #[cfg(feature = "redis-storage")]
1289    #[test]
1290    fn redis_construction_fails_closed_without_an_encryption_key() {
1291        let _lock = crate::storage::encryption::TEST_ENCRYPTION_ENV_LOCK.blocking_lock();
1292        // SAFETY: sound against every other test that ALSO takes
1293        // `_lock`; this test does.
1294        unsafe {
1295            std::env::remove_var("AUTH_STORAGE_ENCRYPTION_KEY");
1296            std::env::remove_var("AUTH_STORAGE_ENCRYPTION_KEYS_FILE");
1297        }
1298
1299        let mut config = test_config();
1300        config.storage = crate::config::StorageConfig::Redis {
1301            url: "redis://127.0.0.1:1/".to_string(),
1302            key_prefix: "test:".to_string(),
1303        };
1304        // storage_encryption defaults to enabled: true.
1305
1306        let result = AuthFramework::new(config);
1307        assert!(
1308            result.is_err(),
1309            "constructing this modular framework with Redis storage and no encryption key \
1310             configured must fail closed, not silently build unwrapped (unencrypted) storage"
1311        );
1312    }
1313}