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