Skip to main content

auth_framework/config/
config_manager.rs

1//! Advanced configuration management using the `config` crate.
2//!
3//! This module provides flexible configuration loading from multiple sources:
4//! - Configuration files (TOML, YAML, JSON, RON, INI)
5//! - Environment variables
6//! - Command line arguments (when integrated with clap)
7//! - Include directives for modular configuration files
8//!
9//! The configuration system is designed to be easily integrated into parent applications
10//! while providing sensible defaults for standalone use.
11
12use crate::errors::{AuthError, Result};
13use config::{Config, Environment, File, FileFormat};
14use serde::{Deserialize, Serialize};
15use std::collections::HashMap;
16use std::path::Path;
17
18/// Comprehensive configuration manager for the auth framework
19#[derive(Debug, Clone)]
20pub struct ConfigManager {
21    /// The underlying config builder
22    config: Config,
23    /// Configuration source paths for reference
24    sources: Vec<String>,
25    /// Environment variable prefix
26    env_prefix: String,
27}
28
29/// Configuration builder for easy integration into parent applications
30#[derive(Debug, Clone)]
31pub struct ConfigBuilder {
32    /// Configuration sources in order of priority (later sources override earlier ones)
33    sources: Vec<ConfigSource>,
34    /// Environment variable prefix
35    env_prefix: String,
36    /// Whether to include default auth-framework config files
37    include_defaults: bool,
38    /// Custom configuration file search paths
39    search_paths: Vec<String>,
40}
41
42/// Represents a configuration source
43#[derive(Debug, Clone)]
44pub enum ConfigSource {
45    /// Configuration file (path, format, required)
46    File {
47        path: String,
48        format: FileFormat,
49        required: bool,
50    },
51    /// Environment variables with prefix
52    Environment { prefix: String },
53    /// Direct configuration values
54    Values(HashMap<String, config::Value>),
55    /// Include another configuration directory
56    IncludeDir { path: String, pattern: String },
57}
58
59/// Settings that can be used by parent applications to configure auth-framework
60#[derive(Debug, Clone, Serialize, Deserialize, Default)]
61#[serde(default)]
62pub struct AuthFrameworkSettings {
63    /// Main auth framework configuration
64    #[serde(flatten)]
65    pub auth: super::AuthConfig,
66
67    /// Standalone REST API server runtime settings
68    #[serde(skip_serializing_if = "Option::is_none")]
69    pub api_server: Option<ApiServerSettings>,
70
71    /// Threat intelligence configuration
72    #[serde(skip_serializing_if = "Option::is_none")]
73    pub threat_intelligence: Option<crate::threat_intelligence::ThreatIntelConfig>,
74
75    /// Session configuration
76    #[serde(skip_serializing_if = "Option::is_none")]
77    pub session: Option<SessionSettings>,
78
79    /// Additional custom settings for extensibility
80    #[serde(flatten)]
81    pub custom: HashMap<String, serde_json::Value>,
82}
83
84/// Standalone REST API server runtime settings.
85#[derive(Debug, Clone, Serialize, Deserialize)]
86#[serde(default)]
87pub struct ApiServerSettings {
88    /// Address to bind the standalone server to.
89    pub host: String,
90
91    /// TCP port to bind the standalone server to.
92    pub port: u16,
93
94    /// Maximum allowed request body size in bytes.
95    pub max_body_size: usize,
96
97    /// Whether structured request tracing is enabled.
98    pub enable_tracing: bool,
99}
100
101/// Session-specific configuration settings
102#[derive(Debug, Clone, Serialize, Deserialize)]
103#[serde(default)]
104pub struct SessionSettings {
105    /// Maximum number of concurrent sessions per user
106    pub max_concurrent_sessions: Option<u32>,
107
108    /// Session cleanup interval in seconds
109    pub cleanup_interval: Option<u64>,
110
111    /// Enable session device tracking
112    pub enable_device_tracking: Option<bool>,
113
114    /// Session cookie settings
115    pub cookie: Option<SessionCookieSettings>,
116}
117
118/// Session cookie configuration
119#[derive(Debug, Clone, Serialize, Deserialize)]
120#[serde(default)]
121pub struct SessionCookieSettings {
122    /// Cookie name
123    pub name: Option<String>,
124
125    /// Cookie domain
126    pub domain: Option<String>,
127
128    /// Cookie path
129    pub path: Option<String>,
130
131    /// Cookie max age in seconds
132    pub max_age: Option<u64>,
133
134    /// Whether cookie is HTTP only
135    pub http_only: Option<bool>,
136}
137
138impl Default for ConfigBuilder {
139    fn default() -> Self {
140        Self::new()
141    }
142}
143
144impl ConfigBuilder {
145    /// Create a new configuration builder with sensible defaults
146    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    /// Set the environment variable prefix
163    pub fn with_env_prefix(mut self, prefix: impl Into<String>) -> Self {
164        self.env_prefix = prefix.into();
165        self
166    }
167
168    /// Disable loading of default auth-framework configuration files
169    pub fn without_defaults(mut self) -> Self {
170        self.include_defaults = false;
171        self
172    }
173
174    /// Add a configuration file source
175    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    /// Add a configuration file with explicit format
188    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    /// Add environment variables as a source
203    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    /// Add direct configuration values
211    pub fn add_values(mut self, values: HashMap<String, config::Value>) -> Self {
212        self.sources.push(ConfigSource::Values(values));
213        self
214    }
215
216    /// Add a directory include source (loads all matching files)
217    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    /// Add a search path for configuration files
226    pub fn add_search_path(mut self, path: impl Into<String>) -> Self {
227        self.search_paths.push(path.into());
228        self
229    }
230
231    /// Build the configuration manager
232    pub fn build(self) -> Result<ConfigManager> {
233        let mut config = Config::builder();
234        let mut sources = Vec::new();
235
236        // Add default auth-framework configuration files if requested
237        if self.include_defaults {
238            // Look for auth-framework configuration files in search paths
239            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        // Add user-specified sources in order
262        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                    // Load all matching files from the directory
290                    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                        // Sort for consistent loading order
297                        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        // Always add the main environment source last (highest priority)
313        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    /// Detect file format from extension
332    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, // Default to TOML
341        }
342    }
343}
344
345impl ConfigManager {
346    /// Create a new configuration manager with default settings
347    pub fn new() -> Result<Self> {
348        ConfigBuilder::new().build()
349    }
350
351    /// Create a configuration manager for a specific application
352    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    /// Get the auth framework settings
361    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    /// Get a specific configuration section
369    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    /// Get a configuration value by key
379    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    /// Get a configuration value with a default
389    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    /// Check if a key exists in the configuration
397    pub fn has_key(&self, key: &str) -> bool {
398        self.config.get::<config::Value>(key).is_ok()
399    }
400
401    /// Get all keys with a specific prefix
402    pub fn get_keys_with_prefix(&self, prefix: &str) -> Vec<String> {
403        // Try to deserialize the prefix as a table to enumerate its keys
404        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    /// Get configuration sources used
412    pub fn sources(&self) -> &[String] {
413        &self.sources
414    }
415
416    /// Get the environment prefix
417    pub fn env_prefix(&self) -> &str {
418        &self.env_prefix
419    }
420
421    /// Validate the configuration
422    pub fn validate(&self) -> Result<()> {
423        let auth_config = self.get_auth_settings()?;
424        auth_config.auth.validate()
425    }
426
427    /// Create a nested configuration manager for a subsection
428    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    /// Merge with another configuration (other takes precedence)
453    pub fn merge(self, other: ConfigManager) -> Result<ConfigManager> {
454        let mut sources = self.sources;
455        sources.extend(other.sources);
456
457        // For simplicity, we'll use the other's config as the primary
458        // In a real implementation, we'd properly merge the configurations
459        Ok(ConfigManager {
460            config: other.config,
461            sources,
462            env_prefix: other.env_prefix,
463        })
464    }
465
466    /// Export the current configuration to a specific format
467    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    /// Creates a `ConfigManager` with default settings.
484    ///
485    /// # Panics
486    /// Panics if the default configuration cannot be built (e.g. config files are
487    /// malformed). Prefer `ConfigManager::new()` which returns `Result` for
488    /// graceful error handling in production code.
489    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), // 1 hour
513            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), // 24 hours
526            http_only: Some(true),
527        }
528    }
529}
530
531/// Helper trait for easy integration into parent application configurations
532pub trait ConfigIntegration {
533    /// Get the auth framework configuration section
534    fn auth_framework(&self) -> Option<&AuthFrameworkSettings>;
535
536    /// Get the auth framework configuration section (mutable)
537    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        // Since ConfigManager::new() tries to load from files/env which may not exist,
557        // we'll test the default settings directly instead
558        let settings = AuthFrameworkSettings::default();
559
560        // Should have default values
561        assert!(!settings.auth.enable_multi_factor);
562        assert_eq!(settings.auth.token_lifetime.as_secs(), 3600); // 1 hour
563        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}