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