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