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(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
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/// Standalone REST API server runtime settings.
97#[derive(Debug, Clone, Serialize, Deserialize)]
98#[serde(default)]
99pub struct ApiServerSettings {
100    /// Address to bind the standalone server to.
101    pub host: String,
102
103    /// TCP port to bind the standalone server to.
104    pub port: u16,
105
106    /// Maximum allowed request body size in bytes.
107    pub max_body_size: usize,
108
109    /// Whether structured request tracing is enabled.
110    pub enable_tracing: bool,
111}
112
113/// Session-specific configuration settings
114#[derive(Debug, Clone, Serialize, Deserialize)]
115#[serde(default)]
116pub struct SessionSettings {
117    /// Maximum number of concurrent sessions per user
118    pub max_concurrent_sessions: Option<u32>,
119
120    /// Session cleanup interval in seconds
121    pub cleanup_interval: Option<u64>,
122
123    /// Enable session device tracking
124    pub enable_device_tracking: Option<bool>,
125
126    /// Session cookie settings
127    pub cookie: Option<SessionCookieSettings>,
128}
129
130/// Session cookie configuration
131#[derive(Debug, Clone, Serialize, Deserialize)]
132#[serde(default)]
133pub struct SessionCookieSettings {
134    /// Cookie name
135    pub name: Option<String>,
136
137    /// Cookie domain
138    pub domain: Option<String>,
139
140    /// Cookie path
141    pub path: Option<String>,
142
143    /// Cookie max age in seconds
144    pub max_age: Option<u64>,
145
146    /// Whether cookie is HTTP only
147    pub http_only: Option<bool>,
148}
149
150impl Default for ConfigBuilder {
151    fn default() -> Self {
152        Self::new()
153    }
154}
155
156impl ConfigBuilder {
157    /// Create a new configuration builder with sensible defaults
158    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    /// Set the environment variable prefix
175    pub fn with_env_prefix(mut self, prefix: impl Into<String>) -> Self {
176        self.env_prefix = prefix.into();
177        self
178    }
179
180    /// Disable loading of default auth-framework configuration files
181    pub fn without_defaults(mut self) -> Self {
182        self.include_defaults = false;
183        self
184    }
185
186    /// Add a configuration file source
187    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    /// Add a configuration file with explicit format
200    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    /// Add environment variables as a source
215    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    /// Add direct configuration values
223    pub fn add_values(mut self, values: HashMap<String, config::Value>) -> Self {
224        self.sources.push(ConfigSource::Values(values));
225        self
226    }
227
228    /// Add a directory include source (loads all matching files)
229    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    /// Add a search path for configuration files
238    pub fn add_search_path(mut self, path: impl Into<String>) -> Self {
239        self.search_paths.push(path.into());
240        self
241    }
242
243    /// Build the configuration manager
244    pub fn build(self) -> Result<ConfigManager> {
245        let mut config = Config::builder();
246        let mut sources = Vec::new();
247
248        // Add default auth-framework configuration files if requested
249        if self.include_defaults {
250            // Look for auth-framework configuration files in search paths
251            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        // Add user-specified sources in order
274        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                    // Load all matching files from the directory
302                    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                        // Sort for consistent loading order
309                        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        // Always add the main environment source last (highest priority)
325        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    /// Detect file format from extension
344    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, // Default to TOML
353        }
354    }
355}
356
357impl ConfigManager {
358    /// Create a new configuration manager with default settings
359    pub fn new() -> Result<Self> {
360        ConfigBuilder::new().build()
361    }
362
363    /// Create a configuration manager for a specific application
364    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    /// Get the auth framework settings
373    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    /// Get a specific configuration section
381    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    /// Get a configuration value by key
391    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    /// Get a configuration value with a default
401    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    /// Check if a key exists in the configuration
409    pub fn has_key(&self, key: &str) -> bool {
410        self.config.get::<config::Value>(key).is_ok()
411    }
412
413    /// Get all keys with a specific prefix
414    pub fn get_keys_with_prefix(&self, prefix: &str) -> Vec<String> {
415        // Try to deserialize the prefix as a table to enumerate its keys
416        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    /// Get configuration sources used
424    pub fn sources(&self) -> &[String] {
425        &self.sources
426    }
427
428    /// Get the environment prefix
429    pub fn env_prefix(&self) -> &str {
430        &self.env_prefix
431    }
432
433    /// Validate the configuration
434    pub fn validate(&self) -> Result<()> {
435        let auth_config = self.get_auth_settings()?;
436        auth_config.auth.validate()
437    }
438
439    /// Create a nested configuration manager for a subsection
440    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    /// Merge with another configuration (other takes precedence)
465    pub fn merge(self, other: ConfigManager) -> Result<ConfigManager> {
466        let mut sources = self.sources;
467        sources.extend(other.sources);
468
469        // For simplicity, we'll use the other's config as the primary
470        // In a real implementation, we'd properly merge the configurations
471        Ok(ConfigManager {
472            config: other.config,
473            sources,
474            env_prefix: other.env_prefix,
475        })
476    }
477
478    /// Export the current configuration to a specific format
479    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_saphyr::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    /// Creates a `ConfigManager` with default settings.
496    ///
497    /// # Panics
498    /// Panics if the default configuration cannot be built (e.g. config files are
499    /// malformed). Prefer `ConfigManager::new()` which returns `Result` for
500    /// graceful error handling in production code.
501    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), // 1 hour
525            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), // 24 hours
538            http_only: Some(true),
539        }
540    }
541}
542
543/// Helper trait for easy integration into parent application configurations
544pub trait ConfigIntegration {
545    /// Get the auth framework configuration section
546    fn auth_framework(&self) -> Option<&AuthFrameworkSettings>;
547
548    /// Get the auth framework configuration section (mutable)
549    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        // Since ConfigManager::new() tries to load from files/env which may not exist,
569        // we'll test the default settings directly instead
570        let settings = AuthFrameworkSettings::default();
571
572        // Should have default values
573        assert!(!settings.auth.enable_multi_factor);
574        assert_eq!(settings.auth.token_lifetime.as_secs(), 3600); // 1 hour
575        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}