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