Skip to main content

auth_framework/config/
mod.rs

1//! Configuration types for the authentication framework.
2
3pub mod app_config;
4pub mod config_manager;
5
6// Re-export for easy access
7pub use app_config::{AppConfig, ConfigBuilder as AppConfigBuilder};
8pub use config_manager::{
9    ApiServerSettings, AuthFrameworkSettings, ConfigBuilder as LayeredConfigBuilder,
10    ConfigIntegration, ConfigManager, SessionCookieSettings, SessionSettings,
11};
12
13use crate::errors::{AuthError, Result};
14use serde::{Deserialize, Serialize};
15use std::collections::HashMap;
16use std::time::Duration;
17
18/// Main configuration for the authentication framework.
19#[derive(Debug, Clone, Serialize, Deserialize)]
20#[serde(default)]
21pub struct AuthConfig {
22    /// Default token lifetime
23    pub token_lifetime: Duration,
24
25    /// Refresh token lifetime
26    pub refresh_token_lifetime: Duration,
27
28    /// Whether multi-factor authentication is enabled
29    pub enable_multi_factor: bool,
30
31    /// JWT issuer for token validation
32    pub issuer: String,
33
34    /// JWT audience for token validation
35    pub audience: String,
36
37    /// JWT secret key (optional - can be set via environment)
38    pub secret: Option<String>,
39
40    /// Storage configuration
41    pub storage: StorageConfig,
42
43    /// Rate limiting configuration
44    pub rate_limiting: RateLimitConfig,
45
46    /// Security configuration
47    pub security: SecurityConfig,
48
49    /// CORS configuration used by all web framework integrations.
50    #[serde(default)]
51    pub cors: CorsConfig,
52
53    /// Audit logging configuration
54    pub audit: AuditConfig,
55
56    /// Whether framework-level caching helpers are enabled.
57    #[serde(default)]
58    pub enable_caching: bool,
59
60    /// Maximum failed authentication attempts before a client should be blocked.
61    #[serde(default = "default_max_failed_attempts")]
62    pub max_failed_attempts: u32,
63
64    /// Whether RBAC helpers are enabled in the configuration model.
65    #[serde(default)]
66    pub enable_rbac: bool,
67
68    /// Whether framework middleware helpers are enabled in the configuration model.
69    #[serde(default)]
70    pub enable_middleware: bool,
71
72    /// Custom settings for different auth methods
73    pub method_configs: HashMap<String, serde_json::Value>,
74
75    /// Force production validation regardless of environment variables.
76    /// Used in tests that explicitly verify production-mode error handling.
77    #[serde(default)]
78    pub force_production_mode: bool,
79}
80
81/// Storage configuration options.
82#[derive(Debug, Clone, Serialize, Deserialize)]
83pub enum StorageConfig {
84    /// In-memory storage (not recommended for production)
85    Memory,
86
87    /// Redis storage
88    #[cfg(feature = "redis-storage")]
89    Redis { url: String, key_prefix: String },
90
91    /// PostgreSQL storage
92    #[cfg(feature = "postgres-storage")]
93    Postgres {
94        connection_string: String,
95        table_prefix: String,
96    },
97
98    /// MySQL storage
99    #[cfg(feature = "mysql-storage")]
100    MySQL {
101        connection_string: String,
102        table_prefix: String,
103    },
104
105    /// SQLite storage
106    #[cfg(feature = "sqlite-storage")]
107    Sqlite { connection_string: String },
108
109    /// Custom storage backend
110    Custom(String),
111}
112
113/// Rate limiting configuration.
114///
115/// Controls how many requests each client can make within a sliding time
116/// window.  Use [`RateLimitConfig::new`] for quick construction or
117/// [`Default::default()`] for sensible production defaults (100 req/min).
118#[derive(Debug, Clone, Serialize, Deserialize)]
119#[serde(default)]
120pub struct RateLimitConfig {
121    /// Enable rate limiting
122    pub enabled: bool,
123
124    /// Maximum requests per window
125    pub max_requests: u32,
126
127    /// Time window for rate limiting
128    pub window: Duration,
129
130    /// Burst allowance
131    pub burst: u32,
132}
133
134/// Security configuration options.
135///
136/// Governs password policy, JWT signing, cookie flags, CSRF protection,
137/// and session timeouts.  Two named constructors cover the most common
138/// scenarios:
139///
140/// - [`SecurityConfig::secure()`] — hardened production defaults.
141/// - [`SecurityConfig::development()`] — relaxed settings for local work.
142///
143/// For anything in between, start from [`Default::default()`] and
144/// override individual fields.
145#[derive(Debug, Clone, Serialize, Deserialize)]
146#[serde(default)]
147pub struct SecurityConfig {
148    /// Minimum password length
149    pub min_password_length: usize,
150
151    /// Require password complexity
152    pub require_password_complexity: bool,
153
154    /// Password hash algorithm
155    pub password_hash_algorithm: PasswordHashAlgorithm,
156
157    /// JWT signing algorithm
158    pub jwt_algorithm: JwtAlgorithm,
159
160    /// Secret key for signing (should be loaded from environment)
161    pub secret_key: Option<String>,
162
163    /// Previous secret key to maintain validation capabilities during rotation
164    pub previous_secret_key: Option<String>,
165
166    /// Enable secure cookies
167    pub secure_cookies: bool,
168
169    /// Cookie SameSite policy
170    pub cookie_same_site: CookieSameSite,
171
172    /// CSRF protection
173    pub csrf_protection: bool,
174
175    /// Session timeout
176    pub session_timeout: Duration,
177}
178
179/// Password hashing algorithms.
180#[derive(Debug, Clone, Serialize, Deserialize)]
181pub enum PasswordHashAlgorithm {
182    /// Argon2id — recommended for new applications (memory-hard, side-channel resistant).
183    Argon2,
184    /// bcrypt — widely supported, suitable when Argon2 is unavailable.
185    Bcrypt,
186    /// scrypt — memory-hard alternative to bcrypt.
187    Scrypt,
188}
189
190/// JWT signing algorithms.
191#[derive(Debug, Clone, Serialize, Deserialize)]
192pub enum JwtAlgorithm {
193    /// HMAC-SHA256 (symmetric).
194    HS256,
195    /// HMAC-SHA384 (symmetric).
196    HS384,
197    /// HMAC-SHA512 (symmetric).
198    HS512,
199    /// RSA-SHA256 (asymmetric) — recommended for multi-service deployments.
200    RS256,
201    /// RSA-SHA384 (asymmetric).
202    RS384,
203    /// RSA-SHA512 (asymmetric).
204    RS512,
205    /// ECDSA-SHA256 (asymmetric) — compact signatures.
206    ES256,
207    /// ECDSA-SHA384 (asymmetric).
208    ES384,
209}
210
211/// Cookie SameSite policies.
212#[derive(Debug, Clone, Serialize, Deserialize)]
213pub enum CookieSameSite {
214    /// Cookies sent only in first-party (same-site) requests.
215    Strict,
216    /// Cookies sent in same-site requests and top-level cross-site navigations.
217    Lax,
218    /// Cookies sent in all contexts; requires the `Secure` flag.
219    None,
220}
221
222/// Cross-Origin Resource Sharing (CORS) configuration.
223///
224/// This is the centralized CORS policy used by all web framework integrations
225/// (API server, admin GUI, warp/axum helpers). Individual integrations may
226/// further restrict (but never relax) these settings.
227#[derive(Debug, Clone, Serialize, Deserialize)]
228#[serde(default)]
229pub struct CorsConfig {
230    /// Whether CORS headers are emitted at all.
231    pub enabled: bool,
232
233    /// Explicit list of allowed origins, e.g. `["https://app.example.com"]`.
234    ///
235    /// An empty list with `enabled = true` means no cross-origin requests are
236    /// accepted. Never put `"*"` here — use specific origins.
237    pub allowed_origins: Vec<String>,
238
239    /// HTTP methods that cross-origin requests may use.
240    pub allowed_methods: Vec<String>,
241
242    /// HTTP headers that cross-origin requests may include.
243    pub allowed_headers: Vec<String>,
244
245    /// `Access-Control-Max-Age` value in seconds.
246    pub max_age_secs: u32,
247}
248
249impl Default for CorsConfig {
250    fn default() -> Self {
251        Self {
252            enabled: false,
253            allowed_origins: Vec::new(),
254            allowed_methods: vec![
255                "GET".to_string(),
256                "POST".to_string(),
257                "PUT".to_string(),
258                "DELETE".to_string(),
259                "OPTIONS".to_string(),
260            ],
261            allowed_headers: vec![
262                "Authorization".to_string(),
263                "Content-Type".to_string(),
264                "Accept".to_string(),
265            ],
266            max_age_secs: 3600,
267        }
268    }
269}
270
271impl CorsConfig {
272    /// Enable CORS for the given origin(s).
273    ///
274    /// # Example
275    ///
276    /// ```rust
277    /// use auth_framework::config::CorsConfig;
278    ///
279    /// let cors = CorsConfig::for_origins(["https://app.example.com"]);
280    /// assert!(cors.enabled);
281    /// ```
282    pub fn for_origins<I, S>(origins: I) -> Self
283    where
284        I: IntoIterator<Item = S>,
285        S: Into<String>,
286    {
287        Self {
288            enabled: true,
289            allowed_origins: origins.into_iter().map(Into::into).collect(),
290            ..Default::default()
291        }
292    }
293}
294
295/// Audit logging configuration.
296///
297/// Controls which authentication events are recorded and where the
298/// records are stored.  Enabled by default with [`AuditStorage::Tracing`].
299#[derive(Debug, Clone, Serialize, Deserialize)]
300#[serde(default)]
301pub struct AuditConfig {
302    /// Enable audit logging
303    pub enabled: bool,
304
305    /// Log successful authentications
306    pub log_success: bool,
307
308    /// Log failed authentications
309    pub log_failures: bool,
310
311    /// Log permission checks
312    pub log_permissions: bool,
313
314    /// Log token operations
315    pub log_tokens: bool,
316
317    /// Audit log storage
318    pub storage: AuditStorage,
319}
320
321/// Audit log storage backend.
322///
323/// Pairs with [`AuditConfig`] to specify *where* audit events are persisted.
324#[derive(Debug, Clone, Serialize, Deserialize)]
325pub enum AuditStorage {
326    /// Standard logging (via tracing)
327    Tracing,
328
329    /// File-based storage
330    File { path: String },
331
332    /// Database storage
333    Database { connection_string: String },
334
335    /// External service
336    External { endpoint: String, api_key: String },
337}
338
339const fn default_max_failed_attempts() -> u32 {
340    5
341}
342
343impl Default for AuthConfig {
344    fn default() -> Self {
345        Self {
346            token_lifetime: Duration::from_secs(3600), // 1 hour
347            refresh_token_lifetime: Duration::from_secs(86400 * 7), // 7 days
348            enable_multi_factor: false,
349            issuer: "auth-framework".to_string(),
350            audience: "api".to_string(),
351            secret: None,
352            storage: StorageConfig::Memory,
353            rate_limiting: RateLimitConfig::default(),
354            security: SecurityConfig::default(),
355            cors: CorsConfig::default(),
356            audit: AuditConfig::default(),
357            enable_caching: false,
358            max_failed_attempts: default_max_failed_attempts(),
359            enable_rbac: false,
360            enable_middleware: false,
361            method_configs: HashMap::new(),
362            force_production_mode: false,
363        }
364    }
365}
366
367impl Default for RateLimitConfig {
368    fn default() -> Self {
369        Self {
370            enabled: true,
371            max_requests: 100,
372            window: Duration::from_secs(60), // 1 minute
373            burst: 10,
374        }
375    }
376}
377
378impl Default for SecurityConfig {
379    fn default() -> Self {
380        Self {
381            min_password_length: 8,
382            require_password_complexity: true,
383            password_hash_algorithm: PasswordHashAlgorithm::Argon2,
384            jwt_algorithm: JwtAlgorithm::HS256,
385            secret_key: None,
386            previous_secret_key: None,
387            secure_cookies: true,
388            cookie_same_site: CookieSameSite::Lax,
389            csrf_protection: true,
390            session_timeout: Duration::from_secs(3600 * 24), // 24 hours
391        }
392    }
393}
394
395impl Default for AuditConfig {
396    fn default() -> Self {
397        Self {
398            enabled: true,
399            log_success: true,
400            log_failures: true,
401            log_permissions: true,
402            log_tokens: false, // Tokens can be sensitive
403            storage: AuditStorage::Tracing,
404        }
405    }
406}
407
408// ---------------------------------------------------------------------------
409// Display implementations — human-readable summaries for logging / debugging
410// ---------------------------------------------------------------------------
411
412impl std::fmt::Display for AuthConfig {
413    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
414        write!(
415            f,
416            "AuthConfig {{ tokens: {}s/{}s refresh, storage: {}, mfa: {}, rbac: {}, rate_limit: {}, security: {}, cors: {}, audit: {} }}",
417            self.token_lifetime.as_secs(),
418            self.refresh_token_lifetime.as_secs(),
419            self.storage,
420            if self.enable_multi_factor {
421                "on"
422            } else {
423                "off"
424            },
425            if self.enable_rbac { "on" } else { "off" },
426            self.rate_limiting,
427            self.security,
428            self.cors,
429            self.audit,
430        )
431    }
432}
433
434impl std::fmt::Display for StorageConfig {
435    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
436        match self {
437            Self::Memory => write!(f, "memory"),
438            #[cfg(feature = "redis-storage")]
439            Self::Redis { url, .. } => write!(f, "redis({})", url),
440            #[cfg(feature = "postgres-storage")]
441            Self::Postgres { .. } => write!(f, "postgres"),
442            #[cfg(feature = "mysql-storage")]
443            Self::MySQL { .. } => write!(f, "mysql"),
444            #[cfg(feature = "sqlite-storage")]
445            Self::Sqlite { .. } => write!(f, "sqlite"),
446            Self::Custom(name) => write!(f, "custom({})", name),
447        }
448    }
449}
450
451impl std::fmt::Display for SecurityConfig {
452    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
453        write!(
454            f,
455            "Security {{ pw≥{}, hash: {}, jwt: {}, cookies: {}, csrf: {}, session: {}s }}",
456            self.min_password_length,
457            self.password_hash_algorithm,
458            self.jwt_algorithm,
459            if self.secure_cookies {
460                "secure"
461            } else {
462                "plain"
463            },
464            if self.csrf_protection { "on" } else { "off" },
465            self.session_timeout.as_secs(),
466        )
467    }
468}
469
470impl std::fmt::Display for PasswordHashAlgorithm {
471    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
472        match self {
473            Self::Argon2 => write!(f, "argon2id"),
474            Self::Bcrypt => write!(f, "bcrypt"),
475            Self::Scrypt => write!(f, "scrypt"),
476        }
477    }
478}
479
480impl std::fmt::Display for JwtAlgorithm {
481    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
482        match self {
483            Self::HS256 => write!(f, "HS256"),
484            Self::HS384 => write!(f, "HS384"),
485            Self::HS512 => write!(f, "HS512"),
486            Self::RS256 => write!(f, "RS256"),
487            Self::RS384 => write!(f, "RS384"),
488            Self::RS512 => write!(f, "RS512"),
489            Self::ES256 => write!(f, "ES256"),
490            Self::ES384 => write!(f, "ES384"),
491        }
492    }
493}
494
495impl std::fmt::Display for RateLimitConfig {
496    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
497        if self.enabled {
498            write!(
499                f,
500                "{} req/{}s (burst {})",
501                self.max_requests,
502                self.window.as_secs(),
503                self.burst,
504            )
505        } else {
506            write!(f, "disabled")
507        }
508    }
509}
510
511impl std::fmt::Display for CorsConfig {
512    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
513        if self.enabled {
514            if self.allowed_origins.is_empty() {
515                write!(f, "cors(no origins)")
516            } else {
517                write!(f, "cors({})", self.allowed_origins.join(", "))
518            }
519        } else {
520            write!(f, "cors(off)")
521        }
522    }
523}
524
525impl std::fmt::Display for AuditConfig {
526    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
527        if self.enabled {
528            write!(f, "audit({})", self.storage)
529        } else {
530            write!(f, "audit(off)")
531        }
532    }
533}
534
535impl std::fmt::Display for AuditStorage {
536    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
537        match self {
538            Self::Tracing => write!(f, "tracing"),
539            Self::File { path } => write!(f, "file:{}", path),
540            Self::Database { .. } => write!(f, "database"),
541            Self::External { endpoint, .. } => write!(f, "external:{}", endpoint),
542        }
543    }
544}
545
546/// Runtime-mutable configuration subset.
547///
548/// These fields can be updated via the admin API without restarting the server.
549/// Security-sensitive settings (JWT secret, algorithm, storage backend) are
550/// intentionally excluded and require a process restart to change.
551#[derive(Debug, Clone, Serialize, Deserialize)]
552pub struct RuntimeConfig {
553    /// Token lifetime in seconds.
554    pub token_lifetime_secs: u64,
555    /// Refresh token lifetime in seconds.
556    pub refresh_token_lifetime_secs: u64,
557    /// Whether MFA is globally enabled.
558    pub enable_multi_factor: bool,
559    /// Whether rate limiting is active.
560    pub rate_limiting_enabled: bool,
561    /// Maximum requests per rate-limit window.
562    pub rate_limit_max_requests: u32,
563    /// Rate-limit window in seconds.
564    pub rate_limit_window_secs: u64,
565    /// Rate-limit burst allowance.
566    pub rate_limit_burst: u32,
567    /// Minimum accepted password length.
568    pub min_password_length: usize,
569    /// Whether password complexity requirements are enforced.
570    pub require_password_complexity: bool,
571    /// Whether the `Secure` flag is set on session cookies.
572    pub secure_cookies: bool,
573    /// Whether CSRF protection middleware is active.
574    pub csrf_protection: bool,
575    /// Session timeout in seconds.
576    pub session_timeout_secs: u64,
577    /// Whether audit logging is active.
578    pub audit_enabled: bool,
579    /// Log successful authentication events.
580    pub audit_log_success: bool,
581    /// Log failed authentication events.
582    pub audit_log_failures: bool,
583    /// Log permission-check events.
584    pub audit_log_permissions: bool,
585    /// Log token issuance/revocation events.
586    pub audit_log_tokens: bool,
587}
588
589impl RuntimeConfig {
590    /// Initialise from a full [`AuthConfig`].
591    ///
592    /// # Example
593    ///
594    /// ```rust
595    /// use auth_framework::config::{AuthConfig, RuntimeConfig};
596    ///
597    /// let auth_cfg = AuthConfig::new();
598    /// let rt = RuntimeConfig::from_auth_config(&auth_cfg);
599    /// assert_eq!(rt.token_lifetime_secs, auth_cfg.token_lifetime.as_secs());
600    /// ```
601    pub fn from_auth_config(cfg: &AuthConfig) -> Self {
602        Self {
603            token_lifetime_secs: cfg.token_lifetime.as_secs(),
604            refresh_token_lifetime_secs: cfg.refresh_token_lifetime.as_secs(),
605            enable_multi_factor: cfg.enable_multi_factor,
606            rate_limiting_enabled: cfg.rate_limiting.enabled,
607            rate_limit_max_requests: cfg.rate_limiting.max_requests,
608            rate_limit_window_secs: cfg.rate_limiting.window.as_secs(),
609            rate_limit_burst: cfg.rate_limiting.burst,
610            min_password_length: cfg.security.min_password_length,
611            require_password_complexity: cfg.security.require_password_complexity,
612            secure_cookies: cfg.security.secure_cookies,
613            csrf_protection: cfg.security.csrf_protection,
614            session_timeout_secs: cfg.security.session_timeout.as_secs(),
615            audit_enabled: cfg.audit.enabled,
616            audit_log_success: cfg.audit.log_success,
617            audit_log_failures: cfg.audit.log_failures,
618            audit_log_permissions: cfg.audit.log_permissions,
619            audit_log_tokens: cfg.audit.log_tokens,
620        }
621    }
622}
623
624impl Default for RuntimeConfig {
625    fn default() -> Self {
626        Self::from_auth_config(&AuthConfig::default())
627    }
628}
629
630impl AuthConfig {
631    /// Create a new configuration with default values.
632    ///
633    /// `AuthConfig` supports two construction styles:
634    ///
635    /// ## Fluent setter chain (simple cases)
636    ///
637    /// ```rust,no_run
638    /// use auth_framework::config::AuthConfig;
639    /// use std::time::Duration;
640    ///
641    /// let config = AuthConfig::new()
642    ///     .token_lifetime(Duration::from_secs(3600))
643    ///     .secret("my-secret-key-at-least-32-chars-long!!");
644    /// ```
645    ///
646    /// ## Full builder (complex / multi-backend setups)
647    ///
648    /// ```rust,no_run
649    /// use auth_framework::prelude::*;
650    ///
651    /// # #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> {
652    /// let auth = AuthFramework::builder()
653    ///     .with_jwt().secret("...").issuer("myapp").done()
654    ///     .with_storage().memory().done()
655    ///     .security_preset(SecurityPreset::HighSecurity)
656    ///     .build().await?;
657    /// # Ok(()) }
658    /// ```
659    ///
660    /// See [`AuthFramework::builder`] and [`AuthFramework::quick_start`] for
661    /// the full builder APIs.
662    pub fn new() -> Self {
663        Self::default()
664    }
665
666    /// Build a configuration from common environment variables.
667    ///
668    /// Reads the following environment variables (all optional):
669    ///
670    /// | Variable | Maps to |
671    /// |----------|---------|
672    /// | `JWT_SECRET` | `secret` / `security.secret_key` |
673    /// | `DATABASE_URL` | PostgreSQL storage (requires `postgres-storage` feature) |
674    /// | `REDIS_URL` | Redis storage (requires `redis-storage` feature) |
675    /// | `AUTH_ISSUER` | `issuer` |
676    /// | `AUTH_AUDIENCE` | `audience` |
677    ///
678    /// Missing variables are silently ignored and fall back to defaults.
679    ///
680    /// # Example
681    ///
682    /// ```rust
683    /// use auth_framework::config::AuthConfig;
684    ///
685    /// // In tests or CI you can set the env vars beforehand:
686    /// // std::env::set_var("JWT_SECRET", "my-long-secret-key-for-jwt-signing!!");
687    /// let config = AuthConfig::from_env();
688    /// ```
689    pub fn from_env() -> Self {
690        let mut config = Self::default();
691
692        if let Ok(secret) = std::env::var("JWT_SECRET") {
693            config.secret = Some(secret.clone());
694            config.security.secret_key = Some(secret);
695        }
696
697        if let Ok(issuer) = std::env::var("AUTH_ISSUER") {
698            config.issuer = issuer;
699        }
700
701        if let Ok(audience) = std::env::var("AUTH_AUDIENCE") {
702            config.audience = audience;
703        }
704
705        // Storage: DATABASE_URL → Postgres, REDIS_URL → Redis (first match wins)
706        #[cfg(feature = "postgres-storage")]
707        if let Ok(url) = std::env::var("DATABASE_URL") {
708            config.storage = StorageConfig::Postgres {
709                connection_string: url,
710                table_prefix: "auth_".to_string(),
711            };
712        }
713
714        #[cfg(feature = "redis-storage")]
715        if matches!(config.storage, StorageConfig::Memory) {
716            if let Ok(url) = std::env::var("REDIS_URL") {
717                config.storage = StorageConfig::Redis {
718                    url,
719                    key_prefix: "auth:".to_string(),
720                };
721            }
722        }
723
724        config
725    }
726
727    /// Start the full [`AuthBuilder`](crate::builders::AuthBuilder) workflow.
728    ///
729    /// This is a convenience alias for [`AuthFramework::builder()`] — use it
730    /// when you want to configure storage, security presets, and sub-builders
731    /// from a single fluent chain.
732    ///
733    /// # Example
734    ///
735    /// ```rust,no_run
736    /// use auth_framework::prelude::*;
737    ///
738    /// # #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> {
739    /// let auth = AuthConfig::builder()
740    ///     .with_jwt().secret("...").done()
741    ///     .with_storage().memory().done()
742    ///     .build().await?;
743    /// # Ok(()) }
744    /// ```
745    ///
746    /// For more organized configuration, consider [`AuthConfigBuilder`] which
747    /// groups settings by concern (tokens, security, storage, features, etc.).
748    pub fn builder() -> crate::builders::AuthBuilder {
749        crate::builders::AuthBuilder::new()
750    }
751
752    /// Set the token lifetime.
753    ///
754    /// # Example
755    ///
756    /// ```rust
757    /// use auth_framework::config::AuthConfig;
758    /// use std::time::Duration;
759    ///
760    /// let config = AuthConfig::new().token_lifetime(Duration::from_secs(1800));
761    /// assert_eq!(config.token_lifetime.as_secs(), 1800);
762    /// ```
763    pub fn token_lifetime(mut self, lifetime: Duration) -> Self {
764        self.token_lifetime = lifetime;
765        self
766    }
767
768    /// Set the refresh token lifetime.
769    ///
770    /// # Example
771    ///
772    /// ```rust
773    /// use auth_framework::config::AuthConfig;
774    /// use std::time::Duration;
775    ///
776    /// let config = AuthConfig::new().refresh_token_lifetime(Duration::from_secs(86400));
777    /// assert_eq!(config.refresh_token_lifetime.as_secs(), 86400);
778    /// ```
779    pub fn refresh_token_lifetime(mut self, lifetime: Duration) -> Self {
780        self.refresh_token_lifetime = lifetime;
781        self
782    }
783
784    /// Enable or disable multi-factor authentication.
785    ///
786    /// # Example
787    ///
788    /// ```rust
789    /// use auth_framework::config::AuthConfig;
790    ///
791    /// let config = AuthConfig::new().enable_multi_factor(true);
792    /// assert!(config.enable_multi_factor);
793    /// ```
794    pub fn enable_multi_factor(mut self, enabled: bool) -> Self {
795        self.enable_multi_factor = enabled;
796        self
797    }
798
799    /// Set the JWT issuer.
800    pub fn issuer(mut self, issuer: impl Into<String>) -> Self {
801        self.issuer = issuer.into();
802        self
803    }
804
805    /// Set the JWT audience.
806    pub fn audience(mut self, audience: impl Into<String>) -> Self {
807        self.audience = audience.into();
808        self
809    }
810
811    /// Set the JWT secret key.
812    pub fn secret(mut self, secret: impl Into<String>) -> Self {
813        self.secret = Some(secret.into());
814        self
815    }
816
817    /// Require MFA for all users.
818    ///
819    /// # Example
820    ///
821    /// ```rust
822    /// use auth_framework::config::AuthConfig;
823    ///
824    /// let config = AuthConfig::new().require_mfa(true);
825    /// assert!(config.enable_multi_factor);
826    /// ```
827    pub fn require_mfa(mut self, required: bool) -> Self {
828        self.enable_multi_factor = required;
829        self
830    }
831
832    /// Enable caching.
833    pub fn enable_caching(mut self, enabled: bool) -> Self {
834        self.enable_caching = enabled;
835        self
836    }
837
838    /// Set maximum failed attempts.
839    ///
840    /// # Example
841    ///
842    /// ```rust
843    /// use auth_framework::config::AuthConfig;
844    ///
845    /// let config = AuthConfig::new().max_failed_attempts(10);
846    /// assert_eq!(config.max_failed_attempts, 10);
847    /// ```
848    pub fn max_failed_attempts(mut self, max: u32) -> Self {
849        self.max_failed_attempts = max;
850        self
851    }
852
853    /// Enable RBAC.
854    ///
855    /// # Example
856    ///
857    /// ```rust
858    /// use auth_framework::config::AuthConfig;
859    ///
860    /// let config = AuthConfig::new().enable_rbac(true);
861    /// assert!(config.enable_rbac);
862    /// ```
863    pub fn enable_rbac(mut self, enabled: bool) -> Self {
864        self.enable_rbac = enabled;
865        self
866    }
867
868    /// Enable security audit.
869    ///
870    /// # Example
871    ///
872    /// ```rust
873    /// use auth_framework::config::AuthConfig;
874    ///
875    /// let config = AuthConfig::new().enable_security_audit(true);
876    /// assert!(config.audit.enabled);
877    /// ```
878    pub fn enable_security_audit(mut self, enabled: bool) -> Self {
879        self.audit.enabled = enabled;
880        self
881    }
882
883    /// Enable middleware.
884    ///
885    /// # Example
886    ///
887    /// ```rust
888    /// use auth_framework::config::AuthConfig;
889    ///
890    /// let config = AuthConfig::new().enable_middleware(true);
891    /// assert!(config.enable_middleware);
892    /// ```
893    pub fn enable_middleware(mut self, enabled: bool) -> Self {
894        self.enable_middleware = enabled;
895        self
896    }
897
898    /// Force production-mode validation, bypassing test-environment detection.
899    ///
900    /// Used exclusively in tests that verify production-specific error handling without
901    /// polluting the process-wide environment with `ENVIRONMENT=production`.
902    ///
903    /// # Example
904    ///
905    /// ```rust
906    /// use auth_framework::config::AuthConfig;
907    ///
908    /// let config = AuthConfig::new().force_production_mode();
909    /// ```
910    pub fn force_production_mode(mut self) -> Self {
911        self.force_production_mode = true;
912        self
913    }
914
915    /// Set the storage configuration.
916    ///
917    /// # Example
918    ///
919    /// ```rust
920    /// use auth_framework::config::{AuthConfig, StorageConfig};
921    ///
922    /// let config = AuthConfig::new().storage(StorageConfig::Memory);
923    /// ```
924    pub fn storage(mut self, storage: StorageConfig) -> Self {
925        self.storage = storage;
926        self
927    }
928
929    /// Configure Redis storage.
930    ///
931    /// # Example
932    ///
933    /// ```rust,ignore
934    /// use auth_framework::config::AuthConfig;
935    ///
936    /// let config = AuthConfig::new().redis_storage("redis://127.0.0.1:6379");
937    /// ```
938    #[cfg(feature = "redis-storage")]
939    pub fn redis_storage(mut self, url: impl Into<String>) -> Self {
940        self.storage = StorageConfig::Redis {
941            url: url.into(),
942            key_prefix: "auth:".to_string(),
943        };
944        self
945    }
946
947    /// Set rate limiting configuration.
948    ///
949    /// # Example
950    ///
951    /// ```rust
952    /// use auth_framework::config::{AuthConfig, RateLimitConfig};
953    ///
954    /// let config = AuthConfig::new().rate_limiting(RateLimitConfig::default());
955    /// ```
956    pub fn rate_limiting(mut self, config: RateLimitConfig) -> Self {
957        self.rate_limiting = config;
958        self
959    }
960
961    /// Set security configuration.
962    ///
963    /// # Example
964    ///
965    /// ```rust
966    /// use auth_framework::config::{AuthConfig, SecurityConfig};
967    ///
968    /// let config = AuthConfig::new().security(SecurityConfig::secure());
969    /// ```
970    pub fn security(mut self, config: SecurityConfig) -> Self {
971        self.security = config;
972        self
973    }
974
975    /// Set CORS configuration.
976    ///
977    /// # Example
978    ///
979    /// ```rust
980    /// use auth_framework::config::{AuthConfig, CorsConfig};
981    ///
982    /// let config = AuthConfig::new()
983    ///     .cors(CorsConfig::for_origins(["https://app.example.com"]));
984    /// ```
985    pub fn cors(mut self, config: CorsConfig) -> Self {
986        self.cors = config;
987        self
988    }
989
990    /// Set audit configuration.
991    ///
992    /// # Example
993    ///
994    /// ```rust
995    /// use auth_framework::config::{AuthConfig, AuditConfig};
996    ///
997    /// let config = AuthConfig::new().audit(AuditConfig::default());
998    /// ```
999    pub fn audit(mut self, config: AuditConfig) -> Self {
1000        self.audit = config;
1001        self
1002    }
1003
1004    /// Add configuration for a specific auth method.
1005    ///
1006    /// # Example
1007    ///
1008    /// ```rust
1009    /// use auth_framework::config::AuthConfig;
1010    ///
1011    /// let config = AuthConfig::new()
1012    ///     .method_config("oauth2", serde_json::json!({
1013    ///         "client_id": "my-client",
1014    ///         "client_secret": "my-secret"
1015    ///     }))
1016    ///     .unwrap();
1017    /// ```
1018    pub fn method_config(
1019        mut self,
1020        method_name: impl Into<String>,
1021        config: impl Serialize,
1022    ) -> Result<Self> {
1023        let value = serde_json::to_value(config)
1024            .map_err(|e| AuthError::config(format!("Failed to serialize method config: {e}")))?;
1025
1026        self.method_configs.insert(method_name.into(), value);
1027        Ok(self)
1028    }
1029
1030    /// Get configuration for a specific auth method.
1031    ///
1032    /// # Example
1033    ///
1034    /// ```rust
1035    /// use auth_framework::config::AuthConfig;
1036    ///
1037    /// let config = AuthConfig::new();
1038    /// let oauth: Option<serde_json::Value> = config.get_method_config("oauth2").unwrap();
1039    /// assert!(oauth.is_none()); // no oauth2 config set yet
1040    /// ```
1041    pub fn get_method_config<T>(&self, method_name: &str) -> Result<Option<T>>
1042    where
1043        T: for<'de> Deserialize<'de>,
1044    {
1045        if let Some(value) = self.method_configs.get(method_name) {
1046            let config = serde_json::from_value(value.clone()).map_err(|e| {
1047                AuthError::config(format!("Failed to deserialize method config: {e}"))
1048            })?;
1049            Ok(Some(config))
1050        } else {
1051            Ok(None)
1052        }
1053    }
1054
1055    /// Validate the configuration.
1056    ///
1057    /// # Example
1058    ///
1059    /// ```rust
1060    /// use auth_framework::config::AuthConfig;
1061    ///
1062    /// let config = AuthConfig::new();
1063    /// assert!(config.validate().is_ok());
1064    /// ```
1065    pub fn validate(&self) -> Result<()> {
1066        // Validate token lifetimes
1067        if self.token_lifetime.as_secs() == 0 {
1068            return Err(AuthError::config("Token lifetime must be greater than 0"));
1069        }
1070
1071        if self.refresh_token_lifetime.as_secs() == 0 {
1072            return Err(AuthError::config(
1073                "Refresh token lifetime must be greater than 0",
1074            ));
1075        }
1076
1077        if self.refresh_token_lifetime <= self.token_lifetime {
1078            return Err(AuthError::config(
1079                "Refresh token lifetime must be greater than token lifetime",
1080            ));
1081        }
1082
1083        // Validate JWT secret configuration
1084        self.validate_jwt_secret()?;
1085
1086        // Validate security settings
1087        if self.security.min_password_length < 4 {
1088            return Err(AuthError::config(
1089                "Minimum password length must be at least 4 characters",
1090            ));
1091        }
1092
1093        // Enhanced security validation for production
1094        if self.is_production_environment() && !self.is_test_environment() {
1095            self.validate_production_security()?;
1096        }
1097
1098        // Validate rate limiting
1099        if self.rate_limiting.enabled && self.rate_limiting.max_requests == 0 {
1100            return Err(AuthError::config(
1101                "Rate limit max requests must be greater than 0 when enabled",
1102            ));
1103        }
1104
1105        // Validate storage configuration
1106        self.validate_storage_config()?;
1107
1108        // Validate built-in auth method configuration blobs eagerly so invalid
1109        // method settings fail during startup instead of at first use.
1110        self.validate_method_configs()?;
1111
1112        Ok(())
1113    }
1114
1115    fn validate_method_configs(&self) -> Result<()> {
1116        for (method_name, raw_config) in &self.method_configs {
1117            match method_name.as_str() {
1118                #[cfg(feature = "saml")]
1119                "saml" => {
1120                    let config: crate::methods::saml::SamlConfig =
1121                        serde_json::from_value(raw_config.clone()).map_err(|e| {
1122                            AuthError::config(format!(
1123                                "Failed to deserialize SAML method config: {e}"
1124                            ))
1125                        })?;
1126
1127                    if config.entity_id.trim().is_empty() {
1128                        return Err(AuthError::config("SAML entity_id cannot be empty"));
1129                    }
1130                    if config.acs_url.trim().is_empty() {
1131                        return Err(AuthError::config("SAML acs_url cannot be empty"));
1132                    }
1133                    if config.max_assertion_age == 0 {
1134                        return Err(AuthError::config(
1135                            "SAML max_assertion_age must be greater than 0",
1136                        ));
1137                    }
1138                }
1139                #[cfg(not(feature = "saml"))]
1140                "saml" => {
1141                    return Err(AuthError::config(
1142                        "SAML method config is present but the 'saml' feature is not enabled",
1143                    ));
1144                }
1145                #[cfg(feature = "passkeys")]
1146                "passkey" => {
1147                    let config: crate::methods::passkey::PasskeyConfig =
1148                        serde_json::from_value(raw_config.clone()).map_err(|e| {
1149                            AuthError::config(format!(
1150                                "Failed to deserialize passkey method config: {e}"
1151                            ))
1152                        })?;
1153
1154                    if config.rp_id.trim().is_empty() {
1155                        return Err(AuthError::config("Passkey RP ID cannot be empty"));
1156                    }
1157                    if config.origin.trim().is_empty() {
1158                        return Err(AuthError::config("Passkey origin cannot be empty"));
1159                    }
1160                    if config.timeout_ms == 0 {
1161                        return Err(AuthError::config("Passkey timeout must be greater than 0"));
1162                    }
1163                    match config.user_verification.as_str() {
1164                        "required" | "preferred" | "discouraged" => {}
1165                        _ => {
1166                            return Err(AuthError::config(
1167                                "Invalid passkey user_verification value",
1168                            ));
1169                        }
1170                    }
1171                    url::Url::parse(&config.origin).map_err(|e| {
1172                        AuthError::config(format!("Invalid passkey origin URL: {e}"))
1173                    })?;
1174                }
1175                #[cfg(not(feature = "passkeys"))]
1176                "passkey" => {
1177                    return Err(AuthError::config(
1178                        "Passkey method config is present but the 'passkeys' feature is not enabled",
1179                    ));
1180                }
1181                "enhanced_device_flow" => {
1182                    let client_id = raw_config
1183                        .get("client_id")
1184                        .and_then(serde_json::Value::as_str)
1185                        .unwrap_or_default();
1186                    let auth_url = raw_config
1187                        .get("auth_url")
1188                        .and_then(serde_json::Value::as_str)
1189                        .unwrap_or_default();
1190                    let token_url = raw_config
1191                        .get("token_url")
1192                        .and_then(serde_json::Value::as_str)
1193                        .unwrap_or_default();
1194                    let device_auth_url = raw_config
1195                        .get("device_auth_url")
1196                        .and_then(serde_json::Value::as_str)
1197                        .unwrap_or_default();
1198
1199                    if client_id.trim().is_empty()
1200                        || auth_url.trim().is_empty()
1201                        || token_url.trim().is_empty()
1202                        || device_auth_url.trim().is_empty()
1203                    {
1204                        return Err(AuthError::config(
1205                            "Enhanced device flow config requires non-empty client_id, auth_url, token_url, and device_auth_url",
1206                        ));
1207                    }
1208                }
1209                _ => {}
1210            }
1211        }
1212
1213        Ok(())
1214    }
1215
1216    /// Validate JWT secret configuration for security
1217    fn validate_jwt_secret(&self) -> Result<()> {
1218        // Check multiple sources for JWT secret
1219        let env_secret = std::env::var("JWT_SECRET").ok();
1220        let jwt_secret = self
1221            .security
1222            .secret_key
1223            .as_ref()
1224            .or(self.secret.as_ref())
1225            .or(env_secret.as_ref());
1226
1227        if let Some(secret) = jwt_secret {
1228            // Enforce minimum length only outside test environments.
1229            // In tests, short secrets are acceptable for convenience.
1230            if !self.is_test_environment() && secret.len() < 32 {
1231                return Err(AuthError::config(
1232                    "JWT secret must be at least 32 characters for security. \
1233                     Generate with: openssl rand -base64 32",
1234                ));
1235            }
1236
1237            // Check for low-entropy secrets using Shannon entropy measurement
1238            // rather than pattern matching, which is trivially bypassed.
1239            if !self.is_test_environment() {
1240                let mut char_counts = std::collections::HashMap::new();
1241                for c in secret.chars() {
1242                    *char_counts.entry(c).or_insert(0u32) += 1;
1243                }
1244                let len = secret.len() as f64;
1245                let entropy: f64 = char_counts
1246                    .values()
1247                    .map(|&count| {
1248                        let p = count as f64 / len;
1249                        -p * p.log2()
1250                    })
1251                    .sum();
1252                if entropy < 3.5 {
1253                    return Err(AuthError::config(
1254                        "JWT secret has insufficient entropy (too predictable). \
1255                         Use a cryptographically secure random string.",
1256                    ));
1257                }
1258            }
1259
1260            // Warn if secret looks like it might be base64 but too short
1261            if secret.len() < 44
1262                && secret
1263                    .chars()
1264                    .all(|c| c.is_alphanumeric() || c == '+' || c == '/' || c == '=')
1265            {
1266                tracing::warn!(
1267                    "JWT secret may be too short for optimal security. \
1268                     Consider using at least 44 characters (32 bytes base64-encoded)."
1269                );
1270            }
1271        } else if self.is_production_environment() {
1272            return Err(AuthError::config(
1273                "JWT secret is required for production environments. \
1274                 Set JWT_SECRET environment variable or configure security.secret_key",
1275            ));
1276        }
1277
1278        Ok(())
1279    }
1280
1281    /// Validate production-specific security requirements
1282    fn validate_production_security(&self) -> Result<()> {
1283        // Require strong password policies in production
1284        if self.security.min_password_length < 8 {
1285            return Err(AuthError::config(
1286                "Production environments require minimum password length of 8 characters",
1287            ));
1288        }
1289
1290        if !self.security.require_password_complexity {
1291            tracing::warn!("Production deployment should enable password complexity requirements");
1292        }
1293
1294        // Require secure cookies in production
1295        if !self.security.secure_cookies {
1296            return Err(AuthError::config(
1297                "Production environments must use secure cookies (HTTPS required)",
1298            ));
1299        }
1300
1301        // Ensure rate limiting is enabled
1302        if !self.rate_limiting.enabled {
1303            tracing::warn!("Production deployment should enable rate limiting for security");
1304        }
1305
1306        // Validate audit configuration for compliance
1307        if !self.audit.enabled {
1308            return Err(AuthError::config(
1309                "Production environments require audit logging for compliance",
1310            ));
1311        }
1312
1313        Ok(())
1314    }
1315
1316    /// Validate storage configuration
1317    fn validate_storage_config(&self) -> Result<()> {
1318        match &self.storage {
1319            StorageConfig::Memory => {
1320                if self.is_production_environment() && !self.is_test_environment() {
1321                    return Err(AuthError::config(
1322                        "Memory storage is not suitable for production environments. \
1323                         Use PostgreSQL, Redis, MySQL, or SQLite storage.",
1324                    ));
1325                }
1326            }
1327            #[cfg(feature = "mysql-storage")]
1328            StorageConfig::MySQL { .. } => {
1329                tracing::warn!(
1330                    "MySQL storage has known RSA vulnerability (RUSTSEC-2023-0071). \
1331                     Consider using PostgreSQL for enhanced security."
1332                );
1333            }
1334            _ => {} // PostgreSQL and Redis are production-ready
1335        }
1336
1337        Ok(())
1338    }
1339
1340    /// Detect production environment
1341    fn is_production_environment(&self) -> bool {
1342        // An explicit config flag always wins — used by tests that need production behaviour.
1343        if self.force_production_mode {
1344            return true;
1345        }
1346
1347        // Check common production environment indicators
1348        if let Ok(env) = std::env::var("ENVIRONMENT")
1349            && (env.to_lowercase() == "production" || env.to_lowercase() == "prod")
1350        {
1351            return true;
1352        }
1353
1354        if let Ok(env) = std::env::var("ENV")
1355            && (env.to_lowercase() == "production" || env.to_lowercase() == "prod")
1356        {
1357            return true;
1358        }
1359
1360        if let Ok(env) = std::env::var("NODE_ENV")
1361            && env.to_lowercase() == "production"
1362        {
1363            return true;
1364        }
1365
1366        if let Ok(env) = std::env::var("RUST_ENV")
1367            && env.to_lowercase() == "production"
1368        {
1369            return true;
1370        }
1371
1372        // Check for containerized environments
1373        if std::env::var("KUBERNETES_SERVICE_HOST").is_ok() {
1374            return true;
1375        }
1376
1377        if std::env::var("DOCKER_CONTAINER").is_ok() {
1378            return true;
1379        }
1380
1381        false
1382    }
1383
1384    /// Detect test environment
1385    fn is_test_environment(&self) -> bool {
1386        // An explicit config flag forces production mode — never treat it as a test environment.
1387        if self.force_production_mode {
1388            return false;
1389        }
1390        // Check if we're running in a test environment
1391        cfg!(test)
1392            || std::thread::current()
1393                .name()
1394                .is_some_and(|name| name.contains("test"))
1395            || std::env::var("RUST_TEST").is_ok()
1396            || std::env::var("ENVIRONMENT").as_deref() == Ok("test")
1397            || std::env::var("ENV").as_deref() == Ok("test")
1398            || std::env::args().any(|arg| arg.contains("test"))
1399    }
1400}
1401
1402impl RateLimitConfig {
1403    /// Create a new rate limit configuration.
1404    ///
1405    /// # Example
1406    ///
1407    /// ```rust
1408    /// use auth_framework::config::RateLimitConfig;
1409    /// use std::time::Duration;
1410    ///
1411    /// let rl = RateLimitConfig::new(100, Duration::from_secs(60));
1412    /// assert!(rl.enabled);
1413    /// assert_eq!(rl.max_requests, 100);
1414    /// ```
1415    pub fn new(max_requests: u32, window: Duration) -> Self {
1416        Self {
1417            enabled: true,
1418            max_requests,
1419            window,
1420            burst: max_requests / 10, // 10% of max as burst
1421        }
1422    }
1423
1424    /// Disable rate limiting.
1425    ///
1426    /// # Example
1427    ///
1428    /// ```rust
1429    /// use auth_framework::config::RateLimitConfig;
1430    ///
1431    /// let rl = RateLimitConfig::disabled();
1432    /// assert!(!rl.enabled);
1433    /// ```
1434    pub fn disabled() -> Self {
1435        Self {
1436            enabled: false,
1437            ..Default::default()
1438        }
1439    }
1440
1441    /// Shorthand: allow `max` requests per second.
1442    ///
1443    /// # Example
1444    ///
1445    /// ```rust
1446    /// use auth_framework::config::RateLimitConfig;
1447    ///
1448    /// let rl = RateLimitConfig::per_second(50);
1449    /// assert_eq!(rl.max_requests, 50);
1450    /// ```
1451    pub fn per_second(max: u32) -> Self {
1452        Self::new(max, Duration::from_secs(1))
1453    }
1454
1455    /// Shorthand: allow `max` requests per minute.
1456    ///
1457    /// # Example
1458    ///
1459    /// ```rust
1460    /// use auth_framework::config::RateLimitConfig;
1461    ///
1462    /// let rl = RateLimitConfig::per_minute(100);
1463    /// assert_eq!(rl.max_requests, 100);
1464    /// ```
1465    pub fn per_minute(max: u32) -> Self {
1466        Self::new(max, Duration::from_secs(60))
1467    }
1468
1469    /// Shorthand: allow `max` requests per hour.
1470    ///
1471    /// # Example
1472    ///
1473    /// ```rust
1474    /// use auth_framework::config::RateLimitConfig;
1475    ///
1476    /// let rl = RateLimitConfig::per_hour(1000);
1477    /// assert_eq!(rl.max_requests, 1000);
1478    /// ```
1479    pub fn per_hour(max: u32) -> Self {
1480        Self::new(max, Duration::from_secs(3600))
1481    }
1482}
1483
1484impl SecurityConfig {
1485    /// Create a new security configuration with secure defaults.
1486    ///
1487    /// # Example
1488    ///
1489    /// ```rust
1490    /// use auth_framework::config::SecurityConfig;
1491    ///
1492    /// let sec = SecurityConfig::secure();
1493    /// assert!(sec.secure_cookies);
1494    /// assert!(sec.csrf_protection);
1495    /// assert_eq!(sec.min_password_length, 12);
1496    /// ```
1497    pub fn secure() -> Self {
1498        Self {
1499            min_password_length: 12,
1500            require_password_complexity: true,
1501            password_hash_algorithm: PasswordHashAlgorithm::Argon2,
1502            jwt_algorithm: JwtAlgorithm::RS256,
1503            secret_key: None,
1504            previous_secret_key: None,
1505            secure_cookies: true,
1506            cookie_same_site: CookieSameSite::Strict,
1507            csrf_protection: true,
1508            session_timeout: Duration::from_secs(3600 * 8), // 8 hours
1509        }
1510    }
1511
1512    /// Create a development-friendly configuration.
1513    /// WARNING: You MUST set a secret key before using this configuration!
1514    /// Use either config.security.secret_key or JWT_SECRET environment variable.
1515    ///
1516    /// # Example
1517    ///
1518    /// ```rust
1519    /// use auth_framework::config::SecurityConfig;
1520    ///
1521    /// let sec = SecurityConfig::development();
1522    /// assert_eq!(sec.min_password_length, 6);
1523    /// assert!(!sec.secure_cookies);
1524    /// ```
1525    pub fn development() -> Self {
1526        Self {
1527            min_password_length: 6,
1528            require_password_complexity: false,
1529            password_hash_algorithm: PasswordHashAlgorithm::Bcrypt,
1530            jwt_algorithm: JwtAlgorithm::HS256,
1531            secret_key: None, // Must be set by developer for security
1532            previous_secret_key: None,
1533            secure_cookies: false,
1534            cookie_same_site: CookieSameSite::Lax,
1535            csrf_protection: false,
1536            session_timeout: Duration::from_secs(3600 * 24), // 24 hours
1537        }
1538    }
1539}
1540
1541/// A comprehensive builder for `AuthConfig` that organizes configuration into logical groups.
1542///
1543/// This builder provides better developer experience by grouping related settings
1544/// and providing sensible defaults for each category. Use this when you need fine-grained
1545/// control over the configuration but want better organization than the flat setter API.
1546///
1547/// # Example
1548///
1549/// ```rust,no_run
1550/// use auth_framework::config::{AuthConfig, AuthConfigBuilder};
1551/// use std::time::Duration;
1552///
1553/// let builder = AuthConfigBuilder::new()
1554///     .tokens()
1555///         .lifetime(Duration::from_secs(3600))
1556///         .refresh_lifetime(Duration::from_secs(86400 * 7))
1557///         .issuer("myapp")
1558///         .audience("myapp-users")
1559///         .secret("my-32-char-secret-key-here!!!!!")
1560///         .done()
1561///     .security()
1562///         .min_password_length(8)
1563///         .require_complexity(true)
1564///         .secure_cookies(true)
1565///         .done()
1566///     .storage()
1567///         .memory()
1568///         .done()
1569///     .features()
1570///         .enable_multi_factor(true)
1571///         .enable_rbac(true)
1572///         .enable_caching(true)
1573///         .done();
1574///
1575/// let config = builder.build().expect("Failed to build config");
1576/// ```
1577#[derive(Debug)]
1578pub struct AuthConfigBuilder {
1579    config: AuthConfig,
1580}
1581
1582impl Default for AuthConfigBuilder {
1583    fn default() -> Self {
1584        Self::new()
1585    }
1586}
1587
1588impl AuthConfigBuilder {
1589    /// Create a new builder with sensible defaults.
1590    pub fn new() -> Self {
1591        Self {
1592            config: AuthConfig::default(),
1593        }
1594    }
1595
1596    /// Configure token-related settings.
1597    pub fn tokens(self) -> TokenConfigBuilder {
1598        TokenConfigBuilder { builder: self }
1599    }
1600
1601    /// Configure security-related settings.
1602    pub fn security(self) -> SecurityConfigBuilder {
1603        SecurityConfigBuilder { builder: self }
1604    }
1605
1606    /// Configure storage settings.
1607    pub fn storage(self) -> StorageConfigBuilder {
1608        StorageConfigBuilder { builder: self }
1609    }
1610
1611    /// Configure feature flags and capabilities.
1612    pub fn features(self) -> FeatureConfigBuilder {
1613        FeatureConfigBuilder { builder: self }
1614    }
1615
1616    /// Configure rate limiting.
1617    pub fn rate_limiting(self) -> RateLimitConfigBuilder {
1618        RateLimitConfigBuilder { builder: self }
1619    }
1620
1621    /// Configure CORS settings.
1622    pub fn cors(self) -> CorsConfigBuilder {
1623        CorsConfigBuilder { builder: self }
1624    }
1625
1626    /// Configure audit logging.
1627    pub fn audit(self) -> AuditConfigBuilder {
1628        AuditConfigBuilder { builder: self }
1629    }
1630
1631    /// Build the final configuration, validating it in the process.
1632    pub fn build(self) -> Result<AuthConfig> {
1633        let config = self.config;
1634        config.validate()?;
1635        Ok(config)
1636    }
1637}
1638
1639/// Builder for token-related configuration.
1640#[derive(Debug)]
1641pub struct TokenConfigBuilder {
1642    builder: AuthConfigBuilder,
1643}
1644
1645impl TokenConfigBuilder {
1646    /// Set the access token lifetime.
1647    pub fn lifetime(mut self, duration: Duration) -> Self {
1648        self.builder.config.token_lifetime = duration;
1649        self
1650    }
1651
1652    /// Set the refresh token lifetime.
1653    pub fn refresh_lifetime(mut self, duration: Duration) -> Self {
1654        self.builder.config.refresh_token_lifetime = duration;
1655        self
1656    }
1657
1658    /// Set the JWT issuer.
1659    pub fn issuer(mut self, issuer: impl Into<String>) -> Self {
1660        self.builder.config.issuer = issuer.into();
1661        self
1662    }
1663
1664    /// Set the JWT audience.
1665    pub fn audience(mut self, audience: impl Into<String>) -> Self {
1666        self.builder.config.audience = audience.into();
1667        self
1668    }
1669
1670    /// Set the JWT secret key.
1671    pub fn secret(mut self, secret: impl Into<String>) -> Self {
1672        self.builder.config.secret = Some(secret.into());
1673        self
1674    }
1675
1676    /// Finish token configuration and return to the main builder.
1677    pub fn done(self) -> AuthConfigBuilder {
1678        self.builder
1679    }
1680}
1681
1682/// Builder for security-related configuration.
1683#[derive(Debug)]
1684pub struct SecurityConfigBuilder {
1685    builder: AuthConfigBuilder,
1686}
1687
1688impl SecurityConfigBuilder {
1689    /// Set minimum password length.
1690    pub fn min_password_length(mut self, length: usize) -> Self {
1691        self.builder.config.security.min_password_length = length;
1692        self
1693    }
1694
1695    /// Require password complexity.
1696    pub fn require_complexity(mut self, required: bool) -> Self {
1697        self.builder.config.security.require_password_complexity = required;
1698        self
1699    }
1700
1701    /// Set password hash algorithm.
1702    pub fn password_algorithm(mut self, algorithm: PasswordHashAlgorithm) -> Self {
1703        self.builder.config.security.password_hash_algorithm = algorithm;
1704        self
1705    }
1706
1707    /// Set JWT algorithm.
1708    pub fn jwt_algorithm(mut self, algorithm: JwtAlgorithm) -> Self {
1709        self.builder.config.security.jwt_algorithm = algorithm;
1710        self
1711    }
1712
1713    /// Enable secure cookies.
1714    pub fn secure_cookies(mut self, enabled: bool) -> Self {
1715        self.builder.config.security.secure_cookies = enabled;
1716        self
1717    }
1718
1719    /// Set cookie SameSite policy.
1720    pub fn cookie_same_site(mut self, policy: CookieSameSite) -> Self {
1721        self.builder.config.security.cookie_same_site = policy;
1722        self
1723    }
1724
1725    /// Enable CSRF protection.
1726    pub fn csrf_protection(mut self, enabled: bool) -> Self {
1727        self.builder.config.security.csrf_protection = enabled;
1728        self
1729    }
1730
1731    /// Set session timeout.
1732    pub fn session_timeout(mut self, timeout: Duration) -> Self {
1733        self.builder.config.security.session_timeout = timeout;
1734        self
1735    }
1736
1737    /// Finish security configuration and return to the main builder.
1738    pub fn done(self) -> AuthConfigBuilder {
1739        self.builder
1740    }
1741}
1742
1743/// Builder for storage configuration.
1744#[derive(Debug)]
1745pub struct StorageConfigBuilder {
1746    builder: AuthConfigBuilder,
1747}
1748
1749impl StorageConfigBuilder {
1750    /// Use in-memory storage (development only).
1751    pub fn memory(mut self) -> Self {
1752        self.builder.config.storage = StorageConfig::Memory;
1753        self
1754    }
1755
1756    /// Use Redis storage.
1757    #[cfg(feature = "redis-storage")]
1758    pub fn redis(mut self, url: impl Into<String>) -> Self {
1759        self.builder.config.storage = StorageConfig::Redis {
1760            url: url.into(),
1761            key_prefix: "auth:".to_string(),
1762        };
1763        self
1764    }
1765
1766    /// Use PostgreSQL storage.
1767    #[cfg(feature = "postgres-storage")]
1768    pub fn postgres(mut self, connection_string: impl Into<String>) -> Self {
1769        self.builder.config.storage = StorageConfig::Postgres {
1770            connection_string: connection_string.into(),
1771            table_prefix: "auth_".to_string(),
1772        };
1773        self
1774    }
1775
1776    /// Use MySQL storage.
1777    #[cfg(feature = "mysql-storage")]
1778    pub fn mysql(mut self, connection_string: impl Into<String>) -> Self {
1779        self.builder.config.storage = StorageConfig::MySQL {
1780            connection_string: connection_string.into(),
1781            table_prefix: "auth_".to_string(),
1782        };
1783        self
1784    }
1785
1786    /// Use SQLite storage.
1787    #[cfg(feature = "sqlite-storage")]
1788    pub fn sqlite(mut self, connection_string: impl Into<String>) -> Self {
1789        self.builder.config.storage = StorageConfig::Sqlite {
1790            connection_string: connection_string.into(),
1791        };
1792        self
1793    }
1794
1795    /// Finish storage configuration and return to the main builder.
1796    pub fn done(self) -> AuthConfigBuilder {
1797        self.builder
1798    }
1799}
1800
1801/// Builder for feature flags and capabilities.
1802#[derive(Debug)]
1803pub struct FeatureConfigBuilder {
1804    builder: AuthConfigBuilder,
1805}
1806
1807impl FeatureConfigBuilder {
1808    /// Enable multi-factor authentication.
1809    pub fn enable_multi_factor(mut self, enabled: bool) -> Self {
1810        self.builder.config.enable_multi_factor = enabled;
1811        self
1812    }
1813
1814    /// Enable RBAC (Role-Based Access Control).
1815    pub fn enable_rbac(mut self, enabled: bool) -> Self {
1816        self.builder.config.enable_rbac = enabled;
1817        self
1818    }
1819
1820    /// Enable caching.
1821    pub fn enable_caching(mut self, enabled: bool) -> Self {
1822        self.builder.config.enable_caching = enabled;
1823        self
1824    }
1825
1826    /// Enable middleware helpers.
1827    pub fn enable_middleware(mut self, enabled: bool) -> Self {
1828        self.builder.config.enable_middleware = enabled;
1829        self
1830    }
1831
1832    /// Set maximum failed authentication attempts.
1833    pub fn max_failed_attempts(mut self, max: u32) -> Self {
1834        self.builder.config.max_failed_attempts = max;
1835        self
1836    }
1837
1838    /// Finish feature configuration and return to the main builder.
1839    pub fn done(self) -> AuthConfigBuilder {
1840        self.builder
1841    }
1842}
1843
1844/// Builder for rate limiting configuration.
1845#[derive(Debug)]
1846pub struct RateLimitConfigBuilder {
1847    builder: AuthConfigBuilder,
1848}
1849
1850impl RateLimitConfigBuilder {
1851    /// Enable rate limiting with specified limits.
1852    pub fn enabled(mut self, max_requests: u32, window: Duration) -> Self {
1853        self.builder.config.rate_limiting = RateLimitConfig::new(max_requests, window);
1854        self
1855    }
1856
1857    /// Disable rate limiting.
1858    pub fn disabled(mut self) -> Self {
1859        self.builder.config.rate_limiting = RateLimitConfig::disabled();
1860        self
1861    }
1862
1863    /// Set maximum requests per window.
1864    pub fn max_requests(mut self, max: u32) -> Self {
1865        self.builder.config.rate_limiting.max_requests = max;
1866        self
1867    }
1868
1869    /// Set rate limiting window.
1870    pub fn window(mut self, window: Duration) -> Self {
1871        self.builder.config.rate_limiting.window = window;
1872        self
1873    }
1874
1875    /// Set burst allowance.
1876    pub fn burst(mut self, burst: u32) -> Self {
1877        self.builder.config.rate_limiting.burst = burst;
1878        self
1879    }
1880
1881    /// Finish rate limiting configuration and return to the main builder.
1882    pub fn done(self) -> AuthConfigBuilder {
1883        self.builder
1884    }
1885}
1886
1887/// Builder for CORS configuration.
1888#[derive(Debug)]
1889pub struct CorsConfigBuilder {
1890    builder: AuthConfigBuilder,
1891}
1892
1893impl CorsConfigBuilder {
1894    /// Enable CORS for specific origins.
1895    pub fn allow_origins<I, S>(mut self, origins: I) -> Self
1896    where
1897        I: IntoIterator<Item = S>,
1898        S: Into<String>,
1899    {
1900        self.builder.config.cors = CorsConfig::for_origins(origins);
1901        self
1902    }
1903
1904    /// Disable CORS.
1905    pub fn disabled(mut self) -> Self {
1906        self.builder.config.cors.enabled = false;
1907        self
1908    }
1909
1910    /// Allow specific HTTP methods.
1911    pub fn allow_methods<I, S>(mut self, methods: I) -> Self
1912    where
1913        I: IntoIterator<Item = S>,
1914        S: Into<String>,
1915    {
1916        self.builder.config.cors.allowed_methods = methods.into_iter().map(Into::into).collect();
1917        self
1918    }
1919
1920    /// Allow specific headers.
1921    pub fn allow_headers<I, S>(mut self, headers: I) -> Self
1922    where
1923        I: IntoIterator<Item = S>,
1924        S: Into<String>,
1925    {
1926        self.builder.config.cors.allowed_headers = headers.into_iter().map(Into::into).collect();
1927        self
1928    }
1929
1930    /// Set max age for preflight requests.
1931    pub fn max_age(mut self, seconds: u32) -> Self {
1932        self.builder.config.cors.max_age_secs = seconds;
1933        self
1934    }
1935
1936    /// Finish CORS configuration and return to the main builder.
1937    pub fn done(self) -> AuthConfigBuilder {
1938        self.builder
1939    }
1940}
1941
1942/// Builder for audit configuration.
1943#[derive(Debug)]
1944pub struct AuditConfigBuilder {
1945    builder: AuthConfigBuilder,
1946}
1947
1948impl AuditConfigBuilder {
1949    /// Enable audit logging.
1950    pub fn enabled(mut self) -> Self {
1951        self.builder.config.audit.enabled = true;
1952        self
1953    }
1954
1955    /// Disable audit logging.
1956    pub fn disabled(mut self) -> Self {
1957        self.builder.config.audit.enabled = false;
1958        self
1959    }
1960
1961    /// Log successful authentications.
1962    pub fn log_success(mut self, enabled: bool) -> Self {
1963        self.builder.config.audit.log_success = enabled;
1964        self
1965    }
1966
1967    /// Log failed authentications.
1968    pub fn log_failures(mut self, enabled: bool) -> Self {
1969        self.builder.config.audit.log_failures = enabled;
1970        self
1971    }
1972
1973    /// Log permission checks.
1974    pub fn log_permissions(mut self, enabled: bool) -> Self {
1975        self.builder.config.audit.log_permissions = enabled;
1976        self
1977    }
1978
1979    /// Log token operations.
1980    pub fn log_tokens(mut self, enabled: bool) -> Self {
1981        self.builder.config.audit.log_tokens = enabled;
1982        self
1983    }
1984
1985    /// Finish audit configuration and return to the main builder.
1986    pub fn done(self) -> AuthConfigBuilder {
1987        self.builder
1988    }
1989}