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