1pub mod app_config;
4pub mod config_manager;
5
6pub use config_manager::{
8 AuthFrameworkSettings, ConfigBuilder, ConfigIntegration, ConfigManager, SessionCookieSettings,
9 SessionSettings,
10};
11
12use crate::errors::{AuthError, Result};
13use serde::{Deserialize, Serialize};
14use std::collections::HashMap;
15use std::time::Duration;
16
17#[derive(Clone, Serialize, Deserialize)]
19pub struct AuthConfig {
20 pub token_lifetime: Duration,
22
23 pub refresh_token_lifetime: Duration,
25
26 pub enable_multi_factor: bool,
28
29 pub issuer: String,
31
32 pub audience: String,
34
35 pub secret: Option<String>,
37
38 pub storage: StorageConfig,
40
41 pub rate_limiting: RateLimitConfig,
43
44 pub security: SecurityConfig,
46
47 pub audit: AuditConfig,
49
50 pub method_configs: HashMap<String, serde_json::Value>,
52}
53
54impl std::fmt::Debug for AuthConfig {
55 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
56 let mut d = f.debug_struct("AuthConfig");
57 d.field("token_lifetime", &self.token_lifetime);
58 d.field("refresh_token_lifetime", &self.refresh_token_lifetime);
59 d.field("enable_multi_factor", &self.enable_multi_factor);
60 d.field("issuer", &self.issuer);
61 d.field("audience", &self.audience);
62 d.field("secret", &crate::utils::redact::redacted(&self.secret));
63 d.field("storage", &self.storage);
64 d.field("rate_limiting", &self.rate_limiting);
65 d.field("security", &self.security);
66 d.field("audit", &self.audit);
67 d.field(
68 "method_configs",
69 &crate::utils::redact::redacted(&self.method_configs),
70 );
71 d.finish()
72 }
73}
74
75#[derive(Clone, Serialize, Deserialize)]
77pub enum StorageConfig {
78 Memory,
80
81 #[cfg(feature = "redis-storage")]
83 Redis { url: String, key_prefix: String },
84
85 #[cfg(feature = "postgres-storage")]
87 Postgres {
88 connection_string: String,
89 table_prefix: String,
90 },
91
92 Custom(String),
94}
95
96impl std::fmt::Debug for StorageConfig {
97 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
98 use crate::utils::redact::redacted;
99 match self {
100 Self::Memory => f.write_str("Memory"),
101 #[cfg(feature = "redis-storage")]
102 Self::Redis { url, key_prefix } => f
103 .debug_struct("Redis")
104 .field("url", &redacted(url))
105 .field("key_prefix", key_prefix)
106 .finish(),
107 #[cfg(feature = "postgres-storage")]
108 Self::Postgres {
109 connection_string,
110 table_prefix,
111 } => f
112 .debug_struct("Postgres")
113 .field("connection_string", &redacted(connection_string))
114 .field("table_prefix", table_prefix)
115 .finish(),
116 Self::Custom(name) => f.debug_tuple("Custom").field(name).finish(),
118 }
119 }
120}
121
122#[derive(Debug, Clone, Serialize, Deserialize)]
124pub struct RateLimitConfig {
125 pub enabled: bool,
127
128 pub max_requests: u32,
130
131 pub window: Duration,
133
134 pub burst: u32,
136}
137
138#[derive(Clone, Serialize, Deserialize)]
140pub struct SecurityConfig {
141 pub min_password_length: usize,
143
144 pub require_password_complexity: bool,
146
147 pub password_hash_algorithm: PasswordHashAlgorithm,
149
150 pub jwt_algorithm: JwtAlgorithm,
152
153 pub secret_key: Option<String>,
155
156 pub secure_cookies: bool,
158
159 pub cookie_same_site: CookieSameSite,
161
162 pub csrf_protection: bool,
164
165 pub session_timeout: Duration,
167}
168
169impl std::fmt::Debug for SecurityConfig {
170 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
171 let mut d = f.debug_struct("SecurityConfig");
172 d.field("min_password_length", &self.min_password_length);
173 d.field(
174 "require_password_complexity",
175 &self.require_password_complexity,
176 );
177 d.field("password_hash_algorithm", &self.password_hash_algorithm);
178 d.field("jwt_algorithm", &self.jwt_algorithm);
179 d.field(
180 "secret_key",
181 &crate::utils::redact::redacted(&self.secret_key),
182 );
183 d.field("secure_cookies", &self.secure_cookies);
184 d.field("cookie_same_site", &self.cookie_same_site);
185 d.field("csrf_protection", &self.csrf_protection);
186 d.field("session_timeout", &self.session_timeout);
187 d.finish()
188 }
189}
190
191#[derive(Debug, Clone, Serialize, Deserialize)]
193pub enum PasswordHashAlgorithm {
194 Argon2,
195 Bcrypt,
196 Scrypt,
197}
198
199#[derive(Debug, Clone, Serialize, Deserialize)]
201pub enum JwtAlgorithm {
202 HS256,
203 HS384,
204 HS512,
205 RS256,
206 RS384,
207 RS512,
208 ES256,
209 ES384,
210}
211
212#[derive(Debug, Clone, Serialize, Deserialize)]
214pub enum CookieSameSite {
215 Strict,
216 Lax,
217 None,
218}
219
220#[derive(Debug, Clone, Serialize, Deserialize)]
222pub struct AuditConfig {
223 pub enabled: bool,
225
226 pub log_success: bool,
228
229 pub log_failures: bool,
231
232 pub log_permissions: bool,
234
235 pub log_tokens: bool,
237
238 pub storage: AuditStorage,
240}
241
242#[derive(Clone, Serialize, Deserialize)]
244pub enum AuditStorage {
245 Tracing,
247
248 File { path: String },
250
251 Database { connection_string: String },
253
254 External { endpoint: String, api_key: String },
256}
257
258impl std::fmt::Debug for AuditStorage {
259 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
260 use crate::utils::redact::redacted;
261 match self {
262 Self::Tracing => f.write_str("Tracing"),
263 Self::File { path } => f.debug_struct("File").field("path", path).finish(),
264 Self::Database { connection_string } => f
265 .debug_struct("Database")
266 .field("connection_string", &redacted(connection_string))
267 .finish(),
268 Self::External { endpoint, api_key } => f
269 .debug_struct("External")
270 .field("endpoint", endpoint)
271 .field("api_key", &redacted(api_key))
272 .finish(),
273 }
274 }
275}
276
277impl Default for AuthConfig {
278 fn default() -> Self {
279 Self {
280 token_lifetime: Duration::from_secs(3600), refresh_token_lifetime: Duration::from_secs(86400 * 7), enable_multi_factor: false,
283 issuer: "auth-framework".to_string(),
284 audience: "api".to_string(),
285 secret: None,
286 storage: StorageConfig::Memory,
287 rate_limiting: RateLimitConfig::default(),
288 security: SecurityConfig::default(),
289 audit: AuditConfig::default(),
290 method_configs: HashMap::new(),
291 }
292 }
293}
294
295impl Default for RateLimitConfig {
296 fn default() -> Self {
297 Self {
298 enabled: true,
299 max_requests: 100,
300 window: Duration::from_secs(60), burst: 10,
302 }
303 }
304}
305
306impl Default for SecurityConfig {
307 fn default() -> Self {
308 Self {
309 min_password_length: 8,
310 require_password_complexity: true,
311 password_hash_algorithm: PasswordHashAlgorithm::Argon2,
312 jwt_algorithm: JwtAlgorithm::HS256,
313 secret_key: None,
314 secure_cookies: true,
315 cookie_same_site: CookieSameSite::Lax,
316 csrf_protection: true,
317 session_timeout: Duration::from_secs(3600 * 24), }
319 }
320}
321
322impl Default for AuditConfig {
323 fn default() -> Self {
324 Self {
325 enabled: true,
326 log_success: true,
327 log_failures: true,
328 log_permissions: true,
329 log_tokens: false, storage: AuditStorage::Tracing,
331 }
332 }
333}
334
335impl AuthConfig {
336 pub fn new() -> Self {
338 Self::default()
339 }
340
341 pub fn token_lifetime(mut self, lifetime: Duration) -> Self {
343 self.token_lifetime = lifetime;
344 self
345 }
346
347 pub fn refresh_token_lifetime(mut self, lifetime: Duration) -> Self {
349 self.refresh_token_lifetime = lifetime;
350 self
351 }
352
353 pub fn enable_multi_factor(mut self, enabled: bool) -> Self {
355 self.enable_multi_factor = enabled;
356 self
357 }
358
359 pub fn issuer(mut self, issuer: impl Into<String>) -> Self {
361 self.issuer = issuer.into();
362 self
363 }
364
365 pub fn audience(mut self, audience: impl Into<String>) -> Self {
367 self.audience = audience.into();
368 self
369 }
370
371 pub fn secret(mut self, secret: impl Into<String>) -> Self {
373 self.secret = Some(secret.into());
374 self
375 }
376
377 pub fn require_mfa(mut self, required: bool) -> Self {
379 self.enable_multi_factor = required;
380 self
381 }
382
383 pub fn enable_caching(self, _enabled: bool) -> Self {
385 self
387 }
388
389 pub fn max_failed_attempts(self, _max: u32) -> Self {
391 self
393 }
394
395 pub fn enable_rbac(self, _enabled: bool) -> Self {
397 self
399 }
400
401 pub fn enable_security_audit(self, _enabled: bool) -> Self {
403 self
405 }
406
407 pub fn enable_middleware(self, _enabled: bool) -> Self {
409 self
411 }
412
413 pub fn storage(mut self, storage: StorageConfig) -> Self {
415 self.storage = storage;
416 self
417 }
418
419 #[cfg(feature = "redis-storage")]
421 pub fn redis_storage(mut self, url: impl Into<String>) -> Self {
422 self.storage = StorageConfig::Redis {
423 url: url.into(),
424 key_prefix: "auth:".to_string(),
425 };
426 self
427 }
428
429 pub fn rate_limiting(mut self, config: RateLimitConfig) -> Self {
431 self.rate_limiting = config;
432 self
433 }
434
435 pub fn security(mut self, config: SecurityConfig) -> Self {
437 self.security = config;
438 self
439 }
440
441 pub fn audit(mut self, config: AuditConfig) -> Self {
443 self.audit = config;
444 self
445 }
446
447 pub fn method_config(
449 mut self,
450 method_name: impl Into<String>,
451 config: impl Serialize,
452 ) -> Result<Self> {
453 let value = serde_json::to_value(config)
454 .map_err(|e| AuthError::config(format!("Failed to serialize method config: {e}")))?;
455
456 self.method_configs.insert(method_name.into(), value);
457 Ok(self)
458 }
459
460 pub fn get_method_config<T>(&self, method_name: &str) -> Result<Option<T>>
462 where
463 T: for<'de> Deserialize<'de>,
464 {
465 if let Some(value) = self.method_configs.get(method_name) {
466 let config = serde_json::from_value(value.clone()).map_err(|e| {
467 AuthError::config(format!("Failed to deserialize method config: {e}"))
468 })?;
469 Ok(Some(config))
470 } else {
471 Ok(None)
472 }
473 }
474
475 pub fn validate(&self) -> Result<()> {
477 if self.token_lifetime.as_secs() == 0 {
479 return Err(AuthError::config("Token lifetime must be greater than 0"));
480 }
481
482 if self.refresh_token_lifetime.as_secs() == 0 {
483 return Err(AuthError::config(
484 "Refresh token lifetime must be greater than 0",
485 ));
486 }
487
488 if self.refresh_token_lifetime <= self.token_lifetime {
489 return Err(AuthError::config(
490 "Refresh token lifetime must be greater than token lifetime",
491 ));
492 }
493
494 self.validate_jwt_secret()?;
496
497 if self.security.min_password_length < 4 {
499 return Err(AuthError::config(
500 "Minimum password length must be at least 4 characters",
501 ));
502 }
503
504 if self.is_production_environment() && !self.is_test_environment() {
506 self.validate_production_security()?;
507 }
508
509 if self.rate_limiting.enabled && self.rate_limiting.max_requests == 0 {
511 return Err(AuthError::config(
512 "Rate limit max requests must be greater than 0 when enabled",
513 ));
514 }
515
516 self.validate_storage_config()?;
518
519 Ok(())
520 }
521
522 fn validate_jwt_secret(&self) -> Result<()> {
524 let env_secret = std::env::var("JWT_SECRET").ok();
526 let jwt_secret = self
527 .security
528 .secret_key
529 .as_ref()
530 .or(self.secret.as_ref())
531 .or(env_secret.as_ref());
532
533 if let Some(secret) = jwt_secret {
534 if secret.len() < 32 {
535 return Err(AuthError::config(
536 "JWT secret must be at least 32 characters for security. \
537 Generate with: openssl rand -base64 32",
538 ));
539 }
540
541 if !self.is_test_environment()
543 && (secret.contains("secret")
544 || secret.contains("password")
545 || secret.contains("123"))
546 {
547 return Err(AuthError::config(
548 "JWT secret appears to contain common words or patterns. \
549 Use a cryptographically secure random string.",
550 ));
551 }
552
553 if secret.len() < 44
555 && secret
556 .chars()
557 .all(|c| c.is_alphanumeric() || c == '+' || c == '/' || c == '=')
558 {
559 tracing::warn!(
560 "JWT secret may be too short for optimal security. \
561 Consider using at least 44 characters (32 bytes base64-encoded)."
562 );
563 }
564 } else if self.is_production_environment() {
565 return Err(AuthError::config(
566 "JWT secret is required for production environments. \
567 Set JWT_SECRET environment variable or configure security.secret_key",
568 ));
569 }
570
571 Ok(())
572 }
573
574 fn validate_production_security(&self) -> Result<()> {
576 if self.security.min_password_length < 8 {
578 return Err(AuthError::config(
579 "Production environments require minimum password length of 8 characters",
580 ));
581 }
582
583 if !self.security.require_password_complexity {
584 tracing::warn!("Production deployment should enable password complexity requirements");
585 }
586
587 if !self.security.secure_cookies {
589 return Err(AuthError::config(
590 "Production environments must use secure cookies (HTTPS required)",
591 ));
592 }
593
594 if !self.rate_limiting.enabled {
596 tracing::warn!("Production deployment should enable rate limiting for security");
597 }
598
599 if !self.audit.enabled {
601 return Err(AuthError::config(
602 "Production environments require audit logging for compliance",
603 ));
604 }
605
606 Ok(())
607 }
608
609 fn validate_storage_config(&self) -> Result<()> {
611 match &self.storage {
612 StorageConfig::Memory
613 if self.is_production_environment() && !self.is_test_environment() =>
614 {
615 return Err(AuthError::config(
616 "Memory storage is not suitable for production environments. \
617 Use PostgreSQL or Redis storage.",
618 ));
619 }
620 _ => {} }
622
623 Ok(())
624 }
625
626 fn is_production_environment(&self) -> bool {
628 if let Ok(env) = std::env::var("ENVIRONMENT")
630 && (env.to_lowercase() == "production" || env.to_lowercase() == "prod")
631 {
632 return true;
633 }
634
635 if let Ok(env) = std::env::var("ENV")
636 && (env.to_lowercase() == "production" || env.to_lowercase() == "prod")
637 {
638 return true;
639 }
640
641 if let Ok(env) = std::env::var("NODE_ENV")
642 && env.to_lowercase() == "production"
643 {
644 return true;
645 }
646
647 if let Ok(env) = std::env::var("RUST_ENV")
648 && env.to_lowercase() == "production"
649 {
650 return true;
651 }
652
653 if std::env::var("KUBERNETES_SERVICE_HOST").is_ok() {
655 return true;
656 }
657
658 if std::env::var("DOCKER_CONTAINER").is_ok() {
659 return true;
660 }
661
662 false
663 }
664
665 fn is_test_environment(&self) -> bool {
667 cfg!(test)
669 || std::thread::current()
670 .name()
671 .is_some_and(|name| name.contains("test"))
672 || std::env::var("RUST_TEST").is_ok()
673 || std::env::var("ENVIRONMENT").as_deref() == Ok("test")
674 || std::env::var("ENV").as_deref() == Ok("test")
675 || std::env::args().any(|arg| arg.contains("test"))
676 }
677}
678
679impl RateLimitConfig {
680 pub fn new(max_requests: u32, window: Duration) -> Self {
682 Self {
683 enabled: true,
684 max_requests,
685 window,
686 burst: max_requests / 10, }
688 }
689
690 pub fn disabled() -> Self {
692 Self {
693 enabled: false,
694 ..Default::default()
695 }
696 }
697}
698
699impl SecurityConfig {
700 pub fn secure() -> Self {
702 Self {
703 min_password_length: 12,
704 require_password_complexity: true,
705 password_hash_algorithm: PasswordHashAlgorithm::Argon2,
706 jwt_algorithm: JwtAlgorithm::RS256,
707 secret_key: None,
708 secure_cookies: true,
709 cookie_same_site: CookieSameSite::Strict,
710 csrf_protection: true,
711 session_timeout: Duration::from_secs(3600 * 8), }
713 }
714
715 pub fn development() -> Self {
719 Self {
720 min_password_length: 6,
721 require_password_complexity: false,
722 password_hash_algorithm: PasswordHashAlgorithm::Bcrypt,
723 jwt_algorithm: JwtAlgorithm::HS256,
724 secret_key: None, secure_cookies: false,
726 cookie_same_site: CookieSameSite::Lax,
727 csrf_protection: false,
728 session_timeout: Duration::from_secs(3600 * 24), }
730 }
731}