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(Debug, 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
54#[derive(Debug, Clone, Serialize, Deserialize)]
56pub enum StorageConfig {
57 Memory,
59
60 #[cfg(feature = "redis-storage")]
62 Redis { url: String, key_prefix: String },
63
64 #[cfg(feature = "postgres-storage")]
66 Postgres {
67 connection_string: String,
68 table_prefix: String,
69 },
70
71 Custom(String),
73}
74
75#[derive(Debug, Clone, Serialize, Deserialize)]
77pub struct RateLimitConfig {
78 pub enabled: bool,
80
81 pub max_requests: u32,
83
84 pub window: Duration,
86
87 pub burst: u32,
89}
90
91#[derive(Debug, Clone, Serialize, Deserialize)]
93pub struct SecurityConfig {
94 pub min_password_length: usize,
96
97 pub require_password_complexity: bool,
99
100 pub password_hash_algorithm: PasswordHashAlgorithm,
102
103 pub jwt_algorithm: JwtAlgorithm,
105
106 pub secret_key: Option<String>,
108
109 pub secure_cookies: bool,
111
112 pub cookie_same_site: CookieSameSite,
114
115 pub csrf_protection: bool,
117
118 pub session_timeout: Duration,
120}
121
122#[derive(Debug, Clone, Serialize, Deserialize)]
124pub enum PasswordHashAlgorithm {
125 Argon2,
126 Bcrypt,
127 Scrypt,
128}
129
130#[derive(Debug, Clone, Serialize, Deserialize)]
132pub enum JwtAlgorithm {
133 HS256,
134 HS384,
135 HS512,
136 RS256,
137 RS384,
138 RS512,
139 ES256,
140 ES384,
141}
142
143#[derive(Debug, Clone, Serialize, Deserialize)]
145pub enum CookieSameSite {
146 Strict,
147 Lax,
148 None,
149}
150
151#[derive(Debug, Clone, Serialize, Deserialize)]
153pub struct AuditConfig {
154 pub enabled: bool,
156
157 pub log_success: bool,
159
160 pub log_failures: bool,
162
163 pub log_permissions: bool,
165
166 pub log_tokens: bool,
168
169 pub storage: AuditStorage,
171}
172
173#[derive(Debug, Clone, Serialize, Deserialize)]
175pub enum AuditStorage {
176 Tracing,
178
179 File { path: String },
181
182 Database { connection_string: String },
184
185 External { endpoint: String, api_key: String },
187}
188
189impl Default for AuthConfig {
190 fn default() -> Self {
191 Self {
192 token_lifetime: Duration::from_secs(3600), refresh_token_lifetime: Duration::from_secs(86400 * 7), enable_multi_factor: false,
195 issuer: "auth-framework".to_string(),
196 audience: "api".to_string(),
197 secret: None,
198 storage: StorageConfig::Memory,
199 rate_limiting: RateLimitConfig::default(),
200 security: SecurityConfig::default(),
201 audit: AuditConfig::default(),
202 method_configs: HashMap::new(),
203 }
204 }
205}
206
207impl Default for RateLimitConfig {
208 fn default() -> Self {
209 Self {
210 enabled: true,
211 max_requests: 100,
212 window: Duration::from_secs(60), burst: 10,
214 }
215 }
216}
217
218impl Default for SecurityConfig {
219 fn default() -> Self {
220 Self {
221 min_password_length: 8,
222 require_password_complexity: true,
223 password_hash_algorithm: PasswordHashAlgorithm::Argon2,
224 jwt_algorithm: JwtAlgorithm::HS256,
225 secret_key: None,
226 secure_cookies: true,
227 cookie_same_site: CookieSameSite::Lax,
228 csrf_protection: true,
229 session_timeout: Duration::from_secs(3600 * 24), }
231 }
232}
233
234impl Default for AuditConfig {
235 fn default() -> Self {
236 Self {
237 enabled: true,
238 log_success: true,
239 log_failures: true,
240 log_permissions: true,
241 log_tokens: false, storage: AuditStorage::Tracing,
243 }
244 }
245}
246
247impl AuthConfig {
248 pub fn new() -> Self {
250 Self::default()
251 }
252
253 pub fn token_lifetime(mut self, lifetime: Duration) -> Self {
255 self.token_lifetime = lifetime;
256 self
257 }
258
259 pub fn refresh_token_lifetime(mut self, lifetime: Duration) -> Self {
261 self.refresh_token_lifetime = lifetime;
262 self
263 }
264
265 pub fn enable_multi_factor(mut self, enabled: bool) -> Self {
267 self.enable_multi_factor = enabled;
268 self
269 }
270
271 pub fn issuer(mut self, issuer: impl Into<String>) -> Self {
273 self.issuer = issuer.into();
274 self
275 }
276
277 pub fn audience(mut self, audience: impl Into<String>) -> Self {
279 self.audience = audience.into();
280 self
281 }
282
283 pub fn secret(mut self, secret: impl Into<String>) -> Self {
285 self.secret = Some(secret.into());
286 self
287 }
288
289 pub fn require_mfa(mut self, required: bool) -> Self {
291 self.enable_multi_factor = required;
292 self
293 }
294
295 pub fn enable_caching(self, _enabled: bool) -> Self {
297 self
299 }
300
301 pub fn max_failed_attempts(self, _max: u32) -> Self {
303 self
305 }
306
307 pub fn enable_rbac(self, _enabled: bool) -> Self {
309 self
311 }
312
313 pub fn enable_security_audit(self, _enabled: bool) -> Self {
315 self
317 }
318
319 pub fn enable_middleware(self, _enabled: bool) -> Self {
321 self
323 }
324
325 pub fn storage(mut self, storage: StorageConfig) -> Self {
327 self.storage = storage;
328 self
329 }
330
331 #[cfg(feature = "redis-storage")]
333 pub fn redis_storage(mut self, url: impl Into<String>) -> Self {
334 self.storage = StorageConfig::Redis {
335 url: url.into(),
336 key_prefix: "auth:".to_string(),
337 };
338 self
339 }
340
341 pub fn rate_limiting(mut self, config: RateLimitConfig) -> Self {
343 self.rate_limiting = config;
344 self
345 }
346
347 pub fn security(mut self, config: SecurityConfig) -> Self {
349 self.security = config;
350 self
351 }
352
353 pub fn audit(mut self, config: AuditConfig) -> Self {
355 self.audit = config;
356 self
357 }
358
359 pub fn method_config(
361 mut self,
362 method_name: impl Into<String>,
363 config: impl Serialize,
364 ) -> Result<Self> {
365 let value = serde_json::to_value(config)
366 .map_err(|e| AuthError::config(format!("Failed to serialize method config: {e}")))?;
367
368 self.method_configs.insert(method_name.into(), value);
369 Ok(self)
370 }
371
372 pub fn get_method_config<T>(&self, method_name: &str) -> Result<Option<T>>
374 where
375 T: for<'de> Deserialize<'de>,
376 {
377 if let Some(value) = self.method_configs.get(method_name) {
378 let config = serde_json::from_value(value.clone()).map_err(|e| {
379 AuthError::config(format!("Failed to deserialize method config: {e}"))
380 })?;
381 Ok(Some(config))
382 } else {
383 Ok(None)
384 }
385 }
386
387 pub fn validate(&self) -> Result<()> {
389 if self.token_lifetime.as_secs() == 0 {
391 return Err(AuthError::config("Token lifetime must be greater than 0"));
392 }
393
394 if self.refresh_token_lifetime.as_secs() == 0 {
395 return Err(AuthError::config(
396 "Refresh token lifetime must be greater than 0",
397 ));
398 }
399
400 if self.refresh_token_lifetime <= self.token_lifetime {
401 return Err(AuthError::config(
402 "Refresh token lifetime must be greater than token lifetime",
403 ));
404 }
405
406 self.validate_jwt_secret()?;
408
409 if self.security.min_password_length < 4 {
411 return Err(AuthError::config(
412 "Minimum password length must be at least 4 characters",
413 ));
414 }
415
416 if self.is_production_environment() && !self.is_test_environment() {
418 self.validate_production_security()?;
419 }
420
421 if self.rate_limiting.enabled && self.rate_limiting.max_requests == 0 {
423 return Err(AuthError::config(
424 "Rate limit max requests must be greater than 0 when enabled",
425 ));
426 }
427
428 self.validate_storage_config()?;
430
431 Ok(())
432 }
433
434 fn validate_jwt_secret(&self) -> Result<()> {
436 let env_secret = std::env::var("JWT_SECRET").ok();
438 let jwt_secret = self
439 .security
440 .secret_key
441 .as_ref()
442 .or(self.secret.as_ref())
443 .or(env_secret.as_ref());
444
445 if let Some(secret) = jwt_secret {
446 if secret.len() < 32 {
447 return Err(AuthError::config(
448 "JWT secret must be at least 32 characters for security. \
449 Generate with: openssl rand -base64 32",
450 ));
451 }
452
453 if !self.is_test_environment()
455 && (secret.contains("secret")
456 || secret.contains("password")
457 || secret.contains("123"))
458 {
459 return Err(AuthError::config(
460 "JWT secret appears to contain common words or patterns. \
461 Use a cryptographically secure random string.",
462 ));
463 }
464
465 if secret.len() < 44
467 && secret
468 .chars()
469 .all(|c| c.is_alphanumeric() || c == '+' || c == '/' || c == '=')
470 {
471 tracing::warn!(
472 "JWT secret may be too short for optimal security. \
473 Consider using at least 44 characters (32 bytes base64-encoded)."
474 );
475 }
476 } else if self.is_production_environment() {
477 return Err(AuthError::config(
478 "JWT secret is required for production environments. \
479 Set JWT_SECRET environment variable or configure security.secret_key",
480 ));
481 }
482
483 Ok(())
484 }
485
486 fn validate_production_security(&self) -> Result<()> {
488 if self.security.min_password_length < 8 {
490 return Err(AuthError::config(
491 "Production environments require minimum password length of 8 characters",
492 ));
493 }
494
495 if !self.security.require_password_complexity {
496 tracing::warn!("Production deployment should enable password complexity requirements");
497 }
498
499 if !self.security.secure_cookies {
501 return Err(AuthError::config(
502 "Production environments must use secure cookies (HTTPS required)",
503 ));
504 }
505
506 if !self.rate_limiting.enabled {
508 tracing::warn!("Production deployment should enable rate limiting for security");
509 }
510
511 if !self.audit.enabled {
513 return Err(AuthError::config(
514 "Production environments require audit logging for compliance",
515 ));
516 }
517
518 Ok(())
519 }
520
521 fn validate_storage_config(&self) -> Result<()> {
523 match &self.storage {
524 StorageConfig::Memory
525 if self.is_production_environment() && !self.is_test_environment() =>
526 {
527 return Err(AuthError::config(
528 "Memory storage is not suitable for production environments. \
529 Use PostgreSQL or Redis storage.",
530 ));
531 }
532 _ => {} }
534
535 Ok(())
536 }
537
538 fn is_production_environment(&self) -> bool {
540 if let Ok(env) = std::env::var("ENVIRONMENT")
542 && (env.to_lowercase() == "production" || env.to_lowercase() == "prod")
543 {
544 return true;
545 }
546
547 if let Ok(env) = std::env::var("ENV")
548 && (env.to_lowercase() == "production" || env.to_lowercase() == "prod")
549 {
550 return true;
551 }
552
553 if let Ok(env) = std::env::var("NODE_ENV")
554 && env.to_lowercase() == "production"
555 {
556 return true;
557 }
558
559 if let Ok(env) = std::env::var("RUST_ENV")
560 && env.to_lowercase() == "production"
561 {
562 return true;
563 }
564
565 if std::env::var("KUBERNETES_SERVICE_HOST").is_ok() {
567 return true;
568 }
569
570 if std::env::var("DOCKER_CONTAINER").is_ok() {
571 return true;
572 }
573
574 false
575 }
576
577 fn is_test_environment(&self) -> bool {
579 cfg!(test)
581 || std::thread::current()
582 .name()
583 .is_some_and(|name| name.contains("test"))
584 || std::env::var("RUST_TEST").is_ok()
585 || std::env::var("ENVIRONMENT").as_deref() == Ok("test")
586 || std::env::var("ENV").as_deref() == Ok("test")
587 || std::env::args().any(|arg| arg.contains("test"))
588 }
589}
590
591impl RateLimitConfig {
592 pub fn new(max_requests: u32, window: Duration) -> Self {
594 Self {
595 enabled: true,
596 max_requests,
597 window,
598 burst: max_requests / 10, }
600 }
601
602 pub fn disabled() -> Self {
604 Self {
605 enabled: false,
606 ..Default::default()
607 }
608 }
609}
610
611impl SecurityConfig {
612 pub fn secure() -> Self {
614 Self {
615 min_password_length: 12,
616 require_password_complexity: true,
617 password_hash_algorithm: PasswordHashAlgorithm::Argon2,
618 jwt_algorithm: JwtAlgorithm::RS256,
619 secret_key: None,
620 secure_cookies: true,
621 cookie_same_site: CookieSameSite::Strict,
622 csrf_protection: true,
623 session_timeout: Duration::from_secs(3600 * 8), }
625 }
626
627 pub fn development() -> Self {
631 Self {
632 min_password_length: 6,
633 require_password_complexity: false,
634 password_hash_algorithm: PasswordHashAlgorithm::Bcrypt,
635 jwt_algorithm: JwtAlgorithm::HS256,
636 secret_key: None, secure_cookies: false,
638 cookie_same_site: CookieSameSite::Lax,
639 csrf_protection: false,
640 session_timeout: Duration::from_secs(3600 * 24), }
642 }
643}