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
//! Environment variable handling module
//!
//! Provides Django-environ compatible functionality for loading and parsing
//! environment variables with type safety.

use indexmap::IndexMap;
use std::env;
use std::path::PathBuf;

pub use super::env_loader::EnvLoader;
pub use super::env_parser::{DatabaseUrl, parse_bool, parse_database_url, parse_list};

/// Environment variable manager with prefix support
#[derive(Debug, Clone)]
pub struct Env {
	/// Optional prefix for environment variables (e.g., "REINHARDT_")
	pub prefix: Option<String>,

	/// Whether to enable variable expansion (e.g., $VAR)
	pub interpolate: bool,

	/// Cached environment variables (reserved for future use)
	#[allow(dead_code)]
	cache: IndexMap<String, String>,
}

impl Env {
	/// Create a new Env instance
	pub fn new() -> Self {
		Self {
			prefix: None,
			interpolate: false,
			cache: IndexMap::new(),
		}
	}
	/// Set a prefix for all environment variable lookups
	pub fn with_prefix(mut self, prefix: impl Into<String>) -> Self {
		self.prefix = Some(prefix.into());
		self
	}
	/// Enable variable interpolation
	pub fn with_interpolation(mut self, enabled: bool) -> Self {
		self.interpolate = enabled;
		self
	}

	/// Get the full key name with prefix
	fn get_key_name(&self, key: &str) -> String {
		match &self.prefix {
			Some(prefix) => format!("{}{}", prefix, key),
			None => key.to_string(),
		}
	}
	/// Read a string value from environment
	///
	pub fn str(&self, key: &str) -> Result<String, EnvError> {
		self.str_with_default(key, None)
	}
	/// Read a string value with a default
	///
	pub fn str_with_default(&self, key: &str, default: Option<&str>) -> Result<String, EnvError> {
		let full_key = self.get_key_name(key);
		validate_env_var_name(&full_key)?;

		match env::var(&full_key) {
			Ok(val) => Ok(val),
			Err(_) => match default {
				Some(d) => Ok(d.to_string()),
				None => Err(EnvError::MissingVariable(full_key)),
			},
		}
	}
	/// Read a boolean value from environment
	///
	pub fn bool(&self, key: &str) -> Result<bool, EnvError> {
		self.bool_with_default(key, None)
	}
	/// Read a boolean value with a default
	///
	pub fn bool_with_default(&self, key: &str, default: Option<bool>) -> Result<bool, EnvError> {
		let full_key = self.get_key_name(key);
		validate_env_var_name(&full_key)?;

		match env::var(&full_key) {
			Ok(val) => parse_bool(&val).map_err(|e| EnvError::ParseError {
				key: full_key,
				value_len: val.len(),
				error: e,
			}),
			Err(_) => match default {
				Some(d) => Ok(d),
				None => Err(EnvError::MissingVariable(full_key)),
			},
		}
	}
	/// Read an integer value from environment
	///
	pub fn int(&self, key: &str) -> Result<i64, EnvError> {
		self.int_with_default(key, None)
	}
	/// Read an integer value with a default
	///
	pub fn int_with_default(&self, key: &str, default: Option<i64>) -> Result<i64, EnvError> {
		let full_key = self.get_key_name(key);
		validate_env_var_name(&full_key)?;

		match env::var(&full_key) {
			Ok(val) => val.parse::<i64>().map_err(|e| EnvError::ParseError {
				key: full_key,
				value_len: val.len(),
				error: e.to_string(),
			}),
			Err(_) => match default {
				Some(d) => Ok(d),
				None => Err(EnvError::MissingVariable(full_key)),
			},
		}
	}
	/// Read a list value from environment (comma-separated)
	///
	pub fn list(&self, key: &str) -> Result<Vec<String>, EnvError> {
		self.list_with_default(key, None)
	}
	/// Read a list value with a default
	///
	pub fn list_with_default(
		&self,
		key: &str,
		default: Option<Vec<String>>,
	) -> Result<Vec<String>, EnvError> {
		let full_key = self.get_key_name(key);
		validate_env_var_name(&full_key)?;

		match env::var(&full_key) {
			Ok(val) => Ok(parse_list(&val)),
			Err(_) => match default {
				Some(d) => Ok(d),
				None => Err(EnvError::MissingVariable(full_key)),
			},
		}
	}
	/// Read a database URL from environment
	///
	pub fn database_url(&self, key: &str) -> Result<DatabaseUrl, EnvError> {
		self.database_url_with_default(key, None)
	}
	/// Read a database URL with a default
	///
	pub fn database_url_with_default(
		&self,
		key: &str,
		default: Option<&str>,
	) -> Result<DatabaseUrl, EnvError> {
		let full_key = self.get_key_name(key);
		validate_env_var_name(&full_key)?;

		let url_str = match env::var(&full_key) {
			Ok(val) => val,
			Err(_) => match default {
				Some(d) => d.to_string(),
				None => return Err(EnvError::MissingVariable(full_key)),
			},
		};

		parse_database_url(&url_str).map_err(|e| EnvError::ParseError {
			key: full_key,
			value_len: url_str.len(),
			error: e,
		})
	}
	/// Read a path value from environment
	///
	pub fn path(&self, key: &str) -> Result<PathBuf, EnvError> {
		self.path_with_default(key, None)
	}
	/// Read a path value with a default
	///
	pub fn path_with_default(
		&self,
		key: &str,
		default: Option<PathBuf>,
	) -> Result<PathBuf, EnvError> {
		let full_key = self.get_key_name(key);
		validate_env_var_name(&full_key)?;

		match env::var(&full_key) {
			Ok(val) => Ok(PathBuf::from(val)),
			Err(_) => match default {
				Some(d) => Ok(d),
				None => Err(EnvError::MissingVariable(full_key)),
			},
		}
	}
}

impl Default for Env {
	fn default() -> Self {
		Self::new()
	}
}

/// Validates an environment variable name.
///
/// Rejects names that are empty, contain control characters, or contain
/// the `=` character (which is used as the key-value separator).
pub fn validate_env_var_name(name: &str) -> Result<(), EnvError> {
	if name.is_empty() {
		return Err(EnvError::InvalidVariableName {
			name: name.to_string(),
			reason: "environment variable name must not be empty".to_string(),
		});
	}

	if let Some(pos) = name.find(|c: char| c.is_control()) {
		return Err(EnvError::InvalidVariableName {
			name: name.to_string(),
			reason: format!(
				"environment variable name contains control character at position {}",
				pos
			),
		});
	}

	if name.contains('=') {
		return Err(EnvError::InvalidVariableName {
			name: name.to_string(),
			reason: "environment variable name must not contain '='".to_string(),
		});
	}

	Ok(())
}

/// Environment variable errors
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
pub enum EnvError {
	/// The required environment variable is not set.
	#[error("Missing environment variable: {0}")]
	MissingVariable(String),

	/// The environment variable value could not be parsed to the expected type.
	#[error("Failed to parse environment variable '{key}' (value length: {value_len}): {error}")]
	ParseError {
		/// The environment variable key.
		key: String,
		/// Length of the original value (stored instead of the raw value to prevent secret leakage).
		value_len: usize,
		/// Description of the parse failure.
		error: String,
	},

	/// An I/O error occurred while reading environment files.
	#[error("IO error: {0}")]
	IoError(#[from] std::io::Error),

	/// The environment variable format is invalid.
	#[error("Invalid format: {0}")]
	InvalidFormat(String),

	/// The environment variable name contains invalid characters.
	#[error("Invalid environment variable name '{name}': {reason}")]
	InvalidVariableName {
		/// The invalid variable name.
		name: String,
		/// Description of why the name is invalid.
		reason: String,
	},
}

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

	#[rstest]
	#[serial(env)]
	fn test_env_str() {
		// SAFETY: Setting environment variables is unsafe in multi-threaded programs.
		// This test uses #[serial] to ensure exclusive access to environment variables.
		unsafe {
			env::set_var("TEST_STR", "hello");
		}
		let env = Env::new();
		assert_eq!(env.str("TEST_STR").unwrap(), "hello");
		// SAFETY: Removing environment variables is unsafe in multi-threaded programs.
		// This test uses #[serial] to ensure exclusive access to environment variables.
		unsafe {
			env::remove_var("TEST_STR");
		}
	}

	#[rstest]
	fn test_env_str_with_default() {
		let env = Env::new();
		assert_eq!(
			env.str_with_default("NONEXISTENT", Some("default"))
				.unwrap(),
			"default"
		);
	}

	#[rstest]
	#[serial(env)]
	fn test_env_bool() {
		// SAFETY: Setting environment variables is unsafe in multi-threaded programs.
		// This test uses #[serial] to ensure exclusive access to environment variables.
		unsafe {
			env::set_var("TEST_BOOL_TRUE", "true");
			env::set_var("TEST_BOOL_FALSE", "false");
			env::set_var("TEST_BOOL_1", "1");
			env::set_var("TEST_BOOL_0", "0");
		}

		let env = Env::new();
		assert!(env.bool("TEST_BOOL_TRUE").unwrap());
		assert!(!env.bool("TEST_BOOL_FALSE").unwrap());
		assert!(env.bool("TEST_BOOL_1").unwrap());
		assert!(!env.bool("TEST_BOOL_0").unwrap());

		// SAFETY: Removing environment variables is unsafe in multi-threaded programs.
		// This test uses #[serial] to ensure exclusive access to environment variables.
		unsafe {
			env::remove_var("TEST_BOOL_TRUE");
			env::remove_var("TEST_BOOL_FALSE");
			env::remove_var("TEST_BOOL_1");
			env::remove_var("TEST_BOOL_0");
		}
	}

	#[rstest]
	#[serial(env)]
	fn test_env_int() {
		// SAFETY: Setting environment variables is unsafe in multi-threaded programs.
		// This test uses #[serial] to ensure exclusive access to environment variables.
		unsafe {
			env::set_var("TEST_INT", "42");
		}
		let env = Env::new();
		assert_eq!(env.int("TEST_INT").unwrap(), 42);
		// SAFETY: Removing environment variables is unsafe in multi-threaded programs.
		// This test uses #[serial] to ensure exclusive access to environment variables.
		unsafe {
			env::remove_var("TEST_INT");
		}
	}

	#[rstest]
	#[serial(env)]
	fn test_env_list() {
		// SAFETY: Setting environment variables is unsafe in multi-threaded programs.
		// This test uses #[serial] to ensure exclusive access to environment variables.
		unsafe {
			env::set_var("TEST_LIST", "a,b,c");
		}
		let env = Env::new();
		assert_eq!(env.list("TEST_LIST").unwrap(), vec!["a", "b", "c"]);
		// SAFETY: Removing environment variables is unsafe in multi-threaded programs.
		// This test uses #[serial] to ensure exclusive access to environment variables.
		unsafe {
			env::remove_var("TEST_LIST");
		}
	}

	#[rstest]
	#[serial(env)]
	fn test_settings_env_with_prefix() {
		// SAFETY: Setting environment variables is unsafe in multi-threaded programs.
		// This test uses #[serial] to ensure exclusive access to environment variables.
		unsafe {
			env::set_var("REINHARDT_DEBUG", "true");
		}
		let env = Env::new().with_prefix("REINHARDT_");
		assert!(env.bool("DEBUG").unwrap());
		// SAFETY: Removing environment variables is unsafe in multi-threaded programs.
		// This test uses #[serial] to ensure exclusive access to environment variables.
		unsafe {
			env::remove_var("REINHARDT_DEBUG");
		}
	}

	#[rstest]
	#[serial(env)]
	fn test_env_path() {
		// SAFETY: Setting environment variables is unsafe in multi-threaded programs.
		// This test uses #[serial] to ensure exclusive access to environment variables.
		unsafe {
			env::set_var("TEST_PATH", "/tmp/test");
		}
		let env = Env::new();
		assert_eq!(env.path("TEST_PATH").unwrap(), PathBuf::from("/tmp/test"));
		// SAFETY: Removing environment variables is unsafe in multi-threaded programs.
		// This test uses #[serial] to ensure exclusive access to environment variables.
		unsafe {
			env::remove_var("TEST_PATH");
		}
	}

	#[rstest]
	fn test_validate_env_var_name_rejects_empty() {
		// Arrange & Act
		let result = validate_env_var_name("");

		// Assert
		assert!(result.is_err());
		assert!(matches!(
			result.unwrap_err(),
			EnvError::InvalidVariableName { .. }
		));
	}

	#[rstest]
	fn test_validate_env_var_name_rejects_control_chars() {
		// Arrange & Act
		let result = validate_env_var_name("MY\x00VAR");

		// Assert
		assert!(result.is_err());
		let err = result.unwrap_err();
		match &err {
			EnvError::InvalidVariableName { reason, .. } => {
				assert!(reason.contains("control character"));
			}
			_ => panic!("Expected InvalidVariableName error"),
		}
	}

	#[rstest]
	fn test_validate_env_var_name_rejects_equals_sign() {
		// Arrange & Act
		let result = validate_env_var_name("MY=VAR");

		// Assert
		assert!(result.is_err());
		let err = result.unwrap_err();
		match &err {
			EnvError::InvalidVariableName { reason, .. } => {
				assert!(reason.contains("'='"));
			}
			_ => panic!("Expected InvalidVariableName error"),
		}
	}

	#[rstest]
	fn test_validate_env_var_name_accepts_valid_name() {
		// Arrange & Act & Assert
		assert!(validate_env_var_name("MY_VALID_VAR_123").is_ok());
		assert!(validate_env_var_name("REINHARDT_DEBUG").is_ok());
	}

	#[rstest]
	fn test_parse_error_does_not_leak_value() {
		// Arrange
		let err = EnvError::ParseError {
			key: "SECRET_KEY".to_string(),
			value_len: 32,
			error: "invalid format".to_string(),
		};

		// Act
		let error_msg = format!("{}", err);

		// Assert - the error message must not contain the actual secret value
		assert!(error_msg.contains("value length: 32"));
		assert!(!error_msg.contains("secret"));
	}

	#[rstest]
	fn test_env_rejects_empty_key_name() {
		// Arrange
		let env = Env::new();

		// Act
		let result = env.str("");

		// Assert
		assert!(result.is_err());
		assert!(matches!(
			result.unwrap_err(),
			EnvError::InvalidVariableName { .. }
		));
	}
}