Skip to main content

auth_framework/config/
app_config.rs

1/// Configuration management with environment variable support.
2///
3/// This module provides easy configuration loading from environment
4/// variables, config files, and other sources.
5use 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/// Complete application configuration
16#[derive(Debug, Clone, Serialize, Deserialize)]
17pub struct AppConfig {
18    /// Database configuration
19    pub database: DatabaseConfig,
20    /// Redis configuration
21    pub redis: Option<RedisConfig>,
22    /// JWT configuration
23    pub jwt: JwtConfig,
24    /// OAuth providers
25    pub oauth: OAuthConfig,
26    /// Security settings
27    pub security: SecuritySettings,
28    /// Logging configuration
29    pub logging: LoggingConfig,
30}
31
32#[derive(Clone, Serialize, Deserialize)]
33pub struct DatabaseConfig {
34    pub url: String,
35    pub max_connections: u32,
36    pub min_connections: u32,
37    pub connect_timeout_seconds: u64,
38}
39
40impl std::fmt::Debug for DatabaseConfig {
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        let mut d = f.debug_struct("DatabaseConfig");
43        d.field("url", &crate::utils::redact::redacted(&self.url));
44        d.field("max_connections", &self.max_connections);
45        d.field("min_connections", &self.min_connections);
46        d.field("connect_timeout_seconds", &self.connect_timeout_seconds);
47        d.finish()
48    }
49}
50
51#[derive(Clone, Serialize, Deserialize)]
52pub struct RedisConfig {
53    pub url: String,
54    pub pool_size: u32,
55}
56
57impl std::fmt::Debug for RedisConfig {
58    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
59        let mut d = f.debug_struct("RedisConfig");
60        d.field("url", &crate::utils::redact::redacted(&self.url));
61        d.field("pool_size", &self.pool_size);
62        d.finish()
63    }
64}
65
66#[derive(Clone, Serialize, Deserialize)]
67pub struct JwtConfig {
68    pub secret_key: String,
69    pub issuer: String,
70    pub audience: String,
71    pub access_token_ttl_seconds: u64,
72    pub refresh_token_ttl_seconds: u64,
73}
74
75impl std::fmt::Debug for JwtConfig {
76    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77        let mut d = f.debug_struct("JwtConfig");
78        d.field(
79            "secret_key",
80            &crate::utils::redact::redacted(&self.secret_key),
81        );
82        d.field("issuer", &self.issuer);
83        d.field("audience", &self.audience);
84        d.field("access_token_ttl_seconds", &self.access_token_ttl_seconds);
85        d.field("refresh_token_ttl_seconds", &self.refresh_token_ttl_seconds);
86        d.finish()
87    }
88}
89
90#[derive(Debug, Clone, Serialize, Deserialize)]
91pub struct OAuthConfig {
92    pub google: Option<OAuthProviderConfig>,
93    pub github: Option<OAuthProviderConfig>,
94    pub microsoft: Option<OAuthProviderConfig>,
95}
96
97#[derive(Clone, Serialize, Deserialize)]
98pub struct OAuthProviderConfig {
99    pub client_id: String,
100    pub client_secret: String,
101    pub redirect_uri: String,
102    pub scopes: Vec<String>,
103}
104
105impl std::fmt::Debug for OAuthProviderConfig {
106    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
107        let mut d = f.debug_struct("OAuthProviderConfig");
108        d.field("client_id", &self.client_id);
109        d.field(
110            "client_secret",
111            &crate::utils::redact::redacted(&self.client_secret),
112        );
113        d.field("redirect_uri", &self.redirect_uri);
114        d.field("scopes", &self.scopes);
115        d.finish()
116    }
117}
118
119#[derive(Debug, Clone, Serialize, Deserialize)]
120pub struct SecuritySettings {
121    pub password_min_length: usize,
122    pub password_require_special: bool,
123    pub rate_limit_requests_per_minute: u32,
124    pub session_timeout_hours: u64,
125    pub max_concurrent_sessions: u32,
126    pub require_mfa: bool,
127}
128
129#[derive(Debug, Clone, Serialize, Deserialize)]
130pub struct LoggingConfig {
131    pub level: String,
132    pub audit_enabled: bool,
133    pub audit_storage: String, // "database", "file", "syslog"
134}
135
136impl AppConfig {
137    /// Load configuration from environment variables
138    pub fn from_env() -> Result<Self, ConfigError> {
139        Ok(Self {
140            database: DatabaseConfig {
141                url: env::var("DATABASE_URL")
142                    .map_err(|_| ConfigError::MissingEnvVar("DATABASE_URL"))?,
143                max_connections: env::var("DB_MAX_CONNECTIONS")
144                    .unwrap_or_else(|_| "10".to_string())
145                    .parse()
146                    .map_err(|_| ConfigError::InvalidValue("DB_MAX_CONNECTIONS"))?,
147                min_connections: 1,
148                connect_timeout_seconds: 30,
149            },
150            redis: if let Ok(redis_url) = env::var("REDIS_URL") {
151                Some(RedisConfig {
152                    url: redis_url,
153                    pool_size: 10,
154                })
155            } else {
156                None
157            },
158            jwt: JwtConfig {
159                secret_key: env::var("JWT_SECRET")
160                    .map_err(|_| ConfigError::MissingEnvVar("JWT_SECRET"))?,
161                issuer: env::var("JWT_ISSUER").unwrap_or_else(|_| "auth-framework".to_string()),
162                audience: env::var("JWT_AUDIENCE").unwrap_or_else(|_| "api".to_string()),
163                access_token_ttl_seconds: 3600,
164                refresh_token_ttl_seconds: 86400 * 7,
165            },
166            oauth: OAuthConfig {
167                google: Self::load_oauth_provider("GOOGLE"),
168                github: Self::load_oauth_provider("GITHUB"),
169                microsoft: Self::load_oauth_provider("MICROSOFT"),
170            },
171            security: SecuritySettings {
172                password_min_length: 8,
173                password_require_special: true,
174                rate_limit_requests_per_minute: 60,
175                session_timeout_hours: 24,
176                max_concurrent_sessions: 5,
177                require_mfa: env::var("REQUIRE_MFA").unwrap_or_default() == "true",
178            },
179            logging: LoggingConfig {
180                level: env::var("LOG_LEVEL").unwrap_or_else(|_| "info".to_string()),
181                audit_enabled: true,
182                audit_storage: env::var("AUDIT_STORAGE").unwrap_or_else(|_| "database".to_string()),
183            },
184        })
185    }
186
187    fn load_oauth_provider(provider: &str) -> Option<OAuthProviderConfig> {
188        let client_id = env::var(format!("{}_CLIENT_ID", provider)).ok()?;
189        let client_secret = env::var(format!("{}_CLIENT_SECRET", provider)).ok()?;
190
191        Some(OAuthProviderConfig {
192            client_id,
193            client_secret,
194            redirect_uri: env::var(format!("{}_REDIRECT_URI", provider))
195                .unwrap_or_else(|_| format!("/auth/{}/callback", provider.to_lowercase())),
196            scopes: env::var(format!("{}_SCOPES", provider))
197                .unwrap_or_default()
198                .split(',')
199                .map(|s| s.trim().to_string())
200                .filter(|s| !s.is_empty())
201                .collect(),
202        })
203    }
204
205    /// Convert to AuthConfig
206    pub fn to_auth_config(&self) -> super::AuthConfig {
207        super::AuthConfig::new()
208            .token_lifetime(Duration::from_secs(self.jwt.access_token_ttl_seconds))
209            .refresh_token_lifetime(Duration::from_secs(self.jwt.refresh_token_ttl_seconds))
210            .issuer(&self.jwt.issuer)
211            .audience(&self.jwt.audience)
212            .secret(&self.jwt.secret_key)
213    }
214
215    /// Convert to SecurityConfig
216    pub fn to_security_config(&self) -> SecurityConfig {
217        SecurityConfig::default() // Would customize based on security settings
218    }
219}
220
221#[derive(Debug, thiserror::Error)]
222pub enum ConfigError {
223    #[error("Missing environment variable: {0}")]
224    MissingEnvVar(&'static str),
225    #[error("Invalid value for: {0}")]
226    InvalidValue(&'static str),
227    #[error("Configuration validation error: {0}")]
228    Validation(String),
229}
230
231/// Configuration builder for easy setup
232pub struct ConfigBuilder {
233    config: AppConfig,
234}
235
236impl ConfigBuilder {
237    pub fn new() -> Self {
238        Self {
239            config: AppConfig::from_env().unwrap_or_else(|_| AppConfig::default()),
240        }
241    }
242
243    pub fn with_database_url(mut self, url: impl Into<String>) -> Self {
244        self.config.database.url = url.into();
245        self
246    }
247
248    pub fn with_jwt_secret(mut self, secret: impl Into<String>) -> Self {
249        self.config.jwt.secret_key = secret.into();
250        self
251    }
252
253    pub fn with_redis_url(mut self, url: impl Into<String>) -> Self {
254        self.config.redis = Some(RedisConfig {
255            url: url.into(),
256            pool_size: 10,
257        });
258        self
259    }
260
261    pub fn build(self) -> AppConfig {
262        self.config
263    }
264}
265
266/// The signing secret `AppConfig::default()` uses: random, generated once per process.
267///
268/// Every default configuration in a process agrees (a token signed under one verifies under another),
269/// and no two processes share it, so it is not a value anyone can know in advance. Tokens signed with it
270/// do not survive a restart; set `JWT_SECRET` (or `ConfigBuilder::with_jwt_secret`) for a stable key.
271fn process_signing_secret() -> &'static str {
272    static SECRET: std::sync::OnceLock<String> = std::sync::OnceLock::new();
273    SECRET.get_or_init(|| {
274        // Two random v4 UUIDs from the operating system's CSPRNG: 64 hex digits.
275        format!(
276            "{}{}",
277            uuid::Uuid::new_v4().simple(),
278            uuid::Uuid::new_v4().simple()
279        )
280    })
281}
282
283impl Default for AppConfig {
284    fn default() -> Self {
285        Self {
286            database: DatabaseConfig {
287                url: "postgresql://localhost/auth_framework".to_string(),
288                max_connections: 10,
289                min_connections: 1,
290                connect_timeout_seconds: 30,
291            },
292            redis: None,
293            jwt: JwtConfig {
294                secret_key: process_signing_secret().to_string(),
295                issuer: "auth-framework".to_string(),
296                audience: "api".to_string(),
297                access_token_ttl_seconds: 3600,
298                refresh_token_ttl_seconds: 86400 * 7,
299            },
300            oauth: OAuthConfig {
301                google: None,
302                github: None,
303                microsoft: None,
304            },
305            security: SecuritySettings {
306                password_min_length: 8,
307                password_require_special: true,
308                rate_limit_requests_per_minute: 60,
309                session_timeout_hours: 24,
310                max_concurrent_sessions: 5,
311                require_mfa: false,
312            },
313            logging: LoggingConfig {
314                level: "info".to_string(),
315                audit_enabled: true,
316                audit_storage: "database".to_string(),
317            },
318        }
319    }
320}
321
322#[cfg(test)]
323mod tests {
324    use super::*;
325
326    #[test]
327    fn test_config_builder() {
328        let config = ConfigBuilder::new()
329            .with_database_url("postgresql://test")
330            .with_jwt_secret("test-secret")
331            .build();
332
333        assert_eq!(config.database.url, "postgresql://test");
334        assert_eq!(config.jwt.secret_key, "test-secret");
335    }
336}