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