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        if !self.validate_token(token).await? {
1443            return Ok(false);
1444        }
1445        self.authorization_manager
1446            .check_token_permission(token, action, resource)
1447            .await
1448    }
1449
1450    /// Refresh a token.
1451    pub async fn refresh_token(&self, token: &AuthToken) -> Result<AuthToken> {
1452        self.require_initialized()?;
1453        debug!("Refreshing token for user '{}'", token.user_id);
1454
1455        // Check if the auth method supports refresh
1456        if let Some(method) = self.methods.get(&token.auth_method)
1457            && method.supports_refresh()
1458            && let Some(ref refresh_token) = token.refresh_token
1459        {
1460            let new_token = method.refresh_token(refresh_token.to_string()).await?;
1461            self.storage.store_token(&new_token).await?;
1462            return Ok(new_token);
1463        }
1464
1465        // Fallback to creating a new token with the same properties. Only a token that is
1466        // valid right now (live, not revoked, stored, and whose fields agree with its JWT)
1467        // can be renewed: the caller's value is not trusted on its own.
1468        if !self.validate_token(token).await? {
1469            return Err(AuthError::Token(crate::errors::TokenError::Invalid {
1470                message: "Cannot refresh a token that is not valid".to_string(),
1471            }));
1472        }
1473        // Renew from the STORED token (scopes, client binding), never from the caller's value.
1474        let stored = self
1475            .storage
1476            .get_token(&token.token_id)
1477            .await?
1478            .ok_or_else(|| {
1479                AuthError::Token(crate::errors::TokenError::Invalid {
1480                    message: "Cannot refresh a token that is not stored".to_string(),
1481                })
1482            })?;
1483        let new_token = self.token_manager.refresh_token(&stored)?;
1484        self.storage.store_token(&new_token).await?;
1485
1486        info!("Token refreshed for user '{}'", token.user_id);
1487
1488        Ok(new_token)
1489    }
1490
1491    /// Revoke a token.
1492    pub async fn revoke_token(&self, token: &AuthToken) -> Result<()> {
1493        self.require_initialized()?;
1494        debug!("Revoking token for user '{}'", token.user_id);
1495
1496        // Mark token as revoked
1497        let mut revoked_token = token.clone();
1498        revoked_token.revoke(Some("Manual revocation".to_string()));
1499
1500        // Update in storage
1501        self.storage.update_token(&revoked_token).await?;
1502
1503        // Bearer-JWT validation consults the revocation list by jti, so record it there too
1504        // for as long as the token could still be presented.
1505        let jti = self
1506            .token_manager
1507            .validate_jwt_token(&token.access_token)
1508            .map(|claims| claims.jti)
1509            .unwrap_or_else(|_| token.token_id.clone());
1510        let remaining = (token.expires_at - chrono::Utc::now())
1511            .to_std()
1512            .unwrap_or_default()
1513            .max(Duration::from_secs(60));
1514        self.storage
1515            .store_kv(&format!("revoked_token:{jti}"), b"revoked", Some(remaining))
1516            .await?;
1517
1518        info!("Token revoked for user '{}'", token.user_id);
1519
1520        Ok(())
1521    }
1522
1523    /// Create a new API key for a user.
1524    pub async fn create_api_key(
1525        &self,
1526        user_id: &str,
1527        expires_in: Option<Duration>,
1528    ) -> Result<String> {
1529        self.require_initialized()?;
1530        self.user_manager.create_api_key(user_id, expires_in).await
1531    }
1532
1533    /// Validate an API key and return user information.
1534    pub async fn validate_api_key(&self, api_key: &str) -> Result<UserInfo> {
1535        self.require_initialized()?;
1536        self.user_manager.validate_api_key(api_key).await
1537    }
1538
1539    /// Revoke an API key.
1540    pub async fn revoke_api_key(&self, api_key: &str) -> Result<()> {
1541        self.require_initialized()?;
1542        self.user_manager.revoke_api_key(api_key).await
1543    }
1544
1545    /// Create a new session.
1546    pub async fn create_session(
1547        &self,
1548        user_id: &str,
1549        expires_in: Duration,
1550        ip_address: Option<String>,
1551        user_agent: Option<String>,
1552    ) -> Result<String> {
1553        self.require_initialized()?;
1554        let (session_id, new_total) = self
1555            .session_manager
1556            .create_session_limited(user_id, expires_in, ip_address, user_agent)
1557            .await?;
1558        self.monitoring_manager
1559            .update_session_count(new_total)
1560            .await;
1561        Ok(session_id)
1562    }
1563
1564    /// Create a new session using a [`SessionCreateRequest`] for better readability.
1565    ///
1566    /// Prefer [`create_session_with_request`](Self::create_session_with_request)
1567    /// with a [`SessionCreateRequest`] for better readability when using optional fields.
1568    ///
1569    /// # Example
1570    ///
1571    /// ```rust,no_run
1572    /// # use auth_framework::{prelude::*, auth_operations::SessionCreateRequest};
1573    /// # use std::time::Duration;
1574    /// # async fn example(auth: &AuthFramework) -> Result<(), auth_framework::errors::AuthError> {
1575    /// let session_id = auth.create_session_with_request(
1576    ///     SessionCreateRequest::new("user_123", Duration::from_secs(3600))
1577    ///         .ip_address("192.168.1.1")
1578    ///         .user_agent("MyApp/1.0")
1579    /// ).await?;
1580    /// # Ok(())
1581    /// # }
1582    /// ```
1583    pub async fn create_session_with_request(&self, req: SessionCreateRequest) -> Result<String> {
1584        self.create_session(
1585            req.get_user_id(),
1586            req.get_expires_in(),
1587            req.get_ip_address().map(|s| s.to_string()),
1588            req.get_user_agent().map(|s| s.to_string()),
1589        )
1590        .await
1591    }
1592
1593    /// Get session information.
1594    pub async fn get_session(&self, session_id: &str) -> Result<Option<SessionData>> {
1595        self.require_initialized()?;
1596        self.session_manager.get_session(session_id).await
1597    }
1598
1599    /// Delete a session.
1600    pub async fn delete_session(&self, session_id: &str) -> Result<()> {
1601        self.require_initialized()?;
1602        self.session_manager.delete_session(session_id).await?;
1603
1604        let remaining = self
1605            .session_manager
1606            .count_active_sessions()
1607            .await
1608            .unwrap_or(0);
1609        self.monitoring_manager
1610            .update_session_count(remaining)
1611            .await;
1612
1613        Ok(())
1614    }
1615
1616    /// Get all tokens for a user.
1617    pub async fn list_user_tokens(&self, user_id: &str) -> Result<Vec<AuthToken>> {
1618        self.require_initialized()?;
1619        self.storage.list_user_tokens(user_id).await
1620    }
1621
1622    /// Clean up expired data.
1623    pub async fn cleanup_expired_data(&self) -> Result<()> {
1624        debug!("Cleaning up expired data");
1625
1626        // Clean up storage
1627        self.storage.cleanup_expired().await?;
1628
1629        // Clean up MFA challenges via mfa manager
1630        self.mfa_manager.cleanup_expired_challenges().await?;
1631
1632        // Clean up sessions via session manager
1633        self.session_manager.cleanup_expired_sessions().await?;
1634
1635        // Clean up rate limiter
1636        if let Some(ref rate_limiter) = self.rate_limiter {
1637            let _ = rate_limiter.cleanup().ok();
1638        }
1639
1640        Ok(())
1641    }
1642
1643    /// Detect if the process is running in a production environment by inspecting
1644    /// well-known environment variables and container indicators.
1645    fn is_production_environment() -> bool {
1646        if let Ok(env) = std::env::var("ENVIRONMENT")
1647            && (env.to_lowercase() == "production" || env.to_lowercase() == "prod")
1648        {
1649            return true;
1650        }
1651        if let Ok(env) = std::env::var("ENV")
1652            && (env.to_lowercase() == "production" || env.to_lowercase() == "prod")
1653        {
1654            return true;
1655        }
1656        if let Ok(env) = std::env::var("NODE_ENV")
1657            && env.to_lowercase() == "production"
1658        {
1659            return true;
1660        }
1661        if let Ok(env) = std::env::var("RUST_ENV")
1662            && env.to_lowercase() == "production"
1663        {
1664            return true;
1665        }
1666        std::env::var("KUBERNETES_SERVICE_HOST").is_ok()
1667            || std::env::var("DOCKER_CONTAINER").is_ok()
1668    }
1669
1670    /// Get authentication framework statistics.
1671    pub async fn get_stats(&self) -> Result<AuthStats> {
1672        let mut stats = AuthStats::default();
1673
1674        if let Err(e) = self.storage.cleanup_expired().await {
1675            warn!("Failed to cleanup expired data: {}", e);
1676        }
1677        if let Some(rate_limiter) = &self.rate_limiter {
1678            let _ = rate_limiter.cleanup().ok();
1679        }
1680
1681        let active_sessions = self
1682            .session_manager
1683            .count_active_sessions()
1684            .await
1685            .unwrap_or(0) as u32;
1686
1687        stats.registered_methods = self.methods.keys().cloned().collect();
1688        stats.active_sessions = active_sessions as u64;
1689        stats.active_mfa_challenges = self.mfa_manager.get_active_challenge_count().await as u64;
1690        // Use monitoring counters for accurate cumulative tracking
1691        let perf = self.monitoring_manager.get_performance_metrics();
1692        stats.tokens_issued = perf.get("token_creations").copied().unwrap_or(0);
1693        stats.auth_attempts = perf.get("auth_successes").copied().unwrap_or(0)
1694            + perf.get("auth_failures").copied().unwrap_or(0);
1695
1696        Ok(stats)
1697    }
1698
1699    /// Returns a reference to the underlying [`TokenManager`].
1700    ///
1701    /// Useful for advanced token operations not exposed by the
1702    /// [`TokenOperations`] facade.
1703    pub fn token_manager(&self) -> &TokenManager {
1704        &self.token_manager
1705    }
1706
1707    /// Redeem a refresh JWT: it is single-use. On success the presented token is spent and the
1708    /// next token of its chain is returned; the caller mints the access token.
1709    ///
1710    /// Refused (all as `Token(Invalid)`): not a refresh token, revoked, its chain revoked,
1711    /// the account deactivated, or already redeemed. Presenting an already-redeemed token is
1712    /// treated as theft: the whole chain is revoked, so the legitimate holder must sign in again.
1713    pub async fn redeem_refresh_jwt(&self, token: &str) -> Result<RefreshRedemption> {
1714        let claims = self.token_manager.validate_jwt_token(token)?;
1715        if !claims.is_refresh_token() {
1716            return Err(rejected("Expected a refresh token"));
1717        }
1718        let read = |key: String| async move {
1719            self.storage.get_kv(&key).await.map_err(|e| {
1720                tracing::error!("Could not read refresh-token state: {}", e);
1721                rejected("Unable to verify token status")
1722            })
1723        };
1724        let family = claims.refresh_family().to_string();
1725        if read(format!("revoked_token:{}", claims.jti))
1726            .await?
1727            .is_some()
1728            || read(format!("revoked_family:{family}")).await?.is_some()
1729        {
1730            return Err(rejected("Refresh token has been revoked"));
1731        }
1732        ensure_account_active(self.storage.as_ref(), &claims.sub, true).await?;
1733
1734        let remaining =
1735            Duration::from_secs((claims.exp - chrono::Utc::now().timestamp()).max(60) as u64);
1736        // A revoked chain stays revoked for as long as its NEWEST token could live.
1737        let family_ttl = self.config.refresh_token_lifetime + Duration::from_secs(60);
1738        let consumed_key = format!("refresh_consumed:{}", claims.jti);
1739        // Spend it BEFORE issuing the next one, with an atomic set-if-absent: of any number
1740        // of simultaneous redemptions of the same token exactly one proceeds. Presenting it
1741        // again afterwards is treated as theft and revokes its chain. (A storage backend that
1742        // keeps the trait's default `store_kv_if_absent` is not atomic here.) If minting fails
1743        // after this point the client has lost the token and must sign in again.
1744        let first_use = self
1745            .storage
1746            .store_kv_if_absent(&consumed_key, b"used", Some(remaining))
1747            .await
1748            .map_err(|e| {
1749                tracing::error!("Could not record refresh token use: {}", e);
1750                rejected("Unable to record refresh token use")
1751            })?;
1752        if !first_use {
1753            warn!(
1754                "Refresh token reuse detected for user '{}'; revoking its chain",
1755                claims.sub
1756            );
1757            if let Err(e) = self
1758                .storage
1759                .store_kv(
1760                    &format!("revoked_family:{family}"),
1761                    b"reuse",
1762                    Some(family_ttl),
1763                )
1764                .await
1765            {
1766                tracing::error!("Could not revoke refresh chain after reuse: {}", e);
1767            }
1768            return Err(rejected("Refresh token has already been used"));
1769        }
1770
1771        let lifetime = self.config.refresh_token_lifetime;
1772        let new_refresh_token = self.token_manager.create_refresh_jwt_token_in_family(
1773            &claims.sub,
1774            Some(lifetime),
1775            &family,
1776        )?;
1777        Ok(RefreshRedemption {
1778            claims,
1779            new_refresh_token,
1780        })
1781    }
1782
1783    /// Validate a JWT presented as an ACCESS token and return its claims.
1784    ///
1785    /// This is the one check every place that accepts a bearer JWT should use: it verifies
1786    /// the signature and claims, refuses refresh tokens (they are only good at the refresh
1787    /// endpoint), and refuses tokens that were revoked (`revoked_token:{jti}`, written by
1788    /// logout and revocation). If the revocation list cannot be read the token is refused.
1789    pub async fn validate_access_jwt(&self, token: &str) -> Result<crate::tokens::JwtClaims> {
1790        validate_access_jwt_with(
1791            &self.token_manager,
1792            self.storage.as_ref(),
1793            token,
1794            true,
1795            false,
1796        )
1797        .await
1798    }
1799
1800    /// Like [`validate_access_jwt`](Self::validate_access_jwt) but also accepts a token that was
1801    /// issued to an OAuth client on a user's behalf (it carries a `client_id`). Use it ONLY on
1802    /// resource routes that are meant for delegated access; scope is advisory unless the route
1803    /// checks it. Everything that guards sessions (admin, account management) must keep using
1804    /// `validate_access_jwt`, which refuses client-bound tokens.
1805    pub async fn validate_delegated_jwt(&self, token: &str) -> Result<crate::tokens::JwtClaims> {
1806        validate_access_jwt_with(
1807            &self.token_manager,
1808            self.storage.as_ref(),
1809            token,
1810            true,
1811            true,
1812        )
1813        .await
1814    }
1815
1816    /// Validates a username against the configured format rules.
1817    ///
1818    /// Returns `Ok(true)` when the name is acceptable, or an error describing
1819    /// the specific rule that was violated (length, characters, etc.).
1820    ///
1821    /// # Errors
1822    ///
1823    /// Returns [`AuthError`] if the username is empty, too long, or contains
1824    /// forbidden characters per the active [`SecurityConfig`].
1825    pub async fn validate_username(&self, username: &str) -> Result<bool> {
1826        self.user_manager.validate_username(username).await
1827    }
1828
1829    /// Validates a display name against the configured format rules.
1830    ///
1831    /// # Errors
1832    ///
1833    /// Returns [`AuthError`] if the display name is empty or exceeds the
1834    /// configured maximum length.
1835    pub async fn validate_display_name(&self, display_name: &str) -> Result<bool> {
1836        self.user_manager.validate_display_name(display_name).await
1837    }
1838
1839    /// Checks a password against the active security policy.
1840    ///
1841    /// Validates minimum length, character-class requirements, and (optionally)
1842    /// checks against known-breached password lists.
1843    ///
1844    /// # Errors
1845    ///
1846    /// Returns [`AuthError`] describing which policy rule the password violates.
1847    pub async fn validate_password_strength(&self, password: &str) -> Result<bool> {
1848        self.user_manager.validate_password_strength(password).await
1849    }
1850
1851    /// Validates arbitrary user input against common injection patterns.
1852    ///
1853    /// Checks for SQL injection, XSS, and command injection markers.
1854    /// Returns `Ok(true)` when the input is safe.
1855    pub async fn validate_user_input(&self, input: &str) -> Result<bool> {
1856        Ok(crate::utils::validation::validate_user_input(input))
1857    }
1858
1859    /// Creates an authentication token directly.
1860    ///
1861    /// This is a low-level API intended for **testing, migration tools, and
1862    /// administrative tasks**. In production, tokens should be created through
1863    /// [`authenticate`](Self::authenticate) instead.
1864    ///
1865    /// # Parameters
1866    ///
1867    /// * `user_id`     — the subject the token is issued to.
1868    /// * `scopes`      — OAuth-style scopes (accepts `Vec<String>`, `Scopes`, or `&[&str]`).
1869    /// * `method_name` — the auth method to record (must be registered).
1870    /// * `lifetime`    — override the default token TTL; `None` uses the
1871    ///   framework-configured default.
1872    ///
1873    /// # Errors
1874    ///
1875    /// * [`AuthError::AuthMethod`] if `method_name` is not registered.
1876    /// * [`AuthError::RateLimit`] if the user already holds the maximum number
1877    ///   of active tokens.
1878    pub async fn create_auth_token(
1879        &self,
1880        user_id: impl Into<String>,
1881        scopes: impl Into<crate::types::Scopes>,
1882        method_name: impl Into<String>,
1883        lifetime: Option<Duration>,
1884    ) -> Result<AuthToken> {
1885        let method_name = method_name.into();
1886        let user_id = user_id.into();
1887        let scopes: crate::types::Scopes = scopes.into();
1888
1889        // Validate the method exists and is correctly configured
1890        let auth_method = self
1891            .methods
1892            .get(&method_name)
1893            .ok_or_else(|| AuthError::auth_method(&method_name, "Method not found"))?;
1894        auth_method.validate_config()?;
1895
1896        // ENTERPRISE SECURITY: Check token limits to prevent resource exhaustion
1897        const MAX_TOKENS_PER_USER: usize = 100;
1898        let user_tokens = self.storage.list_user_tokens(&user_id).await?;
1899        if user_tokens.len() >= MAX_TOKENS_PER_USER {
1900            warn!(
1901                "User '{}' has reached maximum tokens ({})",
1902                user_id, MAX_TOKENS_PER_USER
1903            );
1904            return Err(AuthError::rate_limit(
1905                "Maximum tokens per user exceeded. Please revoke unused tokens.",
1906            ));
1907        }
1908
1909        let token = self
1910            .mint_and_store_token(&user_id, scopes, &method_name, lifetime)
1911            .await?;
1912        self.monitoring_manager
1913            .record_token_creation(&method_name)
1914            .await;
1915        Ok(token)
1916    }
1917
1918    /// Initiates an SMS-based MFA challenge for `user_id`.
1919    ///
1920    /// Sends a one-time code via the configured SMS provider and returns a
1921    /// challenge ID that must be passed to [`verify_sms_code`](Self::verify_sms_code).
1922    ///
1923    /// # Errors
1924    ///
1925    /// Returns [`AuthError`] if no phone number is registered or the SMS
1926    /// provider fails to deliver.
1927    pub async fn initiate_sms_challenge(&self, user_id: &str) -> Result<String> {
1928        self.mfa_manager.sms.initiate_challenge(user_id).await
1929    }
1930
1931    /// Verifies an SMS challenge code previously issued by
1932    /// [`initiate_sms_challenge`](Self::initiate_sms_challenge).
1933    ///
1934    /// # Errors
1935    ///
1936    /// Returns [`AuthError`] if the challenge has expired or if the code is
1937    /// invalid.
1938    pub async fn verify_sms_code(&self, challenge_id: &str, code: &str) -> Result<bool> {
1939        self.mfa_manager.sms.verify_code(challenge_id, code).await
1940    }
1941
1942    /// Registers an email address for email-based MFA for `user_id`.
1943    ///
1944    /// # Errors
1945    ///
1946    /// Returns [`AuthError`] if the email format is invalid or the user does
1947    /// not exist.
1948    pub async fn register_email(&self, user_id: &str, email: &str) -> Result<()> {
1949        self.mfa_manager.email.register_email(user_id, email).await
1950    }
1951
1952    /// Generates a new TOTP secret and stores it for `user_id`.
1953    ///
1954    /// The returned string is a Base32-encoded secret suitable for importing
1955    /// into authenticator apps. Pair with
1956    /// [`generate_totp_qr_code`](Self::generate_totp_qr_code) for a scan-ready
1957    /// URI.
1958    ///
1959    /// # Errors
1960    ///
1961    /// Returns [`AuthError`] if secret generation or storage fails.
1962    pub async fn generate_totp_secret(&self, user_id: &str) -> Result<String> {
1963        self.mfa_manager.totp.generate_secret(user_id).await
1964    }
1965
1966    /// Generates an `otpauth://` URI suitable for rendering as a QR code.
1967    ///
1968    /// # Parameters
1969    ///
1970    /// * `user_id`  — identifies the user in the authenticator label.
1971    /// * `app_name` — the issuer name shown in the authenticator app.
1972    /// * `secret`   — the Base32 TOTP secret from [`generate_totp_secret`](Self::generate_totp_secret).
1973    pub async fn generate_totp_qr_code(
1974        &self,
1975        user_id: &str,
1976        app_name: &str,
1977        secret: &str,
1978    ) -> Result<String> {
1979        self.mfa_manager
1980            .totp
1981            .generate_qr_code(user_id, app_name, secret)
1982            .await
1983    }
1984
1985    /// Generates the current TOTP code for the given Base32 `secret`.
1986    ///
1987    /// Primarily useful for testing; in production the *user* generates the
1988    /// code on their device.
1989    pub async fn generate_totp_code(&self, secret: &str) -> Result<String> {
1990        self.mfa_manager.totp.generate_code(secret).await
1991    }
1992
1993    /// Generates a TOTP code for the given `secret` and optional time window.
1994    ///
1995    /// When `time_window` is `None`, the current 30-second window is used.
1996    pub async fn generate_totp_code_for_window(
1997        &self,
1998        secret: &str,
1999        time_window: Option<u64>,
2000    ) -> Result<String> {
2001        self.mfa_manager
2002            .totp
2003            .generate_code_for_window(secret, time_window)
2004            .await
2005    }
2006
2007    /// Verifies a TOTP code against the stored secret for `user_id`.
2008    ///
2009    /// Applies a configurable clock-skew window (default: ±1 step).
2010    ///
2011    /// # Errors
2012    ///
2013    /// Returns [`AuthError`] if no TOTP secret is registered for the user.
2014    pub async fn verify_totp_code(&self, user_id: &str, code: &str) -> Result<bool> {
2015        self.mfa_manager.totp.verify_code(user_id, code).await
2016    }
2017
2018    /// Checks whether the given IP address is within the configured rate limit.
2019    ///
2020    /// Returns `Ok(true)` if the request is allowed, or an
2021    /// [`AuthError::RateLimit`] if the caller should be throttled.
2022    pub async fn check_ip_rate_limit(&self, ip: &str) -> Result<bool> {
2023        debug!("Checking IP rate limit for '{}'", ip);
2024        let Some(ref rate_limiter) = self.rate_limiter else {
2025            return Ok(true);
2026        };
2027        if !rate_limiter.is_allowed(&format!("ip:{}", ip)) {
2028            warn!("Rate limit exceeded for IP: {}", ip);
2029            return Err(AuthError::rate_limit(format!(
2030                "Too many requests from IP {}. Please try again later.",
2031                ip
2032            )));
2033        }
2034        Ok(true)
2035    }
2036
2037    /// Return security metrics for monitoring dashboards.
2038    ///
2039    /// Keys include `active_sessions`, `total_tokens`, `failed_attempts`,
2040    /// `successful_attempts`, and `expired_tokens`.
2041    pub async fn get_security_metrics(&self) -> Result<std::collections::HashMap<String, u64>> {
2042        debug!("Getting security metrics");
2043        let mut metrics = std::collections::HashMap::new();
2044        let total_active_sessions = self
2045            .session_manager
2046            .count_active_sessions()
2047            .await
2048            .unwrap_or(0);
2049        metrics.insert("active_sessions".to_string(), total_active_sessions);
2050        metrics.insert("total_tokens".to_string(), total_active_sessions);
2051        metrics.insert(
2052            "failed_attempts".to_string(),
2053            self.audit_manager
2054                .get_failed_login_count_24h()
2055                .await
2056                .unwrap_or(0),
2057        );
2058        metrics.insert(
2059            "successful_attempts".to_string(),
2060            self.audit_manager
2061                .get_successful_login_count_24h()
2062                .await
2063                .unwrap_or(0),
2064        );
2065        metrics.insert("expired_tokens".to_string(), 0u64);
2066        Ok(metrics)
2067    }
2068
2069    /// Registers a phone number for SMS-based MFA.
2070    ///
2071    /// # Errors
2072    ///
2073    /// Returns [`AuthError`] if the phone number format is invalid.
2074    pub async fn register_phone_number(&self, user_id: &str, phone_number: &str) -> Result<()> {
2075        self.mfa_manager
2076            .sms
2077            .register_phone_number(user_id, phone_number)
2078            .await
2079    }
2080
2081    /// Generate `count` one-time backup codes for the given user.
2082    ///
2083    /// Codes are persisted server-side (hashed); plaintext codes are returned
2084    /// to the caller for display to the user.
2085    pub async fn generate_backup_codes(&self, user_id: &str, count: usize) -> Result<Vec<String>> {
2086        self.mfa_manager
2087            .backup_codes
2088            .generate_codes(user_id, count)
2089            .await
2090    }
2091    /// Grants an authorization permission to a user.
2092    ///
2093    /// # Parameters
2094    ///
2095    /// * `user_id`  — the user receiving the permission.
2096    /// * `action`   — the action being allowed (e.g. `"read"`, `"write"`).
2097    /// * `resource` — the resource scope (e.g. `"documents"`, `"users:*"`).
2098    ///
2099    /// # Errors
2100    ///
2101    /// Returns [`AuthError`] if the user does not exist or storage fails.
2102    pub async fn grant_permission(
2103        &self,
2104        user_id: &str,
2105        action: &str,
2106        resource: &str,
2107    ) -> Result<()> {
2108        self.authorization_manager
2109            .grant_permission(user_id, action, resource)
2110            .await
2111    }
2112
2113    /// Initiates an email-based MFA challenge for `user_id`.
2114    ///
2115    /// Sends a one-time code to the registered email address and returns a
2116    /// challenge ID.
2117    ///
2118    /// # Errors
2119    ///
2120    /// Returns [`AuthError`] if no email is registered for the user or
2121    /// delivery fails.
2122    pub async fn initiate_email_challenge(&self, user_id: &str) -> Result<String> {
2123        self.mfa_manager.email.initiate_challenge(user_id).await
2124    }
2125
2126    /// Returns a cloned handle to the storage backend.
2127    ///
2128    /// Useful when you need to pass storage to another component or run
2129    /// direct queries outside the framework's managed API.
2130    pub fn storage(&self) -> Arc<dyn AuthStorage> {
2131        self.storage.clone()
2132    }
2133
2134    /// Returns a reference to the active framework configuration.
2135    pub fn config(&self) -> &AuthConfig {
2136        &self.config
2137    }
2138
2139    /// Reset runtime authorization state back to the default roles.
2140    pub async fn reset_authorization_runtime(&self) {
2141        self.authorization_manager.reset_runtime_state().await;
2142    }
2143
2144    /// Register a new user with username, email, and password.
2145    ///
2146    /// The password is hashed with the configured algorithm (default: Argon2)
2147    /// before storage.  Returns the generated user ID on success.
2148    ///
2149    /// # Errors
2150    ///
2151    /// Returns [`AuthError`] if:
2152    /// - The username or email is already taken
2153    /// - The password does not meet the configured complexity requirements
2154    /// - The storage backend is unavailable
2155    ///
2156    /// # Example
2157    ///
2158    /// ```rust,no_run
2159    /// # use auth_framework::prelude::*;
2160    /// # async fn example(auth: &AuthFramework) -> Result<(), AuthError> {
2161    /// let user_id = auth.users().register("alice", "alice@example.com", "S3cur3P@ss!").await?;
2162    /// println!("Created user: {user_id}");
2163    /// # Ok(())
2164    /// # }
2165    /// ```
2166    pub async fn register_user(
2167        &self,
2168        username: &str,
2169        email: &str,
2170        password: &str,
2171    ) -> Result<String> {
2172        self.require_initialized()?;
2173        self.user_manager
2174            .register_user(username, email, password)
2175            .await
2176    }
2177
2178    /// List users from the canonical user index with optional filtering and pagination.
2179    ///
2180    /// This method provides paginated access to the user directory with optional
2181    /// filtering by active status.
2182    ///
2183    /// # Parameters
2184    /// - `limit`: Maximum number of users to return (None for no limit)
2185    /// - `offset`: Number of users to skip for pagination (None for start from beginning)
2186    /// - `active_only`: If true, only return active users; if false, return all users
2187    ///
2188    /// # Returns
2189    /// Returns a vector of [`UserInfo`] structs containing user details.
2190    ///
2191    /// # Example
2192    /// ```rust,no_run
2193    /// # use auth_framework::prelude::*;
2194    /// # async fn example(auth: &AuthFramework) -> Result<(), AuthError> {
2195    /// // Get first 10 active users
2196    /// let users = auth.list_users(Some(10), None, true).await?;
2197    /// println!("Found {} active users", users.len());
2198    ///
2199    /// // Get all users (active and inactive)
2200    /// let all_users = auth.list_users(None, None, false).await?;
2201    /// # Ok(())
2202    /// # }
2203    /// ```
2204    #[deprecated(
2205        since = "0.6.0",
2206        note = "use `list_users_with_query(UserListQuery::new().limit(n).active_only())` instead"
2207    )]
2208    pub async fn list_users(
2209        &self,
2210        limit: Option<usize>,
2211        offset: Option<usize>,
2212        active_only: bool,
2213    ) -> Result<Vec<UserInfo>> {
2214        self.require_initialized()?;
2215        self.user_manager
2216            .list_users(limit, offset, active_only)
2217            .await
2218    }
2219
2220    /// List users using a [`UserListQuery`] for better readability.
2221    ///
2222    /// Prefer [`list_users_with_query`](Self::list_users_with_query)
2223    /// with a [`UserListQuery`] for better readability when using pagination or filtering.
2224    ///
2225    /// # Example
2226    ///
2227    /// ```rust,no_run
2228    /// # use auth_framework::{prelude::*, auth_operations::UserListQuery};
2229    /// # async fn example(auth: &AuthFramework) -> Result<(), auth_framework::errors::AuthError> {
2230    /// let users = auth.list_users_with_query(
2231    ///     UserListQuery::new()
2232    ///         .limit(50)
2233    ///         .active_only()
2234    /// ).await?;
2235    /// # Ok(())
2236    /// # }
2237    /// ```
2238    pub async fn list_users_with_query(&self, query: UserListQuery) -> Result<Vec<UserInfo>> {
2239        self.require_initialized()?;
2240        self.user_manager
2241            .list_users(
2242                query.get_limit(),
2243                query.get_offset(),
2244                query.get_active_only(),
2245            )
2246            .await
2247    }
2248
2249    /// Get user information by canonical user ID.
2250    pub async fn get_user_record(&self, user_id: &str) -> Result<UserInfo> {
2251        self.require_initialized()?;
2252        self.user_manager.get_user_info(user_id).await
2253    }
2254
2255    /// Update the roles assigned to a user.
2256    pub async fn update_user_roles(&self, user_id: &str, roles: &[String]) -> Result<()> {
2257        self.require_initialized()?;
2258        self.user_manager.update_user_roles(user_id, roles).await
2259    }
2260
2261    /// Set a user's active / deactivated status.
2262    pub async fn set_user_active(&self, user_id: &str, active: bool) -> Result<()> {
2263        self.require_initialized()?;
2264        self.user_manager.set_user_active(user_id, active).await
2265    }
2266
2267    /// Update a user's email address.
2268    pub async fn update_user_email(&self, user_id: &str, email: &str) -> Result<()> {
2269        self.require_initialized()?;
2270        self.user_manager.update_user_email(user_id, email).await
2271    }
2272
2273    /// Verify a user's password by user_id against the stored bcrypt hash.
2274    pub async fn verify_user_password(&self, user_id: &str, password: &str) -> Result<bool> {
2275        self.require_initialized()?;
2276        self.user_manager
2277            .verify_user_password(user_id, password)
2278            .await
2279    }
2280
2281    /// Look up a user's username by their user_id.
2282    pub async fn get_username_by_id(&self, user_id: &str) -> Result<String> {
2283        self.user_manager.get_username_by_id(user_id).await
2284    }
2285
2286    /// Check if a username exists.
2287    pub async fn username_exists(&self, username: &str) -> Result<bool> {
2288        self.user_manager.username_exists(username).await
2289    }
2290
2291    /// Check if an email exists.
2292    pub async fn email_exists(&self, email: &str) -> Result<bool> {
2293        self.user_manager.email_exists(email).await
2294    }
2295
2296    /// Get user data by username.
2297    pub async fn get_user_by_username(
2298        &self,
2299        username: &str,
2300    ) -> Result<HashMap<String, serde_json::Value>> {
2301        self.user_manager.get_user_by_username(username).await
2302    }
2303
2304    /// Update user password.
2305    pub async fn update_user_password(&self, username: &str, new_password: &str) -> Result<()> {
2306        self.require_initialized()?;
2307        self.user_manager
2308            .update_user_password(username, new_password)
2309            .await
2310    }
2311
2312    /// Update user password by canonical user ID.
2313    pub async fn update_user_password_by_id(
2314        &self,
2315        user_id: &str,
2316        new_password: &str,
2317    ) -> Result<()> {
2318        self.require_initialized()?;
2319        self.user_manager
2320            .update_user_password_by_id(user_id, new_password)
2321            .await
2322    }
2323
2324    /// Delete a user by username.
2325    pub async fn delete_user(&self, username: &str) -> Result<()> {
2326        self.require_initialized()?;
2327        self.user_manager.delete_user(username).await
2328    }
2329
2330    /// Delete a user by canonical user ID.
2331    pub async fn delete_user_by_id(&self, user_id: &str) -> Result<()> {
2332        self.require_initialized()?;
2333        self.user_manager.delete_user_by_id(user_id).await
2334    }
2335
2336    /// Verify MFA code with proper challenge validation.
2337    async fn verify_mfa_code(&self, challenge: &MfaChallenge, code: &str) -> Result<bool> {
2338        self.mfa_manager
2339            .verify_challenge_code(challenge, code)
2340            .await
2341    }
2342
2343    /// Log an audit event via tracing, subject to per-event-type config guards.
2344    async fn log_audit_event(
2345        &self,
2346        event_type: &str,
2347        user_id: &str,
2348        method: &str,
2349        metadata: &CredentialMetadata,
2350    ) {
2351        if !self.config.audit.enabled {
2352            return;
2353        }
2354        let should_log = match event_type {
2355            "auth_success" | "mfa_required" => self.config.audit.log_success,
2356            "auth_failure" => self.config.audit.log_failures,
2357            _ => true,
2358        };
2359        if should_log {
2360            self.audit_manager
2361                .log_auth_trace_event(
2362                    event_type,
2363                    user_id,
2364                    method,
2365                    metadata.client_ip.as_deref().unwrap_or("unknown"),
2366                    metadata.user_agent.as_deref().unwrap_or("unknown"),
2367                )
2368                .await;
2369        }
2370    }
2371
2372    /// Guard the global MFA-challenge budget and store the challenge.
2373    async fn guard_and_store_mfa_challenge(&self, challenge: MfaChallenge) -> Result<()> {
2374        self.mfa_manager.guard_and_store(challenge).await
2375    }
2376
2377    /// Create and immediately store an auth token, returning it.
2378    async fn mint_and_store_token(
2379        &self,
2380        user_id: &str,
2381        scopes: impl Into<crate::types::Scopes>,
2382        method: &str,
2383        lifetime: Option<Duration>,
2384    ) -> Result<AuthToken> {
2385        let token = self
2386            .token_manager
2387            .create_auth_token(user_id, scopes, method, lifetime)?;
2388        self.storage.store_token(&token).await?;
2389        Ok(token)
2390    }
2391
2392    /// Coordinate session state across distributed instances.
2393    pub async fn coordinate_distributed_sessions(&self) -> Result<SessionCoordinationStats> {
2394        self.session_manager.coordinate_distributed_sessions().await
2395    }
2396
2397    /// Synchronize a specific session with remote instances.
2398    pub async fn synchronize_session(&self, session_id: &str) -> Result<()> {
2399        self.session_manager.synchronize_session(session_id).await
2400    }
2401
2402    /// Returns the monitoring manager for metrics collection and health checks.
2403    pub fn monitoring_manager(&self) -> Arc<crate::monitoring::MonitoringManager> {
2404        self.monitoring_manager.clone()
2405    }
2406
2407    /// Returns the security manager for rate limiting, DoS protection, and IP blacklisting.
2408    #[cfg(feature = "api-server")]
2409    pub fn security_manager(&self) -> Option<Arc<crate::api::SecurityManager>> {
2410        Some(self.security_manager.clone())
2411    }
2412
2413    /// Return current performance metrics (token counts, latencies, etc.).
2414    pub async fn get_performance_metrics(&self) -> std::collections::HashMap<String, u64> {
2415        self.monitoring_manager.get_performance_metrics()
2416    }
2417
2418    /// Run a health check on all sub-systems (storage, token engine, etc.).
2419    pub async fn health_check(
2420        &self,
2421    ) -> Result<std::collections::HashMap<String, crate::monitoring::HealthCheckResult>> {
2422        self.monitoring_manager.health_check().await
2423    }
2424
2425    /// Export all collected metrics in Prometheus text exposition format.
2426    pub async fn export_prometheus_metrics(&self) -> String {
2427        self.monitoring_manager.export_prometheus_metrics().await
2428    }
2429    /// Create a new role.
2430    pub async fn create_role(&self, role: crate::permissions::Role) -> Result<()> {
2431        self.require_initialized()?;
2432        self.authorization_manager.create_role(role).await
2433    }
2434
2435    /// Return all defined roles.
2436    pub async fn list_roles(&self) -> Vec<crate::permissions::Role> {
2437        self.authorization_manager.list_roles().await
2438    }
2439
2440    /// Fetch a role definition by name.
2441    pub async fn get_role(&self, role_name: &str) -> Result<crate::permissions::Role> {
2442        self.authorization_manager.get_role(role_name).await
2443    }
2444
2445    /// Add a permission to an existing role.
2446    pub async fn add_role_permission(
2447        &self,
2448        role_name: &str,
2449        permission: crate::permissions::Permission,
2450    ) -> Result<()> {
2451        self.authorization_manager
2452            .add_role_permission(role_name, permission)
2453            .await
2454    }
2455
2456    /// Assign a role to a user.
2457    pub async fn assign_role(&self, user_id: &str, role_name: &str) -> Result<()> {
2458        self.require_initialized()?;
2459        self.authorization_manager
2460            .assign_role(user_id, role_name)
2461            .await
2462    }
2463
2464    /// Remove a role from a user.
2465    pub async fn remove_role(&self, user_id: &str, role_name: &str) -> Result<()> {
2466        self.require_initialized()?;
2467        self.authorization_manager
2468            .remove_role(user_id, role_name)
2469            .await
2470    }
2471
2472    /// Set role inheritance.
2473    pub async fn set_role_inheritance(&self, child_role: &str, parent_role: &str) -> Result<()> {
2474        self.require_initialized()?;
2475        self.authorization_manager
2476            .set_role_inheritance(child_role, parent_role)
2477            .await
2478    }
2479
2480    /// Revoke permission from a user.
2481    pub async fn revoke_permission(
2482        &self,
2483        user_id: &str,
2484        action: &str,
2485        resource: &str,
2486    ) -> Result<()> {
2487        self.require_initialized()?;
2488        self.authorization_manager
2489            .revoke_permission(user_id, action, resource)
2490            .await
2491    }
2492
2493    /// Check if user has a role.
2494    pub async fn user_has_role(&self, user_id: &str, role_name: &str) -> Result<bool> {
2495        self.authorization_manager
2496            .user_has_role(user_id, role_name)
2497            .await
2498    }
2499
2500    /// List the currently assigned runtime roles for a user.
2501    pub async fn list_user_roles(&self, user_id: &str) -> Result<Vec<String>> {
2502        self.authorization_manager.list_user_roles(user_id).await
2503    }
2504
2505    /// Get effective permissions for a user.
2506    pub async fn get_effective_permissions(&self, user_id: &str) -> Result<Vec<String>> {
2507        self.authorization_manager
2508            .get_effective_permissions(user_id)
2509            .await
2510    }
2511
2512    /// Create ABAC policy.
2513    pub async fn create_abac_policy(&self, name: &str, description: &str) -> Result<()> {
2514        self.authorization_manager
2515            .create_abac_policy(name, description)
2516            .await
2517    }
2518
2519    /// Set a user attribute value for ABAC (Attribute-Based Access Control) evaluation.
2520    ///
2521    /// User attributes are key-value pairs associated with users that can be used
2522    /// in dynamic permission rules. This method stores or updates an attribute value.
2523    ///
2524    /// # Parameters
2525    /// - `user_id`: The ID of the user to set the attribute for
2526    /// - `attribute`: The name of the attribute to set
2527    /// - `value`: The value to assign to the attribute
2528    ///
2529    /// # Example
2530    /// ```rust,no_run
2531    /// # use auth_framework::prelude::*;
2532    /// # async fn example(auth: &AuthFramework) -> Result<(), AuthError> {
2533    /// // Set user attributes for policy evaluation
2534    /// auth.map_user_attribute("example_user", "department", "engineering").await?;
2535    /// auth.map_user_attribute("example_user", "clearance_level", "confidential").await?;
2536    /// # Ok(())
2537    /// # }
2538    /// ```
2539    pub async fn map_user_attribute(
2540        &self,
2541        user_id: &str,
2542        attribute: &str,
2543        value: &str,
2544    ) -> Result<()> {
2545        self.authorization_manager
2546            .map_user_attribute(user_id, attribute, value)
2547            .await
2548    }
2549
2550    /// Get a user attribute value for ABAC (Attribute-Based Access Control) evaluation.
2551    ///
2552    /// User attributes are key-value pairs associated with users that can be used
2553    /// in dynamic permission rules. Common attributes include department, clearance level,
2554    /// location, etc.
2555    ///
2556    /// # Parameters
2557    /// - `user_id`: The ID of the user whose attribute to retrieve
2558    /// - `attribute`: The name of the attribute to retrieve
2559    ///
2560    /// # Returns
2561    /// Returns `Some(value)` if the attribute exists, `None` if it doesn't exist.
2562    ///
2563    /// # Example
2564    /// ```rust,no_run
2565    /// # use auth_framework::prelude::*;
2566    /// # async fn example(auth: &AuthFramework) -> Result<(), AuthError> {
2567    /// if let Some(dept) = auth.get_user_attribute("example_user", "department").await? {
2568    ///     println!("User is in department: {}", dept);
2569    /// }
2570    /// # Ok(())
2571    /// # }
2572    /// ```
2573    pub async fn get_user_attribute(
2574        &self,
2575        user_id: &str,
2576        attribute: &str,
2577    ) -> Result<Option<String>> {
2578        self.authorization_manager
2579            .get_user_attribute(user_id, attribute)
2580            .await
2581    }
2582
2583    /// Check dynamic permission with context evaluation (ABAC - Attribute-Based Access Control).
2584    ///
2585    /// This method evaluates permissions based on user attributes, resource attributes,
2586    /// and environmental context rather than just role assignments. It's more flexible
2587    /// than simple role-based checks but requires more complex policy rules.
2588    ///
2589    /// # Parameters
2590    /// - `user_id`: The ID of the user requesting access
2591    /// - `action`: The action being requested (e.g., "read", "write", "delete")
2592    /// - `resource`: The resource being accessed (e.g., "documents", "users", "reports/123")
2593    /// - `context`: Additional context key-value pairs for policy evaluation
2594    ///
2595    /// # Returns
2596    /// Returns `true` if the permission is granted based on the dynamic policy evaluation.
2597    ///
2598    /// # Example
2599    /// ```rust,no_run
2600    /// # use auth_framework::prelude::*;
2601    /// # use std::collections::HashMap;
2602    /// # async fn example(auth: &AuthFramework) -> Result<(), AuthError> {
2603    /// let mut context = HashMap::new();
2604    /// context.insert("time_of_day".to_string(), "business_hours".to_string());
2605    /// context.insert("ip_location".to_string(), "office".to_string());
2606    ///
2607    /// if auth.check_dynamic_permission("example_user", "read", "confidential_docs", context).await? {
2608    ///     println!("Access granted based on dynamic policy");
2609    /// }
2610    /// # Ok(())
2611    /// # }
2612    /// ```
2613    pub async fn check_dynamic_permission(
2614        &self,
2615        user_id: &str,
2616        action: &str,
2617        resource: &str,
2618        context: std::collections::HashMap<String, String>,
2619    ) -> Result<bool> {
2620        self.authorization_manager
2621            .check_dynamic_permission(user_id, action, resource, context)
2622            .await
2623    }
2624
2625    /// Check dynamic permission using a structured context (preferred).
2626    ///
2627    /// Prefer [`check_dynamic_permission_with_context`](Self::check_dynamic_permission_with_context)
2628    /// with a [`PermissionContext`] for better type safety and readability.
2629    ///
2630    /// # Example
2631    /// ```rust,no_run
2632    /// # use auth_framework::{prelude::*, auth_operations::PermissionContext};
2633    /// # async fn example(auth: &AuthFramework) -> Result<(), AuthError> {
2634    /// let context = PermissionContext::new()
2635    ///     .with_attribute("time_of_day", "business_hours")
2636    ///     .with_attribute("ip_location", "office");
2637    ///
2638    /// if auth.check_dynamic_permission_with_context("example_user", "read", "confidential_docs", context).await? {
2639    ///     println!("Access granted based on dynamic policy");
2640    /// }
2641    /// # Ok(())
2642    /// # }
2643    /// ```
2644    pub async fn check_dynamic_permission_with_context(
2645        &self,
2646        user_id: &str,
2647        action: &str,
2648        resource: &str,
2649        context: PermissionContext,
2650    ) -> Result<bool> {
2651        self.check_dynamic_permission(user_id, action, resource, context.into_attributes())
2652            .await
2653    }
2654
2655    /// Create resource for permission management.
2656    pub async fn create_resource(&self, resource: &str) -> Result<()> {
2657        self.authorization_manager.create_resource(resource).await
2658    }
2659
2660    /// Delegate permission from one user to another using a [`DelegationRequest`].
2661    ///
2662    /// This is the preferred method for delegation as it avoids passing multiple
2663    /// parameters and makes the call site self-documenting.
2664    ///
2665    /// # Example
2666    ///
2667    /// ```rust,no_run
2668    /// # use auth_framework::{AuthFramework, AuthConfig};
2669    /// # use auth_framework::auth_operations::DelegationRequest;
2670    /// # use std::time::Duration;
2671    /// # async fn example(auth: &AuthFramework) -> Result<(), auth_framework::errors::AuthError> {
2672    /// let req = DelegationRequest::new("admin_1", "user_2", "write", "reports")
2673    ///     .duration(Duration::from_secs(3600));
2674    /// auth.delegate_permission_with_request(req).await?;
2675    /// # Ok(())
2676    /// # }
2677    /// ```
2678    pub async fn delegate_permission_with_request(&self, req: DelegationRequest) -> Result<()> {
2679        self.authorization_manager
2680            .delegate_permission(
2681                req.delegator_id(),
2682                req.delegatee_id(),
2683                req.action(),
2684                req.resource(),
2685                req.get_duration(),
2686            )
2687            .await
2688    }
2689
2690    /// Delegate permission from one user to another.
2691    ///
2692    /// Prefer [`delegate_permission_with_request`](Self::delegate_permission_with_request)
2693    /// with a [`DelegationRequest`] for better readability when delegating permissions.
2694    pub async fn delegate_permission(
2695        &self,
2696        delegator_id: &str,
2697        delegatee_id: &str,
2698        action: &str,
2699        resource: &str,
2700        duration: std::time::Duration,
2701    ) -> Result<()> {
2702        self.authorization_manager
2703            .delegate_permission(delegator_id, delegatee_id, action, resource, duration)
2704            .await
2705    }
2706
2707    /// Get active delegations for a user.
2708    pub async fn get_active_delegations(&self, user_id: &str) -> Result<Vec<String>> {
2709        self.authorization_manager
2710            .get_active_delegations(user_id)
2711            .await
2712    }
2713
2714    /// Get permission audit logs with filtering.
2715    pub async fn get_permission_audit_logs(
2716        &self,
2717        user_id: Option<&str>,
2718        action: Option<&str>,
2719        resource: Option<&str>,
2720        limit: Option<usize>,
2721    ) -> Result<Vec<String>> {
2722        self.audit_manager
2723            .get_permission_audit_logs(user_id, action, resource, limit)
2724            .await
2725    }
2726
2727    /// Get permission audit logs using an [`AuditLogQuery`] for better readability.
2728    ///
2729    /// Prefer [`get_permission_audit_logs_with_query`](Self::get_permission_audit_logs_with_query)
2730    /// with an [`AuditLogQuery`] for better readability when using multiple filters.
2731    ///
2732    /// # Example
2733    ///
2734    /// ```rust,no_run
2735    /// # use auth_framework::{prelude::*, auth_operations::AuditLogQuery};
2736    /// # async fn example(auth: &AuthFramework) -> Result<(), auth_framework::errors::AuthError> {
2737    /// let logs = auth.get_permission_audit_logs_with_query(
2738    ///     AuditLogQuery::new()
2739    ///         .user("user_123")
2740    ///         .action("read")
2741    ///         .limit(50)
2742    /// ).await?;
2743    /// # Ok(())
2744    /// # }
2745    /// ```
2746    pub async fn get_permission_audit_logs_with_query(
2747        &self,
2748        query: AuditLogQuery,
2749    ) -> Result<Vec<String>> {
2750        self.audit_manager
2751            .get_permission_audit_logs(
2752                query.get_user_id(),
2753                query.get_action(),
2754                query.get_resource(),
2755                query.get_limit(),
2756            )
2757            .await
2758    }
2759
2760    /// Get permission metrics for monitoring.
2761    pub async fn get_permission_metrics(
2762        &self,
2763    ) -> Result<std::collections::HashMap<String, u64>, AuthError> {
2764        let active_sessions = self.storage.count_active_sessions().await.unwrap_or(0);
2765        let permission_checks_last_hour = self
2766            .audit_manager
2767            .get_permission_checks_last_hour()
2768            .await
2769            .unwrap_or(0);
2770        self.authorization_manager
2771            .get_permission_metrics(active_sessions, permission_checks_last_hour)
2772            .await
2773    }
2774
2775    /// Collect comprehensive security audit statistics.
2776    pub async fn get_security_audit_stats(&self) -> Result<SecurityAuditStats> {
2777        let active_sessions = self
2778            .session_manager
2779            .count_active_sessions()
2780            .await
2781            .unwrap_or(0);
2782        self.audit_manager
2783            .get_security_audit_stats(active_sessions)
2784            .await
2785    }
2786
2787    /// Get user profile information
2788    pub async fn get_user_profile(
2789        &self,
2790        user_id: &str,
2791    ) -> Result<crate::providers::ProviderProfile> {
2792        self.user_manager.get_user_profile(user_id).await
2793    }
2794}
2795
2796pub use crate::audit::SecurityAuditStats;
2797
2798pub use crate::auth_modular::session_manager::SessionCoordinationStats;
2799
2800/// Authentication framework statistics.
2801#[derive(Debug, Clone, Default)]
2802pub struct AuthStats {
2803    /// Number of registered authentication methods
2804    pub registered_methods: Vec<String>,
2805
2806    /// Number of active sessions
2807    pub active_sessions: u64,
2808
2809    /// Number of active MFA challenges
2810    pub active_mfa_challenges: u64,
2811
2812    /// Number of tokens issued (this would need proper tracking)
2813    pub tokens_issued: u64,
2814
2815    /// Number of authentication attempts (this would need proper tracking)
2816    pub auth_attempts: u64,
2817}
2818
2819#[cfg(test)]
2820mod tests {
2821    use super::*;
2822    use crate::config::{AuthConfig, SecurityConfig};
2823    #[tokio::test]
2824    async fn test_framework_initialization() {
2825        let config = AuthConfig::new().security(SecurityConfig {
2826            min_password_length: 8,
2827            require_password_complexity: false,
2828            password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
2829            jwt_algorithm: crate::config::JwtAlgorithm::HS256,
2830            secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string().into()),
2831            secure_cookies: false,
2832            cookie_same_site: crate::config::CookieSameSite::Lax,
2833            csrf_protection: false,
2834            session_timeout: Duration::from_secs(3600),
2835            previous_secret_key: None,
2836        });
2837        let mut framework = AuthFramework::new(config);
2838
2839        assert!(framework.initialize().await.is_ok());
2840        assert!(framework.initialized);
2841    }
2842
2843    #[tokio::test]
2844    async fn test_method_registration() {
2845        // Method registration test disabled due to trait object lifetime constraints
2846        // This test would require dynamic trait objects which have complex lifetime requirements
2847        // Production implementations should use static method registration or dependency injection
2848
2849        let config = AuthConfig::new().security(SecurityConfig {
2850            min_password_length: 8,
2851            require_password_complexity: false,
2852            password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
2853            jwt_algorithm: crate::config::JwtAlgorithm::HS256,
2854            secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string().into()),
2855            secure_cookies: false,
2856            cookie_same_site: crate::config::CookieSameSite::Lax,
2857            csrf_protection: false,
2858            session_timeout: Duration::from_secs(3600),
2859            previous_secret_key: None,
2860        });
2861        let framework = AuthFramework::new(config);
2862
2863        // Verify framework initialization works without dynamic method registration
2864        assert!(!framework.initialized);
2865
2866        // Method registration system supports flexible authentication methods
2867        // using factory pattern for better lifetime management
2868    }
2869
2870    #[tokio::test]
2871    async fn test_token_validation() {
2872        let config = AuthConfig::new().security(SecurityConfig {
2873            min_password_length: 8,
2874            require_password_complexity: false,
2875            password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
2876            jwt_algorithm: crate::config::JwtAlgorithm::HS256,
2877            secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string().into()),
2878            secure_cookies: false,
2879            cookie_same_site: crate::config::CookieSameSite::Lax,
2880            csrf_protection: false,
2881            session_timeout: Duration::from_secs(3600),
2882            previous_secret_key: None,
2883        });
2884        let mut framework = AuthFramework::new(config);
2885        framework.initialize().await.unwrap();
2886
2887        let token = framework
2888            .token_manager
2889            .create_auth_token("test-user", vec!["read".to_string()], "test", None)
2890            .unwrap();
2891
2892        // Store the token first
2893        framework.storage.store_token(&token).await.unwrap();
2894
2895        assert!(framework.validate_token(&token).await.unwrap());
2896    }
2897
2898    #[tokio::test]
2899    async fn test_session_management() {
2900        let config = AuthConfig::new().security(SecurityConfig {
2901            min_password_length: 8,
2902            require_password_complexity: false,
2903            password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
2904            jwt_algorithm: crate::config::JwtAlgorithm::HS256,
2905            secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string().into()),
2906            secure_cookies: false,
2907            cookie_same_site: crate::config::CookieSameSite::Lax,
2908            csrf_protection: false,
2909            session_timeout: Duration::from_secs(3600),
2910            previous_secret_key: None,
2911        });
2912        let mut framework = AuthFramework::new(config);
2913        framework.initialize().await.unwrap();
2914
2915        let session_id = framework
2916            .create_session(
2917                "test-user",
2918                Duration::from_secs(3600),
2919                Some("192.168.1.1".to_string()),
2920                Some("Test Agent".to_string()),
2921            )
2922            .await
2923            .unwrap();
2924
2925        let session = framework.get_session(&session_id).await.unwrap();
2926        assert!(session.is_some());
2927
2928        framework.delete_session(&session_id).await.unwrap();
2929        let session = framework.get_session(&session_id).await.unwrap();
2930        assert!(session.is_none());
2931    }
2932
2933    #[tokio::test]
2934    async fn test_grouped_operations_accessors() {
2935        let config = AuthConfig::new().security(SecurityConfig {
2936            min_password_length: 8,
2937            require_password_complexity: false,
2938            password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
2939            jwt_algorithm: crate::config::JwtAlgorithm::HS256,
2940            secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string().into()),
2941            secure_cookies: false,
2942            cookie_same_site: crate::config::CookieSameSite::Lax,
2943            csrf_protection: false,
2944            session_timeout: Duration::from_secs(3600),
2945            previous_secret_key: None,
2946        });
2947        let mut framework = AuthFramework::new(config);
2948        framework.initialize().await.unwrap();
2949
2950        let user_id = framework
2951            .users()
2952            .register("grouped-user", "grouped-user@example.com", "P@ssw0rd123")
2953            .await
2954            .unwrap();
2955        assert!(
2956            framework
2957                .users()
2958                .exists_by_username("grouped-user")
2959                .await
2960                .unwrap()
2961        );
2962
2963        let session_id = framework
2964            .sessions()
2965            .create(&user_id, Duration::from_secs(300), None, None)
2966            .await
2967            .unwrap();
2968        assert!(
2969            framework
2970                .sessions()
2971                .get(&session_id)
2972                .await
2973                .unwrap()
2974                .is_some()
2975        );
2976        assert_eq!(
2977            framework
2978                .sessions()
2979                .list_for_user(&user_id)
2980                .await
2981                .unwrap()
2982                .len(),
2983            1
2984        );
2985
2986        framework
2987            .authorization()
2988            .grant(&user_id, "read", "documents")
2989            .await
2990            .unwrap();
2991        let permissions = framework
2992            .authorization()
2993            .effective_permissions(&user_id)
2994            .await
2995            .unwrap();
2996        assert!(
2997            permissions
2998                .iter()
2999                .any(|permission| permission == "read:documents")
3000        );
3001
3002        framework.sessions().delete(&session_id).await.unwrap();
3003        assert!(
3004            framework
3005                .sessions()
3006                .get(&session_id)
3007                .await
3008                .unwrap()
3009                .is_none()
3010        );
3011    }
3012
3013    #[tokio::test]
3014    async fn test_cleanup_expired_data() {
3015        let config = AuthConfig::new().security(SecurityConfig {
3016            min_password_length: 8,
3017            require_password_complexity: false,
3018            password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
3019            jwt_algorithm: crate::config::JwtAlgorithm::HS256,
3020            secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string().into()),
3021            secure_cookies: false,
3022            cookie_same_site: crate::config::CookieSameSite::Lax,
3023            csrf_protection: false,
3024            session_timeout: Duration::from_secs(3600),
3025            previous_secret_key: None,
3026        });
3027        let mut framework = AuthFramework::new(config);
3028        framework.initialize().await.unwrap();
3029
3030        // This test would need expired data to be meaningful
3031        assert!(framework.cleanup_expired_data().await.is_ok());
3032    }
3033
3034    /// Regression test: `new_validated`'s own Redis construction path used
3035    /// to build `RedisStorage` directly with no encryption wrapping at
3036    /// all (a separate gap from `auth_modular`'s, fixed the same way). If
3037    /// the `wrap_with_encryption_if_enabled` call this fix added is ever
3038    /// removed again, construction would SUCCEED here instead of failing
3039    /// closed. `RedisStorage::new` only parses the URL -- it doesn't
3040    /// connect -- so this doesn't need a live server.
3041    #[cfg(feature = "redis-storage")]
3042    #[test]
3043    fn new_validated_redis_fails_closed_without_an_encryption_key() {
3044        let _lock = crate::storage::encryption::TEST_ENCRYPTION_ENV_LOCK.blocking_lock();
3045        // SAFETY: sound against every other test that ALSO takes
3046        // `_lock`; this test does.
3047        unsafe {
3048            std::env::remove_var("AUTH_STORAGE_ENCRYPTION_KEY");
3049            std::env::remove_var("AUTH_STORAGE_ENCRYPTION_KEYS_FILE");
3050        }
3051
3052        let mut config = AuthConfig::new().secret("test_secret_key_32_bytes_long!!!!");
3053        config.storage = crate::config::StorageConfig::Redis {
3054            url: "redis://127.0.0.1:1/".to_string(),
3055            key_prefix: "test:".to_string(),
3056        };
3057        // storage_encryption defaults to enabled: true.
3058
3059        let result = AuthFramework::new_validated(config);
3060        assert!(
3061            result.is_err(),
3062            "constructing with Redis storage and no encryption key configured must fail \
3063             closed, not silently build unwrapped (unencrypted) storage"
3064        );
3065    }
3066
3067    #[tokio::test]
3068    async fn initialize_refuses_unwrapped_custom_storage_when_wrapping_is_required() {
3069        let mut config = AuthConfig::new().secret("test_secret_key_32_bytes_long!!!!");
3070        config.storage_encryption.require_wrapped_storage = true;
3071        let mut framework = AuthFramework::new_with_storage(config, Arc::new(MemoryStorage::new()));
3072        assert!(
3073            framework.initialize().await.is_err(),
3074            "caller-supplied unwrapped storage must be refused when wrapping is required"
3075        );
3076    }
3077
3078    #[tokio::test]
3079    async fn initialize_accepts_wrapped_or_unrequired_custom_storage() {
3080        let mut required = AuthConfig::new().secret("test_secret_key_32_bytes_long!!!!");
3081        required.storage_encryption.require_wrapped_storage = true;
3082        let wrapped: Arc<dyn AuthStorage> =
3083            Arc::new(crate::storage::encryption::EncryptedStorage::new(
3084                MemoryStorage::new(),
3085                crate::storage::encryption::StorageEncryption::new_random(),
3086                false,
3087                false,
3088            ));
3089        let mut framework = AuthFramework::new_with_storage(required, wrapped);
3090        framework.initialize().await.unwrap();
3091
3092        // Default config only warns.
3093        let config = AuthConfig::new().secret("test_secret_key_32_bytes_long!!!!");
3094        let mut framework = AuthFramework::new_with_storage(config, Arc::new(MemoryStorage::new()));
3095        framework.initialize().await.unwrap();
3096    }
3097
3098    #[tokio::test]
3099    async fn factory_built_storage_is_not_treated_as_caller_supplied() {
3100        let mut config = AuthConfig::new().secret("test_secret_key_32_bytes_long!!!!");
3101        config.storage_encryption.require_wrapped_storage = true;
3102        let mut framework = AuthFramework::new(config);
3103        // The factory deliberately leaves in-memory storage unwrapped.
3104        framework.replace_storage_from_factory(Arc::new(MemoryStorage::new()));
3105        framework.initialize().await.unwrap();
3106    }
3107}