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