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
723/// Fragments that mark a signing secret as a template or placeholder rather than a generated value.
724const PLACEHOLDER_SECRET_MARKERS: &[&str] = &[
725    "change-in-production",
726    "change_in_production",
727    "change-me",
728    "change_me",
729    "changeme",
730    "your-secret",
731    "your_secret",
732    "yoursecret",
733    "development-only",
734    "replace-with",
735    "replace_with",
736];
737
738/// Whether `secret` is (or contains) a known placeholder, compared case-insensitively.
739fn is_placeholder_secret(secret: &str) -> bool {
740    let lowered = secret.trim().to_ascii_lowercase();
741    PLACEHOLDER_SECRET_MARKERS
742        .iter()
743        .any(|marker| lowered.contains(marker))
744}
745
746impl AuthConfig {
747    /// Create a new configuration with default values.
748    ///
749    /// `AuthConfig` supports two construction styles:
750    ///
751    /// ## Fluent setter chain (simple cases)
752    ///
753    /// ```rust,no_run
754    /// use auth_framework::config::AuthConfig;
755    /// use std::time::Duration;
756    ///
757    /// let config = AuthConfig::new()
758    ///     .token_lifetime(Duration::from_secs(3600))
759    ///     .secret("my-secret-key-at-least-32-chars-long!!");
760    /// ```
761    ///
762    /// ## Full builder (complex / multi-backend setups)
763    ///
764    /// ```rust,no_run
765    /// use auth_framework::prelude::*;
766    ///
767    /// # #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> {
768    /// let auth = AuthFramework::builder()
769    ///     .with_jwt().secret("...").issuer("myapp").done()
770    ///     .with_storage().memory().done()
771    ///     .security_preset(SecurityPreset::HighSecurity)
772    ///     .build().await?;
773    /// # Ok(()) }
774    /// ```
775    ///
776    /// See [`AuthFramework::builder`] and [`AuthFramework::quick_start`] for
777    /// the full builder APIs.
778    pub fn new() -> Self {
779        Self::default()
780    }
781
782    /// Build a configuration from common environment variables.
783    ///
784    /// Reads the following environment variables (all optional):
785    ///
786    /// | Variable | Maps to |
787    /// |----------|---------|
788    /// | `JWT_SECRET` | `secret` / `security.secret_key` |
789    /// | `DATABASE_URL` | PostgreSQL storage (requires `postgres-storage` feature) |
790    /// | `REDIS_URL` | Redis storage (requires `redis-storage` feature) |
791    /// | `AUTH_ISSUER` | `issuer` |
792    /// | `AUTH_AUDIENCE` | `audience` |
793    ///
794    /// Missing variables are silently ignored and fall back to defaults.
795    ///
796    /// # Example
797    ///
798    /// ```rust
799    /// use auth_framework::config::AuthConfig;
800    ///
801    /// // In tests or CI you can set the env vars beforehand:
802    /// // std::env::set_var("JWT_SECRET", "my-long-secret-key-for-jwt-signing!!");
803    /// let config = AuthConfig::from_env();
804    /// ```
805    pub fn from_env() -> Self {
806        let mut config = Self::default();
807
808        if let Ok(secret) = std::env::var("JWT_SECRET") {
809            config.secret = Some(secret.clone());
810            config.security.secret_key = Some(secret.into());
811        }
812
813        if let Ok(issuer) = std::env::var("AUTH_ISSUER") {
814            config.issuer = issuer;
815        }
816
817        if let Ok(audience) = std::env::var("AUTH_AUDIENCE") {
818            config.audience = audience;
819        }
820
821        // Storage: DATABASE_URL → Postgres, REDIS_URL → Redis (first match wins)
822        #[cfg(feature = "postgres-storage")]
823        if let Ok(url) = std::env::var("DATABASE_URL") {
824            config.storage = StorageConfig::Postgres {
825                connection_string: url,
826                table_prefix: "auth_".to_string(),
827            };
828        }
829
830        #[cfg(feature = "redis-storage")]
831        if matches!(config.storage, StorageConfig::Memory)
832            && let Ok(url) = std::env::var("REDIS_URL")
833        {
834            config.storage = StorageConfig::Redis {
835                url,
836                key_prefix: "auth:".to_string(),
837            };
838        }
839
840        config
841    }
842
843    /// Start the full [`AuthBuilder`](crate::builders::AuthBuilder) workflow.
844    ///
845    /// This is a convenience alias for [`AuthFramework::builder()`] — use it
846    /// when you want to configure storage, security presets, and sub-builders
847    /// from a single fluent chain.
848    ///
849    /// # Example
850    ///
851    /// ```rust,no_run
852    /// use auth_framework::prelude::*;
853    ///
854    /// # #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> {
855    /// let auth = AuthConfig::builder()
856    ///     .with_jwt().secret("...").done()
857    ///     .with_storage().memory().done()
858    ///     .build().await?;
859    /// # Ok(()) }
860    /// ```
861    ///
862    /// For more organized configuration, consider [`AuthConfigBuilder`] which
863    /// groups settings by concern (tokens, security, storage, features, etc.).
864    pub fn builder() -> crate::builders::AuthBuilder {
865        crate::builders::AuthBuilder::new()
866    }
867
868    /// Set the token lifetime.
869    ///
870    /// # Example
871    ///
872    /// ```rust
873    /// use auth_framework::config::AuthConfig;
874    /// use std::time::Duration;
875    ///
876    /// let config = AuthConfig::new().token_lifetime(Duration::from_secs(1800));
877    /// assert_eq!(config.token_lifetime.as_secs(), 1800);
878    /// ```
879    pub fn token_lifetime(mut self, lifetime: Duration) -> Self {
880        self.token_lifetime = lifetime;
881        self
882    }
883
884    /// Set the refresh token lifetime.
885    ///
886    /// # Example
887    ///
888    /// ```rust
889    /// use auth_framework::config::AuthConfig;
890    /// use std::time::Duration;
891    ///
892    /// let config = AuthConfig::new().refresh_token_lifetime(Duration::from_secs(86400));
893    /// assert_eq!(config.refresh_token_lifetime.as_secs(), 86400);
894    /// ```
895    pub fn refresh_token_lifetime(mut self, lifetime: Duration) -> Self {
896        self.refresh_token_lifetime = lifetime;
897        self
898    }
899
900    /// Enable or disable multi-factor authentication.
901    ///
902    /// # Example
903    ///
904    /// ```rust
905    /// use auth_framework::config::AuthConfig;
906    ///
907    /// let config = AuthConfig::new().enable_multi_factor(true);
908    /// assert!(config.enable_multi_factor);
909    /// ```
910    pub fn enable_multi_factor(mut self, enabled: bool) -> Self {
911        self.enable_multi_factor = enabled;
912        self
913    }
914
915    /// Set the JWT issuer.
916    pub fn issuer(mut self, issuer: impl Into<String>) -> Self {
917        self.issuer = issuer.into();
918        self
919    }
920
921    /// Set the JWT audience.
922    pub fn audience(mut self, audience: impl Into<String>) -> Self {
923        self.audience = audience.into();
924        self
925    }
926
927    /// Set the JWT secret key.
928    pub fn secret(mut self, secret: impl Into<String>) -> Self {
929        self.secret = Some(secret.into());
930        self
931    }
932
933    /// Require MFA for all users.
934    ///
935    /// # Example
936    ///
937    /// ```rust
938    /// use auth_framework::config::AuthConfig;
939    ///
940    /// let config = AuthConfig::new().require_mfa(true);
941    /// assert!(config.enable_multi_factor);
942    /// ```
943    pub fn require_mfa(mut self, required: bool) -> Self {
944        self.enable_multi_factor = required;
945        self
946    }
947
948    /// Enable caching.
949    pub fn enable_caching(mut self, enabled: bool) -> Self {
950        self.enable_caching = enabled;
951        self
952    }
953
954    /// Set maximum failed attempts.
955    ///
956    /// # Example
957    ///
958    /// ```rust
959    /// use auth_framework::config::AuthConfig;
960    ///
961    /// let config = AuthConfig::new().max_failed_attempts(10);
962    /// assert_eq!(config.max_failed_attempts, 10);
963    /// ```
964    pub fn max_failed_attempts(mut self, max: u32) -> Self {
965        self.max_failed_attempts = max;
966        self
967    }
968
969    /// Enable RBAC.
970    ///
971    /// # Example
972    ///
973    /// ```rust
974    /// use auth_framework::config::AuthConfig;
975    ///
976    /// let config = AuthConfig::new().enable_rbac(true);
977    /// assert!(config.enable_rbac);
978    /// ```
979    pub fn enable_rbac(mut self, enabled: bool) -> Self {
980        self.enable_rbac = enabled;
981        self
982    }
983
984    /// Enable security audit.
985    ///
986    /// # Example
987    ///
988    /// ```rust
989    /// use auth_framework::config::AuthConfig;
990    ///
991    /// let config = AuthConfig::new().enable_security_audit(true);
992    /// assert!(config.audit.enabled);
993    /// ```
994    pub fn enable_security_audit(mut self, enabled: bool) -> Self {
995        self.audit.enabled = enabled;
996        self
997    }
998
999    /// Enable middleware.
1000    ///
1001    /// # Example
1002    ///
1003    /// ```rust
1004    /// use auth_framework::config::AuthConfig;
1005    ///
1006    /// let config = AuthConfig::new().enable_middleware(true);
1007    /// assert!(config.enable_middleware);
1008    /// ```
1009    pub fn enable_middleware(mut self, enabled: bool) -> Self {
1010        self.enable_middleware = enabled;
1011        self
1012    }
1013
1014    /// Force production-mode validation, bypassing test-environment detection.
1015    ///
1016    /// Used exclusively in tests that verify production-specific error handling without
1017    /// polluting the process-wide environment with `ENVIRONMENT=production`.
1018    ///
1019    /// # Example
1020    ///
1021    /// ```rust
1022    /// use auth_framework::config::AuthConfig;
1023    ///
1024    /// let config = AuthConfig::new().force_production_mode();
1025    /// ```
1026    pub fn force_production_mode(mut self) -> Self {
1027        self.force_production_mode = true;
1028        self
1029    }
1030
1031    /// Set the storage configuration.
1032    ///
1033    /// # Example
1034    ///
1035    /// ```rust
1036    /// use auth_framework::config::{AuthConfig, StorageConfig};
1037    ///
1038    /// let config = AuthConfig::new().storage(StorageConfig::Memory);
1039    /// ```
1040    pub fn storage(mut self, storage: StorageConfig) -> Self {
1041        self.storage = storage;
1042        self
1043    }
1044
1045    /// Configure whether KV-layer storage is encrypted at rest. See
1046    /// [`StorageEncryptionConfig`].
1047    ///
1048    /// # Example
1049    ///
1050    /// ```rust
1051    /// use auth_framework::config::{AuthConfig, StorageEncryptionConfig};
1052    ///
1053    /// let config = AuthConfig::new().storage_encryption(StorageEncryptionConfig {
1054    ///     enabled: false,
1055    ///     ..Default::default()
1056    /// });
1057    /// ```
1058    pub fn storage_encryption(mut self, storage_encryption: StorageEncryptionConfig) -> Self {
1059        self.storage_encryption = storage_encryption;
1060        self
1061    }
1062
1063    /// Configure Redis storage.
1064    ///
1065    /// # Example
1066    ///
1067    /// ```rust,ignore
1068    /// use auth_framework::config::AuthConfig;
1069    ///
1070    /// let config = AuthConfig::new().redis_storage("redis://127.0.0.1:6379");
1071    /// ```
1072    #[cfg(feature = "redis-storage")]
1073    pub fn redis_storage(mut self, url: impl Into<String>) -> Self {
1074        self.storage = StorageConfig::Redis {
1075            url: url.into(),
1076            key_prefix: "auth:".to_string(),
1077        };
1078        self
1079    }
1080
1081    /// Set rate limiting configuration.
1082    ///
1083    /// # Example
1084    ///
1085    /// ```rust
1086    /// use auth_framework::config::{AuthConfig, RateLimitConfig};
1087    ///
1088    /// let config = AuthConfig::new().rate_limiting(RateLimitConfig::default());
1089    /// ```
1090    pub fn rate_limiting(mut self, config: RateLimitConfig) -> Self {
1091        self.rate_limiting = config;
1092        self
1093    }
1094
1095    /// Set security configuration.
1096    ///
1097    /// # Example
1098    ///
1099    /// ```rust
1100    /// use auth_framework::config::{AuthConfig, SecurityConfig};
1101    ///
1102    /// let config = AuthConfig::new().security(SecurityConfig::secure());
1103    /// ```
1104    pub fn security(mut self, config: SecurityConfig) -> Self {
1105        self.security = config;
1106        self
1107    }
1108
1109    /// Set CORS configuration.
1110    ///
1111    /// # Example
1112    ///
1113    /// ```rust
1114    /// use auth_framework::config::{AuthConfig, CorsConfig};
1115    ///
1116    /// let config = AuthConfig::new()
1117    ///     .cors(CorsConfig::for_origins(["https://app.example.com"]));
1118    /// ```
1119    pub fn cors(mut self, config: CorsConfig) -> Self {
1120        self.cors = config;
1121        self
1122    }
1123
1124    /// Set audit configuration.
1125    ///
1126    /// # Example
1127    ///
1128    /// ```rust
1129    /// use auth_framework::config::{AuthConfig, AuditConfig};
1130    ///
1131    /// let config = AuthConfig::new().audit(AuditConfig::default());
1132    /// ```
1133    pub fn audit(mut self, config: AuditConfig) -> Self {
1134        self.audit = config;
1135        self
1136    }
1137
1138    /// Add configuration for a specific auth method.
1139    ///
1140    /// # Example
1141    ///
1142    /// ```rust
1143    /// use auth_framework::config::AuthConfig;
1144    ///
1145    /// let config = AuthConfig::new()
1146    ///     .method_config("oauth2", serde_json::json!({
1147    ///         "client_id": "my-client",
1148    ///         "client_secret": "my-secret"
1149    ///     }))
1150    ///     .unwrap();
1151    /// ```
1152    pub fn method_config(
1153        mut self,
1154        method_name: impl Into<String>,
1155        config: impl Serialize,
1156    ) -> Result<Self> {
1157        let value = serde_json::to_value(config)
1158            .map_err(|e| AuthError::config(format!("Failed to serialize method config: {e}")))?;
1159
1160        self.method_configs.insert(method_name.into(), value);
1161        Ok(self)
1162    }
1163
1164    /// Get configuration for a specific auth method.
1165    ///
1166    /// # Example
1167    ///
1168    /// ```rust
1169    /// use auth_framework::config::AuthConfig;
1170    ///
1171    /// let config = AuthConfig::new();
1172    /// let oauth: Option<serde_json::Value> = config.get_method_config("oauth2").unwrap();
1173    /// assert!(oauth.is_none()); // no oauth2 config set yet
1174    /// ```
1175    pub fn get_method_config<T>(&self, method_name: &str) -> Result<Option<T>>
1176    where
1177        T: for<'de> Deserialize<'de>,
1178    {
1179        if let Some(value) = self.method_configs.get(method_name) {
1180            let config = serde_json::from_value(value.clone()).map_err(|e| {
1181                AuthError::config(format!("Failed to deserialize method config: {e}"))
1182            })?;
1183            Ok(Some(config))
1184        } else {
1185            Ok(None)
1186        }
1187    }
1188
1189    /// Validate the configuration.
1190    ///
1191    /// # Example
1192    ///
1193    /// ```rust
1194    /// use auth_framework::config::AuthConfig;
1195    ///
1196    /// let config = AuthConfig::new();
1197    /// assert!(config.validate().is_ok());
1198    /// ```
1199    pub fn validate(&self) -> Result<()> {
1200        // Validate token lifetimes
1201        if self.token_lifetime.as_secs() == 0 {
1202            return Err(AuthError::config("Token lifetime must be greater than 0"));
1203        }
1204
1205        if self.refresh_token_lifetime.as_secs() == 0 {
1206            return Err(AuthError::config(
1207                "Refresh token lifetime must be greater than 0",
1208            ));
1209        }
1210
1211        if self.refresh_token_lifetime <= self.token_lifetime {
1212            return Err(AuthError::config(
1213                "Refresh token lifetime must be greater than token lifetime",
1214            ));
1215        }
1216
1217        // Validate JWT secret configuration
1218        self.validate_jwt_secret()?;
1219
1220        // Validate security settings
1221        if self.security.min_password_length < 4 {
1222            return Err(AuthError::config(
1223                "Minimum password length must be at least 4 characters",
1224            ));
1225        }
1226
1227        if matches!(
1228            self.security.password_hash_algorithm,
1229            PasswordHashAlgorithm::Scrypt
1230        ) {
1231            return Err(AuthError::config(
1232                "PasswordHashAlgorithm::Scrypt is not yet implemented; configure Argon2 or \
1233                 Bcrypt instead",
1234            ));
1235        }
1236
1237        // Enhanced security validation for production
1238        if self.is_production_environment() && !self.is_test_environment() {
1239            self.validate_production_security()?;
1240        }
1241
1242        // Validate rate limiting
1243        if self.rate_limiting.enabled && self.rate_limiting.max_requests == 0 {
1244            return Err(AuthError::config(
1245                "Rate limit max requests must be greater than 0 when enabled",
1246            ));
1247        }
1248
1249        // Validate storage configuration
1250        self.validate_storage_config()?;
1251
1252        // Validate built-in auth method configuration blobs eagerly so invalid
1253        // method settings fail during startup instead of at first use.
1254        self.validate_method_configs()?;
1255
1256        Ok(())
1257    }
1258
1259    fn validate_method_configs(&self) -> Result<()> {
1260        for (method_name, raw_config) in &self.method_configs {
1261            match method_name.as_str() {
1262                #[cfg(feature = "saml")]
1263                "saml" => {
1264                    let config: crate::methods::saml::SamlConfig =
1265                        serde_json::from_value(raw_config.clone()).map_err(|e| {
1266                            AuthError::config(format!(
1267                                "Failed to deserialize SAML method config: {e}"
1268                            ))
1269                        })?;
1270
1271                    if config.entity_id.trim().is_empty() {
1272                        return Err(AuthError::config("SAML entity_id cannot be empty"));
1273                    }
1274                    if config.acs_url.trim().is_empty() {
1275                        return Err(AuthError::config("SAML acs_url cannot be empty"));
1276                    }
1277                    if config.max_assertion_age == 0 {
1278                        return Err(AuthError::config(
1279                            "SAML max_assertion_age must be greater than 0",
1280                        ));
1281                    }
1282                }
1283                #[cfg(not(feature = "saml"))]
1284                "saml" => {
1285                    return Err(AuthError::config(
1286                        "SAML method config is present but the 'saml' feature is not enabled",
1287                    ));
1288                }
1289                #[cfg(feature = "passkeys")]
1290                "passkey" => {
1291                    let config: crate::methods::passkey::PasskeyConfig =
1292                        serde_json::from_value(raw_config.clone()).map_err(|e| {
1293                            AuthError::config(format!(
1294                                "Failed to deserialize passkey method config: {e}"
1295                            ))
1296                        })?;
1297
1298                    if config.rp_id.trim().is_empty() {
1299                        return Err(AuthError::config("Passkey RP ID cannot be empty"));
1300                    }
1301                    if config.origin.trim().is_empty() {
1302                        return Err(AuthError::config("Passkey origin cannot be empty"));
1303                    }
1304                    if config.timeout_ms == 0 {
1305                        return Err(AuthError::config("Passkey timeout must be greater than 0"));
1306                    }
1307                    match config.user_verification.as_str() {
1308                        "required" | "preferred" | "discouraged" => {}
1309                        _ => {
1310                            return Err(AuthError::config(
1311                                "Invalid passkey user_verification value",
1312                            ));
1313                        }
1314                    }
1315                    url::Url::parse(&config.origin).map_err(|e| {
1316                        AuthError::config(format!("Invalid passkey origin URL: {e}"))
1317                    })?;
1318                }
1319                #[cfg(not(feature = "passkeys"))]
1320                "passkey" => {
1321                    return Err(AuthError::config(
1322                        "Passkey method config is present but the 'passkeys' feature is not enabled",
1323                    ));
1324                }
1325                "enhanced_device_flow" => {
1326                    let client_id = raw_config
1327                        .get("client_id")
1328                        .and_then(serde_json::Value::as_str)
1329                        .unwrap_or_default();
1330                    let auth_url = raw_config
1331                        .get("auth_url")
1332                        .and_then(serde_json::Value::as_str)
1333                        .unwrap_or_default();
1334                    let token_url = raw_config
1335                        .get("token_url")
1336                        .and_then(serde_json::Value::as_str)
1337                        .unwrap_or_default();
1338                    let device_auth_url = raw_config
1339                        .get("device_auth_url")
1340                        .and_then(serde_json::Value::as_str)
1341                        .unwrap_or_default();
1342
1343                    if client_id.trim().is_empty()
1344                        || auth_url.trim().is_empty()
1345                        || token_url.trim().is_empty()
1346                        || device_auth_url.trim().is_empty()
1347                    {
1348                        return Err(AuthError::config(
1349                            "Enhanced device flow config requires non-empty client_id, auth_url, token_url, and device_auth_url",
1350                        ));
1351                    }
1352                }
1353                _ => {}
1354            }
1355        }
1356
1357        Ok(())
1358    }
1359
1360    /// Validate JWT secret configuration for security
1361    fn validate_jwt_secret(&self) -> Result<()> {
1362        // Check multiple sources for JWT secret
1363        let env_secret = std::env::var("JWT_SECRET").ok();
1364        let jwt_secret = self
1365            .security
1366            .secret_key
1367            .as_ref()
1368            .map(|s| s.as_str())
1369            .or(self.secret.as_deref())
1370            .or(env_secret.as_deref());
1371
1372        if let Some(secret) = jwt_secret {
1373            // A placeholder is a value that is the same in every deployment that copied it, so it
1374            // is no secret at all. Production refuses it however long and varied it looks.
1375            if self.is_production_environment() && is_placeholder_secret(secret) {
1376                return Err(AuthError::config(
1377                    "JWT secret is a known placeholder value, the same in every deployment that                      copied it. Generate your own with: openssl rand -base64 32",
1378                ));
1379            }
1380
1381            // Enforce minimum length only outside test environments.
1382            // In tests, short secrets are acceptable for convenience.
1383            if !self.is_test_environment() && secret.len() < 32 {
1384                return Err(AuthError::config(
1385                    "JWT secret must be at least 32 characters for security. \
1386                     Generate with: openssl rand -base64 32",
1387                ));
1388            }
1389
1390            // Check for low-entropy secrets using Shannon entropy measurement
1391            // rather than pattern matching, which is trivially bypassed.
1392            if !self.is_test_environment() {
1393                let mut char_counts = std::collections::HashMap::new();
1394                for c in secret.chars() {
1395                    *char_counts.entry(c).or_insert(0u32) += 1;
1396                }
1397                let len = secret.len() as f64;
1398                let entropy: f64 = char_counts
1399                    .values()
1400                    .map(|&count| {
1401                        let p = count as f64 / len;
1402                        -p * p.log2()
1403                    })
1404                    .sum();
1405                if entropy < 3.5 {
1406                    return Err(AuthError::config(
1407                        "JWT secret has insufficient entropy (too predictable). \
1408                         Use a cryptographically secure random string.",
1409                    ));
1410                }
1411            }
1412
1413            // Warn if secret looks like it might be base64 but too short
1414            if secret.len() < 44
1415                && secret
1416                    .chars()
1417                    .all(|c| c.is_alphanumeric() || c == '+' || c == '/' || c == '=')
1418            {
1419                tracing::warn!(
1420                    "JWT secret may be too short for optimal security. \
1421                     Consider using at least 44 characters (32 bytes base64-encoded)."
1422                );
1423            }
1424        } else if self.is_production_environment() {
1425            return Err(AuthError::config(
1426                "JWT secret is required for production environments. \
1427                 Set JWT_SECRET environment variable or configure security.secret_key",
1428            ));
1429        }
1430
1431        Ok(())
1432    }
1433
1434    /// Validate production-specific security requirements
1435    fn validate_production_security(&self) -> Result<()> {
1436        // Require strong password policies in production
1437        if self.security.min_password_length < 8 {
1438            return Err(AuthError::config(
1439                "Production environments require minimum password length of 8 characters",
1440            ));
1441        }
1442
1443        if !self.security.require_password_complexity {
1444            tracing::warn!("Production deployment should enable password complexity requirements");
1445        }
1446
1447        // Require secure cookies in production
1448        if !self.security.secure_cookies {
1449            return Err(AuthError::config(
1450                "Production environments must use secure cookies (HTTPS required)",
1451            ));
1452        }
1453
1454        // Ensure rate limiting is enabled
1455        if !self.rate_limiting.enabled {
1456            tracing::warn!("Production deployment should enable rate limiting for security");
1457        }
1458
1459        // Validate audit configuration for compliance
1460        if !self.audit.enabled {
1461            return Err(AuthError::config(
1462                "Production environments require audit logging for compliance",
1463            ));
1464        }
1465
1466        Ok(())
1467    }
1468
1469    /// Validate storage configuration
1470    fn validate_storage_config(&self) -> Result<()> {
1471        // PostgreSQL, Redis, and SQLite are all production-ready; only
1472        // Memory needs the environment check below.
1473        if let StorageConfig::Memory = &self.storage
1474            && self.is_production_environment()
1475            && !self.is_test_environment()
1476        {
1477            return Err(AuthError::config(
1478                "Memory storage is not suitable for production environments. \
1479                 Use PostgreSQL, Redis, or SQLite storage.",
1480            ));
1481        }
1482
1483        Ok(())
1484    }
1485
1486    /// Detect production environment
1487    fn is_production_environment(&self) -> bool {
1488        // An explicit config flag always wins — used by tests that need production behaviour.
1489        if self.force_production_mode {
1490            return true;
1491        }
1492
1493        // Check common production environment indicators
1494        if let Ok(env) = std::env::var("ENVIRONMENT")
1495            && (env.to_lowercase() == "production" || env.to_lowercase() == "prod")
1496        {
1497            return true;
1498        }
1499
1500        if let Ok(env) = std::env::var("ENV")
1501            && (env.to_lowercase() == "production" || env.to_lowercase() == "prod")
1502        {
1503            return true;
1504        }
1505
1506        if let Ok(env) = std::env::var("NODE_ENV")
1507            && env.to_lowercase() == "production"
1508        {
1509            return true;
1510        }
1511
1512        if let Ok(env) = std::env::var("RUST_ENV")
1513            && env.to_lowercase() == "production"
1514        {
1515            return true;
1516        }
1517
1518        // Check for containerized environments
1519        if std::env::var("KUBERNETES_SERVICE_HOST").is_ok() {
1520            return true;
1521        }
1522
1523        if std::env::var("DOCKER_CONTAINER").is_ok() {
1524            return true;
1525        }
1526
1527        false
1528    }
1529
1530    /// Detect test environment
1531    fn is_test_environment(&self) -> bool {
1532        // An explicit config flag forces production mode — never treat it as a test environment.
1533        if self.force_production_mode {
1534            return false;
1535        }
1536        // Check if we're running in a test environment
1537        cfg!(test)
1538            || std::thread::current()
1539                .name()
1540                .is_some_and(|name| name.contains("test"))
1541            || std::env::var("RUST_TEST").is_ok()
1542            || std::env::var("ENVIRONMENT").as_deref() == Ok("test")
1543            || std::env::var("ENV").as_deref() == Ok("test")
1544            || std::env::args().any(|arg| arg.contains("test"))
1545    }
1546}
1547
1548impl RateLimitConfig {
1549    /// Create a new rate limit configuration.
1550    ///
1551    /// # Example
1552    ///
1553    /// ```rust
1554    /// use auth_framework::config::RateLimitConfig;
1555    /// use std::time::Duration;
1556    ///
1557    /// let rl = RateLimitConfig::new(100, Duration::from_secs(60));
1558    /// assert!(rl.enabled);
1559    /// assert_eq!(rl.max_requests, 100);
1560    /// ```
1561    pub fn new(max_requests: u32, window: Duration) -> Self {
1562        Self {
1563            enabled: true,
1564            max_requests,
1565            window,
1566            burst: max_requests / 10, // 10% of max as burst
1567        }
1568    }
1569
1570    /// Disable rate limiting.
1571    ///
1572    /// # Example
1573    ///
1574    /// ```rust
1575    /// use auth_framework::config::RateLimitConfig;
1576    ///
1577    /// let rl = RateLimitConfig::disabled();
1578    /// assert!(!rl.enabled);
1579    /// ```
1580    pub fn disabled() -> Self {
1581        Self {
1582            enabled: false,
1583            ..Default::default()
1584        }
1585    }
1586
1587    /// Shorthand: allow `max` requests per second.
1588    ///
1589    /// # Example
1590    ///
1591    /// ```rust
1592    /// use auth_framework::config::RateLimitConfig;
1593    ///
1594    /// let rl = RateLimitConfig::per_second(50);
1595    /// assert_eq!(rl.max_requests, 50);
1596    /// ```
1597    pub fn per_second(max: u32) -> Self {
1598        Self::new(max, Duration::from_secs(1))
1599    }
1600
1601    /// Shorthand: allow `max` requests per minute.
1602    ///
1603    /// # Example
1604    ///
1605    /// ```rust
1606    /// use auth_framework::config::RateLimitConfig;
1607    ///
1608    /// let rl = RateLimitConfig::per_minute(100);
1609    /// assert_eq!(rl.max_requests, 100);
1610    /// ```
1611    pub fn per_minute(max: u32) -> Self {
1612        Self::new(max, Duration::from_secs(60))
1613    }
1614
1615    /// Shorthand: allow `max` requests per hour.
1616    ///
1617    /// # Example
1618    ///
1619    /// ```rust
1620    /// use auth_framework::config::RateLimitConfig;
1621    ///
1622    /// let rl = RateLimitConfig::per_hour(1000);
1623    /// assert_eq!(rl.max_requests, 1000);
1624    /// ```
1625    pub fn per_hour(max: u32) -> Self {
1626        Self::new(max, Duration::from_secs(3600))
1627    }
1628}
1629
1630impl SecurityConfig {
1631    /// Create a new security configuration with secure defaults.
1632    ///
1633    /// # Example
1634    ///
1635    /// ```rust
1636    /// use auth_framework::config::SecurityConfig;
1637    ///
1638    /// let sec = SecurityConfig::secure();
1639    /// assert!(sec.secure_cookies);
1640    /// assert!(sec.csrf_protection);
1641    /// assert_eq!(sec.min_password_length, 12);
1642    /// ```
1643    pub fn secure() -> Self {
1644        Self {
1645            min_password_length: 12,
1646            require_password_complexity: true,
1647            password_hash_algorithm: PasswordHashAlgorithm::Argon2,
1648            // ES256, not RS256 -- see security/presets.rs::to_config for why
1649            // (rsa has an open, unpatched timing-sidechannel advisory,
1650            // RUSTSEC-2023-0071). This constructor is the one actually
1651            // reached by AuthBuilder/QuickStartBuilder's
1652            // .security_preset(HighSecurity | Paranoid) and
1653            // .use_case(Enterprise) -- not SecurityPreset::to_config() --
1654            // so it needs the same fix independently.
1655            jwt_algorithm: JwtAlgorithm::ES256,
1656            secret_key: None,
1657            previous_secret_key: None,
1658            secure_cookies: true,
1659            cookie_same_site: CookieSameSite::Strict,
1660            csrf_protection: true,
1661            session_timeout: Duration::from_secs(3600 * 8), // 8 hours
1662        }
1663    }
1664
1665    /// Create a development-friendly configuration.
1666    /// WARNING: You MUST set a secret key before using this configuration!
1667    /// Use either config.security.secret_key or JWT_SECRET environment variable.
1668    ///
1669    /// # Example
1670    ///
1671    /// ```rust
1672    /// use auth_framework::config::SecurityConfig;
1673    ///
1674    /// let sec = SecurityConfig::development();
1675    /// assert_eq!(sec.min_password_length, 6);
1676    /// assert!(!sec.secure_cookies);
1677    /// ```
1678    pub fn development() -> Self {
1679        Self {
1680            min_password_length: 6,
1681            require_password_complexity: false,
1682            password_hash_algorithm: PasswordHashAlgorithm::Bcrypt,
1683            jwt_algorithm: JwtAlgorithm::HS256,
1684            secret_key: None, // Must be set by developer for security
1685            previous_secret_key: None,
1686            secure_cookies: false,
1687            cookie_same_site: CookieSameSite::Lax,
1688            csrf_protection: false,
1689            session_timeout: Duration::from_secs(3600 * 24), // 24 hours
1690        }
1691    }
1692}
1693
1694/// A comprehensive builder for `AuthConfig` that organizes configuration into logical groups.
1695///
1696/// This builder provides better developer experience by grouping related settings
1697/// and providing sensible defaults for each category. Use this when you need fine-grained
1698/// control over the configuration but want better organization than the flat setter API.
1699///
1700/// # Example
1701///
1702/// ```rust,no_run
1703/// use auth_framework::config::{AuthConfig, AuthConfigBuilder};
1704/// use std::time::Duration;
1705///
1706/// let builder = AuthConfigBuilder::new()
1707///     .tokens()
1708///         .lifetime(Duration::from_secs(3600))
1709///         .refresh_lifetime(Duration::from_secs(86400 * 7))
1710///         .issuer("myapp")
1711///         .audience("myapp-users")
1712///         .secret("my-32-char-secret-key-here!!!!!")
1713///         .done()
1714///     .security()
1715///         .min_password_length(8)
1716///         .require_complexity(true)
1717///         .secure_cookies(true)
1718///         .done()
1719///     .storage()
1720///         .memory()
1721///         .done()
1722///     .features()
1723///         .enable_multi_factor(true)
1724///         .enable_rbac(true)
1725///         .enable_caching(true)
1726///         .done();
1727///
1728/// let config = builder.build().expect("Failed to build config");
1729/// ```
1730#[derive(Debug)]
1731pub struct AuthConfigBuilder {
1732    config: AuthConfig,
1733}
1734
1735impl Default for AuthConfigBuilder {
1736    fn default() -> Self {
1737        Self::new()
1738    }
1739}
1740
1741impl AuthConfigBuilder {
1742    /// Create a new builder with sensible defaults.
1743    pub fn new() -> Self {
1744        Self {
1745            config: AuthConfig::default(),
1746        }
1747    }
1748
1749    /// Configure token-related settings.
1750    pub fn tokens(self) -> TokenConfigBuilder {
1751        TokenConfigBuilder { builder: self }
1752    }
1753
1754    /// Configure security-related settings.
1755    pub fn security(self) -> SecurityConfigBuilder {
1756        SecurityConfigBuilder { builder: self }
1757    }
1758
1759    /// Configure storage settings.
1760    pub fn storage(self) -> StorageConfigBuilder {
1761        StorageConfigBuilder { builder: self }
1762    }
1763
1764    /// Configure feature flags and capabilities.
1765    pub fn features(self) -> FeatureConfigBuilder {
1766        FeatureConfigBuilder { builder: self }
1767    }
1768
1769    /// Configure rate limiting.
1770    pub fn rate_limiting(self) -> RateLimitConfigBuilder {
1771        RateLimitConfigBuilder { builder: self }
1772    }
1773
1774    /// Configure CORS settings.
1775    pub fn cors(self) -> CorsConfigBuilder {
1776        CorsConfigBuilder { builder: self }
1777    }
1778
1779    /// Configure audit logging.
1780    pub fn audit(self) -> AuditConfigBuilder {
1781        AuditConfigBuilder { builder: self }
1782    }
1783
1784    /// Build the final configuration, validating it in the process.
1785    pub fn build(self) -> Result<AuthConfig> {
1786        let config = self.config;
1787        config.validate()?;
1788        Ok(config)
1789    }
1790}
1791
1792/// Builder for token-related configuration.
1793#[derive(Debug)]
1794pub struct TokenConfigBuilder {
1795    builder: AuthConfigBuilder,
1796}
1797
1798impl TokenConfigBuilder {
1799    /// Set the access token lifetime.
1800    pub fn lifetime(mut self, duration: Duration) -> Self {
1801        self.builder.config.token_lifetime = duration;
1802        self
1803    }
1804
1805    /// Set the refresh token lifetime.
1806    pub fn refresh_lifetime(mut self, duration: Duration) -> Self {
1807        self.builder.config.refresh_token_lifetime = duration;
1808        self
1809    }
1810
1811    /// Set the JWT issuer.
1812    pub fn issuer(mut self, issuer: impl Into<String>) -> Self {
1813        self.builder.config.issuer = issuer.into();
1814        self
1815    }
1816
1817    /// Set the JWT audience.
1818    pub fn audience(mut self, audience: impl Into<String>) -> Self {
1819        self.builder.config.audience = audience.into();
1820        self
1821    }
1822
1823    /// Set the JWT secret key.
1824    pub fn secret(mut self, secret: impl Into<String>) -> Self {
1825        self.builder.config.secret = Some(secret.into());
1826        self
1827    }
1828
1829    /// Finish token configuration and return to the main builder.
1830    pub fn done(self) -> AuthConfigBuilder {
1831        self.builder
1832    }
1833}
1834
1835/// Builder for security-related configuration.
1836#[derive(Debug)]
1837pub struct SecurityConfigBuilder {
1838    builder: AuthConfigBuilder,
1839}
1840
1841impl SecurityConfigBuilder {
1842    /// Set minimum password length.
1843    pub fn min_password_length(mut self, length: usize) -> Self {
1844        self.builder.config.security.min_password_length = length;
1845        self
1846    }
1847
1848    /// Require password complexity.
1849    pub fn require_complexity(mut self, required: bool) -> Self {
1850        self.builder.config.security.require_password_complexity = required;
1851        self
1852    }
1853
1854    /// Set password hash algorithm.
1855    pub fn password_algorithm(mut self, algorithm: PasswordHashAlgorithm) -> Self {
1856        self.builder.config.security.password_hash_algorithm = algorithm;
1857        self
1858    }
1859
1860    /// Set JWT algorithm.
1861    pub fn jwt_algorithm(mut self, algorithm: JwtAlgorithm) -> Self {
1862        self.builder.config.security.jwt_algorithm = algorithm;
1863        self
1864    }
1865
1866    /// Enable secure cookies.
1867    pub fn secure_cookies(mut self, enabled: bool) -> Self {
1868        self.builder.config.security.secure_cookies = enabled;
1869        self
1870    }
1871
1872    /// Set cookie SameSite policy.
1873    pub fn cookie_same_site(mut self, policy: CookieSameSite) -> Self {
1874        self.builder.config.security.cookie_same_site = policy;
1875        self
1876    }
1877
1878    /// Enable CSRF protection.
1879    pub fn csrf_protection(mut self, enabled: bool) -> Self {
1880        self.builder.config.security.csrf_protection = enabled;
1881        self
1882    }
1883
1884    /// Set session timeout.
1885    pub fn session_timeout(mut self, timeout: Duration) -> Self {
1886        self.builder.config.security.session_timeout = timeout;
1887        self
1888    }
1889
1890    /// Finish security configuration and return to the main builder.
1891    pub fn done(self) -> AuthConfigBuilder {
1892        self.builder
1893    }
1894}
1895
1896/// Builder for storage configuration.
1897#[derive(Debug)]
1898pub struct StorageConfigBuilder {
1899    builder: AuthConfigBuilder,
1900}
1901
1902impl StorageConfigBuilder {
1903    /// Use in-memory storage (development only).
1904    pub fn memory(mut self) -> Self {
1905        self.builder.config.storage = StorageConfig::Memory;
1906        self
1907    }
1908
1909    /// Use Redis storage.
1910    #[cfg(feature = "redis-storage")]
1911    pub fn redis(mut self, url: impl Into<String>) -> Self {
1912        self.builder.config.storage = StorageConfig::Redis {
1913            url: url.into(),
1914            key_prefix: "auth:".to_string(),
1915        };
1916        self
1917    }
1918
1919    /// Use PostgreSQL storage.
1920    #[cfg(feature = "postgres-storage")]
1921    pub fn postgres(mut self, connection_string: impl Into<String>) -> Self {
1922        self.builder.config.storage = StorageConfig::Postgres {
1923            connection_string: connection_string.into(),
1924            table_prefix: "auth_".to_string(),
1925        };
1926        self
1927    }
1928
1929    /// Use SQLite storage.
1930    #[cfg(feature = "sqlite-storage")]
1931    pub fn sqlite(mut self, connection_string: impl Into<String>) -> Self {
1932        self.builder.config.storage = StorageConfig::Sqlite {
1933            connection_string: connection_string.into(),
1934        };
1935        self
1936    }
1937
1938    /// Finish storage configuration and return to the main builder.
1939    pub fn done(self) -> AuthConfigBuilder {
1940        self.builder
1941    }
1942}
1943
1944/// Builder for feature flags and capabilities.
1945#[derive(Debug)]
1946pub struct FeatureConfigBuilder {
1947    builder: AuthConfigBuilder,
1948}
1949
1950impl FeatureConfigBuilder {
1951    /// Enable multi-factor authentication.
1952    pub fn enable_multi_factor(mut self, enabled: bool) -> Self {
1953        self.builder.config.enable_multi_factor = enabled;
1954        self
1955    }
1956
1957    /// Enable RBAC (Role-Based Access Control).
1958    pub fn enable_rbac(mut self, enabled: bool) -> Self {
1959        self.builder.config.enable_rbac = enabled;
1960        self
1961    }
1962
1963    /// Enable caching.
1964    pub fn enable_caching(mut self, enabled: bool) -> Self {
1965        self.builder.config.enable_caching = enabled;
1966        self
1967    }
1968
1969    /// Enable middleware helpers.
1970    pub fn enable_middleware(mut self, enabled: bool) -> Self {
1971        self.builder.config.enable_middleware = enabled;
1972        self
1973    }
1974
1975    /// Set maximum failed authentication attempts.
1976    pub fn max_failed_attempts(mut self, max: u32) -> Self {
1977        self.builder.config.max_failed_attempts = max;
1978        self
1979    }
1980
1981    /// Finish feature configuration and return to the main builder.
1982    pub fn done(self) -> AuthConfigBuilder {
1983        self.builder
1984    }
1985}
1986
1987/// Builder for rate limiting configuration.
1988#[derive(Debug)]
1989pub struct RateLimitConfigBuilder {
1990    builder: AuthConfigBuilder,
1991}
1992
1993impl RateLimitConfigBuilder {
1994    /// Enable rate limiting with specified limits.
1995    pub fn enabled(mut self, max_requests: u32, window: Duration) -> Self {
1996        self.builder.config.rate_limiting = RateLimitConfig::new(max_requests, window);
1997        self
1998    }
1999
2000    /// Disable rate limiting.
2001    pub fn disabled(mut self) -> Self {
2002        self.builder.config.rate_limiting = RateLimitConfig::disabled();
2003        self
2004    }
2005
2006    /// Set maximum requests per window.
2007    pub fn max_requests(mut self, max: u32) -> Self {
2008        self.builder.config.rate_limiting.max_requests = max;
2009        self
2010    }
2011
2012    /// Set rate limiting window.
2013    pub fn window(mut self, window: Duration) -> Self {
2014        self.builder.config.rate_limiting.window = window;
2015        self
2016    }
2017
2018    /// Set burst allowance.
2019    pub fn burst(mut self, burst: u32) -> Self {
2020        self.builder.config.rate_limiting.burst = burst;
2021        self
2022    }
2023
2024    /// Finish rate limiting configuration and return to the main builder.
2025    pub fn done(self) -> AuthConfigBuilder {
2026        self.builder
2027    }
2028}
2029
2030/// Builder for CORS configuration.
2031#[derive(Debug)]
2032pub struct CorsConfigBuilder {
2033    builder: AuthConfigBuilder,
2034}
2035
2036impl CorsConfigBuilder {
2037    /// Enable CORS for specific origins.
2038    pub fn allow_origins<I, S>(mut self, origins: I) -> Self
2039    where
2040        I: IntoIterator<Item = S>,
2041        S: Into<String>,
2042    {
2043        self.builder.config.cors = CorsConfig::for_origins(origins);
2044        self
2045    }
2046
2047    /// Disable CORS.
2048    pub fn disabled(mut self) -> Self {
2049        self.builder.config.cors.enabled = false;
2050        self
2051    }
2052
2053    /// Allow specific HTTP methods.
2054    pub fn allow_methods<I, S>(mut self, methods: I) -> Self
2055    where
2056        I: IntoIterator<Item = S>,
2057        S: Into<String>,
2058    {
2059        self.builder.config.cors.allowed_methods = methods.into_iter().map(Into::into).collect();
2060        self
2061    }
2062
2063    /// Allow specific headers.
2064    pub fn allow_headers<I, S>(mut self, headers: I) -> Self
2065    where
2066        I: IntoIterator<Item = S>,
2067        S: Into<String>,
2068    {
2069        self.builder.config.cors.allowed_headers = headers.into_iter().map(Into::into).collect();
2070        self
2071    }
2072
2073    /// Set max age for preflight requests.
2074    pub fn max_age(mut self, seconds: u32) -> Self {
2075        self.builder.config.cors.max_age_secs = seconds;
2076        self
2077    }
2078
2079    /// Finish CORS configuration and return to the main builder.
2080    pub fn done(self) -> AuthConfigBuilder {
2081        self.builder
2082    }
2083}
2084
2085/// Builder for audit configuration.
2086#[derive(Debug)]
2087pub struct AuditConfigBuilder {
2088    builder: AuthConfigBuilder,
2089}
2090
2091impl AuditConfigBuilder {
2092    /// Enable audit logging.
2093    pub fn enabled(mut self) -> Self {
2094        self.builder.config.audit.enabled = true;
2095        self
2096    }
2097
2098    /// Disable audit logging.
2099    pub fn disabled(mut self) -> Self {
2100        self.builder.config.audit.enabled = false;
2101        self
2102    }
2103
2104    /// Log successful authentications.
2105    pub fn log_success(mut self, enabled: bool) -> Self {
2106        self.builder.config.audit.log_success = enabled;
2107        self
2108    }
2109
2110    /// Log failed authentications.
2111    pub fn log_failures(mut self, enabled: bool) -> Self {
2112        self.builder.config.audit.log_failures = enabled;
2113        self
2114    }
2115
2116    /// Log permission checks.
2117    pub fn log_permissions(mut self, enabled: bool) -> Self {
2118        self.builder.config.audit.log_permissions = enabled;
2119        self
2120    }
2121
2122    /// Log token operations.
2123    pub fn log_tokens(mut self, enabled: bool) -> Self {
2124        self.builder.config.audit.log_tokens = enabled;
2125        self
2126    }
2127
2128    /// Finish audit configuration and return to the main builder.
2129    pub fn done(self) -> AuthConfigBuilder {
2130        self.builder
2131    }
2132}
2133
2134#[cfg(test)]
2135mod tests {
2136    use super::*;
2137
2138    #[test]
2139    fn test_validate_rejects_scrypt_password_hash_algorithm() {
2140        // PasswordHashAlgorithm::Scrypt has no implementation in this
2141        // crate. It must be rejected at validate() time (reached by both
2142        // AuthFramework::new_validated and initialize()), not only on the
2143        // first actual hash attempt deep inside UserManager -- reverting
2144        // this check must turn this test red, not leave it silently
2145        // passing on an unrelated code path.
2146        let mut config = AuthConfig::new().secret("test_secret_key_32_bytes_long!!!!".to_string());
2147        config.security.password_hash_algorithm = PasswordHashAlgorithm::Scrypt;
2148        let result = config.validate();
2149        assert!(
2150            result.is_err(),
2151            "AuthConfig::validate() must reject PasswordHashAlgorithm::Scrypt"
2152        );
2153        let message = result.unwrap_err().to_string();
2154        assert!(
2155            message.contains("Scrypt"),
2156            "the error should name the unimplemented algorithm, got: {message}"
2157        );
2158    }
2159
2160    #[test]
2161    fn test_validate_accepts_argon2_and_bcrypt() {
2162        let mut config = AuthConfig::new().secret("test_secret_key_32_bytes_long!!!!".to_string());
2163        config.security.password_hash_algorithm = PasswordHashAlgorithm::Argon2;
2164        assert!(config.validate().is_ok());
2165        config.security.password_hash_algorithm = PasswordHashAlgorithm::Bcrypt;
2166        assert!(config.validate().is_ok());
2167    }
2168}