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(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
81impl std::fmt::Debug for AuthConfig {
82 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
83 let mut d = f.debug_struct("AuthConfig");
84 d.field("token_lifetime", &self.token_lifetime);
85 d.field("refresh_token_lifetime", &self.refresh_token_lifetime);
86 d.field("enable_multi_factor", &self.enable_multi_factor);
87 d.field("issuer", &self.issuer);
88 d.field("audience", &self.audience);
89 d.field("secret", &crate::utils::redact::redacted(&self.secret));
90 d.field("storage", &self.storage);
91 d.field("rate_limiting", &self.rate_limiting);
92 d.field("security", &self.security);
93 d.field("cors", &self.cors);
94 d.field("audit", &self.audit);
95 d.field("enable_caching", &self.enable_caching);
96 d.field("max_failed_attempts", &self.max_failed_attempts);
97 d.field("enable_rbac", &self.enable_rbac);
98 d.field("enable_middleware", &self.enable_middleware);
99 d.field(
100 "method_configs",
101 &crate::utils::redact::redacted(&self.method_configs),
102 );
103 d.field("force_production_mode", &self.force_production_mode);
104 d.finish()
105 }
106}
107
108#[derive(Clone, Serialize, Deserialize)]
110pub enum StorageConfig {
111 Memory,
113
114 #[cfg(feature = "redis-storage")]
116 Redis { url: String, key_prefix: String },
117
118 #[cfg(feature = "postgres-storage")]
120 Postgres {
121 connection_string: String,
122 table_prefix: String,
123 },
124
125 #[cfg(feature = "sqlite-storage")]
127 Sqlite { connection_string: String },
128
129 Custom(String),
131}
132
133impl std::fmt::Debug for StorageConfig {
134 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
135 use crate::utils::redact::redacted;
136 match self {
137 Self::Memory => f.write_str("Memory"),
138 #[cfg(feature = "redis-storage")]
139 Self::Redis { url, key_prefix } => f
140 .debug_struct("Redis")
141 .field("url", &redacted(url))
142 .field("key_prefix", key_prefix)
143 .finish(),
144 #[cfg(feature = "postgres-storage")]
145 Self::Postgres {
146 connection_string,
147 table_prefix,
148 } => f
149 .debug_struct("Postgres")
150 .field("connection_string", &redacted(connection_string))
151 .field("table_prefix", table_prefix)
152 .finish(),
153 #[cfg(feature = "sqlite-storage")]
154 Self::Sqlite { connection_string } => f
155 .debug_struct("Sqlite")
156 .field("connection_string", &redacted(connection_string))
157 .finish(),
158 Self::Custom(name) => f.debug_tuple("Custom").field(name).finish(),
160 }
161 }
162}
163
164#[derive(Debug, Clone, Serialize, Deserialize)]
170#[serde(default)]
171pub struct RateLimitConfig {
172 pub enabled: bool,
174
175 pub max_requests: u32,
177
178 pub window: Duration,
180
181 pub burst: u32,
183}
184
185#[derive(Clone, Serialize, Deserialize)]
197#[serde(default)]
198pub struct SecurityConfig {
199 pub min_password_length: usize,
201
202 pub require_password_complexity: bool,
204
205 pub password_hash_algorithm: PasswordHashAlgorithm,
207
208 pub jwt_algorithm: JwtAlgorithm,
210
211 pub secret_key: Option<String>,
213
214 pub previous_secret_key: Option<String>,
216
217 pub secure_cookies: bool,
219
220 pub cookie_same_site: CookieSameSite,
222
223 pub csrf_protection: bool,
225
226 pub session_timeout: Duration,
228}
229
230impl std::fmt::Debug for SecurityConfig {
231 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
232 let mut d = f.debug_struct("SecurityConfig");
233 d.field("min_password_length", &self.min_password_length);
234 d.field(
235 "require_password_complexity",
236 &self.require_password_complexity,
237 );
238 d.field("password_hash_algorithm", &self.password_hash_algorithm);
239 d.field("jwt_algorithm", &self.jwt_algorithm);
240 d.field(
241 "secret_key",
242 &crate::utils::redact::redacted(&self.secret_key),
243 );
244 d.field(
245 "previous_secret_key",
246 &crate::utils::redact::redacted(&self.previous_secret_key),
247 );
248 d.field("secure_cookies", &self.secure_cookies);
249 d.field("cookie_same_site", &self.cookie_same_site);
250 d.field("csrf_protection", &self.csrf_protection);
251 d.field("session_timeout", &self.session_timeout);
252 d.finish()
253 }
254}
255
256#[derive(Debug, Clone, Serialize, Deserialize)]
258pub enum PasswordHashAlgorithm {
259 Argon2,
261 Bcrypt,
263 Scrypt,
265}
266
267#[derive(Debug, Clone, Serialize, Deserialize)]
269pub enum JwtAlgorithm {
270 HS256,
272 HS384,
274 HS512,
276 RS256,
278 RS384,
280 RS512,
282 ES256,
284 ES384,
286}
287
288#[derive(Debug, Clone, Serialize, Deserialize)]
290pub enum CookieSameSite {
291 Strict,
293 Lax,
295 None,
297}
298
299#[derive(Debug, Clone, Serialize, Deserialize)]
305#[serde(default)]
306pub struct CorsConfig {
307 pub enabled: bool,
309
310 pub allowed_origins: Vec<String>,
315
316 pub allowed_methods: Vec<String>,
318
319 pub allowed_headers: Vec<String>,
321
322 pub max_age_secs: u32,
324}
325
326impl Default for CorsConfig {
327 fn default() -> Self {
328 Self {
329 enabled: false,
330 allowed_origins: Vec::new(),
331 allowed_methods: vec![
332 "GET".to_string(),
333 "POST".to_string(),
334 "PUT".to_string(),
335 "DELETE".to_string(),
336 "OPTIONS".to_string(),
337 ],
338 allowed_headers: vec![
339 "Authorization".to_string(),
340 "Content-Type".to_string(),
341 "Accept".to_string(),
342 ],
343 max_age_secs: 3600,
344 }
345 }
346}
347
348impl CorsConfig {
349 pub fn for_origins<I, S>(origins: I) -> Self
360 where
361 I: IntoIterator<Item = S>,
362 S: Into<String>,
363 {
364 Self {
365 enabled: true,
366 allowed_origins: origins.into_iter().map(Into::into).collect(),
367 ..Default::default()
368 }
369 }
370}
371
372#[derive(Debug, Clone, Serialize, Deserialize)]
377#[serde(default)]
378pub struct AuditConfig {
379 pub enabled: bool,
381
382 pub log_success: bool,
384
385 pub log_failures: bool,
387
388 pub log_permissions: bool,
390
391 pub log_tokens: bool,
393
394 pub storage: AuditStorage,
396}
397
398#[derive(Clone, Serialize, Deserialize)]
402pub enum AuditStorage {
403 Tracing,
405
406 File { path: String },
408
409 Database { connection_string: String },
411
412 External { endpoint: String, api_key: String },
414}
415
416impl std::fmt::Debug for AuditStorage {
417 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
418 use crate::utils::redact::redacted;
419 match self {
420 Self::Tracing => f.write_str("Tracing"),
421 Self::File { path } => f.debug_struct("File").field("path", path).finish(),
422 Self::Database { connection_string } => f
423 .debug_struct("Database")
424 .field("connection_string", &redacted(connection_string))
425 .finish(),
426 Self::External { endpoint, api_key } => f
427 .debug_struct("External")
428 .field("endpoint", endpoint)
429 .field("api_key", &redacted(api_key))
430 .finish(),
431 }
432 }
433}
434
435const fn default_max_failed_attempts() -> u32 {
436 5
437}
438
439impl Default for AuthConfig {
440 fn default() -> Self {
441 Self {
442 token_lifetime: Duration::from_secs(3600), refresh_token_lifetime: Duration::from_secs(86400 * 7), enable_multi_factor: false,
445 issuer: "auth-framework".to_string(),
446 audience: "api".to_string(),
447 secret: None,
448 storage: StorageConfig::Memory,
449 rate_limiting: RateLimitConfig::default(),
450 security: SecurityConfig::default(),
451 cors: CorsConfig::default(),
452 audit: AuditConfig::default(),
453 enable_caching: false,
454 max_failed_attempts: default_max_failed_attempts(),
455 enable_rbac: false,
456 enable_middleware: false,
457 method_configs: HashMap::new(),
458 force_production_mode: false,
459 }
460 }
461}
462
463impl Default for RateLimitConfig {
464 fn default() -> Self {
465 Self {
466 enabled: true,
467 max_requests: 100,
468 window: Duration::from_secs(60), burst: 10,
470 }
471 }
472}
473
474impl Default for SecurityConfig {
475 fn default() -> Self {
476 Self {
477 min_password_length: 8,
478 require_password_complexity: true,
479 password_hash_algorithm: PasswordHashAlgorithm::Argon2,
480 jwt_algorithm: JwtAlgorithm::HS256,
481 secret_key: None,
482 previous_secret_key: None,
483 secure_cookies: true,
484 cookie_same_site: CookieSameSite::Lax,
485 csrf_protection: true,
486 session_timeout: Duration::from_secs(3600 * 24), }
488 }
489}
490
491impl Default for AuditConfig {
492 fn default() -> Self {
493 Self {
494 enabled: true,
495 log_success: true,
496 log_failures: true,
497 log_permissions: true,
498 log_tokens: false, storage: AuditStorage::Tracing,
500 }
501 }
502}
503
504impl std::fmt::Display for AuthConfig {
509 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
510 write!(
511 f,
512 "AuthConfig {{ tokens: {}s/{}s refresh, storage: {}, mfa: {}, rbac: {}, rate_limit: {}, security: {}, cors: {}, audit: {} }}",
513 self.token_lifetime.as_secs(),
514 self.refresh_token_lifetime.as_secs(),
515 self.storage,
516 if self.enable_multi_factor {
517 "on"
518 } else {
519 "off"
520 },
521 if self.enable_rbac { "on" } else { "off" },
522 self.rate_limiting,
523 self.security,
524 self.cors,
525 self.audit,
526 )
527 }
528}
529
530impl std::fmt::Display for StorageConfig {
531 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
532 match self {
533 Self::Memory => write!(f, "memory"),
534 #[cfg(feature = "redis-storage")]
535 Self::Redis { url, .. } => {
537 write!(f, "redis({})", crate::utils::redact::url_origin(url))
538 }
539 #[cfg(feature = "postgres-storage")]
540 Self::Postgres { .. } => write!(f, "postgres"),
541 #[cfg(feature = "sqlite-storage")]
542 Self::Sqlite { .. } => write!(f, "sqlite"),
543 Self::Custom(name) => write!(f, "custom({})", name),
544 }
545 }
546}
547
548impl std::fmt::Display for SecurityConfig {
549 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
550 write!(
551 f,
552 "Security {{ pw≥{}, hash: {}, jwt: {}, cookies: {}, csrf: {}, session: {}s }}",
553 self.min_password_length,
554 self.password_hash_algorithm,
555 self.jwt_algorithm,
556 if self.secure_cookies {
557 "secure"
558 } else {
559 "plain"
560 },
561 if self.csrf_protection { "on" } else { "off" },
562 self.session_timeout.as_secs(),
563 )
564 }
565}
566
567impl std::fmt::Display for PasswordHashAlgorithm {
568 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
569 match self {
570 Self::Argon2 => write!(f, "argon2id"),
571 Self::Bcrypt => write!(f, "bcrypt"),
572 Self::Scrypt => write!(f, "scrypt"),
573 }
574 }
575}
576
577impl std::fmt::Display for JwtAlgorithm {
578 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
579 match self {
580 Self::HS256 => write!(f, "HS256"),
581 Self::HS384 => write!(f, "HS384"),
582 Self::HS512 => write!(f, "HS512"),
583 Self::RS256 => write!(f, "RS256"),
584 Self::RS384 => write!(f, "RS384"),
585 Self::RS512 => write!(f, "RS512"),
586 Self::ES256 => write!(f, "ES256"),
587 Self::ES384 => write!(f, "ES384"),
588 }
589 }
590}
591
592impl std::fmt::Display for RateLimitConfig {
593 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
594 if self.enabled {
595 write!(
596 f,
597 "{} req/{}s (burst {})",
598 self.max_requests,
599 self.window.as_secs(),
600 self.burst,
601 )
602 } else {
603 write!(f, "disabled")
604 }
605 }
606}
607
608impl std::fmt::Display for CorsConfig {
609 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
610 if self.enabled {
611 if self.allowed_origins.is_empty() {
612 write!(f, "cors(no origins)")
613 } else {
614 write!(f, "cors({})", self.allowed_origins.join(", "))
615 }
616 } else {
617 write!(f, "cors(off)")
618 }
619 }
620}
621
622impl std::fmt::Display for AuditConfig {
623 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
624 if self.enabled {
625 write!(f, "audit({})", self.storage)
626 } else {
627 write!(f, "audit(off)")
628 }
629 }
630}
631
632impl std::fmt::Display for AuditStorage {
633 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
634 match self {
635 Self::Tracing => write!(f, "tracing"),
636 Self::File { path } => write!(f, "file:{}", path),
637 Self::Database { .. } => write!(f, "database"),
638 Self::External { endpoint, .. } => write!(f, "external:{}", endpoint),
639 }
640 }
641}
642
643#[derive(Debug, Clone, Serialize, Deserialize)]
649pub struct RuntimeConfig {
650 pub token_lifetime_secs: u64,
652 pub refresh_token_lifetime_secs: u64,
654 pub enable_multi_factor: bool,
656 pub rate_limiting_enabled: bool,
658 pub rate_limit_max_requests: u32,
660 pub rate_limit_window_secs: u64,
662 pub rate_limit_burst: u32,
664 pub min_password_length: usize,
666 pub require_password_complexity: bool,
668 pub secure_cookies: bool,
670 pub csrf_protection: bool,
672 pub session_timeout_secs: u64,
674 pub audit_enabled: bool,
676 pub audit_log_success: bool,
678 pub audit_log_failures: bool,
680 pub audit_log_permissions: bool,
682 pub audit_log_tokens: bool,
684}
685
686impl RuntimeConfig {
687 pub fn from_auth_config(cfg: &AuthConfig) -> Self {
699 Self {
700 token_lifetime_secs: cfg.token_lifetime.as_secs(),
701 refresh_token_lifetime_secs: cfg.refresh_token_lifetime.as_secs(),
702 enable_multi_factor: cfg.enable_multi_factor,
703 rate_limiting_enabled: cfg.rate_limiting.enabled,
704 rate_limit_max_requests: cfg.rate_limiting.max_requests,
705 rate_limit_window_secs: cfg.rate_limiting.window.as_secs(),
706 rate_limit_burst: cfg.rate_limiting.burst,
707 min_password_length: cfg.security.min_password_length,
708 require_password_complexity: cfg.security.require_password_complexity,
709 secure_cookies: cfg.security.secure_cookies,
710 csrf_protection: cfg.security.csrf_protection,
711 session_timeout_secs: cfg.security.session_timeout.as_secs(),
712 audit_enabled: cfg.audit.enabled,
713 audit_log_success: cfg.audit.log_success,
714 audit_log_failures: cfg.audit.log_failures,
715 audit_log_permissions: cfg.audit.log_permissions,
716 audit_log_tokens: cfg.audit.log_tokens,
717 }
718 }
719}
720
721impl Default for RuntimeConfig {
722 fn default() -> Self {
723 Self::from_auth_config(&AuthConfig::default())
724 }
725}
726
727impl AuthConfig {
728 pub fn new() -> Self {
760 Self::default()
761 }
762
763 pub fn from_env() -> Self {
787 let mut config = Self::default();
788
789 if let Ok(secret) = std::env::var("JWT_SECRET") {
790 config.secret = Some(secret.clone());
791 config.security.secret_key = Some(secret);
792 }
793
794 if let Ok(issuer) = std::env::var("AUTH_ISSUER") {
795 config.issuer = issuer;
796 }
797
798 if let Ok(audience) = std::env::var("AUTH_AUDIENCE") {
799 config.audience = audience;
800 }
801
802 #[cfg(feature = "postgres-storage")]
804 if let Ok(url) = std::env::var("DATABASE_URL") {
805 config.storage = StorageConfig::Postgres {
806 connection_string: url,
807 table_prefix: "auth_".to_string(),
808 };
809 }
810
811 #[cfg(feature = "redis-storage")]
812 if matches!(config.storage, StorageConfig::Memory)
813 && let Ok(url) = std::env::var("REDIS_URL")
814 {
815 config.storage = StorageConfig::Redis {
816 url,
817 key_prefix: "auth:".to_string(),
818 };
819 }
820
821 config
822 }
823
824 pub fn builder() -> crate::builders::AuthBuilder {
846 crate::builders::AuthBuilder::new()
847 }
848
849 pub fn token_lifetime(mut self, lifetime: Duration) -> Self {
861 self.token_lifetime = lifetime;
862 self
863 }
864
865 pub fn refresh_token_lifetime(mut self, lifetime: Duration) -> Self {
877 self.refresh_token_lifetime = lifetime;
878 self
879 }
880
881 pub fn enable_multi_factor(mut self, enabled: bool) -> Self {
892 self.enable_multi_factor = enabled;
893 self
894 }
895
896 pub fn issuer(mut self, issuer: impl Into<String>) -> Self {
898 self.issuer = issuer.into();
899 self
900 }
901
902 pub fn audience(mut self, audience: impl Into<String>) -> Self {
904 self.audience = audience.into();
905 self
906 }
907
908 pub fn secret(mut self, secret: impl Into<String>) -> Self {
910 self.secret = Some(secret.into());
911 self
912 }
913
914 pub fn require_mfa(mut self, required: bool) -> Self {
925 self.enable_multi_factor = required;
926 self
927 }
928
929 pub fn enable_caching(mut self, enabled: bool) -> Self {
931 self.enable_caching = enabled;
932 self
933 }
934
935 pub fn max_failed_attempts(mut self, max: u32) -> Self {
946 self.max_failed_attempts = max;
947 self
948 }
949
950 pub fn enable_rbac(mut self, enabled: bool) -> Self {
961 self.enable_rbac = enabled;
962 self
963 }
964
965 pub fn enable_security_audit(mut self, enabled: bool) -> Self {
976 self.audit.enabled = enabled;
977 self
978 }
979
980 pub fn enable_middleware(mut self, enabled: bool) -> Self {
991 self.enable_middleware = enabled;
992 self
993 }
994
995 pub fn force_production_mode(mut self) -> Self {
1008 self.force_production_mode = true;
1009 self
1010 }
1011
1012 pub fn storage(mut self, storage: StorageConfig) -> Self {
1022 self.storage = storage;
1023 self
1024 }
1025
1026 #[cfg(feature = "redis-storage")]
1036 pub fn redis_storage(mut self, url: impl Into<String>) -> Self {
1037 self.storage = StorageConfig::Redis {
1038 url: url.into(),
1039 key_prefix: "auth:".to_string(),
1040 };
1041 self
1042 }
1043
1044 pub fn rate_limiting(mut self, config: RateLimitConfig) -> Self {
1054 self.rate_limiting = config;
1055 self
1056 }
1057
1058 pub fn security(mut self, config: SecurityConfig) -> Self {
1068 self.security = config;
1069 self
1070 }
1071
1072 pub fn cors(mut self, config: CorsConfig) -> Self {
1083 self.cors = config;
1084 self
1085 }
1086
1087 pub fn audit(mut self, config: AuditConfig) -> Self {
1097 self.audit = config;
1098 self
1099 }
1100
1101 pub fn method_config(
1116 mut self,
1117 method_name: impl Into<String>,
1118 config: impl Serialize,
1119 ) -> Result<Self> {
1120 let value = serde_json::to_value(config)
1121 .map_err(|e| AuthError::config(format!("Failed to serialize method config: {e}")))?;
1122
1123 self.method_configs.insert(method_name.into(), value);
1124 Ok(self)
1125 }
1126
1127 pub fn get_method_config<T>(&self, method_name: &str) -> Result<Option<T>>
1139 where
1140 T: for<'de> Deserialize<'de>,
1141 {
1142 if let Some(value) = self.method_configs.get(method_name) {
1143 let config = serde_json::from_value(value.clone()).map_err(|e| {
1144 AuthError::config(format!("Failed to deserialize method config: {e}"))
1145 })?;
1146 Ok(Some(config))
1147 } else {
1148 Ok(None)
1149 }
1150 }
1151
1152 pub fn validate(&self) -> Result<()> {
1163 if self.token_lifetime.as_secs() == 0 {
1165 return Err(AuthError::config("Token lifetime must be greater than 0"));
1166 }
1167
1168 if self.refresh_token_lifetime.as_secs() == 0 {
1169 return Err(AuthError::config(
1170 "Refresh token lifetime must be greater than 0",
1171 ));
1172 }
1173
1174 if self.refresh_token_lifetime <= self.token_lifetime {
1175 return Err(AuthError::config(
1176 "Refresh token lifetime must be greater than token lifetime",
1177 ));
1178 }
1179
1180 self.validate_jwt_secret()?;
1182
1183 if self.security.min_password_length < 4 {
1185 return Err(AuthError::config(
1186 "Minimum password length must be at least 4 characters",
1187 ));
1188 }
1189
1190 if self.is_production_environment() && !self.is_test_environment() {
1192 self.validate_production_security()?;
1193 }
1194
1195 if self.rate_limiting.enabled && self.rate_limiting.max_requests == 0 {
1197 return Err(AuthError::config(
1198 "Rate limit max requests must be greater than 0 when enabled",
1199 ));
1200 }
1201
1202 self.validate_storage_config()?;
1204
1205 self.validate_method_configs()?;
1208
1209 Ok(())
1210 }
1211
1212 fn validate_method_configs(&self) -> Result<()> {
1213 for (method_name, raw_config) in &self.method_configs {
1214 match method_name.as_str() {
1215 #[cfg(feature = "saml")]
1216 "saml" => {
1217 let config: crate::methods::saml::SamlConfig =
1218 serde_json::from_value(raw_config.clone()).map_err(|e| {
1219 AuthError::config(format!(
1220 "Failed to deserialize SAML method config: {e}"
1221 ))
1222 })?;
1223
1224 if config.entity_id.trim().is_empty() {
1225 return Err(AuthError::config("SAML entity_id cannot be empty"));
1226 }
1227 if config.acs_url.trim().is_empty() {
1228 return Err(AuthError::config("SAML acs_url cannot be empty"));
1229 }
1230 if config.max_assertion_age == 0 {
1231 return Err(AuthError::config(
1232 "SAML max_assertion_age must be greater than 0",
1233 ));
1234 }
1235 }
1236 #[cfg(not(feature = "saml"))]
1237 "saml" => {
1238 return Err(AuthError::config(
1239 "SAML method config is present but the 'saml' feature is not enabled",
1240 ));
1241 }
1242 #[cfg(feature = "passkeys")]
1243 "passkey" => {
1244 let config: crate::methods::passkey::PasskeyConfig =
1245 serde_json::from_value(raw_config.clone()).map_err(|e| {
1246 AuthError::config(format!(
1247 "Failed to deserialize passkey method config: {e}"
1248 ))
1249 })?;
1250
1251 if config.rp_id.trim().is_empty() {
1252 return Err(AuthError::config("Passkey RP ID cannot be empty"));
1253 }
1254 if config.origin.trim().is_empty() {
1255 return Err(AuthError::config("Passkey origin cannot be empty"));
1256 }
1257 if config.timeout_ms == 0 {
1258 return Err(AuthError::config("Passkey timeout must be greater than 0"));
1259 }
1260 match config.user_verification.as_str() {
1261 "required" | "preferred" | "discouraged" => {}
1262 _ => {
1263 return Err(AuthError::config(
1264 "Invalid passkey user_verification value",
1265 ));
1266 }
1267 }
1268 url::Url::parse(&config.origin).map_err(|e| {
1269 AuthError::config(format!("Invalid passkey origin URL: {e}"))
1270 })?;
1271 }
1272 #[cfg(not(feature = "passkeys"))]
1273 "passkey" => {
1274 return Err(AuthError::config(
1275 "Passkey method config is present but the 'passkeys' feature is not enabled",
1276 ));
1277 }
1278 "enhanced_device_flow" => {
1279 let client_id = raw_config
1280 .get("client_id")
1281 .and_then(serde_json::Value::as_str)
1282 .unwrap_or_default();
1283 let auth_url = raw_config
1284 .get("auth_url")
1285 .and_then(serde_json::Value::as_str)
1286 .unwrap_or_default();
1287 let token_url = raw_config
1288 .get("token_url")
1289 .and_then(serde_json::Value::as_str)
1290 .unwrap_or_default();
1291 let device_auth_url = raw_config
1292 .get("device_auth_url")
1293 .and_then(serde_json::Value::as_str)
1294 .unwrap_or_default();
1295
1296 if client_id.trim().is_empty()
1297 || auth_url.trim().is_empty()
1298 || token_url.trim().is_empty()
1299 || device_auth_url.trim().is_empty()
1300 {
1301 return Err(AuthError::config(
1302 "Enhanced device flow config requires non-empty client_id, auth_url, token_url, and device_auth_url",
1303 ));
1304 }
1305 }
1306 _ => {}
1307 }
1308 }
1309
1310 Ok(())
1311 }
1312
1313 fn validate_jwt_secret(&self) -> Result<()> {
1315 let env_secret = std::env::var("JWT_SECRET").ok();
1317 let jwt_secret = self
1318 .security
1319 .secret_key
1320 .as_ref()
1321 .or(self.secret.as_ref())
1322 .or(env_secret.as_ref());
1323
1324 if let Some(secret) = jwt_secret {
1325 if !self.is_test_environment() && secret.len() < 32 {
1328 return Err(AuthError::config(
1329 "JWT secret must be at least 32 characters for security. \
1330 Generate with: openssl rand -base64 32",
1331 ));
1332 }
1333
1334 if !self.is_test_environment() {
1337 let mut char_counts = std::collections::HashMap::new();
1338 for c in secret.chars() {
1339 *char_counts.entry(c).or_insert(0u32) += 1;
1340 }
1341 let len = secret.len() as f64;
1342 let entropy: f64 = char_counts
1343 .values()
1344 .map(|&count| {
1345 let p = count as f64 / len;
1346 -p * p.log2()
1347 })
1348 .sum();
1349 if entropy < 3.5 {
1350 return Err(AuthError::config(
1351 "JWT secret has insufficient entropy (too predictable). \
1352 Use a cryptographically secure random string.",
1353 ));
1354 }
1355 }
1356
1357 if secret.len() < 44
1359 && secret
1360 .chars()
1361 .all(|c| c.is_alphanumeric() || c == '+' || c == '/' || c == '=')
1362 {
1363 tracing::warn!(
1364 "JWT secret may be too short for optimal security. \
1365 Consider using at least 44 characters (32 bytes base64-encoded)."
1366 );
1367 }
1368 } else if self.is_production_environment() {
1369 return Err(AuthError::config(
1370 "JWT secret is required for production environments. \
1371 Set JWT_SECRET environment variable or configure security.secret_key",
1372 ));
1373 }
1374
1375 Ok(())
1376 }
1377
1378 fn validate_production_security(&self) -> Result<()> {
1380 if self.security.min_password_length < 8 {
1382 return Err(AuthError::config(
1383 "Production environments require minimum password length of 8 characters",
1384 ));
1385 }
1386
1387 if !self.security.require_password_complexity {
1388 tracing::warn!("Production deployment should enable password complexity requirements");
1389 }
1390
1391 if !self.security.secure_cookies {
1393 return Err(AuthError::config(
1394 "Production environments must use secure cookies (HTTPS required)",
1395 ));
1396 }
1397
1398 if !self.rate_limiting.enabled {
1400 tracing::warn!("Production deployment should enable rate limiting for security");
1401 }
1402
1403 if !self.audit.enabled {
1405 return Err(AuthError::config(
1406 "Production environments require audit logging for compliance",
1407 ));
1408 }
1409
1410 Ok(())
1411 }
1412
1413 fn validate_storage_config(&self) -> Result<()> {
1415 if let StorageConfig::Memory = &self.storage
1418 && self.is_production_environment()
1419 && !self.is_test_environment()
1420 {
1421 return Err(AuthError::config(
1422 "Memory storage is not suitable for production environments. \
1423 Use PostgreSQL, Redis, or SQLite storage.",
1424 ));
1425 }
1426
1427 Ok(())
1428 }
1429
1430 fn is_production_environment(&self) -> bool {
1432 if self.force_production_mode {
1434 return true;
1435 }
1436
1437 if let Ok(env) = std::env::var("ENVIRONMENT")
1439 && (env.to_lowercase() == "production" || env.to_lowercase() == "prod")
1440 {
1441 return true;
1442 }
1443
1444 if let Ok(env) = std::env::var("ENV")
1445 && (env.to_lowercase() == "production" || env.to_lowercase() == "prod")
1446 {
1447 return true;
1448 }
1449
1450 if let Ok(env) = std::env::var("NODE_ENV")
1451 && env.to_lowercase() == "production"
1452 {
1453 return true;
1454 }
1455
1456 if let Ok(env) = std::env::var("RUST_ENV")
1457 && env.to_lowercase() == "production"
1458 {
1459 return true;
1460 }
1461
1462 if std::env::var("KUBERNETES_SERVICE_HOST").is_ok() {
1464 return true;
1465 }
1466
1467 if std::env::var("DOCKER_CONTAINER").is_ok() {
1468 return true;
1469 }
1470
1471 false
1472 }
1473
1474 fn is_test_environment(&self) -> bool {
1476 if self.force_production_mode {
1478 return false;
1479 }
1480 cfg!(test)
1482 || std::thread::current()
1483 .name()
1484 .is_some_and(|name| name.contains("test"))
1485 || std::env::var("RUST_TEST").is_ok()
1486 || std::env::var("ENVIRONMENT").as_deref() == Ok("test")
1487 || std::env::var("ENV").as_deref() == Ok("test")
1488 || std::env::args().any(|arg| arg.contains("test"))
1489 }
1490}
1491
1492impl RateLimitConfig {
1493 pub fn new(max_requests: u32, window: Duration) -> Self {
1506 Self {
1507 enabled: true,
1508 max_requests,
1509 window,
1510 burst: max_requests / 10, }
1512 }
1513
1514 pub fn disabled() -> Self {
1525 Self {
1526 enabled: false,
1527 ..Default::default()
1528 }
1529 }
1530
1531 pub fn per_second(max: u32) -> Self {
1542 Self::new(max, Duration::from_secs(1))
1543 }
1544
1545 pub fn per_minute(max: u32) -> Self {
1556 Self::new(max, Duration::from_secs(60))
1557 }
1558
1559 pub fn per_hour(max: u32) -> Self {
1570 Self::new(max, Duration::from_secs(3600))
1571 }
1572}
1573
1574impl SecurityConfig {
1575 pub fn secure() -> Self {
1588 Self {
1589 min_password_length: 12,
1590 require_password_complexity: true,
1591 password_hash_algorithm: PasswordHashAlgorithm::Argon2,
1592 jwt_algorithm: JwtAlgorithm::RS256,
1593 secret_key: None,
1594 previous_secret_key: None,
1595 secure_cookies: true,
1596 cookie_same_site: CookieSameSite::Strict,
1597 csrf_protection: true,
1598 session_timeout: Duration::from_secs(3600 * 8), }
1600 }
1601
1602 pub fn development() -> Self {
1616 Self {
1617 min_password_length: 6,
1618 require_password_complexity: false,
1619 password_hash_algorithm: PasswordHashAlgorithm::Bcrypt,
1620 jwt_algorithm: JwtAlgorithm::HS256,
1621 secret_key: None, previous_secret_key: None,
1623 secure_cookies: false,
1624 cookie_same_site: CookieSameSite::Lax,
1625 csrf_protection: false,
1626 session_timeout: Duration::from_secs(3600 * 24), }
1628 }
1629}
1630
1631#[derive(Debug)]
1668pub struct AuthConfigBuilder {
1669 config: AuthConfig,
1670}
1671
1672impl Default for AuthConfigBuilder {
1673 fn default() -> Self {
1674 Self::new()
1675 }
1676}
1677
1678impl AuthConfigBuilder {
1679 pub fn new() -> Self {
1681 Self {
1682 config: AuthConfig::default(),
1683 }
1684 }
1685
1686 pub fn tokens(self) -> TokenConfigBuilder {
1688 TokenConfigBuilder { builder: self }
1689 }
1690
1691 pub fn security(self) -> SecurityConfigBuilder {
1693 SecurityConfigBuilder { builder: self }
1694 }
1695
1696 pub fn storage(self) -> StorageConfigBuilder {
1698 StorageConfigBuilder { builder: self }
1699 }
1700
1701 pub fn features(self) -> FeatureConfigBuilder {
1703 FeatureConfigBuilder { builder: self }
1704 }
1705
1706 pub fn rate_limiting(self) -> RateLimitConfigBuilder {
1708 RateLimitConfigBuilder { builder: self }
1709 }
1710
1711 pub fn cors(self) -> CorsConfigBuilder {
1713 CorsConfigBuilder { builder: self }
1714 }
1715
1716 pub fn audit(self) -> AuditConfigBuilder {
1718 AuditConfigBuilder { builder: self }
1719 }
1720
1721 pub fn build(self) -> Result<AuthConfig> {
1723 let config = self.config;
1724 config.validate()?;
1725 Ok(config)
1726 }
1727}
1728
1729#[derive(Debug)]
1731pub struct TokenConfigBuilder {
1732 builder: AuthConfigBuilder,
1733}
1734
1735impl TokenConfigBuilder {
1736 pub fn lifetime(mut self, duration: Duration) -> Self {
1738 self.builder.config.token_lifetime = duration;
1739 self
1740 }
1741
1742 pub fn refresh_lifetime(mut self, duration: Duration) -> Self {
1744 self.builder.config.refresh_token_lifetime = duration;
1745 self
1746 }
1747
1748 pub fn issuer(mut self, issuer: impl Into<String>) -> Self {
1750 self.builder.config.issuer = issuer.into();
1751 self
1752 }
1753
1754 pub fn audience(mut self, audience: impl Into<String>) -> Self {
1756 self.builder.config.audience = audience.into();
1757 self
1758 }
1759
1760 pub fn secret(mut self, secret: impl Into<String>) -> Self {
1762 self.builder.config.secret = Some(secret.into());
1763 self
1764 }
1765
1766 pub fn done(self) -> AuthConfigBuilder {
1768 self.builder
1769 }
1770}
1771
1772#[derive(Debug)]
1774pub struct SecurityConfigBuilder {
1775 builder: AuthConfigBuilder,
1776}
1777
1778impl SecurityConfigBuilder {
1779 pub fn min_password_length(mut self, length: usize) -> Self {
1781 self.builder.config.security.min_password_length = length;
1782 self
1783 }
1784
1785 pub fn require_complexity(mut self, required: bool) -> Self {
1787 self.builder.config.security.require_password_complexity = required;
1788 self
1789 }
1790
1791 pub fn password_algorithm(mut self, algorithm: PasswordHashAlgorithm) -> Self {
1793 self.builder.config.security.password_hash_algorithm = algorithm;
1794 self
1795 }
1796
1797 pub fn jwt_algorithm(mut self, algorithm: JwtAlgorithm) -> Self {
1799 self.builder.config.security.jwt_algorithm = algorithm;
1800 self
1801 }
1802
1803 pub fn secure_cookies(mut self, enabled: bool) -> Self {
1805 self.builder.config.security.secure_cookies = enabled;
1806 self
1807 }
1808
1809 pub fn cookie_same_site(mut self, policy: CookieSameSite) -> Self {
1811 self.builder.config.security.cookie_same_site = policy;
1812 self
1813 }
1814
1815 pub fn csrf_protection(mut self, enabled: bool) -> Self {
1817 self.builder.config.security.csrf_protection = enabled;
1818 self
1819 }
1820
1821 pub fn session_timeout(mut self, timeout: Duration) -> Self {
1823 self.builder.config.security.session_timeout = timeout;
1824 self
1825 }
1826
1827 pub fn done(self) -> AuthConfigBuilder {
1829 self.builder
1830 }
1831}
1832
1833#[derive(Debug)]
1835pub struct StorageConfigBuilder {
1836 builder: AuthConfigBuilder,
1837}
1838
1839impl StorageConfigBuilder {
1840 pub fn memory(mut self) -> Self {
1842 self.builder.config.storage = StorageConfig::Memory;
1843 self
1844 }
1845
1846 #[cfg(feature = "redis-storage")]
1848 pub fn redis(mut self, url: impl Into<String>) -> Self {
1849 self.builder.config.storage = StorageConfig::Redis {
1850 url: url.into(),
1851 key_prefix: "auth:".to_string(),
1852 };
1853 self
1854 }
1855
1856 #[cfg(feature = "postgres-storage")]
1858 pub fn postgres(mut self, connection_string: impl Into<String>) -> Self {
1859 self.builder.config.storage = StorageConfig::Postgres {
1860 connection_string: connection_string.into(),
1861 table_prefix: "auth_".to_string(),
1862 };
1863 self
1864 }
1865
1866 #[cfg(feature = "sqlite-storage")]
1868 pub fn sqlite(mut self, connection_string: impl Into<String>) -> Self {
1869 self.builder.config.storage = StorageConfig::Sqlite {
1870 connection_string: connection_string.into(),
1871 };
1872 self
1873 }
1874
1875 pub fn done(self) -> AuthConfigBuilder {
1877 self.builder
1878 }
1879}
1880
1881#[derive(Debug)]
1883pub struct FeatureConfigBuilder {
1884 builder: AuthConfigBuilder,
1885}
1886
1887impl FeatureConfigBuilder {
1888 pub fn enable_multi_factor(mut self, enabled: bool) -> Self {
1890 self.builder.config.enable_multi_factor = enabled;
1891 self
1892 }
1893
1894 pub fn enable_rbac(mut self, enabled: bool) -> Self {
1896 self.builder.config.enable_rbac = enabled;
1897 self
1898 }
1899
1900 pub fn enable_caching(mut self, enabled: bool) -> Self {
1902 self.builder.config.enable_caching = enabled;
1903 self
1904 }
1905
1906 pub fn enable_middleware(mut self, enabled: bool) -> Self {
1908 self.builder.config.enable_middleware = enabled;
1909 self
1910 }
1911
1912 pub fn max_failed_attempts(mut self, max: u32) -> Self {
1914 self.builder.config.max_failed_attempts = max;
1915 self
1916 }
1917
1918 pub fn done(self) -> AuthConfigBuilder {
1920 self.builder
1921 }
1922}
1923
1924#[derive(Debug)]
1926pub struct RateLimitConfigBuilder {
1927 builder: AuthConfigBuilder,
1928}
1929
1930impl RateLimitConfigBuilder {
1931 pub fn enabled(mut self, max_requests: u32, window: Duration) -> Self {
1933 self.builder.config.rate_limiting = RateLimitConfig::new(max_requests, window);
1934 self
1935 }
1936
1937 pub fn disabled(mut self) -> Self {
1939 self.builder.config.rate_limiting = RateLimitConfig::disabled();
1940 self
1941 }
1942
1943 pub fn max_requests(mut self, max: u32) -> Self {
1945 self.builder.config.rate_limiting.max_requests = max;
1946 self
1947 }
1948
1949 pub fn window(mut self, window: Duration) -> Self {
1951 self.builder.config.rate_limiting.window = window;
1952 self
1953 }
1954
1955 pub fn burst(mut self, burst: u32) -> Self {
1957 self.builder.config.rate_limiting.burst = burst;
1958 self
1959 }
1960
1961 pub fn done(self) -> AuthConfigBuilder {
1963 self.builder
1964 }
1965}
1966
1967#[derive(Debug)]
1969pub struct CorsConfigBuilder {
1970 builder: AuthConfigBuilder,
1971}
1972
1973impl CorsConfigBuilder {
1974 pub fn allow_origins<I, S>(mut self, origins: I) -> Self
1976 where
1977 I: IntoIterator<Item = S>,
1978 S: Into<String>,
1979 {
1980 self.builder.config.cors = CorsConfig::for_origins(origins);
1981 self
1982 }
1983
1984 pub fn disabled(mut self) -> Self {
1986 self.builder.config.cors.enabled = false;
1987 self
1988 }
1989
1990 pub fn allow_methods<I, S>(mut self, methods: I) -> Self
1992 where
1993 I: IntoIterator<Item = S>,
1994 S: Into<String>,
1995 {
1996 self.builder.config.cors.allowed_methods = methods.into_iter().map(Into::into).collect();
1997 self
1998 }
1999
2000 pub fn allow_headers<I, S>(mut self, headers: I) -> Self
2002 where
2003 I: IntoIterator<Item = S>,
2004 S: Into<String>,
2005 {
2006 self.builder.config.cors.allowed_headers = headers.into_iter().map(Into::into).collect();
2007 self
2008 }
2009
2010 pub fn max_age(mut self, seconds: u32) -> Self {
2012 self.builder.config.cors.max_age_secs = seconds;
2013 self
2014 }
2015
2016 pub fn done(self) -> AuthConfigBuilder {
2018 self.builder
2019 }
2020}
2021
2022#[derive(Debug)]
2024pub struct AuditConfigBuilder {
2025 builder: AuthConfigBuilder,
2026}
2027
2028impl AuditConfigBuilder {
2029 pub fn enabled(mut self) -> Self {
2031 self.builder.config.audit.enabled = true;
2032 self
2033 }
2034
2035 pub fn disabled(mut self) -> Self {
2037 self.builder.config.audit.enabled = false;
2038 self
2039 }
2040
2041 pub fn log_success(mut self, enabled: bool) -> Self {
2043 self.builder.config.audit.log_success = enabled;
2044 self
2045 }
2046
2047 pub fn log_failures(mut self, enabled: bool) -> Self {
2049 self.builder.config.audit.log_failures = enabled;
2050 self
2051 }
2052
2053 pub fn log_permissions(mut self, enabled: bool) -> Self {
2055 self.builder.config.audit.log_permissions = enabled;
2056 self
2057 }
2058
2059 pub fn log_tokens(mut self, enabled: bool) -> Self {
2061 self.builder.config.audit.log_tokens = enabled;
2062 self
2063 }
2064
2065 pub fn done(self) -> AuthConfigBuilder {
2067 self.builder
2068 }
2069}