Skip to main content

auth_framework/
auth.rs

1//! Main authentication framework implementation.
2
3use crate::auth_operations::{
4    AuditLogQuery, DelegationRequest, PermissionContext, SessionCreateRequest, UserListQuery,
5};
6use crate::authentication::credentials::{Credential, CredentialMetadata};
7use crate::config::AuthConfig;
8use crate::distributed::DistributedSessionStore;
9use crate::errors::{AuthError, MfaError, Result};
10use crate::methods::{AuthMethod, AuthMethodEnum, MethodResult, MfaChallenge};
11use crate::permissions::PermissionChecker;
12use crate::storage::{AuthStorage, MemoryStorage, SessionData};
13use crate::tokens::{AuthToken, TokenManager};
14use crate::utils::rate_limit::RateLimiter;
15use std::collections::HashMap;
16use std::sync::Arc;
17use std::time::Duration;
18use tokio::sync::RwLock;
19use tracing::{debug, error, info, warn};
20
21/// Result of an authentication attempt.
22#[derive(Debug, Clone)]
23pub enum AuthResult {
24    /// Authentication was successful
25    Success(Box<AuthToken>),
26
27    /// Multi-factor authentication is required
28    MfaRequired(Box<MfaChallenge>),
29
30    /// Authentication failed
31    Failure(String),
32}
33
34/// Information about a user.
35#[derive(Debug, Clone)]
36pub struct UserInfo {
37    /// User ID
38    pub id: String,
39
40    /// Username
41    pub username: String,
42
43    /// Email address
44    pub email: Option<String>,
45
46    /// Display name
47    pub name: Option<String>,
48
49    /// User roles
50    pub roles: crate::types::Roles,
51
52    /// Whether the user is active
53    pub active: bool,
54
55    /// Whether the user's email address has been verified
56    pub email_verified: bool,
57
58    /// Additional user attributes
59    pub attributes: crate::types::UserAttributes,
60}
61
62/// Returns true when running in a test environment.
63///
64/// Checks `cfg!(test)`, the `RUST_TEST` env var (set by `TestEnvironmentGuard`), and the
65/// `ENVIRONMENT=test` convention. This allows relaxed security constraints (e.g. short JWT
66/// secrets) in automated tests while enforcing them in production.
67///
68/// An explicit `ENVIRONMENT=production` setting always overrides → returns `false`, so tests
69/// that deliberately validate production-mode behaviour can opt out of the bypass.
70#[inline]
71fn is_test_env() -> bool {
72    // An explicit production override always wins — never bypass security checks.
73    if std::env::var("ENVIRONMENT").as_deref() == Ok("production") {
74        return false;
75    }
76    cfg!(test)
77        || std::env::var("RUST_TEST").is_ok()
78        || std::env::var("ENVIRONMENT").as_deref() == Ok("test")
79}
80
81/// The primary authentication and authorization framework for Rust applications.
82///
83/// `AuthFramework` is the central component that orchestrates all authentication
84/// and authorization operations. It provides a unified interface for multiple
85/// authentication methods, token management, session handling, and security monitoring.
86///
87/// # Core Capabilities
88///
89/// - **Multi-Method Authentication**: Support for password, OAuth2, MFA, passkeys, and custom methods
90/// - **Token Management**: JWT token creation, validation, and lifecycle management
91/// - **Session Management**: Secure session handling with configurable storage backends
92/// - **Permission System**: Role-based and resource-based authorization
93/// - **Security Monitoring**: Real-time threat detection and audit logging
94/// - **Rate Limiting**: Configurable rate limiting for brute force protection
95///
96/// # Thread Safety
97///
98/// The framework is designed for concurrent use and can be safely shared across
99/// multiple threads using `Arc<AuthFramework>`.
100///
101/// # Storage Backends
102///
103/// Supports multiple storage backends:
104/// - In-memory (for development/testing)
105/// - Redis (for production with clustering)
106/// - PostgreSQL (for persistent storage)
107/// - Custom implementations via the `AuthStorage` trait
108///
109/// # Example
110///
111/// ```rust,no_run
112/// use auth_framework::{AuthFramework, AuthConfig};
113/// use auth_framework::authentication::credentials::Credential;
114/// use auth_framework::methods::AuthMethodEnum;
115///
116/// # #[tokio::main]
117/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
118/// // Create framework with default configuration
119/// let config = AuthConfig::default();
120/// let mut auth = AuthFramework::new(config);
121///
122/// // Register an authentication method
123/// # let password_method: AuthMethodEnum = unimplemented!();
124/// auth.register_method("password", password_method);
125///
126/// // Authenticate a user
127/// # let credential: Credential = unimplemented!();
128/// let result = auth.authenticate("password", credential).await?;
129/// # Ok(())
130/// # }
131/// ```
132///
133/// # Security Considerations
134///
135/// - All tokens are signed with cryptographically secure keys
136/// - Session data is encrypted at rest when using persistent storage
137/// - Rate limiting prevents brute force attacks
138/// - Audit logging captures all security-relevant events
139/// - Configurable security policies for enterprise compliance
140pub struct AuthFramework {
141    /// Configuration
142    config: AuthConfig,
143
144    /// Registered authentication methods
145    methods: HashMap<String, AuthMethodEnum>,
146
147    /// Token manager
148    token_manager: TokenManager,
149
150    /// Storage backend
151    storage: Arc<dyn AuthStorage>,
152
153    /// Authorization manager for role/permission operations
154    authorization_manager: crate::auth_modular::authorization_manager::AuthorizationManager,
155
156    /// Rate limiter
157    rate_limiter: Option<RateLimiter>,
158
159    /// Monitoring manager for metrics and health checks
160    monitoring_manager: Arc<crate::monitoring::MonitoringManager>,
161
162    /// Audit manager for security event logging
163    audit_manager: Arc<crate::audit::AuditLogger<Arc<crate::storage::MemoryStorage>>>,
164
165    /// Security manager for rate limiting, DoS protection, and IP blacklisting
166    #[cfg(feature = "api-server")]
167    security_manager: Arc<crate::api::SecurityManager>,
168
169    /// Runtime-mutable configuration. Updated live by the admin API without restart.
170    pub(crate) runtime_config: Arc<tokio::sync::RwLock<crate::config::RuntimeConfig>>,
171
172    /// Decoupled user lifecycle manager.
173    user_manager: crate::auth_modular::user_manager::UserManager,
174
175    /// Decoupled session lifecycle manager.
176    session_manager: crate::auth_modular::session_manager::SessionManager,
177
178    /// Decoupled MFA manager (TOTP, SMS, email, backup codes).
179    mfa_manager: crate::auth_modular::mfa::MfaManager,
180
181    /// Framework initialization state
182    initialized: bool,
183
184    /// Whether the caller explicitly replaced the storage backend.
185    storage_overridden: bool,
186}
187
188pub use crate::auth_operations::{
189    AdminOperations, AuditOperations, AuthorizationOperations, MaintenanceOperations,
190    MfaOperations, MonitoringOperations, SessionOperations, TokenOperations, UserOperations,
191};
192
193/// Extract JWT secret bytes from `config` or the `JWT_SECRET` env-var.
194///
195/// Tries (in order): `config.security.secret_key`, `config.secret`, `$JWT_SECRET`.
196/// Returns an error when none is present; callers in non-production environments may
197/// substitute a dev-only fallback when this function returns `Err`.
198fn resolve_jwt_secret_bytes(config: &AuthConfig) -> Result<Vec<u8>> {
199    if let Some(secret) = &config.security.secret_key {
200        if secret.len() < 32 && !is_test_env() {
201            return Err(AuthError::configuration(
202                "JWT secret must be at least 32 characters for production security",
203            ));
204        }
205        return Ok(secret.as_bytes().to_vec());
206    }
207    if let Some(secret) = &config.secret {
208        if secret.len() < 32 && !is_test_env() {
209            return Err(AuthError::configuration(
210                "JWT secret must be at least 32 characters for production security",
211            ));
212        }
213        return Ok(secret.as_bytes().to_vec());
214    }
215    if let Ok(jwt_secret) = std::env::var("JWT_SECRET") {
216        if jwt_secret.len() < 32 && !is_test_env() {
217            return Err(AuthError::configuration(
218                "JWT_SECRET must be at least 32 characters for production security",
219            ));
220        }
221        return Ok(jwt_secret.as_bytes().to_vec());
222    }
223    Err(AuthError::configuration(
224        "JWT secret not configured! Please set JWT_SECRET environment variable or provide in configuration.\n\
225           For security reasons, no default secret is provided.\n\
226           Generate a secure secret with: openssl rand -base64 32",
227    ))
228}
229
230impl AuthFramework {
231    /// Access focused user-management operations.
232    pub fn users(&self) -> UserOperations<'_> {
233        UserOperations { framework: self }
234    }
235
236    /// Access focused session-management operations.
237    pub fn sessions(&self) -> SessionOperations<'_> {
238        SessionOperations { framework: self }
239    }
240
241    /// Access focused token-management operations.
242    pub fn tokens(&self) -> TokenOperations<'_> {
243        TokenOperations { framework: self }
244    }
245
246    /// Access focused authorization operations.
247    pub fn authorization(&self) -> AuthorizationOperations<'_> {
248        AuthorizationOperations { framework: self }
249    }
250
251    /// Access focused multi-factor authentication operations.
252    pub fn mfa(&self) -> MfaOperations<'_> {
253        MfaOperations { framework: self }
254    }
255
256    /// Access focused monitoring and health operations.
257    pub fn monitoring(&self) -> MonitoringOperations<'_> {
258        MonitoringOperations { framework: self }
259    }
260
261    /// Access focused audit log operations.
262    pub fn audit(&self) -> AuditOperations<'_> {
263        AuditOperations { framework: self }
264    }
265
266    /// Access focused maintenance operations.
267    pub fn maintenance(&self) -> MaintenanceOperations<'_> {
268        MaintenanceOperations { framework: self }
269    }
270
271    /// Read the current runtime-mutable configuration.
272    pub async fn runtime_config(&self) -> crate::config::RuntimeConfig {
273        self.runtime_config.read().await.clone()
274    }
275
276    #[deprecated(since = "0.6.0", note = "Use `runtime_config()` instead")]
277    #[doc(hidden)]
278    pub async fn get_runtime_config(&self) -> crate::config::RuntimeConfig {
279        self.runtime_config().await
280    }
281
282    /// Apply a partial or full update to the runtime-mutable configuration.
283    ///
284    /// The update is applied atomically. Returns the updated configuration.
285    /// Returns `Err` if any field value is out of range (e.g. zero token lifetime).
286    pub async fn update_runtime_config(
287        &self,
288        update: crate::config::RuntimeConfig,
289    ) -> Result<crate::config::RuntimeConfig> {
290        // Basic sanity checks before persisting.
291        if update.token_lifetime_secs == 0 {
292            return Err(AuthError::config("token_lifetime_secs must be > 0"));
293        }
294        if update.refresh_token_lifetime_secs == 0 {
295            return Err(AuthError::config("refresh_token_lifetime_secs must be > 0"));
296        }
297        if update.refresh_token_lifetime_secs <= update.token_lifetime_secs {
298            return Err(AuthError::config(
299                "refresh_token_lifetime_secs must be greater than token_lifetime_secs",
300            ));
301        }
302        if update.min_password_length == 0 {
303            return Err(AuthError::config("min_password_length must be > 0"));
304        }
305        let mut cfg = self.runtime_config.write().await;
306        *cfg = update.clone();
307        Ok(update)
308    }
309
310    /// Access focused advanced administration operations (ABAC, delegation, role hierarchy).
311    pub fn admin(&self) -> AdminOperations<'_> {
312        AdminOperations { framework: self }
313    }
314
315    /// Create a new authentication framework.
316    ///
317    /// This method is infallible and creates a basic framework instance.
318    /// Configuration validation and component initialization is deferred to `initialize()`.
319    /// An ephemeral random secret is used for the token manager until `initialize()`
320    /// replaces it with the configured secret. Tokens issued before initialization
321    /// will NOT be valid afterwards.
322    pub fn new(config: AuthConfig) -> Self {
323        // Store configuration for later validation during initialize()
324        let storage = Arc::new(MemoryStorage::new()) as Arc<dyn AuthStorage>;
325        let audit_storage = Arc::new(crate::storage::MemoryStorage::new());
326        let audit_manager = Arc::new(crate::audit::AuditLogger::new(audit_storage));
327
328        // Create a token manager with a cryptographically random ephemeral secret.
329        // This avoids holding a well-known hardcoded secret in memory.  The real
330        // configured secret is applied during initialize().
331        // SAFETY: CSPRNG failure at initialization is terminal; the framework
332        // cannot operate without entropy.
333        let ephemeral_secret = {
334            let rng = ring::rand::SystemRandom::new();
335            let mut buf = [0u8; 32];
336            ring::rand::SecureRandom::fill(&rng, &mut buf)
337                .expect("AuthFramework fatal: system CSPRNG unavailable — the operating system cannot provide cryptographic randomness");
338            buf
339        };
340        let token_manager =
341            TokenManager::new_hmac(&ephemeral_secret, "auth-framework", "auth-framework");
342
343        let user_manager = crate::auth_modular::user_manager::UserManager::new(storage.clone());
344        let session_manager =
345            crate::auth_modular::session_manager::SessionManager::new(storage.clone());
346        let mfa_manager = crate::auth_modular::mfa::MfaManager::new(storage.clone());
347        let authorization_manager =
348            crate::auth_modular::authorization_manager::AuthorizationManager::new(
349                Arc::new(RwLock::new(PermissionChecker::new())),
350                storage.clone(),
351            );
352
353        Self {
354            config,
355            methods: HashMap::new(),
356            token_manager,
357            storage,
358            authorization_manager,
359            rate_limiter: None, // Will be set during initialization
360            monitoring_manager: Arc::new(crate::monitoring::MonitoringManager::new(
361                crate::monitoring::MonitoringConfig::default(),
362            )),
363            audit_manager,
364            #[cfg(feature = "api-server")]
365            security_manager: Arc::new(crate::api::SecurityManager::new()),
366            runtime_config: Arc::new(tokio::sync::RwLock::new(
367                crate::config::RuntimeConfig::default(),
368            )),
369            user_manager,
370            session_manager,
371            mfa_manager,
372            initialized: false,
373            storage_overridden: false,
374        }
375    }
376
377    /// Create a new authentication framework with validation.
378    ///
379    /// This method validates the configuration immediately and returns an error
380    /// if the configuration is invalid. Use this when you want early validation.
381    pub fn new_validated(config: AuthConfig) -> Result<Self> {
382        // Validate configuration - return error instead of panicking
383        config.validate().map_err(|e| {
384            AuthError::configuration(format!("Configuration validation failed: {}", e))
385        })?;
386
387        // Create token manager with proper error handling
388        let current_secret_bytes = resolve_jwt_secret_bytes(&config)?;
389
390        let mut token_manager =
391            TokenManager::new_hmac(&current_secret_bytes, "auth-framework", "auth-framework");
392
393        // Handle gracefully retained old secret for zero-downtime key rotation
394        if let Some(prev_secret) = &config.security.previous_secret_key {
395            // Initialize with previous key, then rotate to the new key
396            token_manager =
397                TokenManager::new_hmac(prev_secret.as_bytes(), "auth-framework", "auth-framework");
398            token_manager.rotate_hmac_key(&current_secret_bytes);
399        }
400
401        // Create storage backend with proper error handling
402        let storage: Arc<dyn AuthStorage> = match &config.storage {
403            #[cfg(feature = "redis-storage")]
404            crate::config::StorageConfig::Redis { url, key_prefix } => Arc::new(
405                crate::storage::RedisStorage::new(url, key_prefix).map_err(|e| {
406                    AuthError::configuration(format!("Failed to create Redis storage: {}", e))
407                })?,
408            ),
409            _ => Arc::new(MemoryStorage::new()) as Arc<dyn AuthStorage>,
410        };
411
412        // Create rate limiter if enabled
413        let rate_limiter = if config.rate_limiting.enabled {
414            Some(RateLimiter::new(
415                config.rate_limiting.max_requests,
416                config.rate_limiting.window,
417            ))
418        } else {
419            None
420        };
421
422        // Create audit manager
423        let audit_storage = Arc::new(crate::storage::MemoryStorage::new());
424        let audit_manager = Arc::new(crate::audit::AuditLogger::new(audit_storage));
425
426        let user_manager = crate::auth_modular::user_manager::UserManager::new(storage.clone());
427        let session_manager =
428            crate::auth_modular::session_manager::SessionManager::new(storage.clone());
429        let mfa_manager = crate::auth_modular::mfa::MfaManager::new(storage.clone());
430        let authorization_manager =
431            crate::auth_modular::authorization_manager::AuthorizationManager::new(
432                Arc::new(RwLock::new(PermissionChecker::new())),
433                storage.clone(),
434            );
435
436        Ok(Self {
437            config: config.clone(),
438            methods: HashMap::new(),
439            token_manager,
440            storage,
441            authorization_manager,
442            rate_limiter,
443            monitoring_manager: Arc::new(crate::monitoring::MonitoringManager::new(
444                crate::monitoring::MonitoringConfig::default(),
445            )),
446            audit_manager,
447            #[cfg(feature = "api-server")]
448            security_manager: Arc::new(crate::api::SecurityManager::new()),
449            runtime_config: Arc::new(tokio::sync::RwLock::new(
450                crate::config::RuntimeConfig::from_auth_config(&config),
451            )),
452            user_manager,
453            session_manager,
454            mfa_manager,
455            initialized: false,
456            storage_overridden: false,
457        })
458    }
459
460    /// Replace the storage backend with a custom implementation.
461    ///
462    /// This will swap the internal storage Arc so subsequent operations use
463    /// the provided storage instance. Implementations that rely on a
464    /// different concrete storage may need additional reconfiguration by the
465    /// caller.
466    pub fn replace_storage(&mut self, storage: std::sync::Arc<dyn AuthStorage>) {
467        self.storage = storage.clone();
468        self.user_manager = crate::auth_modular::user_manager::UserManager::new(storage.clone());
469        self.session_manager =
470            crate::auth_modular::session_manager::SessionManager::new(storage.clone());
471        self.mfa_manager = crate::auth_modular::mfa::MfaManager::new(storage.clone());
472        self.authorization_manager =
473            crate::auth_modular::authorization_manager::AuthorizationManager::new(
474                Arc::new(RwLock::new(PermissionChecker::new())),
475                storage,
476            );
477        self.storage_overridden = true;
478    }
479
480    /// Replace the distributed session store.
481    ///
482    /// Call this during application startup after configuring a distributed cache
483    /// (Redis, Valkey, Hazelcast, etc.) so that
484    /// [`coordinate_distributed_sessions`][Self::coordinate_distributed_sessions]
485    /// reports accurate cross-node session counts instead of `0`.
486    pub fn set_distributed_store(&mut self, store: Arc<dyn DistributedSessionStore>) {
487        self.session_manager.set_distributed_store(store);
488    }
489
490    /// Convenience constructor that creates a framework with a custom storage instance.
491    pub fn new_with_storage(config: AuthConfig, storage: std::sync::Arc<dyn AuthStorage>) -> Self {
492        let mut framework = Self::new(config);
493        framework.replace_storage(storage);
494        framework
495    }
496
497    /// Register an authentication method.
498    pub fn register_method(&mut self, name: impl Into<String>, method: AuthMethodEnum) {
499        let name = name.into();
500        info!("Registering authentication method: {}", name);
501
502        // Validate method configuration
503        if let Err(e) = method.validate_config() {
504            error!("Method '{}' configuration validation failed: {}", name, e);
505            return;
506        }
507
508        self.methods.insert(name, method);
509    }
510
511    /// Returns `Ok(())` when the framework has been initialised, or a clear
512    /// error telling the caller what to do.
513    ///
514    /// Prefer calling this at the top of every public method that touches
515    /// storage, tokens, sessions, or authorisation state.
516    fn require_initialized(&self) -> Result<()> {
517        if self.initialized {
518            Ok(())
519        } else {
520            Err(AuthError::configuration(
521                "Framework not initialized. Call `initialize().await` first, \
522                 or use `AuthFramework::builder().build().await` which initializes automatically.",
523            ))
524        }
525    }
526
527    /// Initialize the authentication framework.
528    ///
529    /// This method performs configuration validation, sets up secure components,
530    /// and prepares the framework for use. It must be called before any other operations.
531    ///
532    /// # Security Note
533    ///
534    /// This method validates JWT secrets and replaces any temporary secrets with
535    /// properly configured ones for production security.
536    pub async fn initialize(&mut self) -> Result<()> {
537        if self.initialized {
538            return Ok(());
539        }
540
541        info!("Initializing authentication framework");
542
543        // Validate configuration
544        self.config.validate().map_err(|e| {
545            AuthError::configuration(format!("Configuration validation failed: {}", e))
546        })?;
547
548        // Set up proper token manager with validated configuration
549        let token_manager = match resolve_jwt_secret_bytes(&self.config) {
550            Ok(bytes) => TokenManager::new_hmac(&bytes, "auth-framework", "auth-framework"),
551            Err(_) => {
552                if Self::is_production_environment() {
553                    return Err(AuthError::configuration(
554                        "Production deployment requires JWT_SECRET environment variable or configuration!\n\
555                         Generate a secure secret with: openssl rand -base64 32\n\
556                         Set it with: export JWT_SECRET=\"your-secret-here\"",
557                    ));
558                }
559                warn!("No JWT secret configured, using development-only default");
560                warn!("CRITICAL: Set JWT_SECRET environment variable for production!");
561                warn!("This configuration is NOT SECURE and should only be used in development!");
562                self.token_manager.clone()
563            }
564        };
565
566        // Replace token manager with properly configured one
567        self.token_manager = token_manager;
568
569        // Set up storage backend if not already configured
570        if !self.storage_overridden {
571            let storage =
572                crate::storage::factory::build_storage_backend(&self.config.storage, None).await?;
573            self.replace_storage(storage);
574            self.storage_overridden = false;
575        }
576
577        // Set up rate limiter if enabled
578        if self.config.rate_limiting.enabled {
579            self.rate_limiter = Some(RateLimiter::new(
580                self.config.rate_limiting.max_requests,
581                self.config.rate_limiting.window,
582            ));
583        }
584
585        // Initialize permission checker with default roles
586        self.authorization_manager.create_default_roles().await;
587
588        // Load any previously persisted roles and user→role assignments
589        self.authorization_manager.load_persisted_roles().await?;
590
591        // Perform any necessary setup
592        self.cleanup_expired_data().await?;
593
594        self.initialized = true;
595        info!("Authentication framework initialized successfully");
596
597        Ok(())
598    }
599
600    /// Authenticate a user with the specified method.
601    ///
602    /// `method_name` must match a previously registered authentication method
603    /// (e.g. `"password"`, `"jwt"`, `"oauth2"`).
604    ///
605    /// # Returns
606    ///
607    /// - [`AuthResult::Success`] — authentication succeeded; contains the issued token.
608    /// - [`AuthResult::MfaRequired`] — first factor passed but MFA is required.
609    /// - [`AuthResult::Failure`] — invalid credentials.
610    ///
611    /// # Example
612    ///
613    /// ```rust,no_run
614    /// # use auth_framework::prelude::*;
615    /// # use auth_framework::authentication::credentials::Credential;
616    /// # use auth_framework::auth::AuthResult;
617    /// # async fn example(auth: &AuthFramework) -> Result<(), AuthError> {
618    /// let result = auth.authenticate("password", Credential::password("alice", "S3cur3P@ss!")).await?;
619    /// match result {
620    ///     AuthResult::Success(token) => println!("Token: {}", token.access_token),
621    ///     AuthResult::MfaRequired(challenge) => println!("MFA needed: {:?}", challenge),
622    ///     AuthResult::Failure(msg) => eprintln!("Login failed: {msg}"),
623    /// }
624    /// # Ok(())
625    /// # }
626    /// ```
627    pub async fn authenticate(
628        &self,
629        method_name: &str,
630        credential: Credential,
631    ) -> Result<AuthResult> {
632        self.authenticate_with_metadata(method_name, credential, CredentialMetadata::new())
633            .await
634    }
635
636    /// Authenticate a user with the specified method and metadata.
637    pub async fn authenticate_with_metadata(
638        &self,
639        method_name: &str,
640        credential: Credential,
641        metadata: CredentialMetadata,
642    ) -> Result<AuthResult> {
643        use std::time::Instant;
644        use tokio::time::{Duration as TokioDuration, sleep};
645
646        let start_time = Instant::now();
647
648        // Record authentication request
649        self.monitoring_manager.record_auth_request().await;
650
651        self.require_initialized()?;
652
653        // Perform the authentication logic
654        let result = self
655            .authenticate_internal(method_name, credential, metadata)
656            .await;
657
658        // Ensure minimum response time to prevent timing attacks
659        let min_duration = TokioDuration::from_millis(100); // 100ms minimum
660        let elapsed = start_time.elapsed();
661        if elapsed < min_duration {
662            sleep(min_duration - elapsed).await;
663        }
664
665        // Record authentication performance
666        if let Ok(ref auth_result) = result {
667            match auth_result {
668                AuthResult::Success(token) => {
669                    self.monitoring_manager
670                        .record_auth_success(&token.user_id, elapsed)
671                        .await;
672                }
673                AuthResult::Failure(reason) => {
674                    self.monitoring_manager
675                        .record_auth_failure(None, reason)
676                        .await;
677                }
678                _ => {} // MFA required - not counted as failure
679            }
680        }
681
682        result
683    }
684
685    /// Internal authentication logic without timing protection
686    async fn authenticate_internal(
687        &self,
688        method_name: &str,
689        credential: Credential,
690        metadata: CredentialMetadata,
691    ) -> Result<AuthResult> {
692        // Check rate limiting
693        if let Some(ref rate_limiter) = self.rate_limiter {
694            let rate_key = format!(
695                "auth:{}:{}",
696                method_name,
697                metadata.client_ip.as_deref().unwrap_or("unknown")
698            );
699
700            if !rate_limiter.is_allowed(&rate_key) {
701                warn!(
702                    "Rate limit exceeded for method '{}' from IP {:?}",
703                    method_name, metadata.client_ip
704                );
705                return Err(AuthError::rate_limit("Too many authentication attempts"));
706            }
707        }
708
709        // Built-in password authentication: reads credentials from framework storage directly.
710        // This handles password auth even when no "password" method has been explicitly registered,
711        // allowing the register endpoint and login endpoint to work with the same storage backend.
712        if method_name == "password"
713            && let Credential::Password {
714                ref username,
715                ref password,
716            } = credential
717        {
718            return self
719                .authenticate_password_builtin(username, password, &metadata)
720                .await;
721        }
722
723        if method_name == "jwt" {
724            return match credential {
725                Credential::Jwt { token } | Credential::Bearer { token } => {
726                    self.authenticate_jwt_builtin(&token, &metadata, "jwt")
727                        .await
728                }
729                _ => Ok(AuthResult::Failure(
730                    "JWT authentication expects Credential::jwt or Credential::bearer".to_string(),
731                )),
732            };
733        }
734
735        if matches!(method_name, "api_key" | "api-key") {
736            return match credential {
737                Credential::ApiKey { key } => {
738                    self.authenticate_api_key_builtin(&key, &metadata, "api_key")
739                        .await
740                }
741                _ => Ok(AuthResult::Failure(
742                    "API key authentication expects Credential::api_key".to_string(),
743                )),
744            };
745        }
746
747        if method_name == "oauth2" {
748            return self
749                .authenticate_oauth2_builtin(credential, &metadata)
750                .await;
751        }
752
753        // Get the authentication method
754        let method = self.methods.get(method_name).ok_or_else(|| {
755            AuthError::auth_method(method_name, "Authentication method not found".to_string())
756        })?;
757
758        // Log authentication attempt
759        debug!(
760            "Authentication attempt with method '{}' for credential: {}",
761            method_name,
762            credential.safe_display()
763        );
764
765        // Perform authentication
766        let result = method.authenticate(credential, metadata.clone()).await?;
767
768        // Log and handle the result
769        match &result {
770            MethodResult::Success(token) => {
771                info!(
772                    "Authentication successful for user '{}' with method '{}'",
773                    token.user_id, method_name
774                );
775
776                // Store token
777                self.storage.store_token(token).await?;
778
779                // Log audit event
780                self.log_audit_event("auth_success", &token.user_id, method_name, &metadata)
781                    .await;
782
783                Ok(AuthResult::Success(token.clone()))
784            }
785
786            MethodResult::MfaRequired(challenge) => {
787                info!(
788                    "MFA required for user '{}' with method '{}'",
789                    challenge.user_id, method_name
790                );
791
792                // Store MFA challenge with resource limits
793                self.guard_and_store_mfa_challenge((**challenge).clone())
794                    .await?;
795
796                // Log audit event
797                self.log_audit_event("mfa_required", &challenge.user_id, method_name, &metadata)
798                    .await;
799
800                Ok(AuthResult::MfaRequired(challenge.clone()))
801            }
802
803            MethodResult::Failure { reason } => {
804                warn!(
805                    "Authentication failed for method '{}': {}",
806                    method_name, reason
807                );
808
809                // Log audit event
810                self.log_audit_event("auth_failure", "unknown", method_name, &metadata)
811                    .await;
812
813                Ok(AuthResult::Failure(reason.clone()))
814            }
815        }
816    }
817
818    async fn authenticate_jwt_builtin(
819        &self,
820        token: &str,
821        metadata: &CredentialMetadata,
822        auth_method: &str,
823    ) -> Result<AuthResult> {
824        if token.is_empty() {
825            return Ok(AuthResult::Failure("JWT token cannot be empty".to_string()));
826        }
827
828        // The "jwt" method authenticates a user's own session: a token issued to an OAuth client
829        // is refused there.
830        let validated = if auth_method == "jwt" {
831            self.token_manager.validate_session_jwt_token(token)
832        } else {
833            self.token_manager.validate_jwt_token(token)
834        };
835        match validated {
836            Ok(claims) => {
837                // A token issued before the account's credentials were reset, or for a
838                // deactivated account, is refused.
839                if let Err(e) =
840                    crate::account_state::ensure_account_active(self.storage.as_ref(), &claims.sub)
841                        .await
842                {
843                    return Ok(AuthResult::Failure(e.to_string()));
844                }
845                if let Err(e) = crate::account_state::ensure_issued_after_revocation(
846                    self.storage.as_ref(),
847                    &claims.sub,
848                    claims.iat.saturating_mul(1000),
849                )
850                .await
851                {
852                    return Ok(AuthResult::Failure(e.to_string()));
853                }
854                let token =
855                    Self::build_validated_jwt_auth_token(token, claims, metadata, auth_method);
856                Ok(AuthResult::Success(Box::new(token)))
857            }
858            Err(error) => {
859                if let Some(reason) = Self::credential_failure_reason(&error) {
860                    Ok(AuthResult::Failure(reason))
861                } else {
862                    Err(error)
863                }
864            }
865        }
866    }
867
868    async fn authenticate_api_key_builtin(
869        &self,
870        api_key: &str,
871        metadata: &CredentialMetadata,
872        auth_method: &str,
873    ) -> Result<AuthResult> {
874        if api_key.is_empty() {
875            return Ok(AuthResult::Failure("API key cannot be empty".to_string()));
876        }
877
878        match self.validate_api_key(api_key).await {
879            Ok(user) => {
880                let scopes: Vec<String> = if user.roles.is_empty() {
881                    vec!["api_user".to_string()]
882                } else {
883                    user.roles.to_vec()
884                };
885                let mut token = self
886                    .token_manager
887                    .create_auth_token(&user.id, scopes.clone(), auth_method, None)?
888                    .with_roles(user.roles)
889                    .with_scopes(scopes);
890                token.metadata.issued_ip = metadata.client_ip.clone();
891                token.metadata.user_agent = metadata.user_agent.clone();
892                Ok(AuthResult::Success(Box::new(token)))
893            }
894            Err(error) => {
895                if let Some(reason) = Self::credential_failure_reason(&error) {
896                    Ok(AuthResult::Failure(reason))
897                } else {
898                    Err(error)
899                }
900            }
901        }
902    }
903
904    async fn authenticate_oauth2_builtin(
905        &self,
906        credential: Credential,
907        metadata: &CredentialMetadata,
908    ) -> Result<AuthResult> {
909        match credential {
910            Credential::OAuth {
911                authorization_code, ..
912            } => {
913                if authorization_code.is_empty() {
914                    return Ok(AuthResult::Failure(
915                        "OAuth authorization code cannot be empty".to_string(),
916                    ));
917                }
918                Ok(AuthResult::Failure(
919                    "OAuth 2.0 authorization codes must be exchanged through an OAuth provider or server endpoint before authentication completes"
920                        .to_string(),
921                ))
922            }
923            Credential::OAuthRefresh { refresh_token } => {
924                if refresh_token.is_empty() {
925                    return Ok(AuthResult::Failure(
926                        "OAuth refresh token cannot be empty".to_string(),
927                    ));
928                }
929                Ok(AuthResult::Failure(
930                    "OAuth 2.0 refresh tokens must be exchanged through an OAuth provider or server endpoint before authentication completes"
931                        .to_string(),
932                ))
933            }
934            Credential::Jwt { token }
935            | Credential::Bearer { token }
936            | Credential::OpenIdConnect { id_token: token, .. } => {
937                self.authenticate_jwt_builtin(&token, metadata, "oauth2").await
938            }
939            _ => Ok(AuthResult::Failure(
940                "OAuth2 authentication expects Credential::oauth_code, Credential::oauth_refresh, Credential::jwt, Credential::bearer, or Credential::openid_connect"
941                    .to_string(),
942            )),
943        }
944    }
945
946    fn build_validated_jwt_auth_token(
947        raw_token: &str,
948        claims: crate::tokens::JwtClaims,
949        metadata: &CredentialMetadata,
950        auth_method: &str,
951    ) -> AuthToken {
952        let crate::tokens::JwtClaims {
953            sub,
954            iss,
955            exp,
956            iat,
957            jti,
958            scope,
959            permissions,
960            roles,
961            client_id,
962            ..
963        } = claims;
964
965        let now = chrono::Utc::now();
966        let issued_at = chrono::DateTime::<chrono::Utc>::from_timestamp(iat, 0).unwrap_or(now);
967        let expires_at = chrono::DateTime::<chrono::Utc>::from_timestamp(exp, 0)
968            .unwrap_or(now + chrono::Duration::hours(1));
969        let lifetime = (expires_at - now)
970            .to_std()
971            .unwrap_or_else(|_| Duration::from_secs(1));
972        let scopes = if scope.trim().is_empty() {
973            Vec::new()
974        } else {
975            scope.split_whitespace().map(str::to_string).collect()
976        };
977
978        let mut token = AuthToken::new(sub.clone(), raw_token.to_string(), lifetime, auth_method)
979            .with_scopes(scopes)
980            .with_permissions(permissions.unwrap_or_default())
981            .with_roles(roles.unwrap_or_default());
982        token.token_id = jti;
983        token.subject = Some(sub);
984        token.issuer = Some(iss);
985        token.issued_at = issued_at;
986        token.expires_at = expires_at;
987        token.metadata.issued_ip = metadata.client_ip.clone();
988        token.metadata.user_agent = metadata.user_agent.clone();
989        if let Some(client_id) = client_id {
990            token.client_id = Some(client_id);
991        }
992        token
993    }
994
995    fn credential_failure_reason(error: &AuthError) -> Option<String> {
996        match error {
997            AuthError::Token(_) | AuthError::Jwt(_) => Some(error.to_string()),
998            AuthError::Validation { message } => Some(message.clone()),
999            AuthError::UserNotFound => Some("User not found".to_string()),
1000            _ => None,
1001        }
1002    }
1003
1004    /// Built-in password authentication against framework storage.
1005    async fn authenticate_password_builtin(
1006        &self,
1007        username: &str,
1008        password: &str,
1009        metadata: &CredentialMetadata,
1010    ) -> Result<AuthResult> {
1011        use crate::auth_modular::user_manager::CredentialCheckResult;
1012
1013        if username.is_empty() || password.is_empty() {
1014            return Ok(AuthResult::Failure(
1015                "Username or password cannot be empty".to_string(),
1016            ));
1017        }
1018
1019        match self
1020            .user_manager
1021            .verify_login_credentials(username, password)
1022            .await?
1023        {
1024            None => {
1025                self.log_audit_event("auth_failure", "unknown", "password", metadata)
1026                    .await;
1027                Ok(AuthResult::Failure(
1028                    "Invalid username or password".to_string(),
1029                ))
1030            }
1031            Some(CredentialCheckResult {
1032                ref user_id,
1033                mfa_enabled: true,
1034            }) => {
1035                let now = chrono::Utc::now();
1036                let challenge = MfaChallenge {
1037                    id: crate::utils::string::generate_id(Some("mfa")),
1038                    mfa_type: crate::methods::MfaType::MultiMethod,
1039                    user_id: user_id.clone(),
1040                    created_at: now,
1041                    expires_at: now + chrono::Duration::minutes(5),
1042                    attempts: 0,
1043                    max_attempts: 5,
1044                    code_hash: None,
1045                    message: Some(
1046                        "Provide your current TOTP code or a backup code to complete login"
1047                            .to_string(),
1048                    ),
1049                    data: HashMap::new(),
1050                };
1051                self.guard_and_store_mfa_challenge(challenge.clone())
1052                    .await?;
1053                self.log_audit_event("mfa_required", user_id, "password", metadata)
1054                    .await;
1055                info!(
1056                    "Built-in password authentication requires MFA for user: {}",
1057                    username
1058                );
1059                Ok(AuthResult::MfaRequired(Box::new(challenge)))
1060            }
1061            Some(CredentialCheckResult {
1062                ref user_id,
1063                mfa_enabled: false,
1064            }) => {
1065                let token = self
1066                    .mint_and_store_token(
1067                        user_id,
1068                        vec!["read".to_string(), "write".to_string()],
1069                        "password",
1070                        None,
1071                    )
1072                    .await?;
1073                self.monitoring_manager.record_auth_request().await;
1074                self.log_audit_event("auth_success", user_id, "password", metadata)
1075                    .await;
1076                info!(
1077                    "Built-in password authentication successful for user: {}",
1078                    username
1079                );
1080                Ok(AuthResult::Success(Box::new(token)))
1081            }
1082        }
1083    }
1084
1085    /// Complete multi-factor authentication.
1086    pub async fn complete_mfa(&self, challenge: MfaChallenge, mfa_code: &str) -> Result<AuthToken> {
1087        debug!("Completing MFA for challenge '{}'", challenge.id);
1088
1089        let stored_challenge = self
1090            .mfa_manager
1091            .get_challenge(&challenge.id)
1092            .await?
1093            .ok_or(MfaError::ChallengeExpired)?;
1094
1095        if stored_challenge.is_expired() {
1096            self.mfa_manager.remove_challenge(&challenge.id).await?;
1097            return Err(MfaError::ChallengeExpired.into());
1098        }
1099
1100        if !self.verify_mfa_code(&stored_challenge, mfa_code).await? {
1101            return Err(MfaError::InvalidCode.into());
1102        }
1103
1104        self.mfa_manager.remove_challenge(&challenge.id).await?;
1105
1106        let scopes = self
1107            .user_manager
1108            .get_user_roles(&challenge.user_id)
1109            .await
1110            .unwrap_or_else(|_| vec!["user".to_string()]);
1111
1112        let token = self
1113            .mint_and_store_token(&challenge.user_id, scopes, "mfa", None)
1114            .await?;
1115
1116        info!(
1117            "MFA completed successfully for user '{}'",
1118            challenge.user_id
1119        );
1120        Ok(token)
1121    }
1122
1123    /// Complete MFA using a previously issued challenge ID.
1124    pub async fn complete_mfa_by_id(
1125        &self,
1126        challenge_id: &str,
1127        mfa_code: &str,
1128    ) -> Result<AuthToken> {
1129        let challenge = self
1130            .mfa_manager
1131            .get_challenge(challenge_id)
1132            .await?
1133            .ok_or(MfaError::ChallengeExpired)?;
1134
1135        self.complete_mfa(challenge, mfa_code).await
1136    }
1137
1138    /// Validate a token.
1139    pub async fn validate_token(&self, token: &AuthToken) -> Result<bool> {
1140        self.require_initialized()?;
1141        let account_live =
1142            crate::account_state::ensure_account_active(self.storage.as_ref(), &token.user_id)
1143                .await
1144                .is_ok()
1145                && crate::account_state::ensure_issued_after_revocation(
1146                    self.storage.as_ref(),
1147                    &token.user_id,
1148                    token.issued_at.timestamp_millis(),
1149                )
1150                .await
1151                .is_ok();
1152        let valid = account_live
1153            && token.is_valid()
1154            && self.token_manager.validate_auth_token(token).is_ok()
1155            && self.touch_stored_token(token).await?;
1156        self.monitoring_manager.record_token_validation(valid).await;
1157        Ok(valid)
1158    }
1159
1160    async fn touch_stored_token(&self, token: &AuthToken) -> Result<bool> {
1161        let Some(mut stored) = self.storage.get_token(&token.token_id).await? else {
1162            return Ok(false);
1163        };
1164        stored.mark_used();
1165        self.storage.update_token(&stored).await?;
1166        Ok(true)
1167    }
1168
1169    /// Get user information from a token.
1170    pub async fn get_user_info(&self, token: &AuthToken) -> Result<UserInfo> {
1171        if !self.validate_token(token).await? {
1172            return Err(AuthError::auth_method("token", "Invalid token".to_string()));
1173        }
1174
1175        let token_info = self.token_manager.extract_token_info(&token.access_token)?;
1176
1177        // Fetch authoritative user state (active flag, current roles) from storage.
1178        // Fall back to token claims if the user record is not found.
1179        match self.user_manager.get_user_info(&token_info.user_id).await {
1180            Ok(mut info) => {
1181                // Overlay any token-specific attributes on top of the stored profile.
1182                if !token_info.attributes.is_empty() {
1183                    let string_attrs: HashMap<String, String> = token_info
1184                        .attributes
1185                        .into_iter()
1186                        .map(|(k, v)| {
1187                            (
1188                                k,
1189                                v.as_str()
1190                                    .map(|s| s.to_string())
1191                                    .unwrap_or_else(|| v.to_string()),
1192                            )
1193                        })
1194                        .collect();
1195                    info.attributes = string_attrs.into();
1196                }
1197                Ok(info)
1198            }
1199            Err(_) => {
1200                let string_attrs: HashMap<String, String> = token_info
1201                    .attributes
1202                    .into_iter()
1203                    .map(|(k, v)| {
1204                        (
1205                            k,
1206                            v.as_str()
1207                                .map(|s| s.to_string())
1208                                .unwrap_or_else(|| v.to_string()),
1209                        )
1210                    })
1211                    .collect();
1212                Ok(UserInfo {
1213                    id: token_info.user_id,
1214                    username: token_info.username.unwrap_or_else(|| "unknown".to_string()),
1215                    email: token_info.email,
1216                    name: token_info.name,
1217                    roles: token_info.roles.into(),
1218                    active: false,
1219                    email_verified: false,
1220                    attributes: string_attrs.into(),
1221                })
1222            }
1223        }
1224    }
1225
1226    /// Check if a token has permission to perform an action on a resource.
1227    ///
1228    /// This method validates the token and checks if the authenticated user
1229    /// has the required permission for the specified action on the given resource.
1230    ///
1231    /// # Parameters
1232    /// - `token`: The authentication token to validate and check permissions for
1233    /// - `action`: The action being requested (e.g., "read", "write", "delete")
1234    /// - `resource`: The resource being accessed (e.g., "documents", "users", "reports/123")
1235    ///
1236    /// # Returns
1237    /// Returns `true` if the token is valid and the user has the required permission,
1238    /// `false` if the token is invalid or the user lacks permission.
1239    ///
1240    /// # Example
1241    /// ```rust,no_run
1242    /// # use auth_framework::prelude::*;
1243    /// # async fn example(auth: &AuthFramework, token: &AuthToken) -> Result<(), AuthError> {
1244    /// if auth.check_permission(token, "read", "documents").await? {
1245    ///     println!("User can read documents");
1246    /// } else {
1247    ///     println!("Access denied");
1248    /// }
1249    /// # Ok(())
1250    /// # }
1251    /// ```
1252    pub async fn check_permission(
1253        &self,
1254        token: &AuthToken,
1255        action: &str,
1256        resource: &str,
1257    ) -> Result<bool> {
1258        if !self.validate_token(token).await? {
1259            return Ok(false);
1260        }
1261        self.authorization_manager
1262            .check_token_permission(token, action, resource)
1263            .await
1264    }
1265
1266    /// Refresh a token.
1267    pub async fn refresh_token(&self, token: &AuthToken) -> Result<AuthToken> {
1268        self.require_initialized()?;
1269        debug!("Refreshing token for user '{}'", token.user_id);
1270
1271        // Check if the auth method supports refresh
1272        if let Some(method) = self.methods.get(&token.auth_method)
1273            && method.supports_refresh()
1274            && let Some(ref refresh_token) = token.refresh_token
1275        {
1276            let new_token = method.refresh_token(refresh_token.to_string()).await?;
1277            self.storage.store_token(&new_token).await?;
1278            return Ok(new_token);
1279        }
1280
1281        // Fallback to creating a new token with the same properties
1282        let new_token = self.token_manager.refresh_token(token)?;
1283        self.storage.store_token(&new_token).await?;
1284
1285        info!("Token refreshed for user '{}'", token.user_id);
1286
1287        Ok(new_token)
1288    }
1289
1290    /// Revoke a token.
1291    pub async fn revoke_token(&self, token: &AuthToken) -> Result<()> {
1292        self.require_initialized()?;
1293        debug!("Revoking token for user '{}'", token.user_id);
1294
1295        // Mark token as revoked
1296        let mut revoked_token = token.clone();
1297        revoked_token.revoke(Some("Manual revocation".to_string()));
1298
1299        // Update in storage
1300        self.storage.update_token(&revoked_token).await?;
1301
1302        info!("Token revoked for user '{}'", token.user_id);
1303
1304        Ok(())
1305    }
1306
1307    /// Create a new API key for a user.
1308    pub async fn create_api_key(
1309        &self,
1310        user_id: &str,
1311        expires_in: Option<Duration>,
1312    ) -> Result<String> {
1313        self.require_initialized()?;
1314        self.user_manager.create_api_key(user_id, expires_in).await
1315    }
1316
1317    /// Validate an API key and return user information.
1318    pub async fn validate_api_key(&self, api_key: &str) -> Result<UserInfo> {
1319        self.require_initialized()?;
1320        self.user_manager.validate_api_key(api_key).await
1321    }
1322
1323    /// Revoke an API key.
1324    pub async fn revoke_api_key(&self, api_key: &str) -> Result<()> {
1325        self.require_initialized()?;
1326        self.user_manager.revoke_api_key(api_key).await
1327    }
1328
1329    /// Create a new session.
1330    pub async fn create_session(
1331        &self,
1332        user_id: &str,
1333        expires_in: Duration,
1334        ip_address: Option<String>,
1335        user_agent: Option<String>,
1336    ) -> Result<String> {
1337        self.require_initialized()?;
1338        let (session_id, new_total) = self
1339            .session_manager
1340            .create_session_limited(user_id, expires_in, ip_address, user_agent)
1341            .await?;
1342        self.monitoring_manager
1343            .update_session_count(new_total)
1344            .await;
1345        Ok(session_id)
1346    }
1347
1348    /// Create a new session using a [`SessionCreateRequest`] for better readability.
1349    ///
1350    /// Prefer [`create_session_with_request`](Self::create_session_with_request)
1351    /// with a [`SessionCreateRequest`] for better readability when using optional fields.
1352    ///
1353    /// # Example
1354    ///
1355    /// ```rust,no_run
1356    /// # use auth_framework::{prelude::*, auth_operations::SessionCreateRequest};
1357    /// # use std::time::Duration;
1358    /// # async fn example(auth: &AuthFramework) -> Result<(), auth_framework::errors::AuthError> {
1359    /// let session_id = auth.create_session_with_request(
1360    ///     SessionCreateRequest::new("user_123", Duration::from_secs(3600))
1361    ///         .ip_address("192.168.1.1")
1362    ///         .user_agent("MyApp/1.0")
1363    /// ).await?;
1364    /// # Ok(())
1365    /// # }
1366    /// ```
1367    pub async fn create_session_with_request(&self, req: SessionCreateRequest) -> Result<String> {
1368        self.create_session(
1369            req.get_user_id(),
1370            req.get_expires_in(),
1371            req.get_ip_address().map(|s| s.to_string()),
1372            req.get_user_agent().map(|s| s.to_string()),
1373        )
1374        .await
1375    }
1376
1377    /// Get session information.
1378    pub async fn get_session(&self, session_id: &str) -> Result<Option<SessionData>> {
1379        self.require_initialized()?;
1380        self.session_manager.get_session(session_id).await
1381    }
1382
1383    /// Delete a session.
1384    pub async fn delete_session(&self, session_id: &str) -> Result<()> {
1385        self.require_initialized()?;
1386        self.session_manager.delete_session(session_id).await?;
1387
1388        let remaining = self
1389            .session_manager
1390            .count_active_sessions()
1391            .await
1392            .unwrap_or(0);
1393        self.monitoring_manager
1394            .update_session_count(remaining)
1395            .await;
1396
1397        Ok(())
1398    }
1399
1400    /// Get all tokens for a user.
1401    pub async fn list_user_tokens(&self, user_id: &str) -> Result<Vec<AuthToken>> {
1402        self.require_initialized()?;
1403        self.storage.list_user_tokens(user_id).await
1404    }
1405
1406    /// Clean up expired data.
1407    pub async fn cleanup_expired_data(&self) -> Result<()> {
1408        debug!("Cleaning up expired data");
1409
1410        // Clean up storage
1411        self.storage.cleanup_expired().await?;
1412
1413        // Clean up MFA challenges via mfa manager
1414        self.mfa_manager.cleanup_expired_challenges().await?;
1415
1416        // Clean up sessions via session manager
1417        self.session_manager.cleanup_expired_sessions().await?;
1418
1419        // Clean up rate limiter
1420        if let Some(ref rate_limiter) = self.rate_limiter {
1421            let _ = rate_limiter.cleanup().ok();
1422        }
1423
1424        Ok(())
1425    }
1426
1427    /// Detect if the process is running in a production environment by inspecting
1428    /// well-known environment variables and container indicators.
1429    fn is_production_environment() -> bool {
1430        if let Ok(env) = std::env::var("ENVIRONMENT")
1431            && (env.to_lowercase() == "production" || env.to_lowercase() == "prod")
1432        {
1433            return true;
1434        }
1435        if let Ok(env) = std::env::var("ENV")
1436            && (env.to_lowercase() == "production" || env.to_lowercase() == "prod")
1437        {
1438            return true;
1439        }
1440        if let Ok(env) = std::env::var("NODE_ENV")
1441            && env.to_lowercase() == "production"
1442        {
1443            return true;
1444        }
1445        if let Ok(env) = std::env::var("RUST_ENV")
1446            && env.to_lowercase() == "production"
1447        {
1448            return true;
1449        }
1450        std::env::var("KUBERNETES_SERVICE_HOST").is_ok()
1451            || std::env::var("DOCKER_CONTAINER").is_ok()
1452    }
1453
1454    /// Get authentication framework statistics.
1455    pub async fn get_stats(&self) -> Result<AuthStats> {
1456        let mut stats = AuthStats::default();
1457
1458        if let Err(e) = self.storage.cleanup_expired().await {
1459            warn!("Failed to cleanup expired data: {}", e);
1460        }
1461        if let Some(rate_limiter) = &self.rate_limiter {
1462            let _ = rate_limiter.cleanup().ok();
1463        }
1464
1465        let active_sessions = self
1466            .session_manager
1467            .count_active_sessions()
1468            .await
1469            .unwrap_or(0) as u32;
1470
1471        stats.registered_methods = self.methods.keys().cloned().collect();
1472        stats.active_sessions = active_sessions as u64;
1473        stats.active_mfa_challenges = self.mfa_manager.get_active_challenge_count().await as u64;
1474        // Use monitoring counters for accurate cumulative tracking
1475        let perf = self.monitoring_manager.get_performance_metrics();
1476        stats.tokens_issued = perf.get("token_creations").copied().unwrap_or(0);
1477        stats.auth_attempts = perf.get("auth_successes").copied().unwrap_or(0)
1478            + perf.get("auth_failures").copied().unwrap_or(0);
1479
1480        Ok(stats)
1481    }
1482
1483    /// Returns a reference to the underlying [`TokenManager`].
1484    ///
1485    /// Useful for advanced token operations not exposed by the
1486    /// [`TokenOperations`] facade.
1487    pub fn token_manager(&self) -> &TokenManager {
1488        &self.token_manager
1489    }
1490
1491    /// Validates a username against the configured format rules.
1492    ///
1493    /// Returns `Ok(true)` when the name is acceptable, or an error describing
1494    /// the specific rule that was violated (length, characters, etc.).
1495    ///
1496    /// # Errors
1497    ///
1498    /// Returns [`AuthError`] if the username is empty, too long, or contains
1499    /// forbidden characters per the active [`SecurityConfig`].
1500    pub async fn validate_username(&self, username: &str) -> Result<bool> {
1501        self.user_manager.validate_username(username).await
1502    }
1503
1504    /// Validates a display name against the configured format rules.
1505    ///
1506    /// # Errors
1507    ///
1508    /// Returns [`AuthError`] if the display name is empty or exceeds the
1509    /// configured maximum length.
1510    pub async fn validate_display_name(&self, display_name: &str) -> Result<bool> {
1511        self.user_manager.validate_display_name(display_name).await
1512    }
1513
1514    /// Checks a password against the active security policy.
1515    ///
1516    /// Validates minimum length, character-class requirements, and (optionally)
1517    /// checks against known-breached password lists.
1518    ///
1519    /// # Errors
1520    ///
1521    /// Returns [`AuthError`] describing which policy rule the password violates.
1522    pub async fn validate_password_strength(&self, password: &str) -> Result<bool> {
1523        self.user_manager.validate_password_strength(password).await
1524    }
1525
1526    /// Validates arbitrary user input against common injection patterns.
1527    ///
1528    /// Checks for SQL injection, XSS, and command injection markers.
1529    /// Returns `Ok(true)` when the input is safe.
1530    pub async fn validate_user_input(&self, input: &str) -> Result<bool> {
1531        Ok(crate::utils::validation::validate_user_input(input))
1532    }
1533
1534    /// Creates an authentication token directly.
1535    ///
1536    /// This is a low-level API intended for **testing, migration tools, and
1537    /// administrative tasks**. In production, tokens should be created through
1538    /// [`authenticate`](Self::authenticate) instead.
1539    ///
1540    /// # Parameters
1541    ///
1542    /// * `user_id`     — the subject the token is issued to.
1543    /// * `scopes`      — OAuth-style scopes (accepts `Vec<String>`, `Scopes`, or `&[&str]`).
1544    /// * `method_name` — the auth method to record (must be registered).
1545    /// * `lifetime`    — override the default token TTL; `None` uses the
1546    ///   framework-configured default.
1547    ///
1548    /// # Errors
1549    ///
1550    /// * [`AuthError::AuthMethod`] if `method_name` is not registered.
1551    /// * [`AuthError::RateLimit`] if the user already holds the maximum number
1552    ///   of active tokens.
1553    pub async fn create_auth_token(
1554        &self,
1555        user_id: impl Into<String>,
1556        scopes: impl Into<crate::types::Scopes>,
1557        method_name: impl Into<String>,
1558        lifetime: Option<Duration>,
1559    ) -> Result<AuthToken> {
1560        let method_name = method_name.into();
1561        let user_id = user_id.into();
1562        let scopes: crate::types::Scopes = scopes.into();
1563
1564        // Validate the method exists and is correctly configured
1565        let auth_method = self
1566            .methods
1567            .get(&method_name)
1568            .ok_or_else(|| AuthError::auth_method(&method_name, "Method not found"))?;
1569        auth_method.validate_config()?;
1570
1571        // ENTERPRISE SECURITY: Check token limits to prevent resource exhaustion
1572        const MAX_TOKENS_PER_USER: usize = 100;
1573        let user_tokens = self.storage.list_user_tokens(&user_id).await?;
1574        if user_tokens.len() >= MAX_TOKENS_PER_USER {
1575            warn!(
1576                "User '{}' has reached maximum tokens ({})",
1577                user_id, MAX_TOKENS_PER_USER
1578            );
1579            return Err(AuthError::rate_limit(
1580                "Maximum tokens per user exceeded. Please revoke unused tokens.",
1581            ));
1582        }
1583
1584        let token = self
1585            .mint_and_store_token(&user_id, scopes, &method_name, lifetime)
1586            .await?;
1587        self.monitoring_manager
1588            .record_token_creation(&method_name)
1589            .await;
1590        Ok(token)
1591    }
1592
1593    /// Initiates an SMS-based MFA challenge for `user_id`.
1594    ///
1595    /// Sends a one-time code via the configured SMS provider and returns a
1596    /// challenge ID that must be passed to [`verify_sms_code`](Self::verify_sms_code).
1597    ///
1598    /// # Errors
1599    ///
1600    /// Returns [`AuthError`] if no phone number is registered or the SMS
1601    /// provider fails to deliver.
1602    pub async fn initiate_sms_challenge(&self, user_id: &str) -> Result<String> {
1603        self.mfa_manager.sms.initiate_challenge(user_id).await
1604    }
1605
1606    /// Verifies an SMS challenge code previously issued by
1607    /// [`initiate_sms_challenge`](Self::initiate_sms_challenge).
1608    ///
1609    /// # Errors
1610    ///
1611    /// Returns [`AuthError`] if the challenge has expired or if the code is
1612    /// invalid.
1613    pub async fn verify_sms_code(&self, challenge_id: &str, code: &str) -> Result<bool> {
1614        self.mfa_manager.sms.verify_code(challenge_id, code).await
1615    }
1616
1617    /// Registers an email address for email-based MFA for `user_id`.
1618    ///
1619    /// # Errors
1620    ///
1621    /// Returns [`AuthError`] if the email format is invalid or the user does
1622    /// not exist.
1623    pub async fn register_email(&self, user_id: &str, email: &str) -> Result<()> {
1624        self.mfa_manager.email.register_email(user_id, email).await
1625    }
1626
1627    /// Generates a new TOTP secret and stores it for `user_id`.
1628    ///
1629    /// The returned string is a Base32-encoded secret suitable for importing
1630    /// into authenticator apps. Pair with
1631    /// [`generate_totp_qr_code`](Self::generate_totp_qr_code) for a scan-ready
1632    /// URI.
1633    ///
1634    /// # Errors
1635    ///
1636    /// Returns [`AuthError`] if secret generation or storage fails.
1637    pub async fn generate_totp_secret(&self, user_id: &str) -> Result<String> {
1638        self.mfa_manager.totp.generate_secret(user_id).await
1639    }
1640
1641    /// Generates an `otpauth://` URI suitable for rendering as a QR code.
1642    ///
1643    /// # Parameters
1644    ///
1645    /// * `user_id`  — identifies the user in the authenticator label.
1646    /// * `app_name` — the issuer name shown in the authenticator app.
1647    /// * `secret`   — the Base32 TOTP secret from [`generate_totp_secret`](Self::generate_totp_secret).
1648    pub async fn generate_totp_qr_code(
1649        &self,
1650        user_id: &str,
1651        app_name: &str,
1652        secret: &str,
1653    ) -> Result<String> {
1654        self.mfa_manager
1655            .totp
1656            .generate_qr_code(user_id, app_name, secret)
1657            .await
1658    }
1659
1660    /// Generates the current TOTP code for the given Base32 `secret`.
1661    ///
1662    /// Primarily useful for testing; in production the *user* generates the
1663    /// code on their device.
1664    pub async fn generate_totp_code(&self, secret: &str) -> Result<String> {
1665        self.mfa_manager.totp.generate_code(secret).await
1666    }
1667
1668    /// Generates a TOTP code for the given `secret` and optional time window.
1669    ///
1670    /// When `time_window` is `None`, the current 30-second window is used.
1671    pub async fn generate_totp_code_for_window(
1672        &self,
1673        secret: &str,
1674        time_window: Option<u64>,
1675    ) -> Result<String> {
1676        self.mfa_manager
1677            .totp
1678            .generate_code_for_window(secret, time_window)
1679            .await
1680    }
1681
1682    /// Verifies a TOTP code against the stored secret for `user_id`.
1683    ///
1684    /// Applies a configurable clock-skew window (default: ±1 step).
1685    ///
1686    /// # Errors
1687    ///
1688    /// Returns [`AuthError`] if no TOTP secret is registered for the user.
1689    pub async fn verify_totp_code(&self, user_id: &str, code: &str) -> Result<bool> {
1690        self.mfa_manager.totp.verify_code(user_id, code).await
1691    }
1692
1693    /// Checks whether the given IP address is within the configured rate limit.
1694    ///
1695    /// Returns `Ok(true)` if the request is allowed, or an
1696    /// [`AuthError::RateLimit`] if the caller should be throttled.
1697    pub async fn check_ip_rate_limit(&self, ip: &str) -> Result<bool> {
1698        debug!("Checking IP rate limit for '{}'", ip);
1699        let Some(ref rate_limiter) = self.rate_limiter else {
1700            return Ok(true);
1701        };
1702        if !rate_limiter.is_allowed(&format!("ip:{}", ip)) {
1703            warn!("Rate limit exceeded for IP: {}", ip);
1704            return Err(AuthError::rate_limit(format!(
1705                "Too many requests from IP {}. Please try again later.",
1706                ip
1707            )));
1708        }
1709        Ok(true)
1710    }
1711
1712    /// Return security metrics for monitoring dashboards.
1713    ///
1714    /// Keys include `active_sessions`, `total_tokens`, `failed_attempts`,
1715    /// `successful_attempts`, and `expired_tokens`.
1716    pub async fn get_security_metrics(&self) -> Result<std::collections::HashMap<String, u64>> {
1717        debug!("Getting security metrics");
1718        let mut metrics = std::collections::HashMap::new();
1719        let total_active_sessions = self
1720            .session_manager
1721            .count_active_sessions()
1722            .await
1723            .unwrap_or(0);
1724        metrics.insert("active_sessions".to_string(), total_active_sessions);
1725        metrics.insert("total_tokens".to_string(), total_active_sessions);
1726        metrics.insert(
1727            "failed_attempts".to_string(),
1728            self.audit_manager
1729                .get_failed_login_count_24h()
1730                .await
1731                .unwrap_or(0),
1732        );
1733        metrics.insert(
1734            "successful_attempts".to_string(),
1735            self.audit_manager
1736                .get_successful_login_count_24h()
1737                .await
1738                .unwrap_or(0),
1739        );
1740        metrics.insert("expired_tokens".to_string(), 0u64);
1741        Ok(metrics)
1742    }
1743
1744    /// Registers a phone number for SMS-based MFA.
1745    ///
1746    /// # Errors
1747    ///
1748    /// Returns [`AuthError`] if the phone number format is invalid.
1749    pub async fn register_phone_number(&self, user_id: &str, phone_number: &str) -> Result<()> {
1750        self.mfa_manager
1751            .sms
1752            .register_phone_number(user_id, phone_number)
1753            .await
1754    }
1755
1756    /// Generate `count` one-time backup codes for the given user.
1757    ///
1758    /// Codes are persisted server-side (hashed); plaintext codes are returned
1759    /// to the caller for display to the user.
1760    pub async fn generate_backup_codes(&self, user_id: &str, count: usize) -> Result<Vec<String>> {
1761        self.mfa_manager
1762            .backup_codes
1763            .generate_codes(user_id, count)
1764            .await
1765    }
1766    /// Grants an authorization permission to a user.
1767    ///
1768    /// # Parameters
1769    ///
1770    /// * `user_id`  — the user receiving the permission.
1771    /// * `action`   — the action being allowed (e.g. `"read"`, `"write"`).
1772    /// * `resource` — the resource scope (e.g. `"documents"`, `"users:*"`).
1773    ///
1774    /// # Errors
1775    ///
1776    /// Returns [`AuthError`] if the user does not exist or storage fails.
1777    pub async fn grant_permission(
1778        &self,
1779        user_id: &str,
1780        action: &str,
1781        resource: &str,
1782    ) -> Result<()> {
1783        self.authorization_manager
1784            .grant_permission(user_id, action, resource)
1785            .await
1786    }
1787
1788    /// Initiates an email-based MFA challenge for `user_id`.
1789    ///
1790    /// Sends a one-time code to the registered email address and returns a
1791    /// challenge ID.
1792    ///
1793    /// # Errors
1794    ///
1795    /// Returns [`AuthError`] if no email is registered for the user or
1796    /// delivery fails.
1797    pub async fn initiate_email_challenge(&self, user_id: &str) -> Result<String> {
1798        self.mfa_manager.email.initiate_challenge(user_id).await
1799    }
1800
1801    /// Returns a cloned handle to the storage backend.
1802    ///
1803    /// Useful when you need to pass storage to another component or run
1804    /// direct queries outside the framework's managed API.
1805    pub fn storage(&self) -> Arc<dyn AuthStorage> {
1806        self.storage.clone()
1807    }
1808
1809    /// Returns a reference to the active framework configuration.
1810    pub fn config(&self) -> &AuthConfig {
1811        &self.config
1812    }
1813
1814    /// Reset runtime authorization state back to the default roles.
1815    pub async fn reset_authorization_runtime(&self) {
1816        self.authorization_manager.reset_runtime_state().await;
1817    }
1818
1819    /// Register a new user with username, email, and password.
1820    ///
1821    /// The password is hashed with the configured algorithm (default: Argon2)
1822    /// before storage.  Returns the generated user ID on success.
1823    ///
1824    /// # Errors
1825    ///
1826    /// Returns [`AuthError`] if:
1827    /// - The username or email is already taken
1828    /// - The password does not meet the configured complexity requirements
1829    /// - The storage backend is unavailable
1830    ///
1831    /// # Example
1832    ///
1833    /// ```rust,no_run
1834    /// # use auth_framework::prelude::*;
1835    /// # async fn example(auth: &AuthFramework) -> Result<(), AuthError> {
1836    /// let user_id = auth.users().register("alice", "alice@example.com", "S3cur3P@ss!").await?;
1837    /// println!("Created user: {user_id}");
1838    /// # Ok(())
1839    /// # }
1840    /// ```
1841    pub async fn register_user(
1842        &self,
1843        username: &str,
1844        email: &str,
1845        password: &str,
1846    ) -> Result<String> {
1847        self.require_initialized()?;
1848        self.user_manager
1849            .register_user(username, email, password)
1850            .await
1851    }
1852
1853    /// List users from the canonical user index with optional filtering and pagination.
1854    ///
1855    /// This method provides paginated access to the user directory with optional
1856    /// filtering by active status.
1857    ///
1858    /// # Parameters
1859    /// - `limit`: Maximum number of users to return (None for no limit)
1860    /// - `offset`: Number of users to skip for pagination (None for start from beginning)
1861    /// - `active_only`: If true, only return active users; if false, return all users
1862    ///
1863    /// # Returns
1864    /// Returns a vector of [`UserInfo`] structs containing user details.
1865    ///
1866    /// # Example
1867    /// ```rust,no_run
1868    /// # use auth_framework::prelude::*;
1869    /// # async fn example(auth: &AuthFramework) -> Result<(), AuthError> {
1870    /// // Get first 10 active users
1871    /// let users = auth.list_users(Some(10), None, true).await?;
1872    /// println!("Found {} active users", users.len());
1873    ///
1874    /// // Get all users (active and inactive)
1875    /// let all_users = auth.list_users(None, None, false).await?;
1876    /// # Ok(())
1877    /// # }
1878    /// ```
1879    #[deprecated(
1880        since = "0.6.0",
1881        note = "use `list_users_with_query(UserListQuery::new().limit(n).active_only())` instead"
1882    )]
1883    pub async fn list_users(
1884        &self,
1885        limit: Option<usize>,
1886        offset: Option<usize>,
1887        active_only: bool,
1888    ) -> Result<Vec<UserInfo>> {
1889        self.require_initialized()?;
1890        self.user_manager
1891            .list_users(limit, offset, active_only)
1892            .await
1893    }
1894
1895    /// List users using a [`UserListQuery`] for better readability.
1896    ///
1897    /// Prefer [`list_users_with_query`](Self::list_users_with_query)
1898    /// with a [`UserListQuery`] for better readability when using pagination or filtering.
1899    ///
1900    /// # Example
1901    ///
1902    /// ```rust,no_run
1903    /// # use auth_framework::{prelude::*, auth_operations::UserListQuery};
1904    /// # async fn example(auth: &AuthFramework) -> Result<(), auth_framework::errors::AuthError> {
1905    /// let users = auth.list_users_with_query(
1906    ///     UserListQuery::new()
1907    ///         .limit(50)
1908    ///         .active_only()
1909    /// ).await?;
1910    /// # Ok(())
1911    /// # }
1912    /// ```
1913    pub async fn list_users_with_query(&self, query: UserListQuery) -> Result<Vec<UserInfo>> {
1914        self.require_initialized()?;
1915        self.user_manager
1916            .list_users(
1917                query.get_limit(),
1918                query.get_offset(),
1919                query.get_active_only(),
1920            )
1921            .await
1922    }
1923
1924    /// Get user information by canonical user ID.
1925    pub async fn get_user_record(&self, user_id: &str) -> Result<UserInfo> {
1926        self.require_initialized()?;
1927        self.user_manager.get_user_info(user_id).await
1928    }
1929
1930    /// Update the roles assigned to a user.
1931    pub async fn update_user_roles(&self, user_id: &str, roles: &[String]) -> Result<()> {
1932        self.require_initialized()?;
1933        self.user_manager.update_user_roles(user_id, roles).await
1934    }
1935
1936    /// Set a user's active / deactivated status.
1937    pub async fn set_user_active(&self, user_id: &str, active: bool) -> Result<()> {
1938        self.require_initialized()?;
1939        self.user_manager.set_user_active(user_id, active).await
1940    }
1941
1942    /// Update a user's email address.
1943    pub async fn update_user_email(&self, user_id: &str, email: &str) -> Result<()> {
1944        self.require_initialized()?;
1945        self.user_manager.update_user_email(user_id, email).await
1946    }
1947
1948    /// Verify a user's password by user_id against the stored bcrypt hash.
1949    pub async fn verify_user_password(&self, user_id: &str, password: &str) -> Result<bool> {
1950        self.require_initialized()?;
1951        self.user_manager
1952            .verify_user_password(user_id, password)
1953            .await
1954    }
1955
1956    /// Look up a user's username by their user_id.
1957    pub async fn get_username_by_id(&self, user_id: &str) -> Result<String> {
1958        self.user_manager.get_username_by_id(user_id).await
1959    }
1960
1961    /// Check if a username exists.
1962    pub async fn username_exists(&self, username: &str) -> Result<bool> {
1963        self.user_manager.username_exists(username).await
1964    }
1965
1966    /// Check if an email exists.
1967    pub async fn email_exists(&self, email: &str) -> Result<bool> {
1968        self.user_manager.email_exists(email).await
1969    }
1970
1971    /// Get user data by username.
1972    pub async fn get_user_by_username(
1973        &self,
1974        username: &str,
1975    ) -> Result<HashMap<String, serde_json::Value>> {
1976        self.user_manager.get_user_by_username(username).await
1977    }
1978
1979    /// Update user password.
1980    pub async fn update_user_password(&self, username: &str, new_password: &str) -> Result<()> {
1981        self.require_initialized()?;
1982        self.user_manager
1983            .update_user_password(username, new_password)
1984            .await
1985    }
1986
1987    /// Update user password by canonical user ID.
1988    pub async fn update_user_password_by_id(
1989        &self,
1990        user_id: &str,
1991        new_password: &str,
1992    ) -> Result<()> {
1993        self.require_initialized()?;
1994        self.user_manager
1995            .update_user_password_by_id(user_id, new_password)
1996            .await
1997    }
1998
1999    /// Delete a user by username.
2000    pub async fn delete_user(&self, username: &str) -> Result<()> {
2001        self.require_initialized()?;
2002        self.user_manager.delete_user(username).await
2003    }
2004
2005    /// Delete a user by canonical user ID.
2006    pub async fn delete_user_by_id(&self, user_id: &str) -> Result<()> {
2007        self.require_initialized()?;
2008        self.user_manager.delete_user_by_id(user_id).await
2009    }
2010
2011    /// Verify MFA code with proper challenge validation.
2012    async fn verify_mfa_code(&self, challenge: &MfaChallenge, code: &str) -> Result<bool> {
2013        self.mfa_manager
2014            .verify_challenge_code(challenge, code)
2015            .await
2016    }
2017
2018    /// Log an audit event via tracing, subject to per-event-type config guards.
2019    async fn log_audit_event(
2020        &self,
2021        event_type: &str,
2022        user_id: &str,
2023        method: &str,
2024        metadata: &CredentialMetadata,
2025    ) {
2026        if !self.config.audit.enabled {
2027            return;
2028        }
2029        let should_log = match event_type {
2030            "auth_success" | "mfa_required" => self.config.audit.log_success,
2031            "auth_failure" => self.config.audit.log_failures,
2032            _ => true,
2033        };
2034        if should_log {
2035            self.audit_manager
2036                .log_auth_trace_event(
2037                    event_type,
2038                    user_id,
2039                    method,
2040                    metadata.client_ip.as_deref().unwrap_or("unknown"),
2041                    metadata.user_agent.as_deref().unwrap_or("unknown"),
2042                )
2043                .await;
2044        }
2045    }
2046
2047    /// Guard the global MFA-challenge budget and store the challenge.
2048    async fn guard_and_store_mfa_challenge(&self, challenge: MfaChallenge) -> Result<()> {
2049        self.mfa_manager.guard_and_store(challenge).await
2050    }
2051
2052    /// Create and immediately store an auth token, returning it.
2053    async fn mint_and_store_token(
2054        &self,
2055        user_id: &str,
2056        scopes: impl Into<crate::types::Scopes>,
2057        method: &str,
2058        lifetime: Option<Duration>,
2059    ) -> Result<AuthToken> {
2060        let token = self
2061            .token_manager
2062            .create_auth_token(user_id, scopes, method, lifetime)?;
2063        self.storage.store_token(&token).await?;
2064        Ok(token)
2065    }
2066
2067    /// Coordinate session state across distributed instances.
2068    pub async fn coordinate_distributed_sessions(&self) -> Result<SessionCoordinationStats> {
2069        self.session_manager.coordinate_distributed_sessions().await
2070    }
2071
2072    /// Synchronize a specific session with remote instances.
2073    pub async fn synchronize_session(&self, session_id: &str) -> Result<()> {
2074        self.session_manager.synchronize_session(session_id).await
2075    }
2076
2077    /// Returns the monitoring manager for metrics collection and health checks.
2078    pub fn monitoring_manager(&self) -> Arc<crate::monitoring::MonitoringManager> {
2079        self.monitoring_manager.clone()
2080    }
2081
2082    /// Returns the security manager for rate limiting, DoS protection, and IP blacklisting.
2083    #[cfg(feature = "api-server")]
2084    pub fn security_manager(&self) -> Option<Arc<crate::api::SecurityManager>> {
2085        Some(self.security_manager.clone())
2086    }
2087
2088    /// Return current performance metrics (token counts, latencies, etc.).
2089    pub async fn get_performance_metrics(&self) -> std::collections::HashMap<String, u64> {
2090        self.monitoring_manager.get_performance_metrics()
2091    }
2092
2093    /// Run a health check on all sub-systems (storage, token engine, etc.).
2094    pub async fn health_check(
2095        &self,
2096    ) -> Result<std::collections::HashMap<String, crate::monitoring::HealthCheckResult>> {
2097        self.monitoring_manager.health_check().await
2098    }
2099
2100    /// Export all collected metrics in Prometheus text exposition format.
2101    pub async fn export_prometheus_metrics(&self) -> String {
2102        self.monitoring_manager.export_prometheus_metrics().await
2103    }
2104    /// Create a new role.
2105    pub async fn create_role(&self, role: crate::permissions::Role) -> Result<()> {
2106        self.require_initialized()?;
2107        self.authorization_manager.create_role(role).await
2108    }
2109
2110    /// Return all defined roles.
2111    pub async fn list_roles(&self) -> Vec<crate::permissions::Role> {
2112        self.authorization_manager.list_roles().await
2113    }
2114
2115    /// Fetch a role definition by name.
2116    pub async fn get_role(&self, role_name: &str) -> Result<crate::permissions::Role> {
2117        self.authorization_manager.get_role(role_name).await
2118    }
2119
2120    /// Add a permission to an existing role.
2121    pub async fn add_role_permission(
2122        &self,
2123        role_name: &str,
2124        permission: crate::permissions::Permission,
2125    ) -> Result<()> {
2126        self.authorization_manager
2127            .add_role_permission(role_name, permission)
2128            .await
2129    }
2130
2131    /// Assign a role to a user.
2132    pub async fn assign_role(&self, user_id: &str, role_name: &str) -> Result<()> {
2133        self.require_initialized()?;
2134        self.authorization_manager
2135            .assign_role(user_id, role_name)
2136            .await
2137    }
2138
2139    /// Remove a role from a user.
2140    pub async fn remove_role(&self, user_id: &str, role_name: &str) -> Result<()> {
2141        self.require_initialized()?;
2142        self.authorization_manager
2143            .remove_role(user_id, role_name)
2144            .await
2145    }
2146
2147    /// Set role inheritance.
2148    pub async fn set_role_inheritance(&self, child_role: &str, parent_role: &str) -> Result<()> {
2149        self.require_initialized()?;
2150        self.authorization_manager
2151            .set_role_inheritance(child_role, parent_role)
2152            .await
2153    }
2154
2155    /// Revoke permission from a user.
2156    pub async fn revoke_permission(
2157        &self,
2158        user_id: &str,
2159        action: &str,
2160        resource: &str,
2161    ) -> Result<()> {
2162        self.require_initialized()?;
2163        self.authorization_manager
2164            .revoke_permission(user_id, action, resource)
2165            .await
2166    }
2167
2168    /// Check if user has a role.
2169    pub async fn user_has_role(&self, user_id: &str, role_name: &str) -> Result<bool> {
2170        self.authorization_manager
2171            .user_has_role(user_id, role_name)
2172            .await
2173    }
2174
2175    /// List the currently assigned runtime roles for a user.
2176    pub async fn list_user_roles(&self, user_id: &str) -> Result<Vec<String>> {
2177        self.authorization_manager.list_user_roles(user_id).await
2178    }
2179
2180    /// Get effective permissions for a user.
2181    pub async fn get_effective_permissions(&self, user_id: &str) -> Result<Vec<String>> {
2182        self.authorization_manager
2183            .get_effective_permissions(user_id)
2184            .await
2185    }
2186
2187    /// Create ABAC policy.
2188    pub async fn create_abac_policy(&self, name: &str, description: &str) -> Result<()> {
2189        self.authorization_manager
2190            .create_abac_policy(name, description)
2191            .await
2192    }
2193
2194    /// Set a user attribute value for ABAC (Attribute-Based Access Control) evaluation.
2195    ///
2196    /// User attributes are key-value pairs associated with users that can be used
2197    /// in dynamic permission rules. This method stores or updates an attribute value.
2198    ///
2199    /// # Parameters
2200    /// - `user_id`: The ID of the user to set the attribute for
2201    /// - `attribute`: The name of the attribute to set
2202    /// - `value`: The value to assign to the attribute
2203    ///
2204    /// # Example
2205    /// ```rust,no_run
2206    /// # use auth_framework::prelude::*;
2207    /// # async fn example(auth: &AuthFramework) -> Result<(), AuthError> {
2208    /// // Set user attributes for policy evaluation
2209    /// auth.map_user_attribute("example_user", "department", "engineering").await?;
2210    /// auth.map_user_attribute("example_user", "clearance_level", "confidential").await?;
2211    /// # Ok(())
2212    /// # }
2213    /// ```
2214    pub async fn map_user_attribute(
2215        &self,
2216        user_id: &str,
2217        attribute: &str,
2218        value: &str,
2219    ) -> Result<()> {
2220        self.authorization_manager
2221            .map_user_attribute(user_id, attribute, value)
2222            .await
2223    }
2224
2225    /// Get a user attribute value for ABAC (Attribute-Based Access Control) evaluation.
2226    ///
2227    /// User attributes are key-value pairs associated with users that can be used
2228    /// in dynamic permission rules. Common attributes include department, clearance level,
2229    /// location, etc.
2230    ///
2231    /// # Parameters
2232    /// - `user_id`: The ID of the user whose attribute to retrieve
2233    /// - `attribute`: The name of the attribute to retrieve
2234    ///
2235    /// # Returns
2236    /// Returns `Some(value)` if the attribute exists, `None` if it doesn't exist.
2237    ///
2238    /// # Example
2239    /// ```rust,no_run
2240    /// # use auth_framework::prelude::*;
2241    /// # async fn example(auth: &AuthFramework) -> Result<(), AuthError> {
2242    /// if let Some(dept) = auth.get_user_attribute("example_user", "department").await? {
2243    ///     println!("User is in department: {}", dept);
2244    /// }
2245    /// # Ok(())
2246    /// # }
2247    /// ```
2248    pub async fn get_user_attribute(
2249        &self,
2250        user_id: &str,
2251        attribute: &str,
2252    ) -> Result<Option<String>> {
2253        self.authorization_manager
2254            .get_user_attribute(user_id, attribute)
2255            .await
2256    }
2257
2258    /// Check dynamic permission with context evaluation (ABAC - Attribute-Based Access Control).
2259    ///
2260    /// This method evaluates permissions based on user attributes, resource attributes,
2261    /// and environmental context rather than just role assignments. It's more flexible
2262    /// than simple role-based checks but requires more complex policy rules.
2263    ///
2264    /// # Parameters
2265    /// - `user_id`: The ID of the user requesting access
2266    /// - `action`: The action being requested (e.g., "read", "write", "delete")
2267    /// - `resource`: The resource being accessed (e.g., "documents", "users", "reports/123")
2268    /// - `context`: Additional context key-value pairs for policy evaluation
2269    ///
2270    /// # Returns
2271    /// Returns `true` if the permission is granted based on the dynamic policy evaluation.
2272    ///
2273    /// # Example
2274    /// ```rust,no_run
2275    /// # use auth_framework::prelude::*;
2276    /// # use std::collections::HashMap;
2277    /// # async fn example(auth: &AuthFramework) -> Result<(), AuthError> {
2278    /// let mut context = HashMap::new();
2279    /// context.insert("time_of_day".to_string(), "business_hours".to_string());
2280    /// context.insert("ip_location".to_string(), "office".to_string());
2281    ///
2282    /// if auth.check_dynamic_permission("example_user", "read", "confidential_docs", context).await? {
2283    ///     println!("Access granted based on dynamic policy");
2284    /// }
2285    /// # Ok(())
2286    /// # }
2287    /// ```
2288    pub async fn check_dynamic_permission(
2289        &self,
2290        user_id: &str,
2291        action: &str,
2292        resource: &str,
2293        context: std::collections::HashMap<String, String>,
2294    ) -> Result<bool> {
2295        self.authorization_manager
2296            .check_dynamic_permission(user_id, action, resource, context)
2297            .await
2298    }
2299
2300    /// Check dynamic permission using a structured context (preferred).
2301    ///
2302    /// Prefer [`check_dynamic_permission_with_context`](Self::check_dynamic_permission_with_context)
2303    /// with a [`PermissionContext`] for better type safety and readability.
2304    ///
2305    /// # Example
2306    /// ```rust,no_run
2307    /// # use auth_framework::{prelude::*, auth_operations::PermissionContext};
2308    /// # async fn example(auth: &AuthFramework) -> Result<(), AuthError> {
2309    /// let context = PermissionContext::new()
2310    ///     .with_attribute("time_of_day", "business_hours")
2311    ///     .with_attribute("ip_location", "office");
2312    ///
2313    /// if auth.check_dynamic_permission_with_context("example_user", "read", "confidential_docs", context).await? {
2314    ///     println!("Access granted based on dynamic policy");
2315    /// }
2316    /// # Ok(())
2317    /// # }
2318    /// ```
2319    pub async fn check_dynamic_permission_with_context(
2320        &self,
2321        user_id: &str,
2322        action: &str,
2323        resource: &str,
2324        context: PermissionContext,
2325    ) -> Result<bool> {
2326        self.check_dynamic_permission(user_id, action, resource, context.into_attributes())
2327            .await
2328    }
2329
2330    /// Create resource for permission management.
2331    pub async fn create_resource(&self, resource: &str) -> Result<()> {
2332        self.authorization_manager.create_resource(resource).await
2333    }
2334
2335    /// Delegate permission from one user to another using a [`DelegationRequest`].
2336    ///
2337    /// This is the preferred method for delegation as it avoids passing multiple
2338    /// parameters and makes the call site self-documenting.
2339    ///
2340    /// # Example
2341    ///
2342    /// ```rust,no_run
2343    /// # use auth_framework::{AuthFramework, AuthConfig};
2344    /// # use auth_framework::auth_operations::DelegationRequest;
2345    /// # use std::time::Duration;
2346    /// # async fn example(auth: &AuthFramework) -> Result<(), auth_framework::errors::AuthError> {
2347    /// let req = DelegationRequest::new("admin_1", "user_2", "write", "reports")
2348    ///     .duration(Duration::from_secs(3600));
2349    /// auth.delegate_permission_with_request(req).await?;
2350    /// # Ok(())
2351    /// # }
2352    /// ```
2353    pub async fn delegate_permission_with_request(&self, req: DelegationRequest) -> Result<()> {
2354        self.authorization_manager
2355            .delegate_permission(
2356                req.delegator_id(),
2357                req.delegatee_id(),
2358                req.action(),
2359                req.resource(),
2360                req.get_duration(),
2361            )
2362            .await
2363    }
2364
2365    /// Delegate permission from one user to another.
2366    ///
2367    /// Prefer [`delegate_permission_with_request`](Self::delegate_permission_with_request)
2368    /// with a [`DelegationRequest`] for better readability when delegating permissions.
2369    pub async fn delegate_permission(
2370        &self,
2371        delegator_id: &str,
2372        delegatee_id: &str,
2373        action: &str,
2374        resource: &str,
2375        duration: std::time::Duration,
2376    ) -> Result<()> {
2377        self.authorization_manager
2378            .delegate_permission(delegator_id, delegatee_id, action, resource, duration)
2379            .await
2380    }
2381
2382    /// Get active delegations for a user.
2383    pub async fn get_active_delegations(&self, user_id: &str) -> Result<Vec<String>> {
2384        self.authorization_manager
2385            .get_active_delegations(user_id)
2386            .await
2387    }
2388
2389    /// Get permission audit logs with filtering.
2390    pub async fn get_permission_audit_logs(
2391        &self,
2392        user_id: Option<&str>,
2393        action: Option<&str>,
2394        resource: Option<&str>,
2395        limit: Option<usize>,
2396    ) -> Result<Vec<String>> {
2397        self.audit_manager
2398            .get_permission_audit_logs(user_id, action, resource, limit)
2399            .await
2400    }
2401
2402    /// Get permission audit logs using an [`AuditLogQuery`] for better readability.
2403    ///
2404    /// Prefer [`get_permission_audit_logs_with_query`](Self::get_permission_audit_logs_with_query)
2405    /// with an [`AuditLogQuery`] for better readability when using multiple filters.
2406    ///
2407    /// # Example
2408    ///
2409    /// ```rust,no_run
2410    /// # use auth_framework::{prelude::*, auth_operations::AuditLogQuery};
2411    /// # async fn example(auth: &AuthFramework) -> Result<(), auth_framework::errors::AuthError> {
2412    /// let logs = auth.get_permission_audit_logs_with_query(
2413    ///     AuditLogQuery::new()
2414    ///         .user("user_123")
2415    ///         .action("read")
2416    ///         .limit(50)
2417    /// ).await?;
2418    /// # Ok(())
2419    /// # }
2420    /// ```
2421    pub async fn get_permission_audit_logs_with_query(
2422        &self,
2423        query: AuditLogQuery,
2424    ) -> Result<Vec<String>> {
2425        self.audit_manager
2426            .get_permission_audit_logs(
2427                query.get_user_id(),
2428                query.get_action(),
2429                query.get_resource(),
2430                query.get_limit(),
2431            )
2432            .await
2433    }
2434
2435    /// Get permission metrics for monitoring.
2436    pub async fn get_permission_metrics(
2437        &self,
2438    ) -> Result<std::collections::HashMap<String, u64>, AuthError> {
2439        let active_sessions = self.storage.count_active_sessions().await.unwrap_or(0);
2440        let permission_checks_last_hour = self
2441            .audit_manager
2442            .get_permission_checks_last_hour()
2443            .await
2444            .unwrap_or(0);
2445        self.authorization_manager
2446            .get_permission_metrics(active_sessions, permission_checks_last_hour)
2447            .await
2448    }
2449
2450    /// Collect comprehensive security audit statistics.
2451    pub async fn get_security_audit_stats(&self) -> Result<SecurityAuditStats> {
2452        let active_sessions = self
2453            .session_manager
2454            .count_active_sessions()
2455            .await
2456            .unwrap_or(0);
2457        self.audit_manager
2458            .get_security_audit_stats(active_sessions)
2459            .await
2460    }
2461
2462    /// Get user profile information
2463    pub async fn get_user_profile(
2464        &self,
2465        user_id: &str,
2466    ) -> Result<crate::providers::ProviderProfile> {
2467        self.user_manager.get_user_profile(user_id).await
2468    }
2469}
2470
2471pub use crate::audit::SecurityAuditStats;
2472
2473pub use crate::auth_modular::session_manager::SessionCoordinationStats;
2474
2475/// Authentication framework statistics.
2476#[derive(Debug, Clone, Default)]
2477pub struct AuthStats {
2478    /// Number of registered authentication methods
2479    pub registered_methods: Vec<String>,
2480
2481    /// Number of active sessions
2482    pub active_sessions: u64,
2483
2484    /// Number of active MFA challenges
2485    pub active_mfa_challenges: u64,
2486
2487    /// Number of tokens issued (this would need proper tracking)
2488    pub tokens_issued: u64,
2489
2490    /// Number of authentication attempts (this would need proper tracking)
2491    pub auth_attempts: u64,
2492}
2493
2494#[cfg(test)]
2495mod tests {
2496    use super::*;
2497    use crate::config::{AuthConfig, SecurityConfig};
2498    #[tokio::test]
2499    async fn test_framework_initialization() {
2500        let config = AuthConfig::new().security(SecurityConfig {
2501            min_password_length: 8,
2502            require_password_complexity: false,
2503            password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
2504            jwt_algorithm: crate::config::JwtAlgorithm::HS256,
2505            secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string()),
2506            secure_cookies: false,
2507            cookie_same_site: crate::config::CookieSameSite::Lax,
2508            csrf_protection: false,
2509            session_timeout: Duration::from_secs(3600),
2510            previous_secret_key: None,
2511        });
2512        let mut framework = AuthFramework::new(config);
2513
2514        assert!(framework.initialize().await.is_ok());
2515        assert!(framework.initialized);
2516    }
2517
2518    #[tokio::test]
2519    async fn test_method_registration() {
2520        // Method registration test disabled due to trait object lifetime constraints
2521        // This test would require dynamic trait objects which have complex lifetime requirements
2522        // Production implementations should use static method registration or dependency injection
2523
2524        let config = AuthConfig::new().security(SecurityConfig {
2525            min_password_length: 8,
2526            require_password_complexity: false,
2527            password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
2528            jwt_algorithm: crate::config::JwtAlgorithm::HS256,
2529            secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string()),
2530            secure_cookies: false,
2531            cookie_same_site: crate::config::CookieSameSite::Lax,
2532            csrf_protection: false,
2533            session_timeout: Duration::from_secs(3600),
2534            previous_secret_key: None,
2535        });
2536        let framework = AuthFramework::new(config);
2537
2538        // Verify framework initialization works without dynamic method registration
2539        assert!(!framework.initialized);
2540
2541        // Method registration system supports flexible authentication methods
2542        // using factory pattern for better lifetime management
2543    }
2544
2545    #[tokio::test]
2546    async fn test_token_validation() {
2547        let config = AuthConfig::new().security(SecurityConfig {
2548            min_password_length: 8,
2549            require_password_complexity: false,
2550            password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
2551            jwt_algorithm: crate::config::JwtAlgorithm::HS256,
2552            secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string()),
2553            secure_cookies: false,
2554            cookie_same_site: crate::config::CookieSameSite::Lax,
2555            csrf_protection: false,
2556            session_timeout: Duration::from_secs(3600),
2557            previous_secret_key: None,
2558        });
2559        let mut framework = AuthFramework::new(config);
2560        framework.initialize().await.unwrap();
2561
2562        let token = framework
2563            .token_manager
2564            .create_auth_token("test-user", vec!["read".to_string()], "test", None)
2565            .unwrap();
2566
2567        // Store the token first
2568        framework.storage.store_token(&token).await.unwrap();
2569
2570        assert!(framework.validate_token(&token).await.unwrap());
2571    }
2572
2573    #[tokio::test]
2574    async fn test_session_management() {
2575        let config = AuthConfig::new().security(SecurityConfig {
2576            min_password_length: 8,
2577            require_password_complexity: false,
2578            password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
2579            jwt_algorithm: crate::config::JwtAlgorithm::HS256,
2580            secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string()),
2581            secure_cookies: false,
2582            cookie_same_site: crate::config::CookieSameSite::Lax,
2583            csrf_protection: false,
2584            session_timeout: Duration::from_secs(3600),
2585            previous_secret_key: None,
2586        });
2587        let mut framework = AuthFramework::new(config);
2588        framework.initialize().await.unwrap();
2589
2590        let session_id = framework
2591            .create_session(
2592                "test-user",
2593                Duration::from_secs(3600),
2594                Some("192.168.1.1".to_string()),
2595                Some("Test Agent".to_string()),
2596            )
2597            .await
2598            .unwrap();
2599
2600        let session = framework.get_session(&session_id).await.unwrap();
2601        assert!(session.is_some());
2602
2603        framework.delete_session(&session_id).await.unwrap();
2604        let session = framework.get_session(&session_id).await.unwrap();
2605        assert!(session.is_none());
2606    }
2607
2608    #[tokio::test]
2609    async fn test_grouped_operations_accessors() {
2610        let config = AuthConfig::new().security(SecurityConfig {
2611            min_password_length: 8,
2612            require_password_complexity: false,
2613            password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
2614            jwt_algorithm: crate::config::JwtAlgorithm::HS256,
2615            secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string()),
2616            secure_cookies: false,
2617            cookie_same_site: crate::config::CookieSameSite::Lax,
2618            csrf_protection: false,
2619            session_timeout: Duration::from_secs(3600),
2620            previous_secret_key: None,
2621        });
2622        let mut framework = AuthFramework::new(config);
2623        framework.initialize().await.unwrap();
2624
2625        let user_id = framework
2626            .users()
2627            .register("grouped-user", "grouped-user@example.com", "P@ssw0rd123")
2628            .await
2629            .unwrap();
2630        assert!(
2631            framework
2632                .users()
2633                .exists_by_username("grouped-user")
2634                .await
2635                .unwrap()
2636        );
2637
2638        let session_id = framework
2639            .sessions()
2640            .create(&user_id, Duration::from_secs(300), None, None)
2641            .await
2642            .unwrap();
2643        assert!(
2644            framework
2645                .sessions()
2646                .get(&session_id)
2647                .await
2648                .unwrap()
2649                .is_some()
2650        );
2651        assert_eq!(
2652            framework
2653                .sessions()
2654                .list_for_user(&user_id)
2655                .await
2656                .unwrap()
2657                .len(),
2658            1
2659        );
2660
2661        framework
2662            .authorization()
2663            .grant(&user_id, "read", "documents")
2664            .await
2665            .unwrap();
2666        let permissions = framework
2667            .authorization()
2668            .effective_permissions(&user_id)
2669            .await
2670            .unwrap();
2671        assert!(
2672            permissions
2673                .iter()
2674                .any(|permission| permission == "read:documents")
2675        );
2676
2677        framework.sessions().delete(&session_id).await.unwrap();
2678        assert!(
2679            framework
2680                .sessions()
2681                .get(&session_id)
2682                .await
2683                .unwrap()
2684                .is_none()
2685        );
2686    }
2687
2688    #[tokio::test]
2689    async fn test_cleanup_expired_data() {
2690        let config = AuthConfig::new().security(SecurityConfig {
2691            min_password_length: 8,
2692            require_password_complexity: false,
2693            password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
2694            jwt_algorithm: crate::config::JwtAlgorithm::HS256,
2695            secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string()),
2696            secure_cookies: false,
2697            cookie_same_site: crate::config::CookieSameSite::Lax,
2698            csrf_protection: false,
2699            session_timeout: Duration::from_secs(3600),
2700            previous_secret_key: None,
2701        });
2702        let mut framework = AuthFramework::new(config);
2703        framework.initialize().await.unwrap();
2704
2705        // This test would need expired data to be meaningful
2706        assert!(framework.cleanup_expired_data().await.is_ok());
2707    }
2708}