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
//! .env file loading functionality
//!
//! Provides Django-environ compatible .env file parsing and loading.

use std::env;
use std::fs;
use std::path::PathBuf;

use super::env::{EnvError, validate_env_var_name};

/// Environment file loader
pub struct EnvLoader {
	/// Path to the .env file
	path: Option<PathBuf>,

	/// Whether to overwrite existing environment variables
	overwrite: bool,

	/// Whether to enable variable interpolation
	interpolate: bool,
}

impl EnvLoader {
	/// Create a new EnvLoader
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_conf::settings::env_loader::EnvLoader;
	/// use std::path::PathBuf;
	///
	/// let loader = EnvLoader::new()
	///     .path(PathBuf::from(".env.test"))
	///     .interpolate(true);
	///
	// Loader is configured and ready to load .env files
	// Can call loader.load_optional() to load the file
	/// ```
	pub fn new() -> Self {
		Self {
			path: None,
			overwrite: false,
			interpolate: false,
		}
	}
	/// Set the path to the .env file
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_conf::settings::env_loader::EnvLoader;
	/// use std::path::PathBuf;
	///
	/// let loader = EnvLoader::new()
	///     .path(PathBuf::from(".env.production"));
	///
	/// // Loader is configured to load from .env.production
	/// ```
	pub fn path(mut self, path: impl Into<PathBuf>) -> Self {
		self.path = Some(path.into());
		self
	}
	/// Enable overwriting existing environment variables
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_conf::settings::env_loader::EnvLoader;
	///
	/// let loader = EnvLoader::new()
	///     .overwrite(true);
	///
	/// // When loading .env, existing env vars will be overwritten
	/// ```
	pub fn overwrite(mut self, enabled: bool) -> Self {
		self.overwrite = enabled;
		self
	}
	/// Enable variable interpolation ($VAR expansion)
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_conf::settings::env_loader::EnvLoader;
	///
	/// let loader = EnvLoader::new()
	///     .interpolate(true);
	///
	/// // Variables like $HOME or ${USER} will be expanded
	/// ```
	pub fn interpolate(mut self, enabled: bool) -> Self {
		self.interpolate = enabled;
		self
	}
	/// Load environment variables from the .env file
	///
	/// # Thread Safety
	///
	/// This method calls `env::set_var` internally, which is not thread-safe.
	/// It MUST only be called during single-threaded application startup,
	/// before any worker threads are spawned.
	///
	/// # Examples
	///
	/// ```rust
	/// use reinhardt_conf::settings::env_loader::EnvLoader;
	/// use std::io::Write;
	///
	/// let temp_dir = tempfile::tempdir().unwrap();
	/// let env_path = temp_dir.path().join(".env");
	/// let mut file = std::fs::File::create(&env_path).unwrap();
	/// writeln!(file, "TEST_KEY=test_value").unwrap();
	///
	/// let loader = EnvLoader::new().path(env_path);
	/// loader.load().expect("Failed to load .env");
	///
	/// assert_eq!(std::env::var("TEST_KEY").unwrap(), "test_value");
	/// ```
	pub fn load(&self) -> Result<(), EnvError> {
		let path = match &self.path {
			Some(p) => p.clone(),
			None => self.find_env_file()?,
		};

		if !path.exists() {
			return Err(EnvError::IoError(std::io::Error::new(
				std::io::ErrorKind::NotFound,
				format!(".env file not found: {}", path.display()),
			)));
		}

		let content = fs::read_to_string(&path)?;
		self.parse_and_set(&content)?;

		Ok(())
	}
	/// Try to load the .env file, but don't fail if it doesn't exist
	///
	/// # Thread Safety
	///
	/// This method calls `env::set_var` internally, which is not thread-safe.
	/// It MUST only be called during single-threaded application startup,
	/// before any worker threads are spawned.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_conf::settings::env_loader::EnvLoader;
	/// use std::path::PathBuf;
	///
	/// let loader = EnvLoader::new()
	///     .path(PathBuf::from(".env.optional"));
	///
	/// // Returns Ok(true) if loaded, Ok(false) if not found
	/// let loaded = loader.load_optional().unwrap();
	/// // Won't panic if file doesn't exist
	/// ```
	pub fn load_optional(&self) -> Result<bool, EnvError> {
		let path = match &self.path {
			Some(p) => p.clone(),
			None => match self.find_env_file() {
				Ok(p) => p,
				Err(_) => return Ok(false),
			},
		};

		if !path.exists() {
			return Ok(false);
		}

		let content = fs::read_to_string(&path)?;
		self.parse_and_set(&content)?;

		Ok(true)
	}

	/// Maximum number of parent directories to traverse when searching for .env files.
	/// Prevents unbounded traversal to the filesystem root in deeply nested directories.
	const MAX_TRAVERSAL_DEPTH: usize = 10;

	/// Project root marker files that stop .env file traversal.
	const ROOT_MARKERS: &[&str] = &[".git", "Cargo.toml", "Cargo.lock"];

	/// Find the .env file in current or parent directories.
	///
	/// Traversal stops at:
	/// - A directory containing a `.env` file (found)
	/// - A project root marker (`.git`, `Cargo.toml`, `Cargo.lock`)
	/// - The maximum traversal depth ([`Self::MAX_TRAVERSAL_DEPTH`])
	/// - The filesystem root
	fn find_env_file(&self) -> Result<PathBuf, EnvError> {
		let mut current = env::current_dir()?;

		for _depth in 0..Self::MAX_TRAVERSAL_DEPTH {
			let env_path = current.join(".env");
			if env_path.exists() {
				return Ok(env_path);
			}

			// Stop at project root markers to avoid loading unintended .env files
			if Self::ROOT_MARKERS
				.iter()
				.any(|marker| current.join(marker).exists())
			{
				return Err(EnvError::IoError(std::io::Error::new(
					std::io::ErrorKind::NotFound,
					format!(
						".env file not found (stopped at project root: {})",
						current.display()
					),
				)));
			}

			match current.parent() {
				Some(parent) => current = parent.to_path_buf(),
				None => {
					return Err(EnvError::IoError(std::io::Error::new(
						std::io::ErrorKind::NotFound,
						".env file not found in current or parent directories",
					)));
				}
			}
		}

		Err(EnvError::IoError(std::io::Error::new(
			std::io::ErrorKind::NotFound,
			format!(
				".env file not found within {} parent directories",
				Self::MAX_TRAVERSAL_DEPTH
			),
		)))
	}

	/// Parse .env file content and set environment variables
	fn parse_and_set(&self, content: &str) -> Result<(), EnvError> {
		for (line_num, line) in content.lines().enumerate() {
			let trimmed = line.trim();

			// Skip empty lines and comments
			if trimmed.is_empty() || trimmed.starts_with('#') {
				continue;
			}

			// Handle export prefix
			let line_content = if trimmed.starts_with("export ") {
				trimmed.trim_start_matches("export ").trim()
			} else {
				trimmed
			};

			// Parse key=value
			if let Some((key, value)) = line_content.split_once('=') {
				let key = key.trim();
				validate_env_var_name(key)?;
				let mut value = value.trim().to_string();

				// Remove quotes if present, tracking quote type for POSIX semantics
				let is_single_quoted =
					value.starts_with('\'') && value.ends_with('\'') && value.len() >= 2;
				let is_double_quoted =
					value.starts_with('"') && value.ends_with('"') && value.len() >= 2;
				if is_single_quoted || is_double_quoted {
					value = value[1..value.len() - 1].to_string();
				}

				// Single-quoted values preserve literal content per POSIX semantics:
				// no variable interpolation or escape processing
				if !is_single_quoted {
					// Handle variable interpolation
					if self.interpolate {
						value = self.expand_variables(&value);
					}

					// Handle escaped characters
					value = self.unescape(&value);
				}

				// Set or skip based on overwrite setting
				if self.overwrite || env::var(key).is_err() {
					// SAFETY: `env::set_var` is not thread-safe per POSIX and Rust 2024
					// edition marks it as unsafe. This call is safe because:
					// 1. EnvLoader is designed to run during single-threaded application
					//    startup (before any worker threads are spawned).
					// 2. Callers MUST NOT invoke `parse_and_set` from multi-threaded
					//    contexts. The public API (`load`, `load_optional`) documents
					//    this startup-only constraint.
					// 3. If env mutation is needed after startup, callers should store
					//    values in a thread-safe map (e.g., `RwLock<HashMap>`) instead.
					unsafe {
						env::set_var(key, value);
					}
				}
			} else {
				return Err(EnvError::InvalidFormat(format!(
					"Invalid line format at line {}: {}",
					line_num + 1,
					line
				)));
			}
		}

		Ok(())
	}

	/// Expand variables in the format $VAR or ${VAR}
	fn expand_variables(&self, value: &str) -> String {
		let mut result = String::new();
		let mut chars = value.chars().peekable();

		while let Some(ch) = chars.next() {
			if ch == '$' {
				if chars.peek() == Some(&'{') {
					// ${VAR} format
					chars.next(); // consume '{'
					let var_name: String = chars.by_ref().take_while(|&c| c != '}').collect();

					if let Ok(var_value) = env::var(&var_name) {
						result.push_str(&var_value);
					}
				} else {
					// $VAR format - collect variable name
					let mut var_name = String::new();
					while let Some(&next_ch) = chars.peek() {
						if next_ch.is_alphanumeric() || next_ch == '_' {
							var_name.push(next_ch);
							chars.next();
						} else {
							break;
						}
					}

					if let Ok(var_value) = env::var(&var_name) {
						result.push_str(&var_value);
					}
				}
			} else if ch == '\\' && chars.peek() == Some(&'$') {
				// Escaped dollar sign
				chars.next();
				result.push('$');
			} else {
				result.push(ch);
			}
		}

		result
	}

	/// Unescape common escape sequences
	fn unescape(&self, value: &str) -> String {
		let mut result = String::with_capacity(value.len());
		let mut chars = value.chars().peekable();
		while let Some(c) = chars.next() {
			if c == '\\' {
				match chars.peek() {
					Some('n') => {
						result.push('\n');
						chars.next();
					}
					Some('r') => {
						result.push('\r');
						chars.next();
					}
					Some('t') => {
						result.push('\t');
						chars.next();
					}
					Some('\\') => {
						result.push('\\');
						chars.next();
					}
					_ => result.push(c),
				}
			} else {
				result.push(c);
			}
		}
		result
	}
}

impl Default for EnvLoader {
	fn default() -> Self {
		Self::new()
	}
}
/// Load .env file from the specified path
///
/// # Examples
///
/// ```rust
/// use reinhardt_conf::settings::env_loader::load_env;
/// use std::io::Write;
///
/// let temp_dir = tempfile::tempdir().unwrap();
/// let env_path = temp_dir.path().join(".env");
/// let mut file = std::fs::File::create(&env_path).unwrap();
/// writeln!(file, "LOAD_ENV_KEY=loaded").unwrap();
///
/// load_env(env_path).expect("Failed to load .env");
/// assert_eq!(std::env::var("LOAD_ENV_KEY").unwrap(), "loaded");
/// ```
pub fn load_env(path: impl Into<PathBuf>) -> Result<(), EnvError> {
	EnvLoader::new().path(path).load()
}
/// Load .env file from current or parent directories
///
/// # Examples
///
/// ```rust
/// use reinhardt_conf::settings::env_loader::EnvLoader;
/// use std::io::Write;
///
/// let temp_dir = tempfile::tempdir().unwrap();
/// let env_path = temp_dir.path().join(".env");
/// let mut file = std::fs::File::create(&env_path).unwrap();
/// writeln!(file, "AUTO_LOAD_KEY=auto").unwrap();
///
/// // Change to temp directory for auto-discovery
/// let original_dir = std::env::current_dir().unwrap();
/// std::env::set_current_dir(temp_dir.path()).unwrap();
///
/// let loader = EnvLoader::new();
/// loader.load().expect("Failed to auto-load .env");
///
/// assert_eq!(std::env::var("AUTO_LOAD_KEY").unwrap(), "auto");
///
/// // Restore original directory
/// std::env::set_current_dir(original_dir).unwrap();
/// ```
pub fn load_env_auto() -> Result<(), EnvError> {
	EnvLoader::new().load()
}
/// Load .env file optionally (don't fail if not found)
///
/// # Examples
///
/// ```
/// use reinhardt_conf::settings::env_loader::load_env_optional;
/// use std::path::PathBuf;
///
/// // Returns true if loaded, false if not found
/// let loaded = load_env_optional(PathBuf::from(".env.test")).unwrap();
/// // Will not panic if file doesn't exist
/// ```
pub fn load_env_optional(path: impl Into<PathBuf>) -> Result<bool, EnvError> {
	EnvLoader::new().path(path).load_optional()
}

#[cfg(test)]
mod tests {
	use super::*;
	use rstest::rstest;
	use serial_test::serial;
	use std::fs::File;
	use std::io::Write;
	use tempfile::TempDir;

	#[test]
	fn test_parse_simple_env() {
		let content = r#"
# Comment
KEY1=value1
KEY2=value2
        "#;

		let loader = EnvLoader::new();
		loader.parse_and_set(content).unwrap();

		assert_eq!(env::var("KEY1").unwrap(), "value1");
		assert_eq!(env::var("KEY2").unwrap(), "value2");

		// 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("KEY1");
			env::remove_var("KEY2");
		}
	}

	#[test]
	fn test_parse_quoted_values() {
		let content = r#"
QUOTED_SINGLE='single quoted'
QUOTED_DOUBLE="double quoted"
        "#;

		let loader = EnvLoader::new();
		loader.parse_and_set(content).unwrap();

		assert_eq!(env::var("QUOTED_SINGLE").unwrap(), "single quoted");
		assert_eq!(env::var("QUOTED_DOUBLE").unwrap(), "double quoted");

		// 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("QUOTED_SINGLE");
			env::remove_var("QUOTED_DOUBLE");
		}
	}

	#[test]
	fn test_parse_export() {
		let content = r#"
export EXPORTED_VAR="exported value"
        "#;

		let loader = EnvLoader::new();
		loader.parse_and_set(content).unwrap();

		assert_eq!(env::var("EXPORTED_VAR").unwrap(), "exported value");

		// 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("EXPORTED_VAR");
		}
	}

	#[test]
	fn test_variable_expansion() {
		// 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("BASE_VAR", "base");
		}

		let content = r#"
EXPANDED=$BASE_VAR/expanded
EXPANDED_BRACES=${BASE_VAR}/expanded
        "#;

		let loader = EnvLoader::new().interpolate(true);
		loader.parse_and_set(content).unwrap();

		assert_eq!(env::var("EXPANDED").unwrap(), "base/expanded");
		assert_eq!(env::var("EXPANDED_BRACES").unwrap(), "base/expanded");

		// 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("BASE_VAR");
			env::remove_var("EXPANDED");
			env::remove_var("EXPANDED_BRACES");
		}
	}

	#[test]
	fn test_escaped_dollar() {
		let content = r#"
ESCAPED=\$not_expanded
        "#;

		let loader = EnvLoader::new().interpolate(true);
		loader.parse_and_set(content).unwrap();

		assert_eq!(env::var("ESCAPED").unwrap(), "$not_expanded");

		// 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("ESCAPED");
		}
	}

	#[test]
	fn test_load_from_file() {
		let temp_dir = TempDir::new().unwrap();
		let env_path = temp_dir.path().join(".env");

		let mut file = File::create(&env_path).unwrap();
		writeln!(file, "FILE_VAR=file_value").unwrap();

		let loader = EnvLoader::new().path(&env_path);
		loader.load().unwrap();

		assert_eq!(env::var("FILE_VAR").unwrap(), "file_value");

		// 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("FILE_VAR");
		}
	}

	/// Guard that removes environment variables on drop, ensuring cleanup
	/// even if assertions panic.
	struct EnvGuard(Vec<&'static str>);

	impl Drop for EnvGuard {
		fn drop(&mut self) {
			// SAFETY: Removing environment variables is unsafe in multi-threaded
			// programs.  Tests using this guard run under #[serial] to ensure
			// exclusive access.
			for key in &self.0 {
				unsafe {
					env::remove_var(key);
				}
			}
		}
	}

	#[rstest]
	#[serial(env_vars)]
	fn test_single_quoted_values_preserve_escape_sequences() {
		// Arrange
		let _guard = EnvGuard(vec!["SINGLE_ESCAPE", "DOUBLE_ESCAPE"]);
		let content = r#"
SINGLE_ESCAPE='\n\t\\'
DOUBLE_ESCAPE="\n\t\\"
		"#;

		// Act
		let loader = EnvLoader::new();
		loader.parse_and_set(content).unwrap();

		// Assert
		// Single-quoted: escape sequences preserved literally per POSIX semantics
		assert_eq!(env::var("SINGLE_ESCAPE").unwrap(), r"\n\t\\");

		// Double-quoted: escape sequences are processed
		assert_eq!(
			env::var("DOUBLE_ESCAPE").unwrap(),
			"\n\t\\",
			"Double-quoted value should process escapes to newline, tab, and backslash"
		);
	}

	#[rstest]
	// Basic escape sequences: `\n` → newline, `\r` → carriage return, `\t` → tab
	#[case::newline(r"\n", "\n")]
	#[case::carriage_return(r"\r", "\r")]
	#[case::tab(r"\t", "\t")]
	// `\\` (2 chars) → `\` (1 char)
	#[case::escaped_backslash(r"\\", r"\")]
	// `\\n` (3 chars: \, \, n) → `\` then `n` as literal → `\n` (backslash + n)
	#[case::literal_backslash_n(r"\\n", r"\n")]
	// `\\\\n` (5 chars: \, \, \, \, n) → `\`, `\`, then `n` as literal
	#[case::escaped_backslash_then_literal_n(r"\\\\n", r"\\n")]
	// `\\\\` (4 chars: \, \, \, \) → `\`, `\`
	#[case::double_escaped_backslash(r"\\\\", r"\\")]
	// Trailing lone backslash is preserved as-is
	#[case::trailing_backslash(r"hello\", r"hello\")]
	#[case::mixed_sequences(r"line1\nline2\ttab", "line1\nline2\ttab")]
	#[case::no_escapes("hello world", "hello world")]
	fn test_unescape(#[case] input: &str, #[case] expected: &str) {
		// Arrange
		let loader = EnvLoader::new();

		// Act
		let result = loader.unescape(input);

		// Assert
		assert_eq!(result, expected);
	}
}