Skip to main content

auth_framework/
auth.rs

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