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