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