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 = "mysql-storage")]
100 MySQL {
101 connection_string: String,
102 table_prefix: String,
103 },
104
105 #[cfg(feature = "sqlite-storage")]
107 Sqlite { connection_string: String },
108
109 Custom(String),
111}
112
113#[derive(Debug, Clone, Serialize, Deserialize)]
119#[serde(default)]
120pub struct RateLimitConfig {
121 pub enabled: bool,
123
124 pub max_requests: u32,
126
127 pub window: Duration,
129
130 pub burst: u32,
132}
133
134#[derive(Debug, Clone, Serialize, Deserialize)]
146#[serde(default)]
147pub struct SecurityConfig {
148 pub min_password_length: usize,
150
151 pub require_password_complexity: bool,
153
154 pub password_hash_algorithm: PasswordHashAlgorithm,
156
157 pub jwt_algorithm: JwtAlgorithm,
159
160 pub secret_key: Option<String>,
162
163 pub previous_secret_key: Option<String>,
165
166 pub secure_cookies: bool,
168
169 pub cookie_same_site: CookieSameSite,
171
172 pub csrf_protection: bool,
174
175 pub session_timeout: Duration,
177}
178
179#[derive(Debug, Clone, Serialize, Deserialize)]
181pub enum PasswordHashAlgorithm {
182 Argon2,
184 Bcrypt,
186 Scrypt,
188}
189
190#[derive(Debug, Clone, Serialize, Deserialize)]
192pub enum JwtAlgorithm {
193 HS256,
195 HS384,
197 HS512,
199 RS256,
201 RS384,
203 RS512,
205 ES256,
207 ES384,
209}
210
211#[derive(Debug, Clone, Serialize, Deserialize)]
213pub enum CookieSameSite {
214 Strict,
216 Lax,
218 None,
220}
221
222#[derive(Debug, Clone, Serialize, Deserialize)]
228#[serde(default)]
229pub struct CorsConfig {
230 pub enabled: bool,
232
233 pub allowed_origins: Vec<String>,
238
239 pub allowed_methods: Vec<String>,
241
242 pub allowed_headers: Vec<String>,
244
245 pub max_age_secs: u32,
247}
248
249impl Default for CorsConfig {
250 fn default() -> Self {
251 Self {
252 enabled: false,
253 allowed_origins: Vec::new(),
254 allowed_methods: vec![
255 "GET".to_string(),
256 "POST".to_string(),
257 "PUT".to_string(),
258 "DELETE".to_string(),
259 "OPTIONS".to_string(),
260 ],
261 allowed_headers: vec![
262 "Authorization".to_string(),
263 "Content-Type".to_string(),
264 "Accept".to_string(),
265 ],
266 max_age_secs: 3600,
267 }
268 }
269}
270
271impl CorsConfig {
272 pub fn for_origins<I, S>(origins: I) -> Self
283 where
284 I: IntoIterator<Item = S>,
285 S: Into<String>,
286 {
287 Self {
288 enabled: true,
289 allowed_origins: origins.into_iter().map(Into::into).collect(),
290 ..Default::default()
291 }
292 }
293}
294
295#[derive(Debug, Clone, Serialize, Deserialize)]
300#[serde(default)]
301pub struct AuditConfig {
302 pub enabled: bool,
304
305 pub log_success: bool,
307
308 pub log_failures: bool,
310
311 pub log_permissions: bool,
313
314 pub log_tokens: bool,
316
317 pub storage: AuditStorage,
319}
320
321#[derive(Debug, Clone, Serialize, Deserialize)]
325pub enum AuditStorage {
326 Tracing,
328
329 File { path: String },
331
332 Database { connection_string: String },
334
335 External { endpoint: String, api_key: String },
337}
338
339const fn default_max_failed_attempts() -> u32 {
340 5
341}
342
343impl Default for AuthConfig {
344 fn default() -> Self {
345 Self {
346 token_lifetime: Duration::from_secs(3600), refresh_token_lifetime: Duration::from_secs(86400 * 7), enable_multi_factor: false,
349 issuer: "auth-framework".to_string(),
350 audience: "api".to_string(),
351 secret: None,
352 storage: StorageConfig::Memory,
353 rate_limiting: RateLimitConfig::default(),
354 security: SecurityConfig::default(),
355 cors: CorsConfig::default(),
356 audit: AuditConfig::default(),
357 enable_caching: false,
358 max_failed_attempts: default_max_failed_attempts(),
359 enable_rbac: false,
360 enable_middleware: false,
361 method_configs: HashMap::new(),
362 force_production_mode: false,
363 }
364 }
365}
366
367impl Default for RateLimitConfig {
368 fn default() -> Self {
369 Self {
370 enabled: true,
371 max_requests: 100,
372 window: Duration::from_secs(60), burst: 10,
374 }
375 }
376}
377
378impl Default for SecurityConfig {
379 fn default() -> Self {
380 Self {
381 min_password_length: 8,
382 require_password_complexity: true,
383 password_hash_algorithm: PasswordHashAlgorithm::Argon2,
384 jwt_algorithm: JwtAlgorithm::HS256,
385 secret_key: None,
386 previous_secret_key: None,
387 secure_cookies: true,
388 cookie_same_site: CookieSameSite::Lax,
389 csrf_protection: true,
390 session_timeout: Duration::from_secs(3600 * 24), }
392 }
393}
394
395impl Default for AuditConfig {
396 fn default() -> Self {
397 Self {
398 enabled: true,
399 log_success: true,
400 log_failures: true,
401 log_permissions: true,
402 log_tokens: false, storage: AuditStorage::Tracing,
404 }
405 }
406}
407
408impl std::fmt::Display for AuthConfig {
413 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
414 write!(
415 f,
416 "AuthConfig {{ tokens: {}s/{}s refresh, storage: {}, mfa: {}, rbac: {}, rate_limit: {}, security: {}, cors: {}, audit: {} }}",
417 self.token_lifetime.as_secs(),
418 self.refresh_token_lifetime.as_secs(),
419 self.storage,
420 if self.enable_multi_factor {
421 "on"
422 } else {
423 "off"
424 },
425 if self.enable_rbac { "on" } else { "off" },
426 self.rate_limiting,
427 self.security,
428 self.cors,
429 self.audit,
430 )
431 }
432}
433
434impl std::fmt::Display for StorageConfig {
435 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
436 match self {
437 Self::Memory => write!(f, "memory"),
438 #[cfg(feature = "redis-storage")]
439 Self::Redis { url, .. } => write!(f, "redis({})", url),
440 #[cfg(feature = "postgres-storage")]
441 Self::Postgres { .. } => write!(f, "postgres"),
442 #[cfg(feature = "mysql-storage")]
443 Self::MySQL { .. } => write!(f, "mysql"),
444 #[cfg(feature = "sqlite-storage")]
445 Self::Sqlite { .. } => write!(f, "sqlite"),
446 Self::Custom(name) => write!(f, "custom({})", name),
447 }
448 }
449}
450
451impl std::fmt::Display for SecurityConfig {
452 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
453 write!(
454 f,
455 "Security {{ pw≥{}, hash: {}, jwt: {}, cookies: {}, csrf: {}, session: {}s }}",
456 self.min_password_length,
457 self.password_hash_algorithm,
458 self.jwt_algorithm,
459 if self.secure_cookies {
460 "secure"
461 } else {
462 "plain"
463 },
464 if self.csrf_protection { "on" } else { "off" },
465 self.session_timeout.as_secs(),
466 )
467 }
468}
469
470impl std::fmt::Display for PasswordHashAlgorithm {
471 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
472 match self {
473 Self::Argon2 => write!(f, "argon2id"),
474 Self::Bcrypt => write!(f, "bcrypt"),
475 Self::Scrypt => write!(f, "scrypt"),
476 }
477 }
478}
479
480impl std::fmt::Display for JwtAlgorithm {
481 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
482 match self {
483 Self::HS256 => write!(f, "HS256"),
484 Self::HS384 => write!(f, "HS384"),
485 Self::HS512 => write!(f, "HS512"),
486 Self::RS256 => write!(f, "RS256"),
487 Self::RS384 => write!(f, "RS384"),
488 Self::RS512 => write!(f, "RS512"),
489 Self::ES256 => write!(f, "ES256"),
490 Self::ES384 => write!(f, "ES384"),
491 }
492 }
493}
494
495impl std::fmt::Display for RateLimitConfig {
496 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
497 if self.enabled {
498 write!(
499 f,
500 "{} req/{}s (burst {})",
501 self.max_requests,
502 self.window.as_secs(),
503 self.burst,
504 )
505 } else {
506 write!(f, "disabled")
507 }
508 }
509}
510
511impl std::fmt::Display for CorsConfig {
512 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
513 if self.enabled {
514 if self.allowed_origins.is_empty() {
515 write!(f, "cors(no origins)")
516 } else {
517 write!(f, "cors({})", self.allowed_origins.join(", "))
518 }
519 } else {
520 write!(f, "cors(off)")
521 }
522 }
523}
524
525impl std::fmt::Display for AuditConfig {
526 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
527 if self.enabled {
528 write!(f, "audit({})", self.storage)
529 } else {
530 write!(f, "audit(off)")
531 }
532 }
533}
534
535impl std::fmt::Display for AuditStorage {
536 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
537 match self {
538 Self::Tracing => write!(f, "tracing"),
539 Self::File { path } => write!(f, "file:{}", path),
540 Self::Database { .. } => write!(f, "database"),
541 Self::External { endpoint, .. } => write!(f, "external:{}", endpoint),
542 }
543 }
544}
545
546#[derive(Debug, Clone, Serialize, Deserialize)]
552pub struct RuntimeConfig {
553 pub token_lifetime_secs: u64,
555 pub refresh_token_lifetime_secs: u64,
557 pub enable_multi_factor: bool,
559 pub rate_limiting_enabled: bool,
561 pub rate_limit_max_requests: u32,
563 pub rate_limit_window_secs: u64,
565 pub rate_limit_burst: u32,
567 pub min_password_length: usize,
569 pub require_password_complexity: bool,
571 pub secure_cookies: bool,
573 pub csrf_protection: bool,
575 pub session_timeout_secs: u64,
577 pub audit_enabled: bool,
579 pub audit_log_success: bool,
581 pub audit_log_failures: bool,
583 pub audit_log_permissions: bool,
585 pub audit_log_tokens: bool,
587}
588
589impl RuntimeConfig {
590 pub fn from_auth_config(cfg: &AuthConfig) -> Self {
602 Self {
603 token_lifetime_secs: cfg.token_lifetime.as_secs(),
604 refresh_token_lifetime_secs: cfg.refresh_token_lifetime.as_secs(),
605 enable_multi_factor: cfg.enable_multi_factor,
606 rate_limiting_enabled: cfg.rate_limiting.enabled,
607 rate_limit_max_requests: cfg.rate_limiting.max_requests,
608 rate_limit_window_secs: cfg.rate_limiting.window.as_secs(),
609 rate_limit_burst: cfg.rate_limiting.burst,
610 min_password_length: cfg.security.min_password_length,
611 require_password_complexity: cfg.security.require_password_complexity,
612 secure_cookies: cfg.security.secure_cookies,
613 csrf_protection: cfg.security.csrf_protection,
614 session_timeout_secs: cfg.security.session_timeout.as_secs(),
615 audit_enabled: cfg.audit.enabled,
616 audit_log_success: cfg.audit.log_success,
617 audit_log_failures: cfg.audit.log_failures,
618 audit_log_permissions: cfg.audit.log_permissions,
619 audit_log_tokens: cfg.audit.log_tokens,
620 }
621 }
622}
623
624impl Default for RuntimeConfig {
625 fn default() -> Self {
626 Self::from_auth_config(&AuthConfig::default())
627 }
628}
629
630impl AuthConfig {
631 pub fn new() -> Self {
663 Self::default()
664 }
665
666 pub fn from_env() -> Self {
690 let mut config = Self::default();
691
692 if let Ok(secret) = std::env::var("JWT_SECRET") {
693 config.secret = Some(secret.clone());
694 config.security.secret_key = Some(secret);
695 }
696
697 if let Ok(issuer) = std::env::var("AUTH_ISSUER") {
698 config.issuer = issuer;
699 }
700
701 if let Ok(audience) = std::env::var("AUTH_AUDIENCE") {
702 config.audience = audience;
703 }
704
705 #[cfg(feature = "postgres-storage")]
707 if let Ok(url) = std::env::var("DATABASE_URL") {
708 config.storage = StorageConfig::Postgres {
709 connection_string: url,
710 table_prefix: "auth_".to_string(),
711 };
712 }
713
714 #[cfg(feature = "redis-storage")]
715 if matches!(config.storage, StorageConfig::Memory) {
716 if let Ok(url) = std::env::var("REDIS_URL") {
717 config.storage = StorageConfig::Redis {
718 url,
719 key_prefix: "auth:".to_string(),
720 };
721 }
722 }
723
724 config
725 }
726
727 pub fn builder() -> crate::builders::AuthBuilder {
749 crate::builders::AuthBuilder::new()
750 }
751
752 pub fn token_lifetime(mut self, lifetime: Duration) -> Self {
764 self.token_lifetime = lifetime;
765 self
766 }
767
768 pub fn refresh_token_lifetime(mut self, lifetime: Duration) -> Self {
780 self.refresh_token_lifetime = lifetime;
781 self
782 }
783
784 pub fn enable_multi_factor(mut self, enabled: bool) -> Self {
795 self.enable_multi_factor = enabled;
796 self
797 }
798
799 pub fn issuer(mut self, issuer: impl Into<String>) -> Self {
801 self.issuer = issuer.into();
802 self
803 }
804
805 pub fn audience(mut self, audience: impl Into<String>) -> Self {
807 self.audience = audience.into();
808 self
809 }
810
811 pub fn secret(mut self, secret: impl Into<String>) -> Self {
813 self.secret = Some(secret.into());
814 self
815 }
816
817 pub fn require_mfa(mut self, required: bool) -> Self {
828 self.enable_multi_factor = required;
829 self
830 }
831
832 pub fn enable_caching(mut self, enabled: bool) -> Self {
834 self.enable_caching = enabled;
835 self
836 }
837
838 pub fn max_failed_attempts(mut self, max: u32) -> Self {
849 self.max_failed_attempts = max;
850 self
851 }
852
853 pub fn enable_rbac(mut self, enabled: bool) -> Self {
864 self.enable_rbac = enabled;
865 self
866 }
867
868 pub fn enable_security_audit(mut self, enabled: bool) -> Self {
879 self.audit.enabled = enabled;
880 self
881 }
882
883 pub fn enable_middleware(mut self, enabled: bool) -> Self {
894 self.enable_middleware = enabled;
895 self
896 }
897
898 pub fn force_production_mode(mut self) -> Self {
911 self.force_production_mode = true;
912 self
913 }
914
915 pub fn storage(mut self, storage: StorageConfig) -> Self {
925 self.storage = storage;
926 self
927 }
928
929 #[cfg(feature = "redis-storage")]
939 pub fn redis_storage(mut self, url: impl Into<String>) -> Self {
940 self.storage = StorageConfig::Redis {
941 url: url.into(),
942 key_prefix: "auth:".to_string(),
943 };
944 self
945 }
946
947 pub fn rate_limiting(mut self, config: RateLimitConfig) -> Self {
957 self.rate_limiting = config;
958 self
959 }
960
961 pub fn security(mut self, config: SecurityConfig) -> Self {
971 self.security = config;
972 self
973 }
974
975 pub fn cors(mut self, config: CorsConfig) -> Self {
986 self.cors = config;
987 self
988 }
989
990 pub fn audit(mut self, config: AuditConfig) -> Self {
1000 self.audit = config;
1001 self
1002 }
1003
1004 pub fn method_config(
1019 mut self,
1020 method_name: impl Into<String>,
1021 config: impl Serialize,
1022 ) -> Result<Self> {
1023 let value = serde_json::to_value(config)
1024 .map_err(|e| AuthError::config(format!("Failed to serialize method config: {e}")))?;
1025
1026 self.method_configs.insert(method_name.into(), value);
1027 Ok(self)
1028 }
1029
1030 pub fn get_method_config<T>(&self, method_name: &str) -> Result<Option<T>>
1042 where
1043 T: for<'de> Deserialize<'de>,
1044 {
1045 if let Some(value) = self.method_configs.get(method_name) {
1046 let config = serde_json::from_value(value.clone()).map_err(|e| {
1047 AuthError::config(format!("Failed to deserialize method config: {e}"))
1048 })?;
1049 Ok(Some(config))
1050 } else {
1051 Ok(None)
1052 }
1053 }
1054
1055 pub fn validate(&self) -> Result<()> {
1066 if self.token_lifetime.as_secs() == 0 {
1068 return Err(AuthError::config("Token lifetime must be greater than 0"));
1069 }
1070
1071 if self.refresh_token_lifetime.as_secs() == 0 {
1072 return Err(AuthError::config(
1073 "Refresh token lifetime must be greater than 0",
1074 ));
1075 }
1076
1077 if self.refresh_token_lifetime <= self.token_lifetime {
1078 return Err(AuthError::config(
1079 "Refresh token lifetime must be greater than token lifetime",
1080 ));
1081 }
1082
1083 self.validate_jwt_secret()?;
1085
1086 if self.security.min_password_length < 4 {
1088 return Err(AuthError::config(
1089 "Minimum password length must be at least 4 characters",
1090 ));
1091 }
1092
1093 if self.is_production_environment() && !self.is_test_environment() {
1095 self.validate_production_security()?;
1096 }
1097
1098 if self.rate_limiting.enabled && self.rate_limiting.max_requests == 0 {
1100 return Err(AuthError::config(
1101 "Rate limit max requests must be greater than 0 when enabled",
1102 ));
1103 }
1104
1105 self.validate_storage_config()?;
1107
1108 self.validate_method_configs()?;
1111
1112 Ok(())
1113 }
1114
1115 fn validate_method_configs(&self) -> Result<()> {
1116 for (method_name, raw_config) in &self.method_configs {
1117 match method_name.as_str() {
1118 #[cfg(feature = "saml")]
1119 "saml" => {
1120 let config: crate::methods::saml::SamlConfig =
1121 serde_json::from_value(raw_config.clone()).map_err(|e| {
1122 AuthError::config(format!(
1123 "Failed to deserialize SAML method config: {e}"
1124 ))
1125 })?;
1126
1127 if config.entity_id.trim().is_empty() {
1128 return Err(AuthError::config("SAML entity_id cannot be empty"));
1129 }
1130 if config.acs_url.trim().is_empty() {
1131 return Err(AuthError::config("SAML acs_url cannot be empty"));
1132 }
1133 if config.max_assertion_age == 0 {
1134 return Err(AuthError::config(
1135 "SAML max_assertion_age must be greater than 0",
1136 ));
1137 }
1138 }
1139 #[cfg(not(feature = "saml"))]
1140 "saml" => {
1141 return Err(AuthError::config(
1142 "SAML method config is present but the 'saml' feature is not enabled",
1143 ));
1144 }
1145 #[cfg(feature = "passkeys")]
1146 "passkey" => {
1147 let config: crate::methods::passkey::PasskeyConfig =
1148 serde_json::from_value(raw_config.clone()).map_err(|e| {
1149 AuthError::config(format!(
1150 "Failed to deserialize passkey method config: {e}"
1151 ))
1152 })?;
1153
1154 if config.rp_id.trim().is_empty() {
1155 return Err(AuthError::config("Passkey RP ID cannot be empty"));
1156 }
1157 if config.origin.trim().is_empty() {
1158 return Err(AuthError::config("Passkey origin cannot be empty"));
1159 }
1160 if config.timeout_ms == 0 {
1161 return Err(AuthError::config("Passkey timeout must be greater than 0"));
1162 }
1163 match config.user_verification.as_str() {
1164 "required" | "preferred" | "discouraged" => {}
1165 _ => {
1166 return Err(AuthError::config(
1167 "Invalid passkey user_verification value",
1168 ));
1169 }
1170 }
1171 url::Url::parse(&config.origin).map_err(|e| {
1172 AuthError::config(format!("Invalid passkey origin URL: {e}"))
1173 })?;
1174 }
1175 #[cfg(not(feature = "passkeys"))]
1176 "passkey" => {
1177 return Err(AuthError::config(
1178 "Passkey method config is present but the 'passkeys' feature is not enabled",
1179 ));
1180 }
1181 "enhanced_device_flow" => {
1182 let client_id = raw_config
1183 .get("client_id")
1184 .and_then(serde_json::Value::as_str)
1185 .unwrap_or_default();
1186 let auth_url = raw_config
1187 .get("auth_url")
1188 .and_then(serde_json::Value::as_str)
1189 .unwrap_or_default();
1190 let token_url = raw_config
1191 .get("token_url")
1192 .and_then(serde_json::Value::as_str)
1193 .unwrap_or_default();
1194 let device_auth_url = raw_config
1195 .get("device_auth_url")
1196 .and_then(serde_json::Value::as_str)
1197 .unwrap_or_default();
1198
1199 if client_id.trim().is_empty()
1200 || auth_url.trim().is_empty()
1201 || token_url.trim().is_empty()
1202 || device_auth_url.trim().is_empty()
1203 {
1204 return Err(AuthError::config(
1205 "Enhanced device flow config requires non-empty client_id, auth_url, token_url, and device_auth_url",
1206 ));
1207 }
1208 }
1209 _ => {}
1210 }
1211 }
1212
1213 Ok(())
1214 }
1215
1216 fn validate_jwt_secret(&self) -> Result<()> {
1218 let env_secret = std::env::var("JWT_SECRET").ok();
1220 let jwt_secret = self
1221 .security
1222 .secret_key
1223 .as_ref()
1224 .or(self.secret.as_ref())
1225 .or(env_secret.as_ref());
1226
1227 if let Some(secret) = jwt_secret {
1228 if !self.is_test_environment() && secret.len() < 32 {
1231 return Err(AuthError::config(
1232 "JWT secret must be at least 32 characters for security. \
1233 Generate with: openssl rand -base64 32",
1234 ));
1235 }
1236
1237 if !self.is_test_environment() {
1240 let mut char_counts = std::collections::HashMap::new();
1241 for c in secret.chars() {
1242 *char_counts.entry(c).or_insert(0u32) += 1;
1243 }
1244 let len = secret.len() as f64;
1245 let entropy: f64 = char_counts
1246 .values()
1247 .map(|&count| {
1248 let p = count as f64 / len;
1249 -p * p.log2()
1250 })
1251 .sum();
1252 if entropy < 3.5 {
1253 return Err(AuthError::config(
1254 "JWT secret has insufficient entropy (too predictable). \
1255 Use a cryptographically secure random string.",
1256 ));
1257 }
1258 }
1259
1260 if secret.len() < 44
1262 && secret
1263 .chars()
1264 .all(|c| c.is_alphanumeric() || c == '+' || c == '/' || c == '=')
1265 {
1266 tracing::warn!(
1267 "JWT secret may be too short for optimal security. \
1268 Consider using at least 44 characters (32 bytes base64-encoded)."
1269 );
1270 }
1271 } else if self.is_production_environment() {
1272 return Err(AuthError::config(
1273 "JWT secret is required for production environments. \
1274 Set JWT_SECRET environment variable or configure security.secret_key",
1275 ));
1276 }
1277
1278 Ok(())
1279 }
1280
1281 fn validate_production_security(&self) -> Result<()> {
1283 if self.security.min_password_length < 8 {
1285 return Err(AuthError::config(
1286 "Production environments require minimum password length of 8 characters",
1287 ));
1288 }
1289
1290 if !self.security.require_password_complexity {
1291 tracing::warn!("Production deployment should enable password complexity requirements");
1292 }
1293
1294 if !self.security.secure_cookies {
1296 return Err(AuthError::config(
1297 "Production environments must use secure cookies (HTTPS required)",
1298 ));
1299 }
1300
1301 if !self.rate_limiting.enabled {
1303 tracing::warn!("Production deployment should enable rate limiting for security");
1304 }
1305
1306 if !self.audit.enabled {
1308 return Err(AuthError::config(
1309 "Production environments require audit logging for compliance",
1310 ));
1311 }
1312
1313 Ok(())
1314 }
1315
1316 fn validate_storage_config(&self) -> Result<()> {
1318 match &self.storage {
1319 StorageConfig::Memory => {
1320 if self.is_production_environment() && !self.is_test_environment() {
1321 return Err(AuthError::config(
1322 "Memory storage is not suitable for production environments. \
1323 Use PostgreSQL, Redis, MySQL, or SQLite storage.",
1324 ));
1325 }
1326 }
1327 #[cfg(feature = "mysql-storage")]
1328 StorageConfig::MySQL { .. } => {
1329 tracing::warn!(
1330 "MySQL storage has known RSA vulnerability (RUSTSEC-2023-0071). \
1331 Consider using PostgreSQL for enhanced security."
1332 );
1333 }
1334 _ => {} }
1336
1337 Ok(())
1338 }
1339
1340 fn is_production_environment(&self) -> bool {
1342 if self.force_production_mode {
1344 return true;
1345 }
1346
1347 if let Ok(env) = std::env::var("ENVIRONMENT")
1349 && (env.to_lowercase() == "production" || env.to_lowercase() == "prod")
1350 {
1351 return true;
1352 }
1353
1354 if let Ok(env) = std::env::var("ENV")
1355 && (env.to_lowercase() == "production" || env.to_lowercase() == "prod")
1356 {
1357 return true;
1358 }
1359
1360 if let Ok(env) = std::env::var("NODE_ENV")
1361 && env.to_lowercase() == "production"
1362 {
1363 return true;
1364 }
1365
1366 if let Ok(env) = std::env::var("RUST_ENV")
1367 && env.to_lowercase() == "production"
1368 {
1369 return true;
1370 }
1371
1372 if std::env::var("KUBERNETES_SERVICE_HOST").is_ok() {
1374 return true;
1375 }
1376
1377 if std::env::var("DOCKER_CONTAINER").is_ok() {
1378 return true;
1379 }
1380
1381 false
1382 }
1383
1384 fn is_test_environment(&self) -> bool {
1386 if self.force_production_mode {
1388 return false;
1389 }
1390 cfg!(test)
1392 || std::thread::current()
1393 .name()
1394 .is_some_and(|name| name.contains("test"))
1395 || std::env::var("RUST_TEST").is_ok()
1396 || std::env::var("ENVIRONMENT").as_deref() == Ok("test")
1397 || std::env::var("ENV").as_deref() == Ok("test")
1398 || std::env::args().any(|arg| arg.contains("test"))
1399 }
1400}
1401
1402impl RateLimitConfig {
1403 pub fn new(max_requests: u32, window: Duration) -> Self {
1416 Self {
1417 enabled: true,
1418 max_requests,
1419 window,
1420 burst: max_requests / 10, }
1422 }
1423
1424 pub fn disabled() -> Self {
1435 Self {
1436 enabled: false,
1437 ..Default::default()
1438 }
1439 }
1440
1441 pub fn per_second(max: u32) -> Self {
1452 Self::new(max, Duration::from_secs(1))
1453 }
1454
1455 pub fn per_minute(max: u32) -> Self {
1466 Self::new(max, Duration::from_secs(60))
1467 }
1468
1469 pub fn per_hour(max: u32) -> Self {
1480 Self::new(max, Duration::from_secs(3600))
1481 }
1482}
1483
1484impl SecurityConfig {
1485 pub fn secure() -> Self {
1498 Self {
1499 min_password_length: 12,
1500 require_password_complexity: true,
1501 password_hash_algorithm: PasswordHashAlgorithm::Argon2,
1502 jwt_algorithm: JwtAlgorithm::RS256,
1503 secret_key: None,
1504 previous_secret_key: None,
1505 secure_cookies: true,
1506 cookie_same_site: CookieSameSite::Strict,
1507 csrf_protection: true,
1508 session_timeout: Duration::from_secs(3600 * 8), }
1510 }
1511
1512 pub fn development() -> Self {
1526 Self {
1527 min_password_length: 6,
1528 require_password_complexity: false,
1529 password_hash_algorithm: PasswordHashAlgorithm::Bcrypt,
1530 jwt_algorithm: JwtAlgorithm::HS256,
1531 secret_key: None, previous_secret_key: None,
1533 secure_cookies: false,
1534 cookie_same_site: CookieSameSite::Lax,
1535 csrf_protection: false,
1536 session_timeout: Duration::from_secs(3600 * 24), }
1538 }
1539}
1540
1541#[derive(Debug)]
1578pub struct AuthConfigBuilder {
1579 config: AuthConfig,
1580}
1581
1582impl Default for AuthConfigBuilder {
1583 fn default() -> Self {
1584 Self::new()
1585 }
1586}
1587
1588impl AuthConfigBuilder {
1589 pub fn new() -> Self {
1591 Self {
1592 config: AuthConfig::default(),
1593 }
1594 }
1595
1596 pub fn tokens(self) -> TokenConfigBuilder {
1598 TokenConfigBuilder { builder: self }
1599 }
1600
1601 pub fn security(self) -> SecurityConfigBuilder {
1603 SecurityConfigBuilder { builder: self }
1604 }
1605
1606 pub fn storage(self) -> StorageConfigBuilder {
1608 StorageConfigBuilder { builder: self }
1609 }
1610
1611 pub fn features(self) -> FeatureConfigBuilder {
1613 FeatureConfigBuilder { builder: self }
1614 }
1615
1616 pub fn rate_limiting(self) -> RateLimitConfigBuilder {
1618 RateLimitConfigBuilder { builder: self }
1619 }
1620
1621 pub fn cors(self) -> CorsConfigBuilder {
1623 CorsConfigBuilder { builder: self }
1624 }
1625
1626 pub fn audit(self) -> AuditConfigBuilder {
1628 AuditConfigBuilder { builder: self }
1629 }
1630
1631 pub fn build(self) -> Result<AuthConfig> {
1633 let config = self.config;
1634 config.validate()?;
1635 Ok(config)
1636 }
1637}
1638
1639#[derive(Debug)]
1641pub struct TokenConfigBuilder {
1642 builder: AuthConfigBuilder,
1643}
1644
1645impl TokenConfigBuilder {
1646 pub fn lifetime(mut self, duration: Duration) -> Self {
1648 self.builder.config.token_lifetime = duration;
1649 self
1650 }
1651
1652 pub fn refresh_lifetime(mut self, duration: Duration) -> Self {
1654 self.builder.config.refresh_token_lifetime = duration;
1655 self
1656 }
1657
1658 pub fn issuer(mut self, issuer: impl Into<String>) -> Self {
1660 self.builder.config.issuer = issuer.into();
1661 self
1662 }
1663
1664 pub fn audience(mut self, audience: impl Into<String>) -> Self {
1666 self.builder.config.audience = audience.into();
1667 self
1668 }
1669
1670 pub fn secret(mut self, secret: impl Into<String>) -> Self {
1672 self.builder.config.secret = Some(secret.into());
1673 self
1674 }
1675
1676 pub fn done(self) -> AuthConfigBuilder {
1678 self.builder
1679 }
1680}
1681
1682#[derive(Debug)]
1684pub struct SecurityConfigBuilder {
1685 builder: AuthConfigBuilder,
1686}
1687
1688impl SecurityConfigBuilder {
1689 pub fn min_password_length(mut self, length: usize) -> Self {
1691 self.builder.config.security.min_password_length = length;
1692 self
1693 }
1694
1695 pub fn require_complexity(mut self, required: bool) -> Self {
1697 self.builder.config.security.require_password_complexity = required;
1698 self
1699 }
1700
1701 pub fn password_algorithm(mut self, algorithm: PasswordHashAlgorithm) -> Self {
1703 self.builder.config.security.password_hash_algorithm = algorithm;
1704 self
1705 }
1706
1707 pub fn jwt_algorithm(mut self, algorithm: JwtAlgorithm) -> Self {
1709 self.builder.config.security.jwt_algorithm = algorithm;
1710 self
1711 }
1712
1713 pub fn secure_cookies(mut self, enabled: bool) -> Self {
1715 self.builder.config.security.secure_cookies = enabled;
1716 self
1717 }
1718
1719 pub fn cookie_same_site(mut self, policy: CookieSameSite) -> Self {
1721 self.builder.config.security.cookie_same_site = policy;
1722 self
1723 }
1724
1725 pub fn csrf_protection(mut self, enabled: bool) -> Self {
1727 self.builder.config.security.csrf_protection = enabled;
1728 self
1729 }
1730
1731 pub fn session_timeout(mut self, timeout: Duration) -> Self {
1733 self.builder.config.security.session_timeout = timeout;
1734 self
1735 }
1736
1737 pub fn done(self) -> AuthConfigBuilder {
1739 self.builder
1740 }
1741}
1742
1743#[derive(Debug)]
1745pub struct StorageConfigBuilder {
1746 builder: AuthConfigBuilder,
1747}
1748
1749impl StorageConfigBuilder {
1750 pub fn memory(mut self) -> Self {
1752 self.builder.config.storage = StorageConfig::Memory;
1753 self
1754 }
1755
1756 #[cfg(feature = "redis-storage")]
1758 pub fn redis(mut self, url: impl Into<String>) -> Self {
1759 self.builder.config.storage = StorageConfig::Redis {
1760 url: url.into(),
1761 key_prefix: "auth:".to_string(),
1762 };
1763 self
1764 }
1765
1766 #[cfg(feature = "postgres-storage")]
1768 pub fn postgres(mut self, connection_string: impl Into<String>) -> Self {
1769 self.builder.config.storage = StorageConfig::Postgres {
1770 connection_string: connection_string.into(),
1771 table_prefix: "auth_".to_string(),
1772 };
1773 self
1774 }
1775
1776 #[cfg(feature = "mysql-storage")]
1778 pub fn mysql(mut self, connection_string: impl Into<String>) -> Self {
1779 self.builder.config.storage = StorageConfig::MySQL {
1780 connection_string: connection_string.into(),
1781 table_prefix: "auth_".to_string(),
1782 };
1783 self
1784 }
1785
1786 #[cfg(feature = "sqlite-storage")]
1788 pub fn sqlite(mut self, connection_string: impl Into<String>) -> Self {
1789 self.builder.config.storage = StorageConfig::Sqlite {
1790 connection_string: connection_string.into(),
1791 };
1792 self
1793 }
1794
1795 pub fn done(self) -> AuthConfigBuilder {
1797 self.builder
1798 }
1799}
1800
1801#[derive(Debug)]
1803pub struct FeatureConfigBuilder {
1804 builder: AuthConfigBuilder,
1805}
1806
1807impl FeatureConfigBuilder {
1808 pub fn enable_multi_factor(mut self, enabled: bool) -> Self {
1810 self.builder.config.enable_multi_factor = enabled;
1811 self
1812 }
1813
1814 pub fn enable_rbac(mut self, enabled: bool) -> Self {
1816 self.builder.config.enable_rbac = enabled;
1817 self
1818 }
1819
1820 pub fn enable_caching(mut self, enabled: bool) -> Self {
1822 self.builder.config.enable_caching = enabled;
1823 self
1824 }
1825
1826 pub fn enable_middleware(mut self, enabled: bool) -> Self {
1828 self.builder.config.enable_middleware = enabled;
1829 self
1830 }
1831
1832 pub fn max_failed_attempts(mut self, max: u32) -> Self {
1834 self.builder.config.max_failed_attempts = max;
1835 self
1836 }
1837
1838 pub fn done(self) -> AuthConfigBuilder {
1840 self.builder
1841 }
1842}
1843
1844#[derive(Debug)]
1846pub struct RateLimitConfigBuilder {
1847 builder: AuthConfigBuilder,
1848}
1849
1850impl RateLimitConfigBuilder {
1851 pub fn enabled(mut self, max_requests: u32, window: Duration) -> Self {
1853 self.builder.config.rate_limiting = RateLimitConfig::new(max_requests, window);
1854 self
1855 }
1856
1857 pub fn disabled(mut self) -> Self {
1859 self.builder.config.rate_limiting = RateLimitConfig::disabled();
1860 self
1861 }
1862
1863 pub fn max_requests(mut self, max: u32) -> Self {
1865 self.builder.config.rate_limiting.max_requests = max;
1866 self
1867 }
1868
1869 pub fn window(mut self, window: Duration) -> Self {
1871 self.builder.config.rate_limiting.window = window;
1872 self
1873 }
1874
1875 pub fn burst(mut self, burst: u32) -> Self {
1877 self.builder.config.rate_limiting.burst = burst;
1878 self
1879 }
1880
1881 pub fn done(self) -> AuthConfigBuilder {
1883 self.builder
1884 }
1885}
1886
1887#[derive(Debug)]
1889pub struct CorsConfigBuilder {
1890 builder: AuthConfigBuilder,
1891}
1892
1893impl CorsConfigBuilder {
1894 pub fn allow_origins<I, S>(mut self, origins: I) -> Self
1896 where
1897 I: IntoIterator<Item = S>,
1898 S: Into<String>,
1899 {
1900 self.builder.config.cors = CorsConfig::for_origins(origins);
1901 self
1902 }
1903
1904 pub fn disabled(mut self) -> Self {
1906 self.builder.config.cors.enabled = false;
1907 self
1908 }
1909
1910 pub fn allow_methods<I, S>(mut self, methods: I) -> Self
1912 where
1913 I: IntoIterator<Item = S>,
1914 S: Into<String>,
1915 {
1916 self.builder.config.cors.allowed_methods = methods.into_iter().map(Into::into).collect();
1917 self
1918 }
1919
1920 pub fn allow_headers<I, S>(mut self, headers: I) -> Self
1922 where
1923 I: IntoIterator<Item = S>,
1924 S: Into<String>,
1925 {
1926 self.builder.config.cors.allowed_headers = headers.into_iter().map(Into::into).collect();
1927 self
1928 }
1929
1930 pub fn max_age(mut self, seconds: u32) -> Self {
1932 self.builder.config.cors.max_age_secs = seconds;
1933 self
1934 }
1935
1936 pub fn done(self) -> AuthConfigBuilder {
1938 self.builder
1939 }
1940}
1941
1942#[derive(Debug)]
1944pub struct AuditConfigBuilder {
1945 builder: AuthConfigBuilder,
1946}
1947
1948impl AuditConfigBuilder {
1949 pub fn enabled(mut self) -> Self {
1951 self.builder.config.audit.enabled = true;
1952 self
1953 }
1954
1955 pub fn disabled(mut self) -> Self {
1957 self.builder.config.audit.enabled = false;
1958 self
1959 }
1960
1961 pub fn log_success(mut self, enabled: bool) -> Self {
1963 self.builder.config.audit.log_success = enabled;
1964 self
1965 }
1966
1967 pub fn log_failures(mut self, enabled: bool) -> Self {
1969 self.builder.config.audit.log_failures = enabled;
1970 self
1971 }
1972
1973 pub fn log_permissions(mut self, enabled: bool) -> Self {
1975 self.builder.config.audit.log_permissions = enabled;
1976 self
1977 }
1978
1979 pub fn log_tokens(mut self, enabled: bool) -> Self {
1981 self.builder.config.audit.log_tokens = enabled;
1982 self
1983 }
1984
1985 pub fn done(self) -> AuthConfigBuilder {
1987 self.builder
1988 }
1989}