1use super::SecurityConfig;
6use serde::{Deserialize, Serialize};
7use std::{env, time::Duration};
8use zeroize::Zeroizing;
9
10impl Default for ConfigBuilder {
11 fn default() -> Self {
12 Self::new()
13 }
14}
15
16#[derive(Debug, Clone, Serialize, Deserialize)]
18pub struct AppConfig {
19 pub database: DatabaseConfig,
21 pub redis: Option<RedisConfig>,
23 pub jwt: JwtConfig,
25 pub oauth: OAuthConfig,
27 pub security: SecuritySettings,
29 pub logging: LoggingConfig,
31}
32
33#[derive(Debug, Clone, Serialize, Deserialize)]
35pub struct DatabaseConfig {
36 pub url: String,
38 pub max_connections: u32,
40 pub min_connections: u32,
42 pub connect_timeout_seconds: u64,
44}
45
46#[derive(Debug, Clone, Serialize, Deserialize)]
48pub struct RedisConfig {
49 pub url: String,
51 pub pool_size: u32,
53}
54
55#[derive(Debug, Clone, Serialize, Deserialize)]
57pub struct JwtConfig {
58 pub secret_key: Zeroizing<String>,
60 pub issuer: String,
62 pub audience: String,
64 pub access_token_ttl_seconds: u64,
66 pub refresh_token_ttl_seconds: u64,
68}
69
70#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, std::hash::Hash)]
72#[serde(rename_all = "lowercase")]
73pub enum OAuthProvider {
74 Google,
76 GitHub,
78 Microsoft,
80 Custom(String),
82}
83
84#[derive(Debug, Clone, Serialize, Deserialize)]
86pub struct OAuthConfig {
87 pub providers: std::collections::HashMap<String, OAuthProviderConfig>,
89}
90
91#[derive(Debug, Clone, Serialize, Deserialize)]
93pub struct OAuthProviderConfig {
94 pub client_id: String,
96 pub client_secret: Zeroizing<String>,
98 pub redirect_uri: String,
100 pub scopes: Vec<String>,
102}
103
104#[derive(Debug, Clone, Serialize, Deserialize)]
106pub struct SecuritySettings {
107 pub password_min_length: usize,
109 pub password_require_special_chars: bool,
111 pub rate_limit_requests_per_minute: u32,
113 pub session_timeout_hours: u64,
115 pub max_concurrent_sessions: u32,
117 pub require_mfa: bool,
119}
120
121#[derive(Debug, Clone, Serialize, Deserialize)]
123pub struct LoggingConfig {
124 pub level: String,
126 pub audit_enabled: bool,
128 pub audit_storage: String,
130}
131
132impl AppConfig {
133 pub fn from_env() -> Result<Self, ConfigError> {
135 Ok(Self {
136 database: DatabaseConfig {
137 url: env::var("DATABASE_URL")
138 .map_err(|_| ConfigError::MissingEnvVar("DATABASE_URL"))?,
139 max_connections: env::var("DB_MAX_CONNECTIONS")
140 .unwrap_or_else(|_| "10".to_string())
141 .parse()
142 .map_err(|_| ConfigError::InvalidValue("DB_MAX_CONNECTIONS"))?,
143 min_connections: 1,
144 connect_timeout_seconds: 30,
145 },
146 redis: if let Ok(redis_url) = env::var("REDIS_URL") {
147 Some(RedisConfig {
148 url: redis_url,
149 pool_size: 10,
150 })
151 } else {
152 None
153 },
154 jwt: JwtConfig {
155 secret_key: env::var("JWT_SECRET")
156 .map_err(|_| ConfigError::MissingEnvVar("JWT_SECRET"))?
157 .into(),
158 issuer: env::var("JWT_ISSUER").unwrap_or_else(|_| "auth-framework".to_string()),
159 audience: env::var("JWT_AUDIENCE").unwrap_or_else(|_| "api".to_string()),
160 access_token_ttl_seconds: 3600,
161 refresh_token_ttl_seconds: 86400 * 7,
162 },
163 oauth: OAuthConfig {
164 providers: {
165 let mut map = std::collections::HashMap::new();
166 if let Some(cfg) = Self::load_oauth_provider("GOOGLE") {
167 map.insert("google".to_string(), cfg);
168 }
169 if let Some(cfg) = Self::load_oauth_provider("GITHUB") {
170 map.insert("github".to_string(), cfg);
171 }
172 if let Some(cfg) = Self::load_oauth_provider("MICROSOFT") {
173 map.insert("microsoft".to_string(), cfg);
174 }
175 map
176 },
177 },
178 security: SecuritySettings {
179 password_min_length: 8,
180 password_require_special_chars: true,
181 rate_limit_requests_per_minute: 60,
182 session_timeout_hours: 24,
183 max_concurrent_sessions: 5,
184 require_mfa: env::var("REQUIRE_MFA").unwrap_or_default() == "true",
185 },
186 logging: LoggingConfig {
187 level: env::var("LOG_LEVEL").unwrap_or_else(|_| "info".to_string()),
188 audit_enabled: true,
189 audit_storage: env::var("AUDIT_STORAGE").unwrap_or_else(|_| "database".to_string()),
190 },
191 })
192 }
193
194 fn load_oauth_provider(provider: &str) -> Option<OAuthProviderConfig> {
195 let client_id = env::var(format!("{}_CLIENT_ID", provider)).ok()?;
196 let client_secret = env::var(format!("{}_CLIENT_SECRET", provider)).ok()?;
197
198 Some(OAuthProviderConfig {
199 client_id,
200 client_secret: client_secret.into(),
201 redirect_uri: env::var(format!("{}_REDIRECT_URI", provider))
202 .unwrap_or_else(|_| format!("/auth/{}/callback", provider.to_lowercase())),
203 scopes: env::var(format!("{}_SCOPES", provider))
204 .unwrap_or_default()
205 .split(',')
206 .map(|s| s.trim().to_string())
207 .filter(|s| !s.is_empty())
208 .collect(),
209 })
210 }
211
212 pub fn to_auth_config(&self) -> super::AuthConfig {
214 let mut config = super::AuthConfig::new()
215 .token_lifetime(Duration::from_secs(self.jwt.access_token_ttl_seconds))
216 .refresh_token_lifetime(Duration::from_secs(self.jwt.refresh_token_ttl_seconds))
217 .issuer(&self.jwt.issuer)
218 .audience(&self.jwt.audience)
219 .secret(&*self.jwt.secret_key)
220 .security(self.to_security_config());
221
222 config.storage = self.primary_storage_config();
223 config.enable_multi_factor = self.security.require_mfa;
224 config.rate_limiting = super::RateLimitConfig {
225 enabled: self.security.rate_limit_requests_per_minute > 0,
226 max_requests: self.security.rate_limit_requests_per_minute,
227 window: Duration::from_secs(60),
228 burst: (self.security.rate_limit_requests_per_minute / 10).max(1),
229 };
230 config.audit.enabled = self.logging.audit_enabled;
231 config
232 }
233
234 pub fn to_security_config(&self) -> SecurityConfig {
236 SecurityConfig {
237 min_password_length: self.security.password_min_length,
238 require_password_complexity: self.security.password_require_special_chars,
239 secret_key: Some(self.jwt.secret_key.clone()),
240 session_timeout: Duration::from_secs(self.security.session_timeout_hours * 3600),
241 ..Default::default()
242 }
243 }
244
245 pub async fn build_auth_framework(&self) -> crate::errors::Result<crate::AuthFramework> {
247 let auth_config = self.to_auth_config();
248 let pool_size = self.primary_storage_pool_size();
249
250 let mut framework = crate::AuthFramework::new(auth_config.clone());
251 let storage = crate::storage::factory::build_storage_backend_with_encryption(
252 &auth_config.storage,
253 pool_size,
254 &auth_config.storage_encryption,
255 )
256 .await?;
257 framework.replace_storage_from_factory(storage);
258 framework.initialize().await?;
259 Ok(framework)
260 }
261
262 pub(crate) fn primary_storage_config(&self) -> super::StorageConfig {
263 let database_url = self.database.url.trim();
264
265 if database_url.starts_with("postgres://") || database_url.starts_with("postgresql://") {
266 #[cfg(feature = "postgres-storage")]
267 {
268 return super::StorageConfig::Postgres {
269 connection_string: database_url.to_string(),
270 table_prefix: "auth_".to_string(),
271 };
272 }
273
274 #[cfg(not(feature = "postgres-storage"))]
275 {
276 return super::StorageConfig::Custom(
277 "postgres-storage feature is required for PostgreSQL DATABASE_URL".to_string(),
278 );
279 }
280 }
281
282 if database_url.starts_with("mysql://") {
283 return super::StorageConfig::Custom(
284 "MySQL storage support has been removed; use postgres-storage, \
285 sqlite-storage, or redis-storage instead"
286 .to_string(),
287 );
288 }
289
290 if database_url.starts_with("sqlite:") {
291 #[cfg(feature = "sqlite-storage")]
292 {
293 return super::StorageConfig::Sqlite {
294 connection_string: database_url.to_string(),
295 };
296 }
297
298 #[cfg(not(feature = "sqlite-storage"))]
299 {
300 return super::StorageConfig::Custom(
301 "sqlite-storage feature is required for SQLite DATABASE_URL".to_string(),
302 );
303 }
304 }
305
306 super::StorageConfig::Memory
307 }
308
309 fn primary_storage_pool_size(&self) -> Option<u32> {
310 let database_url = self.database.url.trim();
311 if database_url.starts_with("postgres://")
312 || database_url.starts_with("postgresql://")
313 || database_url.starts_with("mysql://")
314 || database_url.starts_with("sqlite:")
315 {
316 return Some(self.database.max_connections);
317 }
318
319 None
320 }
321}
322
323#[derive(Debug, thiserror::Error)]
324pub enum ConfigError {
325 #[error("Missing environment variable: {0}")]
326 MissingEnvVar(&'static str),
327 #[error("Invalid value for: {0}")]
328 InvalidValue(&'static str),
329 #[error("Configuration validation error: {0}")]
330 Validation(String),
331}
332
333pub struct ConfigBuilder {
335 config: AppConfig,
336}
337
338impl ConfigBuilder {
339 pub fn new() -> Self {
340 Self {
341 config: AppConfig::from_env().unwrap_or_else(|_| AppConfig::default()),
342 }
343 }
344
345 pub fn with_database_url(mut self, url: impl Into<String>) -> Self {
346 self.config.database.url = url.into();
347 self
348 }
349
350 pub fn with_database_max_connections(mut self, max_connections: u32) -> Self {
351 self.config.database.max_connections = max_connections;
352 self
353 }
354
355 pub fn with_database_min_connections(mut self, min_connections: u32) -> Self {
356 self.config.database.min_connections = min_connections;
357 self
358 }
359
360 pub fn with_database_connect_timeout(mut self, seconds: u64) -> Self {
361 self.config.database.connect_timeout_seconds = seconds;
362 self
363 }
364
365 pub fn with_jwt_secret(mut self, secret: impl Into<String>) -> Self {
366 self.config.jwt.secret_key = Zeroizing::new(secret.into());
367 self
368 }
369
370 pub fn with_jwt_issuer(mut self, issuer: impl Into<String>) -> Self {
371 self.config.jwt.issuer = issuer.into();
372 self
373 }
374
375 pub fn with_jwt_audience(mut self, audience: impl Into<String>) -> Self {
376 self.config.jwt.audience = audience.into();
377 self
378 }
379
380 pub fn with_access_token_ttl_seconds(mut self, ttl_seconds: u64) -> Self {
381 self.config.jwt.access_token_ttl_seconds = ttl_seconds;
382 self
383 }
384
385 pub fn with_refresh_token_ttl_seconds(mut self, ttl_seconds: u64) -> Self {
386 self.config.jwt.refresh_token_ttl_seconds = ttl_seconds;
387 self
388 }
389
390 pub fn with_redis_url(mut self, url: impl Into<String>) -> Self {
391 self.config.redis = Some(RedisConfig {
392 url: url.into(),
393 pool_size: 10,
394 });
395 self
396 }
397
398 pub fn with_redis_pool_size(mut self, pool_size: u32) -> Self {
399 let redis = self.config.redis.get_or_insert(RedisConfig {
400 url: "redis://127.0.0.1:6379".to_string(),
401 pool_size: 10,
402 });
403 redis.pool_size = pool_size;
404 self
405 }
406
407 pub fn with_password_policy(mut self, min_length: usize, require_special: bool) -> Self {
413 self.config.security.password_min_length = min_length;
414 self.config.security.password_require_special_chars = require_special;
415 self
416 }
417
418 pub fn with_rate_limit_requests_per_minute(mut self, requests: u32) -> Self {
419 self.config.security.rate_limit_requests_per_minute = requests;
420 self
421 }
422
423 pub fn with_session_timeout_hours(mut self, hours: u64) -> Self {
424 self.config.security.session_timeout_hours = hours;
425 self
426 }
427
428 pub fn with_require_mfa(mut self, require_mfa: bool) -> Self {
429 self.config.security.require_mfa = require_mfa;
430 self
431 }
432
433 pub fn with_log_level(mut self, level: impl Into<String>) -> Self {
434 self.config.logging.level = level.into();
435 self
436 }
437
438 pub fn build(self) -> AppConfig {
439 self.config
440 }
441}
442
443fn process_signing_secret() -> &'static str {
449 static SECRET: std::sync::OnceLock<String> = std::sync::OnceLock::new();
450 SECRET.get_or_init(|| {
451 format!(
453 "{}{}",
454 uuid::Uuid::new_v4().simple(),
455 uuid::Uuid::new_v4().simple()
456 )
457 })
458}
459
460impl Default for AppConfig {
461 fn default() -> Self {
462 Self {
463 database: DatabaseConfig {
464 url: "postgresql://localhost/auth_framework".to_string(),
465 max_connections: 10,
466 min_connections: 1,
467 connect_timeout_seconds: 30,
468 },
469 redis: None,
470 jwt: JwtConfig {
471 secret_key: process_signing_secret().to_string().into(),
472 issuer: "auth-framework".to_string(),
473 audience: "api".to_string(),
474 access_token_ttl_seconds: 3600,
475 refresh_token_ttl_seconds: 86400 * 7,
476 },
477 oauth: OAuthConfig {
478 providers: std::collections::HashMap::new(),
479 },
480 security: SecuritySettings {
481 password_min_length: 8,
482 password_require_special_chars: true,
483 rate_limit_requests_per_minute: 60,
484 session_timeout_hours: 24,
485 max_concurrent_sessions: 5,
486 require_mfa: false,
487 },
488 logging: LoggingConfig {
489 level: "info".to_string(),
490 audit_enabled: true,
491 audit_storage: "database".to_string(),
492 },
493 }
494 }
495}
496
497#[cfg(test)]
498mod tests {
499 use super::*;
500
501 #[test]
502 fn test_config_builder() {
503 let config = ConfigBuilder::new()
504 .with_database_url("postgresql://test")
505 .with_database_max_connections(25)
506 .with_jwt_secret("test-secret")
507 .with_jwt_issuer("issuer")
508 .with_jwt_audience("audience")
509 .with_rate_limit_requests_per_minute(120)
510 .build();
511
512 assert_eq!(config.database.url, "postgresql://test");
513 assert_eq!(config.database.max_connections, 25);
514 assert_eq!(config.jwt.secret_key.as_str(), "test-secret");
515 assert_eq!(config.jwt.issuer, "issuer");
516 assert_eq!(config.jwt.audience, "audience");
517 assert_eq!(config.security.rate_limit_requests_per_minute, 120);
518 }
519}