auth_framework/server/core/
common_config.rs1use crate::errors::Result;
7use serde::{Deserialize, Serialize};
8use std::collections::HashMap;
9use std::time::Duration;
10
11pub trait ServerConfig {
13 fn validate(&self) -> Result<()> {
19 Ok(())
20 }
21
22 fn config_name(&self) -> &'static str;
24
25 fn is_enabled(&self) -> bool {
27 true
28 }
29}
30
31#[derive(Debug, Clone, Serialize, Deserialize)]
33pub struct TimeoutConfig {
34 pub connect_timeout: Duration,
36 pub read_timeout: Duration,
38 pub write_timeout: Duration,
40}
41
42impl Default for TimeoutConfig {
43 fn default() -> Self {
44 Self {
45 connect_timeout: Duration::from_secs(30),
46 read_timeout: Duration::from_secs(30),
47 write_timeout: Duration::from_secs(30),
48 }
49 }
50}
51
52#[derive(Debug, Clone, Serialize, Deserialize)]
54pub struct SecurityConfig {
55 pub enable_tls: bool,
57 pub min_tls_version: String,
59 pub cipher_suites: Vec<String>,
61 pub cert_validation: CertificateValidation,
63 pub verify_certificates: bool,
65 #[serde(default)]
68 pub accept_invalid_certs: bool,
69}
70
71impl Default for SecurityConfig {
72 fn default() -> Self {
73 Self {
74 enable_tls: true,
75 min_tls_version: "1.2".to_string(),
76 cipher_suites: vec![
77 "TLS_AES_256_GCM_SHA384".to_string(),
78 "TLS_CHACHA20_POLY1305_SHA256".to_string(),
79 "TLS_AES_128_GCM_SHA256".to_string(),
80 ],
81 cert_validation: CertificateValidation::Full,
82 verify_certificates: true,
83 accept_invalid_certs: false,
84 }
85 }
86}
87
88#[derive(Debug, Clone, Serialize, Deserialize)]
90pub enum CertificateValidation {
91 Full,
93 SkipHostname,
95 None,
97}
98
99#[derive(Clone, Serialize, Deserialize)]
101pub struct EndpointConfig {
102 pub base_url: String,
104 pub api_version: Option<String>,
106 pub headers: HashMap<String, String>,
108 pub timeout: TimeoutConfig,
110 pub security: SecurityConfig,
112}
113
114impl std::fmt::Debug for EndpointConfig {
115 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
116 let mut d = f.debug_struct("EndpointConfig");
117 d.field("base_url", &self.base_url);
118 d.field("api_version", &self.api_version);
119 d.field("headers", &crate::utils::redact::redacted(&self.headers));
120 d.field("timeout", &self.timeout);
121 d.field("security", &self.security);
122 d.finish()
123 }
124}
125
126impl EndpointConfig {
127 pub fn new(base_url: impl Into<String>) -> Self {
129 Self {
130 base_url: base_url.into(),
131 api_version: None,
132 headers: HashMap::new(),
133 timeout: TimeoutConfig::default(),
134 security: SecurityConfig::default(),
135 }
136 }
137
138 pub fn with_header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
140 self.headers.insert(key.into(), value.into());
141 self
142 }
143
144 pub fn with_api_version(mut self, version: impl Into<String>) -> Self {
146 self.api_version = Some(version.into());
147 self
148 }
149}
150
151#[derive(Debug, Clone, Serialize, Deserialize)]
153pub struct RetryConfig {
154 pub max_attempts: u32,
156 pub initial_delay: Duration,
158 pub max_delay: Duration,
160 pub backoff_multiplier: f64,
162 pub jitter_factor: f64,
164}
165
166impl Default for RetryConfig {
167 fn default() -> Self {
168 Self {
169 max_attempts: 3,
170 initial_delay: Duration::from_millis(100),
171 max_delay: Duration::from_secs(30),
172 backoff_multiplier: 2.0,
173 jitter_factor: 0.1,
174 }
175 }
176}
177
178#[derive(Debug, Clone, Serialize, Deserialize)]
180pub struct LoggingConfig {
181 pub debug: bool,
183 pub log_bodies: bool,
185 pub log_sensitive: bool,
187 pub max_log_size: usize,
189}
190
191impl Default for LoggingConfig {
192 fn default() -> Self {
193 Self {
194 debug: false,
195 log_bodies: false,
196 log_sensitive: false,
197 max_log_size: 4096,
198 }
199 }
200}
201
202pub mod validation {
204 use super::*;
205
206 pub fn validate_url(url: &str) -> Result<()> {
208 if url.is_empty() {
209 return Err(crate::errors::AuthError::config(
210 "URL cannot be empty".to_string(),
211 ));
212 }
213
214 if !url.starts_with("http://") && !url.starts_with("https://") {
215 return Err(crate::errors::AuthError::config(format!(
216 "Invalid URL format: {}",
217 url
218 )));
219 }
220
221 Ok(())
222 }
223
224 pub fn validate_positive_duration(duration: &Duration, field_name: &str) -> Result<()> {
226 if duration.is_zero() {
227 return Err(crate::errors::AuthError::config(format!(
228 "{} must be greater than zero",
229 field_name
230 )));
231 }
232 Ok(())
233 }
234
235 pub fn validate_port(port: u16) -> Result<()> {
237 if port == 0 {
238 return Err(crate::errors::AuthError::config(
239 "Port cannot be zero".to_string(),
240 ));
241 }
242 Ok(())
243 }
244
245 pub fn validate_required_field(value: &str, field_name: &str) -> Result<()> {
247 if value.trim().is_empty() {
248 return Err(crate::errors::AuthError::config(format!(
249 "{} is required and cannot be empty",
250 field_name
251 )));
252 }
253 Ok(())
254 }
255}
256
257#[cfg(test)]
258mod tests {
259 use super::*;
260
261 #[test]
262 fn test_timeout_config_default() {
263 let tc = TimeoutConfig::default();
264 assert_eq!(tc.connect_timeout, Duration::from_secs(30));
265 assert_eq!(tc.read_timeout, Duration::from_secs(30));
266 }
267
268 #[test]
269 fn test_security_config_default() {
270 let sc = SecurityConfig::default();
271 assert!(sc.enable_tls);
272 assert!(sc.verify_certificates);
273 }
274
275 #[test]
276 fn test_retry_config_default() {
277 let rc = RetryConfig::default();
278 assert!(rc.max_attempts > 0);
279 }
280
281 #[test]
282 fn test_logging_config_default() {
283 let lc = LoggingConfig::default();
284 assert!(!lc.debug);
285 assert!(!lc.log_bodies);
286 assert!(!lc.log_sensitive);
287 assert!(lc.max_log_size > 0);
288 }
289
290 #[test]
291 fn test_endpoint_config_new() {
292 let ec = EndpointConfig::new("https://api.example.com");
293 assert_eq!(ec.base_url, "https://api.example.com");
294 assert!(ec.api_version.is_none());
295 }
296
297 #[test]
298 fn test_endpoint_config_with_header() {
299 let ec = EndpointConfig::new("https://api.example.com")
300 .with_header("Authorization", "Bearer xxx");
301 assert_eq!(ec.headers.get("Authorization").unwrap(), "Bearer xxx");
302 }
303
304 #[test]
305 fn test_endpoint_config_with_api_version() {
306 let ec = EndpointConfig::new("https://api.example.com").with_api_version("2024-01-01");
307 assert_eq!(ec.api_version.as_deref(), Some("2024-01-01"));
308 }
309
310 #[test]
311 fn test_validate_url_valid() {
312 assert!(validation::validate_url("https://example.com").is_ok());
313 }
314
315 #[test]
316 fn test_validate_url_empty() {
317 assert!(validation::validate_url("").is_err());
318 }
319
320 #[test]
321 fn test_validate_url_no_scheme() {
322 assert!(validation::validate_url("example.com").is_err());
323 }
324
325 #[test]
326 fn test_validate_positive_duration() {
327 assert!(validation::validate_positive_duration(&Duration::from_secs(1), "timeout").is_ok());
328 }
329
330 #[test]
331 fn test_validate_zero_duration() {
332 assert!(validation::validate_positive_duration(&Duration::ZERO, "timeout").is_err());
333 }
334
335 #[test]
336 fn test_validate_port() {
337 assert!(validation::validate_port(8080).is_ok());
338 assert!(validation::validate_port(0).is_err());
339 }
340
341 #[test]
342 fn test_validate_required_field() {
343 assert!(validation::validate_required_field("value", "name").is_ok());
344 assert!(validation::validate_required_field("", "name").is_err());
345 assert!(validation::validate_required_field(" ", "name").is_err());
346 }
347
348 #[test]
349 fn test_security_config_accept_invalid_certs_defaults_false() {
350 let sc = SecurityConfig::default();
351 assert!(
352 !sc.accept_invalid_certs,
353 "accept_invalid_certs must default to false"
354 );
355 }
356
357 #[test]
358 fn test_security_config_accept_invalid_certs_deserialization_default() {
359 let json = r#"{"enable_tls":true,"min_tls_version":"1.2","cipher_suites":[],"cert_validation":"Full","verify_certificates":true}"#;
361 let sc: SecurityConfig = serde_json::from_str(json).unwrap();
362 assert!(!sc.accept_invalid_certs);
363 }
364}