Skip to main content

auth_framework/server/core/
common_config.rs

1//! Common Configuration Framework
2//!
3//! This module provides shared configuration patterns and utilities
4//! to eliminate duplication across server modules.
5
6use crate::errors::Result;
7use serde::{Deserialize, Serialize};
8use std::collections::HashMap;
9use std::time::Duration;
10
11/// Base configuration trait that all server configs can implement
12pub trait ServerConfig {
13    /// Validate the configuration
14    fn validate(&self) -> Result<()> {
15        Ok(())
16    }
17
18    /// Get configuration name for logging/debugging
19    fn config_name(&self) -> &'static str;
20
21    /// Check if configuration is enabled
22    fn is_enabled(&self) -> bool {
23        true
24    }
25}
26
27/// Common timeout configuration used across modules
28#[derive(Debug, Clone, Serialize, Deserialize)]
29pub struct TimeoutConfig {
30    /// Connection timeout
31    pub connect_timeout: Duration,
32    /// Read timeout
33    pub read_timeout: Duration,
34    /// Write timeout
35    pub write_timeout: Duration,
36}
37
38impl Default for TimeoutConfig {
39    fn default() -> Self {
40        Self {
41            connect_timeout: Duration::from_secs(30),
42            read_timeout: Duration::from_secs(30),
43            write_timeout: Duration::from_secs(30),
44        }
45    }
46}
47
48/// Common security configuration patterns
49#[derive(Debug, Clone, Serialize, Deserialize)]
50pub struct SecurityConfig {
51    /// Enable TLS
52    pub enable_tls: bool,
53    /// Minimum TLS version
54    pub min_tls_version: String,
55    /// Allowed cipher suites
56    pub cipher_suites: Vec<String>,
57    /// Certificate validation mode
58    pub cert_validation: CertificateValidation,
59    /// Whether to verify certificates (legacy compatibility)
60    pub verify_certificates: bool,
61}
62
63impl Default for SecurityConfig {
64    fn default() -> Self {
65        Self {
66            enable_tls: true,
67            min_tls_version: "1.2".to_string(),
68            cipher_suites: vec![
69                "TLS_AES_256_GCM_SHA384".to_string(),
70                "TLS_CHACHA20_POLY1305_SHA256".to_string(),
71                "TLS_AES_128_GCM_SHA256".to_string(),
72            ],
73            cert_validation: CertificateValidation::Full,
74            verify_certificates: true,
75        }
76    }
77}
78
79/// Certificate validation modes
80#[derive(Debug, Clone, Serialize, Deserialize)]
81pub enum CertificateValidation {
82    /// Full certificate chain validation
83    Full,
84    /// Skip hostname verification
85    SkipHostname,
86    /// Skip all certificate validation (insecure)
87    None,
88}
89
90/// Common endpoint configuration
91#[derive(Clone, Serialize, Deserialize)]
92pub struct EndpointConfig {
93    /// Base URL
94    pub base_url: String,
95    /// API version
96    pub api_version: Option<String>,
97    /// Custom headers
98    pub headers: HashMap<String, String>,
99    /// Timeout configuration
100    pub timeout: TimeoutConfig,
101    /// Security configuration
102    pub security: SecurityConfig,
103}
104
105impl std::fmt::Debug for EndpointConfig {
106    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
107        let mut d = f.debug_struct("EndpointConfig");
108        d.field("base_url", &self.base_url);
109        d.field("api_version", &self.api_version);
110        d.field("headers", &crate::utils::redact::redacted(&self.headers));
111        d.field("timeout", &self.timeout);
112        d.field("security", &self.security);
113        d.finish()
114    }
115}
116
117impl EndpointConfig {
118    /// Create a new endpoint config with defaults
119    pub fn new(base_url: impl Into<String>) -> Self {
120        Self {
121            base_url: base_url.into(),
122            api_version: None,
123            headers: HashMap::new(),
124            timeout: TimeoutConfig::default(),
125            security: SecurityConfig::default(),
126        }
127    }
128
129    /// Add a custom header
130    pub fn with_header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
131        self.headers.insert(key.into(), value.into());
132        self
133    }
134
135    /// Set API version
136    pub fn with_api_version(mut self, version: impl Into<String>) -> Self {
137        self.api_version = Some(version.into());
138        self
139    }
140}
141
142/// Common retry configuration
143#[derive(Debug, Clone, Serialize, Deserialize)]
144pub struct RetryConfig {
145    /// Maximum retry attempts
146    pub max_attempts: u32,
147    /// Initial delay between retries
148    pub initial_delay: Duration,
149    /// Maximum delay between retries
150    pub max_delay: Duration,
151    /// Backoff multiplier
152    pub backoff_multiplier: f64,
153    /// Jitter factor (0.0 to 1.0)
154    pub jitter_factor: f64,
155}
156
157impl Default for RetryConfig {
158    fn default() -> Self {
159        Self {
160            max_attempts: 3,
161            initial_delay: Duration::from_millis(100),
162            max_delay: Duration::from_secs(30),
163            backoff_multiplier: 2.0,
164            jitter_factor: 0.1,
165        }
166    }
167}
168
169/// Common logging configuration
170#[derive(Debug, Clone, Serialize, Deserialize)]
171pub struct LoggingConfig {
172    /// Enable debug logging
173    pub debug: bool,
174    /// Log request/response bodies
175    pub log_bodies: bool,
176    /// Log sensitive fields (tokens, keys)
177    pub log_sensitive: bool,
178    /// Maximum log message size
179    pub max_log_size: usize,
180}
181
182impl Default for LoggingConfig {
183    fn default() -> Self {
184        Self {
185            debug: false,
186            log_bodies: false,
187            log_sensitive: false,
188            max_log_size: 4096,
189        }
190    }
191}
192
193/// Configuration validation utilities
194pub mod validation {
195    use super::*;
196
197    /// Validate URL format
198    pub fn validate_url(url: &str) -> Result<()> {
199        if url.is_empty() {
200            return Err(crate::errors::AuthError::ConfigurationError(
201                "URL cannot be empty".to_string(),
202            ));
203        }
204
205        if !url.starts_with("http://") && !url.starts_with("https://") {
206            return Err(crate::errors::AuthError::ConfigurationError(format!(
207                "Invalid URL format: {}",
208                url
209            )));
210        }
211
212        Ok(())
213    }
214
215    /// Validate duration is positive
216    pub fn validate_positive_duration(duration: &Duration, field_name: &str) -> Result<()> {
217        if duration.is_zero() {
218            return Err(crate::errors::AuthError::ConfigurationError(format!(
219                "{} must be greater than zero",
220                field_name
221            )));
222        }
223        Ok(())
224    }
225
226    /// Validate port number
227    pub fn validate_port(port: u16) -> Result<()> {
228        if port == 0 {
229            return Err(crate::errors::AuthError::ConfigurationError(
230                "Port cannot be zero".to_string(),
231            ));
232        }
233        Ok(())
234    }
235
236    /// Validate required field is not empty
237    pub fn validate_required_field(value: &str, field_name: &str) -> Result<()> {
238        if value.trim().is_empty() {
239            return Err(crate::errors::AuthError::ConfigurationError(format!(
240                "{} is required and cannot be empty",
241                field_name
242            )));
243        }
244        Ok(())
245    }
246}