Skip to main content

auth_framework/
auth.rs

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