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