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