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