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