reinhardt-conf 0.3.2

Configuration management framework for Reinhardt - Django-inspired settings with encryption and secrets management
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
//! Configuration validation framework
//!
//! Provides validation rules and checks for settings to ensure security
//! and correctness before application startup.

use super::profile::Profile;
use serde_json::Value;
use std::collections::HashMap;

// Import base SettingsValidator trait from reinhardt-core
use reinhardt_core::validators::SettingsValidator as BaseSettingsValidator;

/// Validation result
pub type ValidationResult = Result<(), ValidationError>;

/// Validation error
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
pub enum ValidationError {
	/// A security-related validation failed (e.g., weak secret key).
	#[error("Security error: {0}")]
	Security(String),

	/// A settings value is invalid for the given key.
	#[error("Invalid value for '{key}': {message}")]
	InvalidValue {
		/// The settings key with the invalid value.
		key: String,
		/// Description of why the value is invalid.
		message: String,
	},

	/// A required settings field is missing.
	#[error("Missing required field: {0}")]
	MissingRequired(String),

	/// A constraint on the settings value was violated.
	#[error("Constraint violation: {0}")]
	Constraint(String),

	/// Multiple validation errors occurred.
	#[error("Multiple validation errors: {0:?}")]
	Multiple(Vec<ValidationError>),
}

impl From<ValidationError> for reinhardt_core::validators::ValidationError {
	fn from(error: ValidationError) -> Self {
		reinhardt_core::validators::ValidationError::Custom(error.to_string())
	}
}

/// Trait for validation rules
pub trait Validator: Send + Sync {
	/// Validate a specific key-value pair
	fn validate(&self, key: &str, value: &Value) -> ValidationResult;

	/// Get validator description
	fn description(&self) -> String;
}

/// Trait for settings validators that can validate entire settings
pub trait SettingsValidator: Send + Sync {
	/// Validate the entire settings map
	fn validate_settings(&self, settings: &HashMap<String, Value>) -> ValidationResult;

	/// Get validator description
	fn description(&self) -> String;
}

/// Required field validator
pub struct RequiredValidator {
	fields: Vec<String>,
}

impl RequiredValidator {
	/// Create a new required field validator
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_conf::settings::validation::RequiredValidator;
	///
	/// let validator = RequiredValidator::new(vec![
	///     "secret_key".to_string(),
	///     "database_url".to_string(),
	/// ]);
	/// // Validator will check that these fields exist in settings
	/// ```
	pub fn new(fields: Vec<String>) -> Self {
		Self { fields }
	}
}

impl SettingsValidator for RequiredValidator {
	fn validate_settings(&self, settings: &HashMap<String, Value>) -> ValidationResult {
		let mut errors = Vec::new();

		for field in &self.fields {
			if !settings.contains_key(field) {
				errors.push(ValidationError::MissingRequired(field.clone()));
			}
		}

		if errors.is_empty() {
			Ok(())
		} else {
			Err(ValidationError::Multiple(errors))
		}
	}

	fn description(&self) -> String {
		format!("Required fields: {:?}", self.fields)
	}
}

impl BaseSettingsValidator for RequiredValidator {
	fn validate_setting(
		&self,
		_key: &str,
		_value: &Value,
	) -> reinhardt_core::validators::ValidationResult<()> {
		// This validator checks presence, not individual values
		// Always pass for individual settings
		Ok(())
	}

	fn description(&self) -> String {
		format!("Required fields: {:?}", self.fields)
	}
}

/// Security validator for production environments
pub struct SecurityValidator {
	profile: Profile,
}

impl SecurityValidator {
	/// Create a new security validator for the given profile
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_conf::settings::validation::SecurityValidator;
	/// use reinhardt_conf::settings::profile::Profile;
	///
	/// let validator = SecurityValidator::new(Profile::Production);
	/// // Validator will enforce production security requirements
	/// ```
	pub fn new(profile: Profile) -> Self {
		Self { profile }
	}
}

impl SettingsValidator for SecurityValidator {
	fn validate_settings(&self, settings: &HashMap<String, Value>) -> ValidationResult {
		if !self.profile.is_production() {
			return Ok(());
		}

		let mut errors = Vec::new();

		// Check DEBUG is false in production
		if let Some(debug) = settings.get("debug")
			&& debug.as_bool() == Some(true)
		{
			errors.push(ValidationError::Security(
				"DEBUG must be false in production".to_string(),
			));
		}

		// Check SECRET_KEY is not default value
		if let Some(secret_key) = settings.get("secret_key")
			&& let Some(key_str) = secret_key.as_str()
			&& (key_str.contains("insecure") || key_str == "change-this" || key_str.len() < 32)
		{
			errors.push(ValidationError::Security(
				"SECRET_KEY must be a strong random value in production".to_string(),
			));
		}

		// Check ALLOWED_HOSTS is set
		if let Some(allowed_hosts) = settings.get("allowed_hosts") {
			if let Some(hosts) = allowed_hosts.as_array()
				&& (hosts.is_empty() || hosts.iter().any(|h| h.as_str() == Some("*")))
			{
				errors.push(ValidationError::Security(
					"ALLOWED_HOSTS must be properly configured in production (no wildcards)"
						.to_string(),
				));
			}
		} else {
			errors.push(ValidationError::Security(
				"ALLOWED_HOSTS must be set in production".to_string(),
			));
		}

		// Check HTTPS settings
		if let Some(secure_ssl) = settings.get("secure_ssl_redirect") {
			if secure_ssl.as_bool() != Some(true) {
				errors.push(ValidationError::Security(
					"SECURE_SSL_REDIRECT should be true in production".to_string(),
				));
			}
		} else {
			errors.push(ValidationError::Security(
				"SECURE_SSL_REDIRECT must be set in production".to_string(),
			));
		}

		if errors.is_empty() {
			Ok(())
		} else {
			Err(ValidationError::Multiple(errors))
		}
	}

	fn description(&self) -> String {
		format!("Security validation for {} environment", self.profile)
	}
}

impl BaseSettingsValidator for SecurityValidator {
	fn validate_setting(
		&self,
		key: &str,
		value: &Value,
	) -> reinhardt_core::validators::ValidationResult<()> {
		if !self.profile.is_production() {
			return Ok(());
		}

		match key {
			"debug" => {
				if value.as_bool() == Some(true) {
					return Err(reinhardt_core::validators::ValidationError::Custom(
						"DEBUG must be false in production".to_string(),
					));
				}
			}
			"secret_key" => {
				if let Some(key_str) = value.as_str()
					&& (key_str.contains("insecure")
						|| key_str == "change-this"
						|| key_str.len() < 32)
				{
					return Err(reinhardt_core::validators::ValidationError::Custom(
						"SECRET_KEY must be a strong random value in production".to_string(),
					));
				}
			}
			"allowed_hosts" => {
				if let Some(hosts) = value.as_array() {
					if hosts.is_empty() || hosts.iter().any(|h| h.as_str() == Some("*")) {
						return Err(reinhardt_core::validators::ValidationError::Custom(
                            "ALLOWED_HOSTS must be properly configured in production (no wildcards)".to_string(),
                        ));
					}
				} else {
					return Err(reinhardt_core::validators::ValidationError::Custom(
						"ALLOWED_HOSTS must be an array".to_string(),
					));
				}
			}
			"secure_ssl_redirect" if value.as_bool() != Some(true) => {
				return Err(reinhardt_core::validators::ValidationError::Custom(
					"SECURE_SSL_REDIRECT should be true in production".to_string(),
				));
			}
			_ => {}
		}

		Ok(())
	}

	fn description(&self) -> String {
		format!("Security validation for {} environment", self.profile)
	}
}

/// Range validator for numeric values
pub struct RangeValidator {
	min: Option<f64>,
	max: Option<f64>,
}

impl RangeValidator {
	/// Create a range validator with optional min and max
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_conf::settings::validation::RangeValidator;
	///
	/// let validator = RangeValidator::new(Some(0.0), Some(100.0));
	/// // Validator will check values are between 0 and 100
	/// ```
	pub fn new(min: Option<f64>, max: Option<f64>) -> Self {
		Self { min, max }
	}
	/// Create a validator with only a minimum value
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_conf::settings::validation::RangeValidator;
	///
	/// let validator = RangeValidator::min(0.0);
	/// // Values must be >= 0
	/// ```
	pub fn min(min: f64) -> Self {
		Self {
			min: Some(min),
			max: None,
		}
	}
	/// Create a validator with only a maximum value
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_conf::settings::validation::RangeValidator;
	///
	/// let validator = RangeValidator::max(100.0);
	/// // Values must be <= 100
	/// ```
	pub fn max(max: f64) -> Self {
		Self {
			min: None,
			max: Some(max),
		}
	}
	/// Create a validator for a range between min and max
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_conf::settings::validation::RangeValidator;
	///
	/// let validator = RangeValidator::between(1.0, 10.0);
	/// // Values must be between 1 and 10 (inclusive)
	/// ```
	pub fn between(min: f64, max: f64) -> Self {
		Self {
			min: Some(min),
			max: Some(max),
		}
	}
}

impl Validator for RangeValidator {
	fn validate(&self, key: &str, value: &Value) -> ValidationResult {
		if let Some(num) = value.as_f64() {
			if let Some(min) = self.min
				&& num < min
			{
				return Err(ValidationError::InvalidValue {
					key: key.to_string(),
					message: format!("Value {} is less than minimum {}", num, min),
				});
			}

			if let Some(max) = self.max
				&& num > max
			{
				return Err(ValidationError::InvalidValue {
					key: key.to_string(),
					message: format!("Value {} is greater than maximum {}", num, max),
				});
			}

			Ok(())
		} else {
			Err(ValidationError::InvalidValue {
				key: key.to_string(),
				message: "Expected numeric value".to_string(),
			})
		}
	}

	fn description(&self) -> String {
		match (self.min, self.max) {
			(Some(min), Some(max)) => format!("Range: {} to {}", min, max),
			(Some(min), None) => format!("Minimum: {}", min),
			(None, Some(max)) => format!("Maximum: {}", max),
			(None, None) => "Range validator".to_string(),
		}
	}
}

impl BaseSettingsValidator for RangeValidator {
	fn validate_setting(
		&self,
		key: &str,
		value: &Value,
	) -> reinhardt_core::validators::ValidationResult<()> {
		if let Some(num) = value.as_f64() {
			if let Some(min) = self.min
				&& num < min
			{
				return Err(reinhardt_core::validators::ValidationError::Custom(
					format!("Value {} for '{}' is less than minimum {}", num, key, min),
				));
			}

			if let Some(max) = self.max
				&& num > max
			{
				return Err(reinhardt_core::validators::ValidationError::Custom(
					format!(
						"Value {} for '{}' is greater than maximum {}",
						num, key, max
					),
				));
			}

			Ok(())
		} else {
			Err(reinhardt_core::validators::ValidationError::Custom(
				format!("Expected numeric value for '{}'", key),
			))
		}
	}

	fn description(&self) -> String {
		match (self.min, self.max) {
			(Some(min), Some(max)) => format!("Range: {} to {}", min, max),
			(Some(min), None) => format!("Minimum: {}", min),
			(None, Some(max)) => format!("Maximum: {}", max),
			(None, None) => "Range validator".to_string(),
		}
	}
}

/// String pattern validator
pub struct PatternValidator {
	pattern: regex::Regex,
}

impl PatternValidator {
	/// Create a pattern validator with a regex pattern
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_conf::settings::validation::PatternValidator;
	///
	/// let validator = PatternValidator::new(r"^\d{3}-\d{3}-\d{4}$").unwrap();
	/// // Validates phone number format
	/// ```
	pub fn new(pattern: &str) -> Result<Self, regex::Error> {
		Ok(Self {
			pattern: regex::Regex::new(pattern)?,
		})
	}
}

impl Validator for PatternValidator {
	fn validate(&self, key: &str, value: &Value) -> ValidationResult {
		if let Some(s) = value.as_str() {
			if self.pattern.is_match(s) {
				Ok(())
			} else {
				Err(ValidationError::InvalidValue {
					key: key.to_string(),
					message: format!("Value does not match pattern: {}", self.pattern.as_str()),
				})
			}
		} else {
			Err(ValidationError::InvalidValue {
				key: key.to_string(),
				message: "Expected string value".to_string(),
			})
		}
	}

	fn description(&self) -> String {
		format!("Pattern: {}", self.pattern.as_str())
	}
}

impl BaseSettingsValidator for PatternValidator {
	fn validate_setting(
		&self,
		key: &str,
		value: &Value,
	) -> reinhardt_core::validators::ValidationResult<()> {
		if let Some(s) = value.as_str() {
			if self.pattern.is_match(s) {
				Ok(())
			} else {
				Err(reinhardt_core::validators::ValidationError::Custom(
					format!(
						"Value for '{}' does not match pattern: {}",
						key,
						self.pattern.as_str()
					),
				))
			}
		} else {
			Err(reinhardt_core::validators::ValidationError::Custom(
				format!("Expected string value for '{}'", key),
			))
		}
	}

	fn description(&self) -> String {
		format!("Pattern: {}", self.pattern.as_str())
	}
}

/// Choice validator (enum-like)
pub struct ChoiceValidator {
	choices: Vec<String>,
}

impl ChoiceValidator {
	/// Create a choice validator with allowed values
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_conf::settings::validation::ChoiceValidator;
	///
	/// let validator = ChoiceValidator::new(vec![
	///     "development".to_string(),
	///     "staging".to_string(),
	///     "production".to_string(),
	/// ]);
	/// // Value must be one of the allowed choices
	/// ```
	pub fn new(choices: Vec<String>) -> Self {
		Self { choices }
	}
}

impl Validator for ChoiceValidator {
	fn validate(&self, key: &str, value: &Value) -> ValidationResult {
		if let Some(s) = value.as_str() {
			if self.choices.contains(&s.to_string()) {
				Ok(())
			} else {
				Err(ValidationError::InvalidValue {
					key: key.to_string(),
					message: format!(
						"Value '{}' is not in allowed choices: {:?}",
						s, self.choices
					),
				})
			}
		} else {
			Err(ValidationError::InvalidValue {
				key: key.to_string(),
				message: "Expected string value".to_string(),
			})
		}
	}

	fn description(&self) -> String {
		format!("Choices: {:?}", self.choices)
	}
}

impl BaseSettingsValidator for ChoiceValidator {
	fn validate_setting(
		&self,
		key: &str,
		value: &Value,
	) -> reinhardt_core::validators::ValidationResult<()> {
		if let Some(s) = value.as_str() {
			if self.choices.contains(&s.to_string()) {
				Ok(())
			} else {
				Err(reinhardt_core::validators::ValidationError::Custom(
					format!(
						"Value '{}' for '{}' is not in allowed choices: {:?}",
						s, key, self.choices
					),
				))
			}
		} else {
			Err(reinhardt_core::validators::ValidationError::Custom(
				format!("Expected string value for '{}'", key),
			))
		}
	}

	fn description(&self) -> String {
		format!("Choices: {:?}", self.choices)
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use rstest::rstest;

	#[test]
	fn test_settings_validation_required() {
		let validator = RequiredValidator::new(vec!["key1".to_string(), "key2".to_string()]);

		let mut settings = HashMap::new();
		settings.insert("key1".to_string(), Value::String("value".to_string()));

		assert!(validator.validate_settings(&settings).is_err());

		settings.insert("key2".to_string(), Value::String("value".to_string()));
		assert!(validator.validate_settings(&settings).is_ok());
	}

	#[test]
	fn test_security_validator_production() {
		let validator = SecurityValidator::new(Profile::Production);

		let mut settings = HashMap::new();
		settings.insert("debug".to_string(), Value::Bool(true));
		settings.insert(
			"secret_key".to_string(),
			Value::String("insecure".to_string()),
		);

		let result = validator.validate_settings(&settings);
		assert!(result.is_err());
	}

	#[test]
	fn test_security_validator_development() {
		let validator = SecurityValidator::new(Profile::Development);

		let mut settings = HashMap::new();
		settings.insert("debug".to_string(), Value::Bool(true));
		settings.insert(
			"secret_key".to_string(),
			Value::String("insecure".to_string()),
		);

		// Should pass in development
		assert!(validator.validate_settings(&settings).is_ok());
	}

	#[test]
	fn test_settings_range_validator() {
		let validator = RangeValidator::between(0.0, 100.0);

		assert!(validator.validate("key", &Value::Number(50.into())).is_ok());
		assert!(
			validator
				.validate("key", &Value::Number((-10).into()))
				.is_err()
		);
		assert!(
			validator
				.validate("key", &Value::Number(150.into()))
				.is_err()
		);
	}

	#[rstest]
	fn test_security_validator_missing_ssl_redirect_in_production() {
		// Arrange
		let validator = SecurityValidator::new(Profile::Production);
		let mut settings = HashMap::new();
		settings.insert("debug".to_string(), Value::Bool(false));
		settings.insert(
			"secret_key".to_string(),
			Value::String("a-very-long-secure-random-key-that-is-at-least-32-chars".to_string()),
		);
		settings.insert(
			"allowed_hosts".to_string(),
			Value::Array(vec![Value::String("example.com".to_string())]),
		);
		// Note: secure_ssl_redirect is intentionally omitted

		// Act
		let result = validator.validate_settings(&settings);

		// Assert
		let err = result.unwrap_err();
		let error_msg = err.to_string();
		assert!(
			error_msg.contains("SECURE_SSL_REDIRECT must be set in production"),
			"Expected error about missing SECURE_SSL_REDIRECT, got: {error_msg}"
		);
	}

	#[rstest]
	fn test_security_validator_ssl_redirect_false_in_production() {
		// Arrange
		let validator = SecurityValidator::new(Profile::Production);
		let mut settings = HashMap::new();
		settings.insert("debug".to_string(), Value::Bool(false));
		settings.insert(
			"secret_key".to_string(),
			Value::String("a-very-long-secure-random-key-that-is-at-least-32-chars".to_string()),
		);
		settings.insert(
			"allowed_hosts".to_string(),
			Value::Array(vec![Value::String("example.com".to_string())]),
		);
		settings.insert("secure_ssl_redirect".to_string(), Value::Bool(false));

		// Act
		let result = validator.validate_settings(&settings);

		// Assert
		let err = result.unwrap_err();
		let error_msg = err.to_string();
		assert!(
			error_msg.contains("SECURE_SSL_REDIRECT should be true in production"),
			"Expected error about SECURE_SSL_REDIRECT being false, got: {error_msg}"
		);
	}

	#[rstest]
	fn test_security_validator_ssl_redirect_true_in_production() {
		// Arrange
		let validator = SecurityValidator::new(Profile::Production);
		let mut settings = HashMap::new();
		settings.insert("debug".to_string(), Value::Bool(false));
		settings.insert(
			"secret_key".to_string(),
			Value::String("a-very-long-secure-random-key-that-is-at-least-32-chars".to_string()),
		);
		settings.insert(
			"allowed_hosts".to_string(),
			Value::Array(vec![Value::String("example.com".to_string())]),
		);
		settings.insert("secure_ssl_redirect".to_string(), Value::Bool(true));

		// Act
		let result = validator.validate_settings(&settings);

		// Assert
		assert!(
			result.is_ok(),
			"Expected validation to pass with valid production settings, got: {result:?}"
		);
	}

	#[test]
	fn test_settings_validation_choice() {
		let validator =
			ChoiceValidator::new(vec!["a".to_string(), "b".to_string(), "c".to_string()]);

		assert!(
			validator
				.validate("key", &Value::String("a".to_string()))
				.is_ok()
		);
		assert!(
			validator
				.validate("key", &Value::String("d".to_string()))
				.is_err()
		);
	}
}