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