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(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
84impl std::fmt::Debug for AuthFrameworkSettings {
85 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
86 let mut d = f.debug_struct("AuthFrameworkSettings");
87 d.field("auth", &self.auth);
88 d.field("api_server", &self.api_server);
89 d.field("threat_intelligence", &self.threat_intelligence);
90 d.field("session", &self.session);
91 d.field("custom", &crate::utils::redact::redacted(&self.custom));
92 d.finish()
93 }
94}
95
96#[derive(Debug, Clone, Serialize, Deserialize)]
98#[serde(default)]
99pub struct ApiServerSettings {
100 pub host: String,
102
103 pub port: u16,
105
106 pub max_body_size: usize,
108
109 pub enable_tracing: bool,
111}
112
113#[derive(Debug, Clone, Serialize, Deserialize)]
115#[serde(default)]
116pub struct SessionSettings {
117 pub max_concurrent_sessions: Option<u32>,
119
120 pub cleanup_interval: Option<u64>,
122
123 pub enable_device_tracking: Option<bool>,
125
126 pub cookie: Option<SessionCookieSettings>,
128}
129
130#[derive(Debug, Clone, Serialize, Deserialize)]
132#[serde(default)]
133pub struct SessionCookieSettings {
134 pub name: Option<String>,
136
137 pub domain: Option<String>,
139
140 pub path: Option<String>,
142
143 pub max_age: Option<u64>,
145
146 pub http_only: Option<bool>,
148}
149
150impl Default for ConfigBuilder {
151 fn default() -> Self {
152 Self::new()
153 }
154}
155
156impl ConfigBuilder {
157 pub fn new() -> Self {
159 Self {
160 sources: Vec::new(),
161 env_prefix: "AUTH_FRAMEWORK".to_string(),
162 include_defaults: true,
163 search_paths: vec![
164 ".".to_string(),
165 "./config".to_string(),
166 "/etc/auth-framework".to_string(),
167 dirs::config_dir()
168 .map(|d| d.join("auth-framework").to_string_lossy().to_string())
169 .unwrap_or_else(|| "./config".to_string()),
170 ],
171 }
172 }
173
174 pub fn with_env_prefix(mut self, prefix: impl Into<String>) -> Self {
176 self.env_prefix = prefix.into();
177 self
178 }
179
180 pub fn without_defaults(mut self) -> Self {
182 self.include_defaults = false;
183 self
184 }
185
186 pub fn add_file<P: AsRef<Path>>(mut self, path: P, required: bool) -> Self {
188 let path_str = path.as_ref().to_string_lossy().to_string();
189 let format = Self::detect_format(&path_str);
190
191 self.sources.push(ConfigSource::File {
192 path: path_str,
193 format,
194 required,
195 });
196 self
197 }
198
199 pub fn add_file_with_format<P: AsRef<Path>>(
201 mut self,
202 path: P,
203 format: FileFormat,
204 required: bool,
205 ) -> Self {
206 self.sources.push(ConfigSource::File {
207 path: path.as_ref().to_string_lossy().to_string(),
208 format,
209 required,
210 });
211 self
212 }
213
214 pub fn add_env_source(mut self, prefix: impl Into<String>) -> Self {
216 self.sources.push(ConfigSource::Environment {
217 prefix: prefix.into(),
218 });
219 self
220 }
221
222 pub fn add_values(mut self, values: HashMap<String, config::Value>) -> Self {
224 self.sources.push(ConfigSource::Values(values));
225 self
226 }
227
228 pub fn add_include_dir(mut self, path: impl Into<String>, pattern: impl Into<String>) -> Self {
230 self.sources.push(ConfigSource::IncludeDir {
231 path: path.into(),
232 pattern: pattern.into(),
233 });
234 self
235 }
236
237 pub fn add_search_path(mut self, path: impl Into<String>) -> Self {
239 self.search_paths.push(path.into());
240 self
241 }
242
243 pub fn build(self) -> Result<ConfigManager> {
245 let mut config = Config::builder();
246 let mut sources = Vec::new();
247
248 if self.include_defaults {
250 for search_path in &self.search_paths {
252 for filename in &[
253 "auth-framework.toml",
254 "auth-framework.yaml",
255 "auth-framework.yml",
256 "auth-framework.json",
257 "auth.toml",
258 "auth.yaml",
259 "auth.yml",
260 "auth.json",
261 ] {
262 let path = Path::new(search_path).join(filename);
263 if path.exists() {
264 let format = Self::detect_format(&path.to_string_lossy());
265 config = config
266 .add_source(File::from(path.clone()).format(format).required(false));
267 sources.push(path.to_string_lossy().to_string());
268 }
269 }
270 }
271 }
272
273 for source in self.sources {
275 match source {
276 ConfigSource::File {
277 path,
278 format,
279 required,
280 } => {
281 config = config.add_source(File::new(&path, format).required(required));
282 sources.push(path);
283 }
284 ConfigSource::Environment { prefix } => {
285 config = config.add_source(
286 Environment::with_prefix(&prefix)
287 .prefix_separator("_")
288 .separator("__"),
289 );
290 sources.push(format!("env:{}", prefix));
291 }
292 ConfigSource::Values(values) => {
293 for (key, value) in values {
294 config = config.set_override(&key, value).map_err(|e| {
295 AuthError::config(format!("Failed to set override: {e}"))
296 })?;
297 }
298 sources.push("values:override".to_string());
299 }
300 ConfigSource::IncludeDir { path, pattern } => {
301 if let Ok(entries) = std::fs::read_dir(&path) {
303 let mut files: Vec<_> = entries
304 .filter_map(|entry| entry.ok())
305 .filter(|entry| entry.file_name().to_string_lossy().contains(&pattern))
306 .collect();
307
308 files.sort_by_key(|e| e.file_name());
310
311 for entry in files {
312 let file_path = entry.path();
313 let format = Self::detect_format(&file_path.to_string_lossy());
314 config = config.add_source(
315 File::from(file_path.clone()).format(format).required(false),
316 );
317 sources.push(file_path.to_string_lossy().to_string());
318 }
319 }
320 }
321 }
322 }
323
324 config = config.add_source(
326 Environment::with_prefix(&self.env_prefix)
327 .prefix_separator("_")
328 .separator("__"),
329 );
330 sources.push(format!("env:{}", self.env_prefix));
331
332 let built_config = config
333 .build()
334 .map_err(|e| AuthError::config(format!("Failed to build configuration: {e}")))?;
335
336 Ok(ConfigManager {
337 config: built_config,
338 sources,
339 env_prefix: self.env_prefix,
340 })
341 }
342
343 fn detect_format(path: &str) -> FileFormat {
345 let path = Path::new(path);
346 match path.extension().and_then(|s| s.to_str()) {
347 Some("toml") => FileFormat::Toml,
348 Some("yaml") | Some("yml") => FileFormat::Yaml,
349 Some("json") => FileFormat::Json,
350 Some("ron") => FileFormat::Ron,
351 Some("ini") => FileFormat::Ini,
352 _ => FileFormat::Toml, }
354 }
355}
356
357impl ConfigManager {
358 pub fn new() -> Result<Self> {
360 ConfigBuilder::new().build()
361 }
362
363 pub fn for_application(app_name: &str) -> Result<Self> {
365 ConfigBuilder::new()
366 .with_env_prefix(format!("{}_AUTH_FRAMEWORK", app_name.to_uppercase()))
367 .add_file(format!("{}.toml", app_name), false)
368 .add_file(format!("config/{}.toml", app_name), false)
369 .build()
370 }
371
372 pub fn get_auth_settings(&self) -> Result<AuthFrameworkSettings> {
374 self.config
375 .clone()
376 .try_deserialize::<AuthFrameworkSettings>()
377 .map_err(|e| AuthError::config(format!("Failed to deserialize auth settings: {e}")))
378 }
379
380 pub fn get_section<T>(&self, section: &str) -> Result<T>
382 where
383 T: for<'de> Deserialize<'de>,
384 {
385 self.config
386 .get::<T>(section)
387 .map_err(|e| AuthError::config(format!("Failed to get section '{}': {e}", section)))
388 }
389
390 pub fn get<T>(&self, key: &str) -> Result<T>
392 where
393 T: for<'de> Deserialize<'de>,
394 {
395 self.config
396 .get::<T>(key)
397 .map_err(|e| AuthError::config(format!("Failed to get key '{}': {e}", key)))
398 }
399
400 pub fn get_or_default<T>(&self, key: &str, default: T) -> T
402 where
403 T: for<'de> Deserialize<'de>,
404 {
405 self.config.get::<T>(key).unwrap_or(default)
406 }
407
408 pub fn has_key(&self, key: &str) -> bool {
410 self.config.get::<config::Value>(key).is_ok()
411 }
412
413 pub fn get_keys_with_prefix(&self, prefix: &str) -> Vec<String> {
415 if let Ok(table) = self.config.get_table(prefix) {
417 table.keys().map(|k| format!("{}.{}", prefix, k)).collect()
418 } else {
419 Vec::new()
420 }
421 }
422
423 pub fn sources(&self) -> &[String] {
425 &self.sources
426 }
427
428 pub fn env_prefix(&self) -> &str {
430 &self.env_prefix
431 }
432
433 pub fn validate(&self) -> Result<()> {
435 let auth_config = self.get_auth_settings()?;
436 auth_config.auth.validate()
437 }
438
439 pub fn section(&self, section: &str) -> Result<ConfigManager> {
441 let section_config = self
442 .config
443 .get::<HashMap<String, config::Value>>(section)
444 .map_err(|e| AuthError::config(format!("Failed to get section '{}': {e}", section)))?;
445
446 let mut config_builder = Config::builder();
447 for (key, value) in section_config {
448 config_builder = config_builder
449 .set_override(&key, value)
450 .map_err(|e| AuthError::config(format!("Failed to set override: {e}")))?;
451 }
452
453 let built_config = config_builder
454 .build()
455 .map_err(|e| AuthError::config(format!("Failed to build section config: {e}")))?;
456
457 Ok(ConfigManager {
458 config: built_config,
459 sources: vec![format!("section:{}", section)],
460 env_prefix: format!("{}_{}", self.env_prefix, section.to_uppercase()),
461 })
462 }
463
464 pub fn merge(self, other: ConfigManager) -> Result<ConfigManager> {
466 let mut sources = self.sources;
467 sources.extend(other.sources);
468
469 Ok(ConfigManager {
472 config: other.config,
473 sources,
474 env_prefix: other.env_prefix,
475 })
476 }
477
478 pub fn export_to_string(&self, format: FileFormat) -> Result<String> {
480 let settings = self.get_auth_settings()?;
481
482 match format {
483 FileFormat::Toml => toml::to_string_pretty(&settings)
484 .map_err(|e| AuthError::config(format!("Failed to serialize to TOML: {e}"))),
485 FileFormat::Yaml => serde_yaml::to_string(&settings)
486 .map_err(|e| AuthError::config(format!("Failed to serialize to YAML: {e}"))),
487 FileFormat::Json => serde_json::to_string_pretty(&settings)
488 .map_err(|e| AuthError::config(format!("Failed to serialize to JSON: {e}"))),
489 _ => Err(AuthError::config("Unsupported export format")),
490 }
491 }
492}
493
494impl Default for ConfigManager {
495 fn default() -> Self {
502 Self::new().expect(
503 "ConfigManager::default(): failed to build default configuration. \
504 Use ConfigManager::new() for Result-based error handling.",
505 )
506 }
507}
508
509impl Default for ApiServerSettings {
510 fn default() -> Self {
511 Self {
512 host: "0.0.0.0".to_string(),
513 port: 8080,
514 max_body_size: 1024 * 1024,
515 enable_tracing: true,
516 }
517 }
518}
519
520impl Default for SessionSettings {
521 fn default() -> Self {
522 Self {
523 max_concurrent_sessions: Some(5),
524 cleanup_interval: Some(3600), enable_device_tracking: Some(true),
526 cookie: Some(SessionCookieSettings::default()),
527 }
528 }
529}
530
531impl Default for SessionCookieSettings {
532 fn default() -> Self {
533 Self {
534 name: Some("auth_session".to_string()),
535 domain: None,
536 path: Some("/".to_string()),
537 max_age: Some(86400), http_only: Some(true),
539 }
540 }
541}
542
543pub trait ConfigIntegration {
545 fn auth_framework(&self) -> Option<&AuthFrameworkSettings>;
547
548 fn auth_framework_mut(&mut self) -> Option<&mut AuthFrameworkSettings>;
550}
551
552#[cfg(test)]
553mod tests {
554 use super::*;
555
556 #[test]
557 fn test_config_builder_basic() {
558 let config = ConfigBuilder::new()
559 .with_env_prefix("TEST")
560 .build()
561 .expect("Failed to build config");
562
563 assert_eq!(config.env_prefix(), "TEST");
564 }
565
566 #[test]
567 fn test_config_manager_default() {
568 let settings = AuthFrameworkSettings::default();
571
572 assert!(!settings.auth.enable_multi_factor);
574 assert_eq!(settings.auth.token_lifetime.as_secs(), 3600); assert_eq!(settings.auth.issuer, "auth-framework");
576 }
577
578 #[test]
579 fn test_application_specific_config() {
580 let config = ConfigManager::for_application("myapp").expect("Failed to create app config");
581
582 assert_eq!(config.env_prefix(), "MYAPP_AUTH_FRAMEWORK");
583 }
584
585 #[test]
586 fn test_partial_settings_file_uses_defaults() {
587 use std::io::Write;
588
589 let mut file = tempfile::NamedTempFile::new().expect("Failed to create temp file");
590 writeln!(file, "issuer = \"example-issuer\"").expect("Failed to write issuer");
591 writeln!(file, "[api_server]").expect("Failed to write api_server header");
592 writeln!(file, "port = 9091").expect("Failed to write port");
593
594 let config = ConfigBuilder::new()
595 .without_defaults()
596 .add_file(file.path(), true)
597 .build()
598 .expect("Failed to build config");
599
600 let settings = config
601 .get_auth_settings()
602 .expect("Failed to deserialize settings");
603
604 assert_eq!(settings.auth.issuer, "example-issuer");
605 assert_eq!(settings.auth.audience, "api");
606 assert_eq!(settings.api_server.expect("Missing api_server").port, 9091);
607 }
608
609 #[test]
610 fn test_config_sources() {
611 let config = ConfigBuilder::new()
612 .add_file("nonexistent.toml", false)
613 .add_env_source("TEST")
614 .build()
615 .expect("Failed to build config");
616
617 let sources = config.sources();
618 assert!(!sources.is_empty());
619 }
620}