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 crate::auth::validate_access_jwt_with(
541            &self.token_manager,
542            self.storage.as_ref(),
543            token,
544            false,
545            false,
546        )
547        .await
548        {
549            Ok(claims) => {
550                let token =
551                    Self::build_validated_jwt_auth_token(token, claims, metadata, auth_method);
552                Ok(AuthResult::Success(Box::new(token)))
553            }
554            Err(error) => {
555                if let Some(reason) = Self::credential_failure_reason(&error) {
556                    Ok(AuthResult::Failure(reason))
557                } else {
558                    Err(error)
559                }
560            }
561        }
562    }
563
564    async fn authenticate_api_key_builtin(
565        &self,
566        api_key: &str,
567        metadata: &CredentialMetadata,
568        auth_method: &str,
569    ) -> Result<AuthResult> {
570        if api_key.is_empty() {
571            return Ok(AuthResult::Failure("API key cannot be empty".to_string()));
572        }
573
574        match self.user_manager.validate_api_key(api_key).await {
575            Ok(user) => {
576                let scopes: Vec<String> = if user.roles.is_empty() {
577                    vec!["api_user".to_string()]
578                } else {
579                    user.roles.to_vec()
580                };
581                let mut token = self
582                    .token_manager
583                    .create_auth_token(&user.id, scopes.clone(), auth_method, None)?
584                    .with_roles(user.roles)
585                    .with_scopes(scopes);
586                token.metadata.issued_ip = metadata.client_ip.clone();
587                token.metadata.user_agent = metadata.user_agent.clone();
588                Ok(AuthResult::Success(Box::new(token)))
589            }
590            Err(error) => {
591                if let Some(reason) = Self::credential_failure_reason(&error) {
592                    Ok(AuthResult::Failure(reason))
593                } else {
594                    Err(error)
595                }
596            }
597        }
598    }
599
600    async fn authenticate_oauth2_builtin(
601        &self,
602        credential: Credential,
603        metadata: &CredentialMetadata,
604    ) -> Result<AuthResult> {
605        match credential {
606            Credential::OAuth {
607                authorization_code, ..
608            } => {
609                if authorization_code.is_empty() {
610                    return Ok(AuthResult::Failure(
611                        "OAuth authorization code cannot be empty".to_string(),
612                    ));
613                }
614                Ok(AuthResult::Failure(
615                    "OAuth 2.0 authorization codes must be exchanged through an OAuth provider or server endpoint before authentication completes"
616                        .to_string(),
617                ))
618            }
619            Credential::OAuthRefresh { refresh_token } => {
620                if refresh_token.is_empty() {
621                    return Ok(AuthResult::Failure(
622                        "OAuth refresh token cannot be empty".to_string(),
623                    ));
624                }
625                Ok(AuthResult::Failure(
626                    "OAuth 2.0 refresh tokens must be exchanged through an OAuth provider or server endpoint before authentication completes"
627                        .to_string(),
628                ))
629            }
630            Credential::Jwt { token }
631            | Credential::Bearer { token }
632            | Credential::OpenIdConnect { id_token: token, .. } => {
633                self.authenticate_jwt_builtin(&token, metadata, "oauth2").await
634            }
635            _ => Ok(AuthResult::Failure(
636                "OAuth2 authentication expects Credential::oauth_code, Credential::oauth_refresh, Credential::jwt, Credential::bearer, or Credential::openid_connect"
637                    .to_string(),
638            )),
639        }
640    }
641
642    fn build_validated_jwt_auth_token(
643        raw_token: &str,
644        claims: crate::tokens::JwtClaims,
645        metadata: &CredentialMetadata,
646        auth_method: &str,
647    ) -> AuthToken {
648        let crate::tokens::JwtClaims {
649            sub,
650            iss,
651            exp,
652            iat,
653            jti,
654            scope,
655            permissions,
656            roles,
657            client_id,
658            ..
659        } = claims;
660
661        let now = chrono::Utc::now();
662        let issued_at = chrono::DateTime::<chrono::Utc>::from_timestamp(iat, 0).unwrap_or(now);
663        let expires_at = chrono::DateTime::<chrono::Utc>::from_timestamp(exp, 0)
664            .unwrap_or(now + chrono::Duration::hours(1));
665        let lifetime = (expires_at - now)
666            .to_std()
667            .unwrap_or_else(|_| std::time::Duration::from_secs(1));
668        let scopes = if scope.trim().is_empty() {
669            Vec::new()
670        } else {
671            scope.split_whitespace().map(str::to_string).collect()
672        };
673
674        let mut token = AuthToken::new(sub.clone(), raw_token.to_string(), lifetime, auth_method)
675            .with_scopes(scopes)
676            .with_permissions(permissions.unwrap_or_default())
677            .with_roles(roles.unwrap_or_default());
678        token.token_id = jti;
679        token.subject = Some(sub);
680        token.issuer = Some(iss);
681        token.issued_at = issued_at;
682        token.expires_at = expires_at;
683        token.metadata.issued_ip = metadata.client_ip.clone();
684        token.metadata.user_agent = metadata.user_agent.clone();
685        if let Some(client_id) = client_id {
686            token.client_id = Some(client_id);
687        }
688        token
689    }
690
691    fn credential_failure_reason(error: &AuthError) -> Option<String> {
692        match error {
693            AuthError::Token(_) | AuthError::Jwt(_) => Some(error.to_string()),
694            AuthError::Validation { message } => Some(message.clone()),
695            AuthError::UserNotFound => Some("User not found".to_string()),
696            _ => None,
697        }
698    }
699
700    /// Complete multi-factor authentication.
701    ///
702    /// # Example
703    /// ```rust,ignore
704    /// let token = fw.complete_mfa(challenge, "123456").await?;
705    /// ```
706    pub async fn complete_mfa(&self, challenge: MfaChallenge, mfa_code: &str) -> Result<AuthToken> {
707        debug!("Completing MFA for challenge '{}'", challenge.id);
708
709        // Only the STORED challenge counts, and each call spends one of its attempts.
710        let stored_challenge = self
711            .mfa_manager
712            .begin_attempt(&challenge.id)
713            .await?
714            .ok_or(MfaError::ChallengeExpired)?;
715
716        // Verify MFA code based on challenge type
717        let is_valid = match &stored_challenge.mfa_type {
718            crate::methods::MfaType::Totp => {
719                self.mfa_manager
720                    .totp
721                    .verify_code(&stored_challenge.user_id, mfa_code)
722                    .await?
723            }
724            crate::methods::MfaType::Sms { .. } => {
725                self.mfa_manager
726                    .sms
727                    .verify_code(&challenge.id, mfa_code)
728                    .await?
729            }
730            crate::methods::MfaType::Email { .. } => {
731                self.mfa_manager
732                    .email
733                    .verify_code(&challenge.id, mfa_code)
734                    .await?
735            }
736            crate::methods::MfaType::BackupCode => {
737                self.mfa_manager
738                    .backup_codes
739                    .verify_code(&stored_challenge.user_id, mfa_code)
740                    .await?
741            }
742            _ => false,
743        };
744
745        if !is_valid {
746            if stored_challenge.attempts >= stored_challenge.max_attempts {
747                self.mfa_manager.remove_challenge(&challenge.id).await?;
748            }
749            return Err(MfaError::InvalidCode.into());
750        }
751
752        // Remove the challenge
753        self.mfa_manager.remove_challenge(&challenge.id).await?;
754
755        // Look up user roles from storage
756        let user_key = format!("user:{}", stored_challenge.user_id);
757        let scopes = if let Ok(Some(data)) = self.storage.get_kv(&user_key).await {
758            serde_json::from_slice::<serde_json::Value>(&data)
759                .ok()
760                .and_then(|v| {
761                    v.get("roles").and_then(|r| {
762                        r.as_array().map(|arr| {
763                            arr.iter()
764                                .filter_map(|v| v.as_str().map(String::from))
765                                .collect::<Vec<_>>()
766                        })
767                    })
768                })
769                .unwrap_or_else(|| vec!["user".to_string()])
770        } else {
771            vec!["user".to_string()]
772        };
773
774        // Create authentication token
775        let token =
776            self.token_manager
777                .create_auth_token(&stored_challenge.user_id, scopes, "mfa", None)?;
778
779        // Store the token
780        self.storage.store_token(&token).await?;
781
782        info!(
783            "MFA completed successfully for user '{}'",
784            stored_challenge.user_id
785        );
786
787        Ok(token)
788    }
789
790    /// Validate a token.
791    ///
792    /// # Example
793    /// ```rust,ignore
794    /// let valid = fw.validate_token(&token).await?;
795    /// ```
796    pub async fn validate_token(&self, token: &AuthToken) -> Result<bool> {
797        if !self.initialized {
798            return Err(AuthError::internal("Framework not initialized"));
799        }
800
801        // Check basic token validity
802        if !token.is_valid() {
803            return Ok(false);
804        }
805
806        // Validate with token manager
807        self.token_manager.validate_auth_token(token)?;
808
809        // The value must agree with the signed JWT it carries
810        if !crate::auth::token_value_matches_jwt(&self.token_manager, token) {
811            return Ok(false);
812        }
813
814        // Refuse tokens on the revocation list (logout / revocation)
815        if crate::auth::access_token_is_revoked(&self.token_manager, self.storage.as_ref(), token)
816            .await?
817        {
818            return Ok(false);
819        }
820
821        // Check if token exists in storage
822        if let Some(stored_token) = self.storage.get_token(&token.token_id).await?
823            && !stored_token.is_revoked()
824        {
825            // Update last used time
826            let mut updated_token = stored_token;
827            updated_token.mark_used();
828            self.storage.update_token(&updated_token).await?;
829
830            Ok(true)
831        } else {
832            Ok(false)
833        }
834    }
835
836    /// Get user information from a token.
837    ///
838    /// # Example
839    /// ```rust,ignore
840    /// let info = fw.get_user_info(&token).await?;
841    /// println!("username: {}", info.username);
842    /// ```
843    pub async fn get_user_info(&self, token: &AuthToken) -> Result<UserInfo> {
844        if !self.validate_token(token).await? {
845            return Err(AuthError::auth_method("token", "Invalid token".to_string()));
846        }
847
848        self.user_manager.get_user_info(&token.user_id).await
849    }
850
851    /// Check if a token has a specific permission.
852    ///
853    /// # Example
854    /// ```rust,ignore
855    /// let allowed = fw.check_permission(&token, "read", "users").await?;
856    /// ```
857    pub async fn check_permission(
858        &self,
859        token: &AuthToken,
860        action: &str,
861        resource: &str,
862    ) -> Result<bool> {
863        if !self.validate_token(token).await? {
864            return Ok(false);
865        }
866
867        let permission = Permission::new(action, resource);
868        let mut checker = self.permission_checker.write().await;
869        checker.check_token_permission(token, &permission)
870    }
871
872    /// Get the token manager.
873    ///
874    /// # Example
875    /// ```rust,ignore
876    /// let tm = fw.token_manager();
877    /// ```
878    pub fn token_manager(&self) -> &TokenManager {
879        &self.token_manager
880    }
881
882    /// Get the MFA manager.
883    ///
884    /// # Example
885    /// ```rust,ignore
886    /// let mfa = fw.mfa_manager();
887    /// ```
888    pub fn mfa_manager(&self) -> &MfaManager {
889        &self.mfa_manager
890    }
891
892    /// Get the session manager.
893    ///
894    /// # Example
895    /// ```rust,ignore
896    /// let sm = fw.session_manager();
897    /// ```
898    pub fn session_manager(&self) -> &SessionManager {
899        &self.session_manager
900    }
901
902    /// Get the user manager.
903    ///
904    /// # Example
905    /// ```rust,ignore
906    /// let um = fw.user_manager();
907    /// ```
908    pub fn user_manager(&self) -> &UserManager {
909        &self.user_manager
910    }
911
912    /// Initiate SMS challenge (uses SMSKit).
913    ///
914    /// # Example
915    /// ```rust,ignore
916    /// let challenge_id = fw.initiate_sms_challenge("user-1").await?;
917    /// ```
918    pub async fn initiate_sms_challenge(&self, user_id: &str) -> Result<String> {
919        self.mfa_manager.sms.initiate_challenge(user_id).await
920    }
921
922    /// Send SMS code (uses SMSKit).
923    ///
924    /// # Example
925    /// ```rust,ignore
926    /// fw.send_sms_code(&challenge_id, "+1234567890").await?;
927    /// ```
928    pub async fn send_sms_code(&self, challenge_id: &str, phone_number: &str) -> Result<()> {
929        self.mfa_manager
930            .sms
931            .send_code(challenge_id, phone_number)
932            .await
933    }
934
935    /// Generate SMS code (uses SMSKit).
936    ///
937    /// # Example
938    /// ```rust,ignore
939    /// let code = fw.generate_sms_code(&challenge_id).await?;
940    /// ```
941    pub async fn generate_sms_code(&self, challenge_id: &str) -> Result<String> {
942        self.mfa_manager.sms.generate_code(challenge_id).await
943    }
944
945    /// Verify SMS code (uses SMSKit).
946    ///
947    /// # Example
948    /// ```rust,ignore
949    /// let ok = fw.verify_sms_code(&challenge_id, "123456").await?;
950    /// ```
951    pub async fn verify_sms_code(&self, challenge_id: &str, code: &str) -> Result<bool> {
952        self.mfa_manager.sms.verify_code(challenge_id, code).await
953    }
954
955    /// Clean up expired data (sessions, MFA challenges, rate limiter entries).
956    ///
957    /// # Example
958    /// ```rust,ignore
959    /// fw.cleanup_expired_data().await?;
960    /// ```
961    pub async fn cleanup_expired_data(&self) -> Result<()> {
962        debug!("Cleaning up expired data");
963
964        // Clean up storage
965        self.storage.cleanup_expired().await?;
966
967        // Clean up MFA challenges
968        self.mfa_manager.cleanup_expired_challenges().await?;
969
970        // Clean up sessions
971        self.session_manager.cleanup_expired_sessions().await?;
972
973        // Clean up rate limiter
974        if let Some(ref rate_limiter) = self.rate_limiter {
975            let _ = rate_limiter.cleanup().ok();
976        }
977
978        Ok(())
979    }
980
981    /// Get authentication framework statistics.
982    ///
983    /// # Example
984    /// ```rust,ignore
985    /// let stats = fw.get_stats().await?;
986    /// println!("methods: {:?}", stats.registered_methods);
987    /// ```
988    pub async fn get_stats(&self) -> Result<AuthStats> {
989        let mut stats = AuthStats::default();
990
991        for method in self.methods.keys() {
992            stats.registered_methods.push(method.clone());
993        }
994
995        stats.active_mfa_challenges = self.mfa_manager.get_active_challenge_count().await as u64;
996
997        // Count tokens from storage as a proxy for tokens_issued
998        stats.tokens_issued = self.storage.count_active_sessions().await.unwrap_or(0) as u64;
999
1000        Ok(stats)
1001    }
1002
1003    /// Log an audit event
1004    async fn log_audit_event(
1005        &self,
1006        event_type: &str,
1007        user_id: &str,
1008        method: &str,
1009        metadata: &CredentialMetadata,
1010    ) {
1011        if self.config.audit.enabled {
1012            let should_log = match event_type {
1013                "auth_success" => self.config.audit.log_success,
1014                "auth_failure" => self.config.audit.log_failures,
1015                "mfa_required" => self.config.audit.log_success,
1016                _ => true,
1017            };
1018
1019            if should_log {
1020                info!(
1021                    target: "auth_audit",
1022                    event_type = event_type,
1023                    user_id = user_id,
1024                    method = method,
1025                    client_ip = metadata.client_ip.as_deref().unwrap_or("unknown"),
1026                    user_agent = metadata.user_agent.as_deref().unwrap_or("unknown"),
1027                    timestamp = chrono::Utc::now().to_rfc3339(),
1028                    "Authentication event"
1029                );
1030            }
1031        }
1032    }
1033}
1034
1035/// Authentication framework statistics
1036#[derive(Debug, Clone, Default)]
1037pub struct AuthStats {
1038    /// Number of registered authentication methods
1039    pub registered_methods: Vec<String>,
1040
1041    /// Number of active MFA challenges
1042    pub active_mfa_challenges: u64,
1043
1044    /// Number of tokens issued (this would need proper tracking)
1045    pub tokens_issued: u64,
1046
1047    /// Number of authentication attempts (this would need proper tracking)
1048    pub auth_attempts: u64,
1049}
1050
1051#[cfg(test)]
1052mod tests {
1053    use super::*;
1054    use crate::authentication::credentials::Credential;
1055    use crate::config::{AuthConfig, SecurityConfig};
1056    use std::time::Duration;
1057
1058    async fn initialized_framework(config: AuthConfig) -> AuthFramework {
1059        let mut framework = AuthFramework::new(config).expect("test config should be valid");
1060        framework
1061            .initialize()
1062            .await
1063            .expect("framework initialization should succeed");
1064        framework
1065    }
1066
1067    fn test_config() -> AuthConfig {
1068        AuthConfig::new().secret("test_secret_key_32_bytes_long!!!!")
1069    }
1070
1071    #[tokio::test]
1072    async fn test_modular_framework_initialization() {
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 mut framework = AuthFramework::new(config).expect("test config should be valid");
1086
1087        assert!(framework.initialize().await.is_ok());
1088        assert!(framework.initialized);
1089    }
1090
1091    #[tokio::test]
1092    async fn test_mfa_manager_access() {
1093        let config = AuthConfig::new().security(SecurityConfig {
1094            min_password_length: 8,
1095            require_password_complexity: false,
1096            password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
1097            jwt_algorithm: crate::config::JwtAlgorithm::HS256,
1098            secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string().into()),
1099            secure_cookies: false,
1100            cookie_same_site: crate::config::CookieSameSite::Lax,
1101            csrf_protection: false,
1102            session_timeout: Duration::from_secs(3600),
1103            previous_secret_key: None,
1104        });
1105        let framework = AuthFramework::new(config).expect("test config should be valid");
1106
1107        // Test that we can access specialized managers
1108        let _mfa_manager = framework.mfa_manager();
1109        let _session_manager = framework.session_manager();
1110        let _user_manager = framework.user_manager();
1111    }
1112
1113    #[tokio::test]
1114    async fn test_authenticate_with_metadata_enforces_minimum_duration() {
1115        let framework = initialized_framework(test_config()).await;
1116        let start = std::time::Instant::now();
1117
1118        let result = framework
1119            .authenticate_with_metadata(
1120                "oauth2",
1121                Credential::oauth_refresh(""),
1122                CredentialMetadata::new(),
1123            )
1124            .await
1125            .expect("empty refresh token should return failure, not error");
1126
1127        assert!(
1128            start.elapsed() >= std::time::Duration::from_millis(90),
1129            "timing floor should add a noticeable delay"
1130        );
1131        assert!(matches!(result, AuthResult::Failure(_)));
1132    }
1133
1134    #[tokio::test]
1135    async fn test_authenticate_oauth2_refresh_empty_returns_failure() {
1136        let framework = initialized_framework(test_config()).await;
1137
1138        let result = framework
1139            .authenticate("oauth2", Credential::oauth_refresh(""))
1140            .await
1141            .expect("empty refresh token should return failure, not error");
1142
1143        match result {
1144            AuthResult::Failure(reason) => {
1145                assert!(reason.contains("refresh token cannot be empty"));
1146            }
1147            _ => panic!("expected failure result for empty OAuth refresh token"),
1148        }
1149    }
1150
1151    #[tokio::test]
1152    async fn test_authenticate_oauth2_openid_connect_routes_to_jwt_validation() {
1153        let framework = initialized_framework(test_config()).await;
1154        let jwt = framework
1155            .token_manager()
1156            .create_jwt_token("oidc-user", vec!["openid".to_string()], None)
1157            .expect("jwt creation should succeed");
1158
1159        let result = framework
1160            .authenticate("oauth2", Credential::openid_connect(jwt))
1161            .await
1162            .expect("valid OIDC credential should authenticate");
1163
1164        match result {
1165            AuthResult::Success(token) => {
1166                assert_eq!(token.user_id, "oidc-user");
1167                assert_eq!(token.auth_method, "oauth2");
1168            }
1169            _ => panic!("expected success result for OpenID Connect credential"),
1170        }
1171    }
1172
1173    #[tokio::test]
1174    async fn test_authenticate_oauth2_unsupported_credential_returns_failure() {
1175        let framework = initialized_framework(test_config()).await;
1176
1177        let result = framework
1178            .authenticate("oauth2", Credential::password("alice", "secret"))
1179            .await
1180            .expect("unsupported credential should return failure, not error");
1181
1182        match result {
1183            AuthResult::Failure(reason) => {
1184                assert!(reason.contains("OAuth2 authentication expects"));
1185            }
1186            _ => panic!("expected failure result for unsupported OAuth2 credential"),
1187        }
1188    }
1189
1190    #[tokio::test]
1191    async fn test_rate_limiting_without_client_ip_uses_shared_unknown_bucket() {
1192        let config = AuthConfig::new()
1193            .secret("test_secret_key_32_bytes_long!!!!")
1194            .rate_limiting(crate::config::RateLimitConfig {
1195                enabled: true,
1196                max_requests: 1,
1197                window: Duration::from_secs(60),
1198                burst: 0,
1199            });
1200        let framework = initialized_framework(config).await;
1201
1202        let first = framework
1203            .authenticate_with_metadata(
1204                "oauth2",
1205                Credential::oauth_code("first-code"),
1206                CredentialMetadata::new(),
1207            )
1208            .await
1209            .expect("first request should pass rate limiting");
1210        assert!(matches!(first, AuthResult::Failure(_)));
1211
1212        let second = framework
1213            .authenticate_with_metadata(
1214                "oauth2",
1215                Credential::oauth_code("second-code"),
1216                CredentialMetadata::new(),
1217            )
1218            .await;
1219        assert!(second.is_err(), "second request should be rate limited");
1220        assert!(
1221            second
1222                .unwrap_err()
1223                .to_string()
1224                .contains("Too many authentication attempts")
1225        );
1226    }
1227
1228    #[tokio::test]
1229    async fn test_complete_mfa_missing_challenge_returns_expired_error() {
1230        let framework = initialized_framework(test_config()).await;
1231        let challenge = MfaChallenge::new(
1232            crate::methods::MfaType::BackupCode,
1233            "user-123",
1234            Duration::from_secs(60),
1235        );
1236
1237        let result = framework.complete_mfa(challenge, "123456").await;
1238        assert!(result.is_err());
1239        assert!(result.unwrap_err().to_string().contains("expired"));
1240    }
1241
1242    #[tokio::test]
1243    async fn test_complete_mfa_expired_challenge_is_removed() {
1244        let framework = initialized_framework(test_config()).await;
1245        let mut challenge = MfaChallenge::new(
1246            crate::methods::MfaType::BackupCode,
1247            "user-123",
1248            Duration::from_secs(60),
1249        );
1250        challenge.expires_at = chrono::Utc::now() - chrono::Duration::seconds(1);
1251        framework
1252            .mfa_manager
1253            .store_challenge(challenge.clone())
1254            .await
1255            .expect("storing challenge should succeed");
1256
1257        let result = framework.complete_mfa(challenge.clone(), "123456").await;
1258        assert!(result.is_err());
1259        assert!(result.unwrap_err().to_string().contains("expired"));
1260        assert!(
1261            framework
1262                .mfa_manager
1263                .get_challenge(&challenge.id)
1264                .await
1265                .expect("challenge lookup should succeed")
1266                .is_none()
1267        );
1268    }
1269
1270    #[tokio::test]
1271    async fn test_validate_token_returns_false_for_expired_token() {
1272        let framework = initialized_framework(test_config()).await;
1273        let mut token = framework
1274            .token_manager()
1275            .create_auth_token("user-123", vec!["read".to_string()], "jwt", None)
1276            .expect("token creation should succeed");
1277        token.expires_at = chrono::Utc::now() - chrono::Duration::seconds(1);
1278
1279        let valid = framework
1280            .validate_token(&token)
1281            .await
1282            .expect("expired token should return false, not error");
1283        assert!(!valid);
1284    }
1285
1286    #[tokio::test]
1287    async fn test_validate_token_returns_false_when_not_in_storage() {
1288        let framework = initialized_framework(test_config()).await;
1289        let token = framework
1290            .token_manager()
1291            .create_auth_token("user-123", vec!["read".to_string()], "jwt", None)
1292            .expect("token creation should succeed");
1293
1294        let valid = framework
1295            .validate_token(&token)
1296            .await
1297            .expect("missing stored token should return false, not error");
1298        assert!(!valid);
1299    }
1300
1301    /// Regression test for a past review finding: this module's Redis
1302    /// construction path used to build `RedisStorage` directly with no
1303    /// encryption wrapping at all. If the `wrap_with_encryption_if_enabled`
1304    /// call this fix added is ever removed again, construction would
1305    /// SUCCEED here instead of failing closed (no key is configured),
1306    /// silently reintroducing the gap. `RedisStorage::new` only parses the
1307    /// URL -- it doesn't connect -- so this doesn't need a live server.
1308    #[cfg(feature = "redis-storage")]
1309    #[test]
1310    fn redis_construction_fails_closed_without_an_encryption_key() {
1311        let _lock = crate::storage::encryption::TEST_ENCRYPTION_ENV_LOCK.blocking_lock();
1312        // SAFETY: sound against every other test that ALSO takes
1313        // `_lock`; this test does.
1314        unsafe {
1315            std::env::remove_var("AUTH_STORAGE_ENCRYPTION_KEY");
1316            std::env::remove_var("AUTH_STORAGE_ENCRYPTION_KEYS_FILE");
1317        }
1318
1319        let mut config = test_config();
1320        config.storage = crate::config::StorageConfig::Redis {
1321            url: "redis://127.0.0.1:1/".to_string(),
1322            key_prefix: "test:".to_string(),
1323        };
1324        // storage_encryption defaults to enabled: true.
1325
1326        let result = AuthFramework::new(config);
1327        assert!(
1328            result.is_err(),
1329            "constructing this modular framework with Redis storage and no encryption key \
1330             configured must fail closed, not silently build unwrapped (unencrypted) storage"
1331        );
1332    }
1333}