1pub mod app_config;
4pub mod config_manager;
5
6pub 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;
17
18#[derive(Debug, Clone, Serialize, Deserialize)]
20#[serde(default)]
21pub struct AuthConfig {
22 pub token_lifetime: Duration,
24
25 pub refresh_token_lifetime: Duration,
27
28 pub enable_multi_factor: bool,
30
31 pub issuer: String,
33
34 pub audience: String,
36
37 pub secret: Option<String>,
39
40 pub storage: StorageConfig,
42
43 pub rate_limiting: RateLimitConfig,
45
46 pub security: SecurityConfig,
48
49 #[serde(default)]
51 pub cors: CorsConfig,
52
53 pub audit: AuditConfig,
55
56 #[serde(default)]
58 pub enable_caching: bool,
59
60 #[serde(default = "default_max_failed_attempts")]
62 pub max_failed_attempts: u32,
63
64 #[serde(default)]
66 pub enable_rbac: bool,
67
68 #[serde(default)]
70 pub enable_middleware: bool,
71
72 pub method_configs: HashMap<String, serde_json::Value>,
74
75 #[serde(default)]
78 pub force_production_mode: bool,
79}
80
81#[derive(Debug, Clone, Serialize, Deserialize)]
83pub enum StorageConfig {
84 Memory,
86
87 #[cfg(feature = "redis-storage")]
89 Redis { url: String, key_prefix: String },
90
91 #[cfg(feature = "postgres-storage")]
93 Postgres {
94 connection_string: String,
95 table_prefix: String,
96 },
97
98 #[cfg(feature = "sqlite-storage")]
100 Sqlite { connection_string: String },
101
102 Custom(String),
104}
105
106#[derive(Debug, Clone, Serialize, Deserialize)]
112#[serde(default)]
113pub struct RateLimitConfig {
114 pub enabled: bool,
116
117 pub max_requests: u32,
119
120 pub window: Duration,
122
123 pub burst: u32,
125}
126
127#[derive(Debug, Clone, Serialize, Deserialize)]
139#[serde(default)]
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 previous_secret_key: Option<String>,
158
159 pub secure_cookies: bool,
161
162 pub cookie_same_site: CookieSameSite,
164
165 pub csrf_protection: bool,
167
168 pub session_timeout: Duration,
170}
171
172#[derive(Debug, Clone, Serialize, Deserialize)]
174pub enum PasswordHashAlgorithm {
175 Argon2,
177 Bcrypt,
179 Scrypt,
181}
182
183#[derive(Debug, Clone, Serialize, Deserialize)]
185pub enum JwtAlgorithm {
186 HS256,
188 HS384,
190 HS512,
192 RS256,
194 RS384,
196 RS512,
198 ES256,
200 ES384,
202}
203
204#[derive(Debug, Clone, Serialize, Deserialize)]
206pub enum CookieSameSite {
207 Strict,
209 Lax,
211 None,
213}
214
215#[derive(Debug, Clone, Serialize, Deserialize)]
221#[serde(default)]
222pub struct CorsConfig {
223 pub enabled: bool,
225
226 pub allowed_origins: Vec<String>,
231
232 pub allowed_methods: Vec<String>,
234
235 pub allowed_headers: Vec<String>,
237
238 pub max_age_secs: u32,
240}
241
242impl Default for CorsConfig {
243 fn default() -> Self {
244 Self {
245 enabled: false,
246 allowed_origins: Vec::new(),
247 allowed_methods: vec![
248 "GET".to_string(),
249 "POST".to_string(),
250 "PUT".to_string(),
251 "DELETE".to_string(),
252 "OPTIONS".to_string(),
253 ],
254 allowed_headers: vec![
255 "Authorization".to_string(),
256 "Content-Type".to_string(),
257 "Accept".to_string(),
258 ],
259 max_age_secs: 3600,
260 }
261 }
262}
263
264impl CorsConfig {
265 pub fn for_origins<I, S>(origins: I) -> Self
276 where
277 I: IntoIterator<Item = S>,
278 S: Into<String>,
279 {
280 Self {
281 enabled: true,
282 allowed_origins: origins.into_iter().map(Into::into).collect(),
283 ..Default::default()
284 }
285 }
286}
287
288#[derive(Debug, Clone, Serialize, Deserialize)]
293#[serde(default)]
294pub struct AuditConfig {
295 pub enabled: bool,
297
298 pub log_success: bool,
300
301 pub log_failures: bool,
303
304 pub log_permissions: bool,
306
307 pub log_tokens: bool,
309
310 pub storage: AuditStorage,
312}
313
314#[derive(Debug, Clone, Serialize, Deserialize)]
318pub enum AuditStorage {
319 Tracing,
321
322 File { path: String },
324
325 Database { connection_string: String },
327
328 External { endpoint: String, api_key: String },
330}
331
332const fn default_max_failed_attempts() -> u32 {
333 5
334}
335
336impl Default for AuthConfig {
337 fn default() -> Self {
338 Self {
339 token_lifetime: Duration::from_secs(3600), refresh_token_lifetime: Duration::from_secs(86400 * 7), enable_multi_factor: false,
342 issuer: "auth-framework".to_string(),
343 audience: "api".to_string(),
344 secret: None,
345 storage: StorageConfig::Memory,
346 rate_limiting: RateLimitConfig::default(),
347 security: SecurityConfig::default(),
348 cors: CorsConfig::default(),
349 audit: AuditConfig::default(),
350 enable_caching: false,
351 max_failed_attempts: default_max_failed_attempts(),
352 enable_rbac: false,
353 enable_middleware: false,
354 method_configs: HashMap::new(),
355 force_production_mode: false,
356 }
357 }
358}
359
360impl Default for RateLimitConfig {
361 fn default() -> Self {
362 Self {
363 enabled: true,
364 max_requests: 100,
365 window: Duration::from_secs(60), burst: 10,
367 }
368 }
369}
370
371impl Default for SecurityConfig {
372 fn default() -> Self {
373 Self {
374 min_password_length: 8,
375 require_password_complexity: true,
376 password_hash_algorithm: PasswordHashAlgorithm::Argon2,
377 jwt_algorithm: JwtAlgorithm::HS256,
378 secret_key: None,
379 previous_secret_key: None,
380 secure_cookies: true,
381 cookie_same_site: CookieSameSite::Lax,
382 csrf_protection: true,
383 session_timeout: Duration::from_secs(3600 * 24), }
385 }
386}
387
388impl Default for AuditConfig {
389 fn default() -> Self {
390 Self {
391 enabled: true,
392 log_success: true,
393 log_failures: true,
394 log_permissions: true,
395 log_tokens: false, storage: AuditStorage::Tracing,
397 }
398 }
399}
400
401impl std::fmt::Display for AuthConfig {
406 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
407 write!(
408 f,
409 "AuthConfig {{ tokens: {}s/{}s refresh, storage: {}, mfa: {}, rbac: {}, rate_limit: {}, security: {}, cors: {}, audit: {} }}",
410 self.token_lifetime.as_secs(),
411 self.refresh_token_lifetime.as_secs(),
412 self.storage,
413 if self.enable_multi_factor {
414 "on"
415 } else {
416 "off"
417 },
418 if self.enable_rbac { "on" } else { "off" },
419 self.rate_limiting,
420 self.security,
421 self.cors,
422 self.audit,
423 )
424 }
425}
426
427impl std::fmt::Display for StorageConfig {
428 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
429 match self {
430 Self::Memory => write!(f, "memory"),
431 #[cfg(feature = "redis-storage")]
432 Self::Redis { url, .. } => write!(f, "redis({})", url),
433 #[cfg(feature = "postgres-storage")]
434 Self::Postgres { .. } => write!(f, "postgres"),
435 #[cfg(feature = "sqlite-storage")]
436 Self::Sqlite { .. } => write!(f, "sqlite"),
437 Self::Custom(name) => write!(f, "custom({})", name),
438 }
439 }
440}
441
442impl std::fmt::Display for SecurityConfig {
443 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
444 write!(
445 f,
446 "Security {{ pw≥{}, hash: {}, jwt: {}, cookies: {}, csrf: {}, session: {}s }}",
447 self.min_password_length,
448 self.password_hash_algorithm,
449 self.jwt_algorithm,
450 if self.secure_cookies {
451 "secure"
452 } else {
453 "plain"
454 },
455 if self.csrf_protection { "on" } else { "off" },
456 self.session_timeout.as_secs(),
457 )
458 }
459}
460
461impl std::fmt::Display for PasswordHashAlgorithm {
462 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
463 match self {
464 Self::Argon2 => write!(f, "argon2id"),
465 Self::Bcrypt => write!(f, "bcrypt"),
466 Self::Scrypt => write!(f, "scrypt"),
467 }
468 }
469}
470
471impl std::fmt::Display for JwtAlgorithm {
472 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
473 match self {
474 Self::HS256 => write!(f, "HS256"),
475 Self::HS384 => write!(f, "HS384"),
476 Self::HS512 => write!(f, "HS512"),
477 Self::RS256 => write!(f, "RS256"),
478 Self::RS384 => write!(f, "RS384"),
479 Self::RS512 => write!(f, "RS512"),
480 Self::ES256 => write!(f, "ES256"),
481 Self::ES384 => write!(f, "ES384"),
482 }
483 }
484}
485
486impl std::fmt::Display for RateLimitConfig {
487 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
488 if self.enabled {
489 write!(
490 f,
491 "{} req/{}s (burst {})",
492 self.max_requests,
493 self.window.as_secs(),
494 self.burst,
495 )
496 } else {
497 write!(f, "disabled")
498 }
499 }
500}
501
502impl std::fmt::Display for CorsConfig {
503 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
504 if self.enabled {
505 if self.allowed_origins.is_empty() {
506 write!(f, "cors(no origins)")
507 } else {
508 write!(f, "cors({})", self.allowed_origins.join(", "))
509 }
510 } else {
511 write!(f, "cors(off)")
512 }
513 }
514}
515
516impl std::fmt::Display for AuditConfig {
517 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
518 if self.enabled {
519 write!(f, "audit({})", self.storage)
520 } else {
521 write!(f, "audit(off)")
522 }
523 }
524}
525
526impl std::fmt::Display for AuditStorage {
527 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
528 match self {
529 Self::Tracing => write!(f, "tracing"),
530 Self::File { path } => write!(f, "file:{}", path),
531 Self::Database { .. } => write!(f, "database"),
532 Self::External { endpoint, .. } => write!(f, "external:{}", endpoint),
533 }
534 }
535}
536
537#[derive(Debug, Clone, Serialize, Deserialize)]
543pub struct RuntimeConfig {
544 pub token_lifetime_secs: u64,
546 pub refresh_token_lifetime_secs: u64,
548 pub enable_multi_factor: bool,
550 pub rate_limiting_enabled: bool,
552 pub rate_limit_max_requests: u32,
554 pub rate_limit_window_secs: u64,
556 pub rate_limit_burst: u32,
558 pub min_password_length: usize,
560 pub require_password_complexity: bool,
562 pub secure_cookies: bool,
564 pub csrf_protection: bool,
566 pub session_timeout_secs: u64,
568 pub audit_enabled: bool,
570 pub audit_log_success: bool,
572 pub audit_log_failures: bool,
574 pub audit_log_permissions: bool,
576 pub audit_log_tokens: bool,
578}
579
580impl RuntimeConfig {
581 pub fn from_auth_config(cfg: &AuthConfig) -> Self {
593 Self {
594 token_lifetime_secs: cfg.token_lifetime.as_secs(),
595 refresh_token_lifetime_secs: cfg.refresh_token_lifetime.as_secs(),
596 enable_multi_factor: cfg.enable_multi_factor,
597 rate_limiting_enabled: cfg.rate_limiting.enabled,
598 rate_limit_max_requests: cfg.rate_limiting.max_requests,
599 rate_limit_window_secs: cfg.rate_limiting.window.as_secs(),
600 rate_limit_burst: cfg.rate_limiting.burst,
601 min_password_length: cfg.security.min_password_length,
602 require_password_complexity: cfg.security.require_password_complexity,
603 secure_cookies: cfg.security.secure_cookies,
604 csrf_protection: cfg.security.csrf_protection,
605 session_timeout_secs: cfg.security.session_timeout.as_secs(),
606 audit_enabled: cfg.audit.enabled,
607 audit_log_success: cfg.audit.log_success,
608 audit_log_failures: cfg.audit.log_failures,
609 audit_log_permissions: cfg.audit.log_permissions,
610 audit_log_tokens: cfg.audit.log_tokens,
611 }
612 }
613}
614
615impl Default for RuntimeConfig {
616 fn default() -> Self {
617 Self::from_auth_config(&AuthConfig::default())
618 }
619}
620
621impl AuthConfig {
622 pub fn new() -> Self {
654 Self::default()
655 }
656
657 pub fn from_env() -> Self {
681 let mut config = Self::default();
682
683 if let Ok(secret) = std::env::var("JWT_SECRET") {
684 config.secret = Some(secret.clone());
685 config.security.secret_key = Some(secret);
686 }
687
688 if let Ok(issuer) = std::env::var("AUTH_ISSUER") {
689 config.issuer = issuer;
690 }
691
692 if let Ok(audience) = std::env::var("AUTH_AUDIENCE") {
693 config.audience = audience;
694 }
695
696 #[cfg(feature = "postgres-storage")]
698 if let Ok(url) = std::env::var("DATABASE_URL") {
699 config.storage = StorageConfig::Postgres {
700 connection_string: url,
701 table_prefix: "auth_".to_string(),
702 };
703 }
704
705 #[cfg(feature = "redis-storage")]
706 if matches!(config.storage, StorageConfig::Memory)
707 && let Ok(url) = std::env::var("REDIS_URL")
708 {
709 config.storage = StorageConfig::Redis {
710 url,
711 key_prefix: "auth:".to_string(),
712 };
713 }
714
715 config
716 }
717
718 pub fn builder() -> crate::builders::AuthBuilder {
740 crate::builders::AuthBuilder::new()
741 }
742
743 pub fn token_lifetime(mut self, lifetime: Duration) -> Self {
755 self.token_lifetime = lifetime;
756 self
757 }
758
759 pub fn refresh_token_lifetime(mut self, lifetime: Duration) -> Self {
771 self.refresh_token_lifetime = lifetime;
772 self
773 }
774
775 pub fn enable_multi_factor(mut self, enabled: bool) -> Self {
786 self.enable_multi_factor = enabled;
787 self
788 }
789
790 pub fn issuer(mut self, issuer: impl Into<String>) -> Self {
792 self.issuer = issuer.into();
793 self
794 }
795
796 pub fn audience(mut self, audience: impl Into<String>) -> Self {
798 self.audience = audience.into();
799 self
800 }
801
802 pub fn secret(mut self, secret: impl Into<String>) -> Self {
804 self.secret = Some(secret.into());
805 self
806 }
807
808 pub fn require_mfa(mut self, required: bool) -> Self {
819 self.enable_multi_factor = required;
820 self
821 }
822
823 pub fn enable_caching(mut self, enabled: bool) -> Self {
825 self.enable_caching = enabled;
826 self
827 }
828
829 pub fn max_failed_attempts(mut self, max: u32) -> Self {
840 self.max_failed_attempts = max;
841 self
842 }
843
844 pub fn enable_rbac(mut self, enabled: bool) -> Self {
855 self.enable_rbac = enabled;
856 self
857 }
858
859 pub fn enable_security_audit(mut self, enabled: bool) -> Self {
870 self.audit.enabled = enabled;
871 self
872 }
873
874 pub fn enable_middleware(mut self, enabled: bool) -> Self {
885 self.enable_middleware = enabled;
886 self
887 }
888
889 pub fn force_production_mode(mut self) -> Self {
902 self.force_production_mode = true;
903 self
904 }
905
906 pub fn storage(mut self, storage: StorageConfig) -> Self {
916 self.storage = storage;
917 self
918 }
919
920 #[cfg(feature = "redis-storage")]
930 pub fn redis_storage(mut self, url: impl Into<String>) -> Self {
931 self.storage = StorageConfig::Redis {
932 url: url.into(),
933 key_prefix: "auth:".to_string(),
934 };
935 self
936 }
937
938 pub fn rate_limiting(mut self, config: RateLimitConfig) -> Self {
948 self.rate_limiting = config;
949 self
950 }
951
952 pub fn security(mut self, config: SecurityConfig) -> Self {
962 self.security = config;
963 self
964 }
965
966 pub fn cors(mut self, config: CorsConfig) -> Self {
977 self.cors = config;
978 self
979 }
980
981 pub fn audit(mut self, config: AuditConfig) -> Self {
991 self.audit = config;
992 self
993 }
994
995 pub fn method_config(
1010 mut self,
1011 method_name: impl Into<String>,
1012 config: impl Serialize,
1013 ) -> Result<Self> {
1014 let value = serde_json::to_value(config)
1015 .map_err(|e| AuthError::config(format!("Failed to serialize method config: {e}")))?;
1016
1017 self.method_configs.insert(method_name.into(), value);
1018 Ok(self)
1019 }
1020
1021 pub fn get_method_config<T>(&self, method_name: &str) -> Result<Option<T>>
1033 where
1034 T: for<'de> Deserialize<'de>,
1035 {
1036 if let Some(value) = self.method_configs.get(method_name) {
1037 let config = serde_json::from_value(value.clone()).map_err(|e| {
1038 AuthError::config(format!("Failed to deserialize method config: {e}"))
1039 })?;
1040 Ok(Some(config))
1041 } else {
1042 Ok(None)
1043 }
1044 }
1045
1046 pub fn validate(&self) -> Result<()> {
1057 if self.token_lifetime.as_secs() == 0 {
1059 return Err(AuthError::config("Token lifetime must be greater than 0"));
1060 }
1061
1062 if self.refresh_token_lifetime.as_secs() == 0 {
1063 return Err(AuthError::config(
1064 "Refresh token lifetime must be greater than 0",
1065 ));
1066 }
1067
1068 if self.refresh_token_lifetime <= self.token_lifetime {
1069 return Err(AuthError::config(
1070 "Refresh token lifetime must be greater than token lifetime",
1071 ));
1072 }
1073
1074 self.validate_jwt_secret()?;
1076
1077 if self.security.min_password_length < 4 {
1079 return Err(AuthError::config(
1080 "Minimum password length must be at least 4 characters",
1081 ));
1082 }
1083
1084 if self.is_production_environment() && !self.is_test_environment() {
1086 self.validate_production_security()?;
1087 }
1088
1089 if self.rate_limiting.enabled && self.rate_limiting.max_requests == 0 {
1091 return Err(AuthError::config(
1092 "Rate limit max requests must be greater than 0 when enabled",
1093 ));
1094 }
1095
1096 self.validate_storage_config()?;
1098
1099 self.validate_method_configs()?;
1102
1103 Ok(())
1104 }
1105
1106 fn validate_method_configs(&self) -> Result<()> {
1107 for (method_name, raw_config) in &self.method_configs {
1108 match method_name.as_str() {
1109 #[cfg(feature = "saml")]
1110 "saml" => {
1111 let config: crate::methods::saml::SamlConfig =
1112 serde_json::from_value(raw_config.clone()).map_err(|e| {
1113 AuthError::config(format!(
1114 "Failed to deserialize SAML method config: {e}"
1115 ))
1116 })?;
1117
1118 if config.entity_id.trim().is_empty() {
1119 return Err(AuthError::config("SAML entity_id cannot be empty"));
1120 }
1121 if config.acs_url.trim().is_empty() {
1122 return Err(AuthError::config("SAML acs_url cannot be empty"));
1123 }
1124 if config.max_assertion_age == 0 {
1125 return Err(AuthError::config(
1126 "SAML max_assertion_age must be greater than 0",
1127 ));
1128 }
1129 }
1130 #[cfg(not(feature = "saml"))]
1131 "saml" => {
1132 return Err(AuthError::config(
1133 "SAML method config is present but the 'saml' feature is not enabled",
1134 ));
1135 }
1136 #[cfg(feature = "passkeys")]
1137 "passkey" => {
1138 let config: crate::methods::passkey::PasskeyConfig =
1139 serde_json::from_value(raw_config.clone()).map_err(|e| {
1140 AuthError::config(format!(
1141 "Failed to deserialize passkey method config: {e}"
1142 ))
1143 })?;
1144
1145 if config.rp_id.trim().is_empty() {
1146 return Err(AuthError::config("Passkey RP ID cannot be empty"));
1147 }
1148 if config.origin.trim().is_empty() {
1149 return Err(AuthError::config("Passkey origin cannot be empty"));
1150 }
1151 if config.timeout_ms == 0 {
1152 return Err(AuthError::config("Passkey timeout must be greater than 0"));
1153 }
1154 match config.user_verification.as_str() {
1155 "required" | "preferred" | "discouraged" => {}
1156 _ => {
1157 return Err(AuthError::config(
1158 "Invalid passkey user_verification value",
1159 ));
1160 }
1161 }
1162 url::Url::parse(&config.origin).map_err(|e| {
1163 AuthError::config(format!("Invalid passkey origin URL: {e}"))
1164 })?;
1165 }
1166 #[cfg(not(feature = "passkeys"))]
1167 "passkey" => {
1168 return Err(AuthError::config(
1169 "Passkey method config is present but the 'passkeys' feature is not enabled",
1170 ));
1171 }
1172 "enhanced_device_flow" => {
1173 let client_id = raw_config
1174 .get("client_id")
1175 .and_then(serde_json::Value::as_str)
1176 .unwrap_or_default();
1177 let auth_url = raw_config
1178 .get("auth_url")
1179 .and_then(serde_json::Value::as_str)
1180 .unwrap_or_default();
1181 let token_url = raw_config
1182 .get("token_url")
1183 .and_then(serde_json::Value::as_str)
1184 .unwrap_or_default();
1185 let device_auth_url = raw_config
1186 .get("device_auth_url")
1187 .and_then(serde_json::Value::as_str)
1188 .unwrap_or_default();
1189
1190 if client_id.trim().is_empty()
1191 || auth_url.trim().is_empty()
1192 || token_url.trim().is_empty()
1193 || device_auth_url.trim().is_empty()
1194 {
1195 return Err(AuthError::config(
1196 "Enhanced device flow config requires non-empty client_id, auth_url, token_url, and device_auth_url",
1197 ));
1198 }
1199 }
1200 _ => {}
1201 }
1202 }
1203
1204 Ok(())
1205 }
1206
1207 fn validate_jwt_secret(&self) -> Result<()> {
1209 let env_secret = std::env::var("JWT_SECRET").ok();
1211 let jwt_secret = self
1212 .security
1213 .secret_key
1214 .as_ref()
1215 .or(self.secret.as_ref())
1216 .or(env_secret.as_ref());
1217
1218 if let Some(secret) = jwt_secret {
1219 if !self.is_test_environment() && secret.len() < 32 {
1222 return Err(AuthError::config(
1223 "JWT secret must be at least 32 characters for security. \
1224 Generate with: openssl rand -base64 32",
1225 ));
1226 }
1227
1228 if !self.is_test_environment() {
1231 let mut char_counts = std::collections::HashMap::new();
1232 for c in secret.chars() {
1233 *char_counts.entry(c).or_insert(0u32) += 1;
1234 }
1235 let len = secret.len() as f64;
1236 let entropy: f64 = char_counts
1237 .values()
1238 .map(|&count| {
1239 let p = count as f64 / len;
1240 -p * p.log2()
1241 })
1242 .sum();
1243 if entropy < 3.5 {
1244 return Err(AuthError::config(
1245 "JWT secret has insufficient entropy (too predictable). \
1246 Use a cryptographically secure random string.",
1247 ));
1248 }
1249 }
1250
1251 if secret.len() < 44
1253 && secret
1254 .chars()
1255 .all(|c| c.is_alphanumeric() || c == '+' || c == '/' || c == '=')
1256 {
1257 tracing::warn!(
1258 "JWT secret may be too short for optimal security. \
1259 Consider using at least 44 characters (32 bytes base64-encoded)."
1260 );
1261 }
1262 } else if self.is_production_environment() {
1263 return Err(AuthError::config(
1264 "JWT secret is required for production environments. \
1265 Set JWT_SECRET environment variable or configure security.secret_key",
1266 ));
1267 }
1268
1269 Ok(())
1270 }
1271
1272 fn validate_production_security(&self) -> Result<()> {
1274 if self.security.min_password_length < 8 {
1276 return Err(AuthError::config(
1277 "Production environments require minimum password length of 8 characters",
1278 ));
1279 }
1280
1281 if !self.security.require_password_complexity {
1282 tracing::warn!("Production deployment should enable password complexity requirements");
1283 }
1284
1285 if !self.security.secure_cookies {
1287 return Err(AuthError::config(
1288 "Production environments must use secure cookies (HTTPS required)",
1289 ));
1290 }
1291
1292 if !self.rate_limiting.enabled {
1294 tracing::warn!("Production deployment should enable rate limiting for security");
1295 }
1296
1297 if !self.audit.enabled {
1299 return Err(AuthError::config(
1300 "Production environments require audit logging for compliance",
1301 ));
1302 }
1303
1304 Ok(())
1305 }
1306
1307 fn validate_storage_config(&self) -> Result<()> {
1309 if let StorageConfig::Memory = &self.storage
1312 && self.is_production_environment()
1313 && !self.is_test_environment()
1314 {
1315 return Err(AuthError::config(
1316 "Memory storage is not suitable for production environments. \
1317 Use PostgreSQL, Redis, or SQLite storage.",
1318 ));
1319 }
1320
1321 Ok(())
1322 }
1323
1324 fn is_production_environment(&self) -> bool {
1326 if self.force_production_mode {
1328 return true;
1329 }
1330
1331 if let Ok(env) = std::env::var("ENVIRONMENT")
1333 && (env.to_lowercase() == "production" || env.to_lowercase() == "prod")
1334 {
1335 return true;
1336 }
1337
1338 if let Ok(env) = std::env::var("ENV")
1339 && (env.to_lowercase() == "production" || env.to_lowercase() == "prod")
1340 {
1341 return true;
1342 }
1343
1344 if let Ok(env) = std::env::var("NODE_ENV")
1345 && env.to_lowercase() == "production"
1346 {
1347 return true;
1348 }
1349
1350 if let Ok(env) = std::env::var("RUST_ENV")
1351 && env.to_lowercase() == "production"
1352 {
1353 return true;
1354 }
1355
1356 if std::env::var("KUBERNETES_SERVICE_HOST").is_ok() {
1358 return true;
1359 }
1360
1361 if std::env::var("DOCKER_CONTAINER").is_ok() {
1362 return true;
1363 }
1364
1365 false
1366 }
1367
1368 fn is_test_environment(&self) -> bool {
1370 if self.force_production_mode {
1372 return false;
1373 }
1374 cfg!(test)
1376 || std::thread::current()
1377 .name()
1378 .is_some_and(|name| name.contains("test"))
1379 || std::env::var("RUST_TEST").is_ok()
1380 || std::env::var("ENVIRONMENT").as_deref() == Ok("test")
1381 || std::env::var("ENV").as_deref() == Ok("test")
1382 || std::env::args().any(|arg| arg.contains("test"))
1383 }
1384}
1385
1386impl RateLimitConfig {
1387 pub fn new(max_requests: u32, window: Duration) -> Self {
1400 Self {
1401 enabled: true,
1402 max_requests,
1403 window,
1404 burst: max_requests / 10, }
1406 }
1407
1408 pub fn disabled() -> Self {
1419 Self {
1420 enabled: false,
1421 ..Default::default()
1422 }
1423 }
1424
1425 pub fn per_second(max: u32) -> Self {
1436 Self::new(max, Duration::from_secs(1))
1437 }
1438
1439 pub fn per_minute(max: u32) -> Self {
1450 Self::new(max, Duration::from_secs(60))
1451 }
1452
1453 pub fn per_hour(max: u32) -> Self {
1464 Self::new(max, Duration::from_secs(3600))
1465 }
1466}
1467
1468impl SecurityConfig {
1469 pub fn secure() -> Self {
1482 Self {
1483 min_password_length: 12,
1484 require_password_complexity: true,
1485 password_hash_algorithm: PasswordHashAlgorithm::Argon2,
1486 jwt_algorithm: JwtAlgorithm::RS256,
1487 secret_key: None,
1488 previous_secret_key: None,
1489 secure_cookies: true,
1490 cookie_same_site: CookieSameSite::Strict,
1491 csrf_protection: true,
1492 session_timeout: Duration::from_secs(3600 * 8), }
1494 }
1495
1496 pub fn development() -> Self {
1510 Self {
1511 min_password_length: 6,
1512 require_password_complexity: false,
1513 password_hash_algorithm: PasswordHashAlgorithm::Bcrypt,
1514 jwt_algorithm: JwtAlgorithm::HS256,
1515 secret_key: None, previous_secret_key: None,
1517 secure_cookies: false,
1518 cookie_same_site: CookieSameSite::Lax,
1519 csrf_protection: false,
1520 session_timeout: Duration::from_secs(3600 * 24), }
1522 }
1523}
1524
1525#[derive(Debug)]
1562pub struct AuthConfigBuilder {
1563 config: AuthConfig,
1564}
1565
1566impl Default for AuthConfigBuilder {
1567 fn default() -> Self {
1568 Self::new()
1569 }
1570}
1571
1572impl AuthConfigBuilder {
1573 pub fn new() -> Self {
1575 Self {
1576 config: AuthConfig::default(),
1577 }
1578 }
1579
1580 pub fn tokens(self) -> TokenConfigBuilder {
1582 TokenConfigBuilder { builder: self }
1583 }
1584
1585 pub fn security(self) -> SecurityConfigBuilder {
1587 SecurityConfigBuilder { builder: self }
1588 }
1589
1590 pub fn storage(self) -> StorageConfigBuilder {
1592 StorageConfigBuilder { builder: self }
1593 }
1594
1595 pub fn features(self) -> FeatureConfigBuilder {
1597 FeatureConfigBuilder { builder: self }
1598 }
1599
1600 pub fn rate_limiting(self) -> RateLimitConfigBuilder {
1602 RateLimitConfigBuilder { builder: self }
1603 }
1604
1605 pub fn cors(self) -> CorsConfigBuilder {
1607 CorsConfigBuilder { builder: self }
1608 }
1609
1610 pub fn audit(self) -> AuditConfigBuilder {
1612 AuditConfigBuilder { builder: self }
1613 }
1614
1615 pub fn build(self) -> Result<AuthConfig> {
1617 let config = self.config;
1618 config.validate()?;
1619 Ok(config)
1620 }
1621}
1622
1623#[derive(Debug)]
1625pub struct TokenConfigBuilder {
1626 builder: AuthConfigBuilder,
1627}
1628
1629impl TokenConfigBuilder {
1630 pub fn lifetime(mut self, duration: Duration) -> Self {
1632 self.builder.config.token_lifetime = duration;
1633 self
1634 }
1635
1636 pub fn refresh_lifetime(mut self, duration: Duration) -> Self {
1638 self.builder.config.refresh_token_lifetime = duration;
1639 self
1640 }
1641
1642 pub fn issuer(mut self, issuer: impl Into<String>) -> Self {
1644 self.builder.config.issuer = issuer.into();
1645 self
1646 }
1647
1648 pub fn audience(mut self, audience: impl Into<String>) -> Self {
1650 self.builder.config.audience = audience.into();
1651 self
1652 }
1653
1654 pub fn secret(mut self, secret: impl Into<String>) -> Self {
1656 self.builder.config.secret = Some(secret.into());
1657 self
1658 }
1659
1660 pub fn done(self) -> AuthConfigBuilder {
1662 self.builder
1663 }
1664}
1665
1666#[derive(Debug)]
1668pub struct SecurityConfigBuilder {
1669 builder: AuthConfigBuilder,
1670}
1671
1672impl SecurityConfigBuilder {
1673 pub fn min_password_length(mut self, length: usize) -> Self {
1675 self.builder.config.security.min_password_length = length;
1676 self
1677 }
1678
1679 pub fn require_complexity(mut self, required: bool) -> Self {
1681 self.builder.config.security.require_password_complexity = required;
1682 self
1683 }
1684
1685 pub fn password_algorithm(mut self, algorithm: PasswordHashAlgorithm) -> Self {
1687 self.builder.config.security.password_hash_algorithm = algorithm;
1688 self
1689 }
1690
1691 pub fn jwt_algorithm(mut self, algorithm: JwtAlgorithm) -> Self {
1693 self.builder.config.security.jwt_algorithm = algorithm;
1694 self
1695 }
1696
1697 pub fn secure_cookies(mut self, enabled: bool) -> Self {
1699 self.builder.config.security.secure_cookies = enabled;
1700 self
1701 }
1702
1703 pub fn cookie_same_site(mut self, policy: CookieSameSite) -> Self {
1705 self.builder.config.security.cookie_same_site = policy;
1706 self
1707 }
1708
1709 pub fn csrf_protection(mut self, enabled: bool) -> Self {
1711 self.builder.config.security.csrf_protection = enabled;
1712 self
1713 }
1714
1715 pub fn session_timeout(mut self, timeout: Duration) -> Self {
1717 self.builder.config.security.session_timeout = timeout;
1718 self
1719 }
1720
1721 pub fn done(self) -> AuthConfigBuilder {
1723 self.builder
1724 }
1725}
1726
1727#[derive(Debug)]
1729pub struct StorageConfigBuilder {
1730 builder: AuthConfigBuilder,
1731}
1732
1733impl StorageConfigBuilder {
1734 pub fn memory(mut self) -> Self {
1736 self.builder.config.storage = StorageConfig::Memory;
1737 self
1738 }
1739
1740 #[cfg(feature = "redis-storage")]
1742 pub fn redis(mut self, url: impl Into<String>) -> Self {
1743 self.builder.config.storage = StorageConfig::Redis {
1744 url: url.into(),
1745 key_prefix: "auth:".to_string(),
1746 };
1747 self
1748 }
1749
1750 #[cfg(feature = "postgres-storage")]
1752 pub fn postgres(mut self, connection_string: impl Into<String>) -> Self {
1753 self.builder.config.storage = StorageConfig::Postgres {
1754 connection_string: connection_string.into(),
1755 table_prefix: "auth_".to_string(),
1756 };
1757 self
1758 }
1759
1760 #[cfg(feature = "sqlite-storage")]
1762 pub fn sqlite(mut self, connection_string: impl Into<String>) -> Self {
1763 self.builder.config.storage = StorageConfig::Sqlite {
1764 connection_string: connection_string.into(),
1765 };
1766 self
1767 }
1768
1769 pub fn done(self) -> AuthConfigBuilder {
1771 self.builder
1772 }
1773}
1774
1775#[derive(Debug)]
1777pub struct FeatureConfigBuilder {
1778 builder: AuthConfigBuilder,
1779}
1780
1781impl FeatureConfigBuilder {
1782 pub fn enable_multi_factor(mut self, enabled: bool) -> Self {
1784 self.builder.config.enable_multi_factor = enabled;
1785 self
1786 }
1787
1788 pub fn enable_rbac(mut self, enabled: bool) -> Self {
1790 self.builder.config.enable_rbac = enabled;
1791 self
1792 }
1793
1794 pub fn enable_caching(mut self, enabled: bool) -> Self {
1796 self.builder.config.enable_caching = enabled;
1797 self
1798 }
1799
1800 pub fn enable_middleware(mut self, enabled: bool) -> Self {
1802 self.builder.config.enable_middleware = enabled;
1803 self
1804 }
1805
1806 pub fn max_failed_attempts(mut self, max: u32) -> Self {
1808 self.builder.config.max_failed_attempts = max;
1809 self
1810 }
1811
1812 pub fn done(self) -> AuthConfigBuilder {
1814 self.builder
1815 }
1816}
1817
1818#[derive(Debug)]
1820pub struct RateLimitConfigBuilder {
1821 builder: AuthConfigBuilder,
1822}
1823
1824impl RateLimitConfigBuilder {
1825 pub fn enabled(mut self, max_requests: u32, window: Duration) -> Self {
1827 self.builder.config.rate_limiting = RateLimitConfig::new(max_requests, window);
1828 self
1829 }
1830
1831 pub fn disabled(mut self) -> Self {
1833 self.builder.config.rate_limiting = RateLimitConfig::disabled();
1834 self
1835 }
1836
1837 pub fn max_requests(mut self, max: u32) -> Self {
1839 self.builder.config.rate_limiting.max_requests = max;
1840 self
1841 }
1842
1843 pub fn window(mut self, window: Duration) -> Self {
1845 self.builder.config.rate_limiting.window = window;
1846 self
1847 }
1848
1849 pub fn burst(mut self, burst: u32) -> Self {
1851 self.builder.config.rate_limiting.burst = burst;
1852 self
1853 }
1854
1855 pub fn done(self) -> AuthConfigBuilder {
1857 self.builder
1858 }
1859}
1860
1861#[derive(Debug)]
1863pub struct CorsConfigBuilder {
1864 builder: AuthConfigBuilder,
1865}
1866
1867impl CorsConfigBuilder {
1868 pub fn allow_origins<I, S>(mut self, origins: I) -> Self
1870 where
1871 I: IntoIterator<Item = S>,
1872 S: Into<String>,
1873 {
1874 self.builder.config.cors = CorsConfig::for_origins(origins);
1875 self
1876 }
1877
1878 pub fn disabled(mut self) -> Self {
1880 self.builder.config.cors.enabled = false;
1881 self
1882 }
1883
1884 pub fn allow_methods<I, S>(mut self, methods: I) -> Self
1886 where
1887 I: IntoIterator<Item = S>,
1888 S: Into<String>,
1889 {
1890 self.builder.config.cors.allowed_methods = methods.into_iter().map(Into::into).collect();
1891 self
1892 }
1893
1894 pub fn allow_headers<I, S>(mut self, headers: I) -> Self
1896 where
1897 I: IntoIterator<Item = S>,
1898 S: Into<String>,
1899 {
1900 self.builder.config.cors.allowed_headers = headers.into_iter().map(Into::into).collect();
1901 self
1902 }
1903
1904 pub fn max_age(mut self, seconds: u32) -> Self {
1906 self.builder.config.cors.max_age_secs = seconds;
1907 self
1908 }
1909
1910 pub fn done(self) -> AuthConfigBuilder {
1912 self.builder
1913 }
1914}
1915
1916#[derive(Debug)]
1918pub struct AuditConfigBuilder {
1919 builder: AuthConfigBuilder,
1920}
1921
1922impl AuditConfigBuilder {
1923 pub fn enabled(mut self) -> Self {
1925 self.builder.config.audit.enabled = true;
1926 self
1927 }
1928
1929 pub fn disabled(mut self) -> Self {
1931 self.builder.config.audit.enabled = false;
1932 self
1933 }
1934
1935 pub fn log_success(mut self, enabled: bool) -> Self {
1937 self.builder.config.audit.log_success = enabled;
1938 self
1939 }
1940
1941 pub fn log_failures(mut self, enabled: bool) -> Self {
1943 self.builder.config.audit.log_failures = enabled;
1944 self
1945 }
1946
1947 pub fn log_permissions(mut self, enabled: bool) -> Self {
1949 self.builder.config.audit.log_permissions = enabled;
1950 self
1951 }
1952
1953 pub fn log_tokens(mut self, enabled: bool) -> Self {
1955 self.builder.config.audit.log_tokens = enabled;
1956 self
1957 }
1958
1959 pub fn done(self) -> AuthConfigBuilder {
1961 self.builder
1962 }
1963}