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