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