1use crate::errors::{AuthError, Result};
13use config::{Config, Environment, File, FileFormat};
14use serde::{Deserialize, Serialize};
15use std::collections::HashMap;
16use std::path::Path;
17
18#[derive(Debug, Clone)]
20pub struct ConfigManager {
21 config: Config,
23 sources: Vec<String>,
25 env_prefix: String,
27}
28
29#[derive(Debug, Clone)]
31pub struct ConfigBuilder {
32 sources: Vec<ConfigSource>,
34 env_prefix: String,
36 include_defaults: bool,
38 search_paths: Vec<String>,
40}
41
42#[derive(Debug, Clone)]
44pub enum ConfigSource {
45 File {
47 path: String,
48 format: FileFormat,
49 required: bool,
50 },
51 Environment { prefix: String },
53 Values(HashMap<String, config::Value>),
55 IncludeDir { path: String, pattern: String },
57}
58
59#[derive(Debug, Clone, Serialize, Deserialize, Default)]
61#[serde(default)]
62pub struct AuthFrameworkSettings {
63 #[serde(flatten)]
65 pub auth: super::AuthConfig,
66
67 #[serde(skip_serializing_if = "Option::is_none")]
69 pub api_server: Option<ApiServerSettings>,
70
71 #[serde(skip_serializing_if = "Option::is_none")]
73 pub threat_intelligence: Option<crate::threat_intelligence::ThreatIntelConfig>,
74
75 #[serde(skip_serializing_if = "Option::is_none")]
77 pub session: Option<SessionSettings>,
78
79 #[serde(flatten)]
81 pub custom: HashMap<String, serde_json::Value>,
82}
83
84#[derive(Debug, Clone, Serialize, Deserialize)]
86#[serde(default)]
87pub struct ApiServerSettings {
88 pub host: String,
90
91 pub port: u16,
93
94 pub max_body_size: usize,
96
97 pub enable_tracing: bool,
99}
100
101#[derive(Debug, Clone, Serialize, Deserialize)]
103#[serde(default)]
104pub struct SessionSettings {
105 pub max_concurrent_sessions: Option<u32>,
107
108 pub cleanup_interval: Option<u64>,
110
111 pub enable_device_tracking: Option<bool>,
113
114 pub cookie: Option<SessionCookieSettings>,
116}
117
118#[derive(Debug, Clone, Serialize, Deserialize)]
120#[serde(default)]
121pub struct SessionCookieSettings {
122 pub name: Option<String>,
124
125 pub domain: Option<String>,
127
128 pub path: Option<String>,
130
131 pub max_age: Option<u64>,
133
134 pub http_only: Option<bool>,
136}
137
138impl Default for ConfigBuilder {
139 fn default() -> Self {
140 Self::new()
141 }
142}
143
144impl ConfigBuilder {
145 pub fn new() -> Self {
147 Self {
148 sources: Vec::new(),
149 env_prefix: "AUTH_FRAMEWORK".to_string(),
150 include_defaults: true,
151 search_paths: vec![
152 ".".to_string(),
153 "./config".to_string(),
154 "/etc/auth-framework".to_string(),
155 dirs::config_dir()
156 .map(|d| d.join("auth-framework").to_string_lossy().to_string())
157 .unwrap_or_else(|| "./config".to_string()),
158 ],
159 }
160 }
161
162 pub fn with_env_prefix(mut self, prefix: impl Into<String>) -> Self {
164 self.env_prefix = prefix.into();
165 self
166 }
167
168 pub fn without_defaults(mut self) -> Self {
170 self.include_defaults = false;
171 self
172 }
173
174 pub fn add_file<P: AsRef<Path>>(mut self, path: P, required: bool) -> Self {
176 let path_str = path.as_ref().to_string_lossy().to_string();
177 let format = Self::detect_format(&path_str);
178
179 self.sources.push(ConfigSource::File {
180 path: path_str,
181 format,
182 required,
183 });
184 self
185 }
186
187 pub fn add_file_with_format<P: AsRef<Path>>(
189 mut self,
190 path: P,
191 format: FileFormat,
192 required: bool,
193 ) -> Self {
194 self.sources.push(ConfigSource::File {
195 path: path.as_ref().to_string_lossy().to_string(),
196 format,
197 required,
198 });
199 self
200 }
201
202 pub fn add_env_source(mut self, prefix: impl Into<String>) -> Self {
204 self.sources.push(ConfigSource::Environment {
205 prefix: prefix.into(),
206 });
207 self
208 }
209
210 pub fn add_values(mut self, values: HashMap<String, config::Value>) -> Self {
212 self.sources.push(ConfigSource::Values(values));
213 self
214 }
215
216 pub fn add_include_dir(mut self, path: impl Into<String>, pattern: impl Into<String>) -> Self {
218 self.sources.push(ConfigSource::IncludeDir {
219 path: path.into(),
220 pattern: pattern.into(),
221 });
222 self
223 }
224
225 pub fn add_search_path(mut self, path: impl Into<String>) -> Self {
227 self.search_paths.push(path.into());
228 self
229 }
230
231 pub fn build(self) -> Result<ConfigManager> {
233 let mut config = Config::builder();
234 let mut sources = Vec::new();
235
236 if self.include_defaults {
238 for search_path in &self.search_paths {
240 for filename in &[
241 "auth-framework.toml",
242 "auth-framework.yaml",
243 "auth-framework.yml",
244 "auth-framework.json",
245 "auth.toml",
246 "auth.yaml",
247 "auth.yml",
248 "auth.json",
249 ] {
250 let path = Path::new(search_path).join(filename);
251 if path.exists() {
252 let format = Self::detect_format(&path.to_string_lossy());
253 config = config
254 .add_source(File::from(path.clone()).format(format).required(false));
255 sources.push(path.to_string_lossy().to_string());
256 }
257 }
258 }
259 }
260
261 for source in self.sources {
263 match source {
264 ConfigSource::File {
265 path,
266 format,
267 required,
268 } => {
269 config = config.add_source(File::new(&path, format).required(required));
270 sources.push(path);
271 }
272 ConfigSource::Environment { prefix } => {
273 config = config.add_source(
274 Environment::with_prefix(&prefix)
275 .prefix_separator("_")
276 .separator("__"),
277 );
278 sources.push(format!("env:{}", prefix));
279 }
280 ConfigSource::Values(values) => {
281 for (key, value) in values {
282 config = config.set_override(&key, value).map_err(|e| {
283 AuthError::config(format!("Failed to set override: {e}"))
284 })?;
285 }
286 sources.push("values:override".to_string());
287 }
288 ConfigSource::IncludeDir { path, pattern } => {
289 if let Ok(entries) = std::fs::read_dir(&path) {
291 let mut files: Vec<_> = entries
292 .filter_map(|entry| entry.ok())
293 .filter(|entry| entry.file_name().to_string_lossy().contains(&pattern))
294 .collect();
295
296 files.sort_by_key(|e| e.file_name());
298
299 for entry in files {
300 let file_path = entry.path();
301 let format = Self::detect_format(&file_path.to_string_lossy());
302 config = config.add_source(
303 File::from(file_path.clone()).format(format).required(false),
304 );
305 sources.push(file_path.to_string_lossy().to_string());
306 }
307 }
308 }
309 }
310 }
311
312 config = config.add_source(
314 Environment::with_prefix(&self.env_prefix)
315 .prefix_separator("_")
316 .separator("__"),
317 );
318 sources.push(format!("env:{}", self.env_prefix));
319
320 let built_config = config
321 .build()
322 .map_err(|e| AuthError::config(format!("Failed to build configuration: {e}")))?;
323
324 Ok(ConfigManager {
325 config: built_config,
326 sources,
327 env_prefix: self.env_prefix,
328 })
329 }
330
331 fn detect_format(path: &str) -> FileFormat {
333 let path = Path::new(path);
334 match path.extension().and_then(|s| s.to_str()) {
335 Some("toml") => FileFormat::Toml,
336 Some("yaml") | Some("yml") => FileFormat::Yaml,
337 Some("json") => FileFormat::Json,
338 Some("ron") => FileFormat::Ron,
339 Some("ini") => FileFormat::Ini,
340 _ => FileFormat::Toml, }
342 }
343}
344
345impl ConfigManager {
346 pub fn new() -> Result<Self> {
348 ConfigBuilder::new().build()
349 }
350
351 pub fn for_application(app_name: &str) -> Result<Self> {
353 ConfigBuilder::new()
354 .with_env_prefix(format!("{}_AUTH_FRAMEWORK", app_name.to_uppercase()))
355 .add_file(format!("{}.toml", app_name), false)
356 .add_file(format!("config/{}.toml", app_name), false)
357 .build()
358 }
359
360 pub fn get_auth_settings(&self) -> Result<AuthFrameworkSettings> {
362 self.config
363 .clone()
364 .try_deserialize::<AuthFrameworkSettings>()
365 .map_err(|e| AuthError::config(format!("Failed to deserialize auth settings: {e}")))
366 }
367
368 pub fn get_section<T>(&self, section: &str) -> Result<T>
370 where
371 T: for<'de> Deserialize<'de>,
372 {
373 self.config
374 .get::<T>(section)
375 .map_err(|e| AuthError::config(format!("Failed to get section '{}': {e}", section)))
376 }
377
378 pub fn get<T>(&self, key: &str) -> Result<T>
380 where
381 T: for<'de> Deserialize<'de>,
382 {
383 self.config
384 .get::<T>(key)
385 .map_err(|e| AuthError::config(format!("Failed to get key '{}': {e}", key)))
386 }
387
388 pub fn get_or_default<T>(&self, key: &str, default: T) -> T
390 where
391 T: for<'de> Deserialize<'de>,
392 {
393 self.config.get::<T>(key).unwrap_or(default)
394 }
395
396 pub fn has_key(&self, key: &str) -> bool {
398 self.config.get::<config::Value>(key).is_ok()
399 }
400
401 pub fn get_keys_with_prefix(&self, prefix: &str) -> Vec<String> {
403 if let Ok(table) = self.config.get_table(prefix) {
405 table.keys().map(|k| format!("{}.{}", prefix, k)).collect()
406 } else {
407 Vec::new()
408 }
409 }
410
411 pub fn sources(&self) -> &[String] {
413 &self.sources
414 }
415
416 pub fn env_prefix(&self) -> &str {
418 &self.env_prefix
419 }
420
421 pub fn validate(&self) -> Result<()> {
423 let auth_config = self.get_auth_settings()?;
424 auth_config.auth.validate()
425 }
426
427 pub fn section(&self, section: &str) -> Result<ConfigManager> {
429 let section_config = self
430 .config
431 .get::<HashMap<String, config::Value>>(section)
432 .map_err(|e| AuthError::config(format!("Failed to get section '{}': {e}", section)))?;
433
434 let mut config_builder = Config::builder();
435 for (key, value) in section_config {
436 config_builder = config_builder
437 .set_override(&key, value)
438 .map_err(|e| AuthError::config(format!("Failed to set override: {e}")))?;
439 }
440
441 let built_config = config_builder
442 .build()
443 .map_err(|e| AuthError::config(format!("Failed to build section config: {e}")))?;
444
445 Ok(ConfigManager {
446 config: built_config,
447 sources: vec![format!("section:{}", section)],
448 env_prefix: format!("{}_{}", self.env_prefix, section.to_uppercase()),
449 })
450 }
451
452 pub fn merge(self, other: ConfigManager) -> Result<ConfigManager> {
454 let mut sources = self.sources;
455 sources.extend(other.sources);
456
457 Ok(ConfigManager {
460 config: other.config,
461 sources,
462 env_prefix: other.env_prefix,
463 })
464 }
465
466 pub fn export_to_string(&self, format: FileFormat) -> Result<String> {
468 let settings = self.get_auth_settings()?;
469
470 match format {
471 FileFormat::Toml => toml::to_string_pretty(&settings)
472 .map_err(|e| AuthError::config(format!("Failed to serialize to TOML: {e}"))),
473 FileFormat::Yaml => serde_yaml::to_string(&settings)
474 .map_err(|e| AuthError::config(format!("Failed to serialize to YAML: {e}"))),
475 FileFormat::Json => serde_json::to_string_pretty(&settings)
476 .map_err(|e| AuthError::config(format!("Failed to serialize to JSON: {e}"))),
477 _ => Err(AuthError::config("Unsupported export format")),
478 }
479 }
480}
481
482impl Default for ConfigManager {
483 fn default() -> Self {
490 Self::new().expect(
491 "ConfigManager::default(): failed to build default configuration. \
492 Use ConfigManager::new() for Result-based error handling.",
493 )
494 }
495}
496
497impl Default for ApiServerSettings {
498 fn default() -> Self {
499 Self {
500 host: "0.0.0.0".to_string(),
501 port: 8080,
502 max_body_size: 1024 * 1024,
503 enable_tracing: true,
504 }
505 }
506}
507
508impl Default for SessionSettings {
509 fn default() -> Self {
510 Self {
511 max_concurrent_sessions: Some(5),
512 cleanup_interval: Some(3600), enable_device_tracking: Some(true),
514 cookie: Some(SessionCookieSettings::default()),
515 }
516 }
517}
518
519impl Default for SessionCookieSettings {
520 fn default() -> Self {
521 Self {
522 name: Some("auth_session".to_string()),
523 domain: None,
524 path: Some("/".to_string()),
525 max_age: Some(86400), http_only: Some(true),
527 }
528 }
529}
530
531pub trait ConfigIntegration {
533 fn auth_framework(&self) -> Option<&AuthFrameworkSettings>;
535
536 fn auth_framework_mut(&mut self) -> Option<&mut AuthFrameworkSettings>;
538}
539
540#[cfg(test)]
541mod tests {
542 use super::*;
543
544 #[test]
545 fn test_config_builder_basic() {
546 let config = ConfigBuilder::new()
547 .with_env_prefix("TEST")
548 .build()
549 .expect("Failed to build config");
550
551 assert_eq!(config.env_prefix(), "TEST");
552 }
553
554 #[test]
555 fn test_config_manager_default() {
556 let settings = AuthFrameworkSettings::default();
559
560 assert!(!settings.auth.enable_multi_factor);
562 assert_eq!(settings.auth.token_lifetime.as_secs(), 3600); assert_eq!(settings.auth.issuer, "auth-framework");
564 }
565
566 #[test]
567 fn test_application_specific_config() {
568 let config = ConfigManager::for_application("myapp").expect("Failed to create app config");
569
570 assert_eq!(config.env_prefix(), "MYAPP_AUTH_FRAMEWORK");
571 }
572
573 #[test]
574 fn test_partial_settings_file_uses_defaults() {
575 use std::io::Write;
576
577 let mut file = tempfile::NamedTempFile::new().expect("Failed to create temp file");
578 writeln!(file, "issuer = \"example-issuer\"").expect("Failed to write issuer");
579 writeln!(file, "[api_server]").expect("Failed to write api_server header");
580 writeln!(file, "port = 9091").expect("Failed to write port");
581
582 let config = ConfigBuilder::new()
583 .without_defaults()
584 .add_file(file.path(), true)
585 .build()
586 .expect("Failed to build config");
587
588 let settings = config
589 .get_auth_settings()
590 .expect("Failed to deserialize settings");
591
592 assert_eq!(settings.auth.issuer, "example-issuer");
593 assert_eq!(settings.auth.audience, "api");
594 assert_eq!(settings.api_server.expect("Missing api_server").port, 9091);
595 }
596
597 #[test]
598 fn test_config_sources() {
599 let config = ConfigBuilder::new()
600 .add_file("nonexistent.toml", false)
601 .add_env_source("TEST")
602 .build()
603 .expect("Failed to build config");
604
605 let sources = config.sources();
606 assert!(!sources.is_empty());
607 }
608}