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
//! Database configuration for settings
//!
//! This module provides the `DatabaseConfig` struct and its methods for
//! configuring database connections in Reinhardt settings files.

use percent_encoding::{AsciiSet, NON_ALPHANUMERIC, utf8_percent_encode};
use reinhardt_core::macros::settings;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt;

use crate::settings::secret_types::SecretString;

/// Characters that must be percent-encoded in URL userinfo components.
/// RFC 3986 Section 3.2.1 defines userinfo = *( unreserved / pct-encoded / sub-delims / ":" )
/// We encode everything except unreserved characters to be safe.
const USERINFO_ENCODE_SET: &AsciiSet = &NON_ALPHANUMERIC
	.remove(b'-')
	.remove(b'.')
	.remove(b'_')
	.remove(b'~');

/// Database configuration
#[settings(fragment = true, default_policy = "required")]
#[non_exhaustive]
#[derive(Clone, Serialize, Deserialize)]
pub struct DatabaseConfig {
	/// Database engine/backend
	pub engine: String,

	/// Database name or path
	pub name: String,

	/// Database user (if applicable)
	#[setting(optional)]
	pub user: Option<String>,

	/// Database password (if applicable) - stored as `SecretString` to prevent accidental exposure
	#[setting(optional)]
	pub password: Option<SecretString>,

	/// Database host (if applicable)
	#[setting(optional)]
	pub host: Option<String>,

	/// Database port (if applicable)
	#[setting(optional)]
	pub port: Option<u16>,

	/// Additional options
	#[setting(optional)]
	#[serde(default)]
	pub options: HashMap<String, String>,
}

impl fmt::Debug for DatabaseConfig {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		f.debug_struct("DatabaseConfig")
			.field("engine", &self.engine)
			.field("name", &self.name)
			.field("user", &self.user)
			.field("password", &self.password.as_ref().map(|_| "[REDACTED]"))
			.field("host", &self.host)
			.field("port", &self.port)
			.field("options", &self.options)
			.finish()
	}
}

impl DatabaseConfig {
	/// Create a new database configuration with the given engine and name
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_conf::settings::DatabaseConfig;
	///
	/// let db = DatabaseConfig::new("reinhardt.db.backends.sqlite3", "myapp.db");
	/// assert_eq!(db.engine, "reinhardt.db.backends.sqlite3");
	/// assert_eq!(db.name, "myapp.db");
	/// ```
	pub fn new(engine: impl Into<String>, name: impl Into<String>) -> Self {
		Self {
			engine: engine.into(),
			name: name.into(),
			user: None,
			password: None,
			host: None,
			port: None,
			options: HashMap::new(),
		}
	}

	/// Set the user for this database configuration
	pub fn with_user(mut self, user: impl Into<String>) -> Self {
		self.user = Some(user.into());
		self
	}

	/// Set the password for this database configuration
	pub fn with_password(mut self, password: impl Into<String>) -> Self {
		self.password = Some(SecretString::new(password.into()));
		self
	}

	/// Set the host for this database configuration
	pub fn with_host(mut self, host: impl Into<String>) -> Self {
		self.host = Some(host.into());
		self
	}

	/// Set the port for this database configuration
	pub fn with_port(mut self, port: u16) -> Self {
		self.port = Some(port);
		self
	}

	/// Create a SQLite database configuration
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_conf::settings::DatabaseConfig;
	///
	/// let db = DatabaseConfig::sqlite("myapp.db");
	///
	/// assert_eq!(db.engine, "reinhardt.db.backends.sqlite3");
	/// assert_eq!(db.name, "myapp.db");
	/// assert!(db.user.is_none());
	/// assert!(db.password.is_none());
	/// ```
	pub fn sqlite(name: impl Into<String>) -> Self {
		Self {
			engine: "reinhardt.db.backends.sqlite3".to_string(),
			name: name.into(),
			user: None,
			password: None,
			host: None,
			port: None,
			options: HashMap::new(),
		}
	}
	/// Create a PostgreSQL database configuration
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_conf::settings::DatabaseConfig;
	///
	/// let db = DatabaseConfig::postgresql("mydb", "admin", "password123", "localhost", 5432);
	///
	/// assert_eq!(db.engine, "reinhardt.db.backends.postgresql");
	/// assert_eq!(db.name, "mydb");
	/// assert_eq!(db.user, Some("admin".to_string()));
	/// assert_eq!(db.password.as_ref().map(|p| p.expose_secret()), Some("password123"));
	/// assert_eq!(db.host, Some("localhost".to_string()));
	/// assert_eq!(db.port, Some(5432));
	/// ```
	pub fn postgresql(
		name: impl Into<String>,
		user: impl Into<String>,
		password: impl Into<String>,
		host: impl Into<String>,
		port: u16,
	) -> Self {
		Self {
			engine: "reinhardt.db.backends.postgresql".to_string(),
			name: name.into(),
			user: Some(user.into()),
			password: Some(SecretString::new(password.into())),
			host: Some(host.into()),
			port: Some(port),
			options: HashMap::new(),
		}
	}
	/// Create a MySQL database configuration
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_conf::settings::DatabaseConfig;
	///
	/// let db = DatabaseConfig::mysql("mydb", "root", "password123", "localhost", 3306);
	///
	/// assert_eq!(db.engine, "reinhardt.db.backends.mysql");
	/// assert_eq!(db.name, "mydb");
	/// assert_eq!(db.user, Some("root".to_string()));
	/// assert_eq!(db.password.as_ref().map(|p| p.expose_secret()), Some("password123"));
	/// assert_eq!(db.host, Some("localhost".to_string()));
	/// assert_eq!(db.port, Some(3306));
	/// ```
	pub fn mysql(
		name: impl Into<String>,
		user: impl Into<String>,
		password: impl Into<String>,
		host: impl Into<String>,
		port: u16,
	) -> Self {
		Self {
			engine: "reinhardt.db.backends.mysql".to_string(),
			name: name.into(),
			user: Some(user.into()),
			password: Some(SecretString::new(password.into())),
			host: Some(host.into()),
			port: Some(port),
			options: HashMap::new(),
		}
	}

	/// Convert `DatabaseConfig` to DATABASE_URL string
	///
	/// Credentials and query parameter values are percent-encoded per RFC 3986
	/// to prevent URL injection and parsing errors from special characters.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_conf::settings::DatabaseConfig;
	///
	/// let db = DatabaseConfig::sqlite("db.sqlite3");
	/// assert_eq!(db.to_url(), "sqlite:db.sqlite3");
	///
	/// let db = DatabaseConfig::postgresql("mydb", "user", "p@ss:word", "localhost", 5432);
	/// assert_eq!(db.to_url(), "postgresql://user:p%40ss%3Aword@localhost:5432/mydb");
	/// ```
	pub fn to_url(&self) -> String {
		// Determine the database scheme from engine
		// Handle both short names (e.g., "sqlite") and full backend paths (e.g., "reinhardt.db.backends.sqlite3")
		let scheme = if self.engine == "sqlite" || self.engine.contains("sqlite") {
			"sqlite"
		} else if self.engine == "postgresql"
			|| self.engine == "postgres"
			|| self.engine.contains("postgresql")
			|| self.engine.contains("postgres")
		{
			"postgresql"
		} else if self.engine == "mysql" || self.engine.contains("mysql") {
			"mysql"
		} else {
			// Default to sqlite for unknown engines
			"sqlite"
		};

		match scheme {
			"sqlite" => {
				if self.name == ":memory:" {
					"sqlite::memory:".to_string()
				} else {
					// Use sqlite: format for relative paths (will be converted to absolute in connect_database)
					// sqlite:/// is for absolute paths
					use std::path::Path;
					let path = Path::new(&self.name);
					if path.is_absolute() {
						// Absolute path: sqlite:///path/to/db.sqlite3
						format!("sqlite:///{}", self.name)
					} else {
						// Relative path: sqlite:db.sqlite3 (will be converted to absolute in connect_database)
						format!("sqlite:{}", self.name)
					}
				}
			}
			"postgresql" | "mysql" => {
				let mut url = format!("{}://", scheme);

				// Add user and password if available, percent-encoded per RFC 3986
				if let Some(user) = &self.user {
					let encoded_user = utf8_percent_encode(user, USERINFO_ENCODE_SET).to_string();
					url.push_str(&encoded_user);
					if let Some(password) = &self.password {
						url.push(':');
						let encoded_password =
							utf8_percent_encode(password.expose_secret(), USERINFO_ENCODE_SET)
								.to_string();
						url.push_str(&encoded_password);
					}
					url.push('@');
				}

				// Add host (default to localhost if not specified)
				let host = self.host.as_deref().unwrap_or("localhost");
				url.push_str(host);

				// Add port if available
				if let Some(port) = self.port {
					url.push(':');
					url.push_str(&port.to_string());
				}

				// Add database name
				url.push('/');
				url.push_str(&self.name);

				// Add query parameters if any, with percent-encoded values
				if !self.options.is_empty() {
					let mut query_parts = Vec::new();
					for (key, value) in &self.options {
						let encoded_key = utf8_percent_encode(key, USERINFO_ENCODE_SET).to_string();
						let encoded_value =
							utf8_percent_encode(value, USERINFO_ENCODE_SET).to_string();
						query_parts.push(format!("{}={}", encoded_key, encoded_value));
					}
					url.push('?');
					url.push_str(&query_parts.join("&"));
				}

				url
			}
			_ => format!("sqlite://{}", self.name),
		}
	}
}

impl fmt::Display for DatabaseConfig {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		// Display a sanitized representation that never exposes credentials
		let scheme = if self.engine.contains("sqlite") {
			"sqlite"
		} else if self.engine.contains("postgresql") || self.engine.contains("postgres") {
			"postgresql"
		} else if self.engine.contains("mysql") {
			"mysql"
		} else {
			"unknown"
		};

		match scheme {
			"sqlite" => write!(f, "sqlite:{}", self.name),
			_ => {
				write!(f, "{}://", scheme)?;
				if self.user.is_some() || self.password.is_some() {
					write!(f, "***@")?;
				}
				if let Some(host) = &self.host {
					write!(f, "{}", host)?;
				}
				if let Some(port) = self.port {
					write!(f, ":{}", port)?;
				}
				write!(f, "/{}", self.name)
			}
		}
	}
}

impl Default for DatabaseConfig {
	fn default() -> Self {
		Self::sqlite("db.sqlite3".to_string())
	}
}

/// Recognized database URL schemes for connection validation.
pub const VALID_DATABASE_SCHEMES: &[&str] = &[
	"postgres://",
	"postgresql://",
	"sqlite://",
	"sqlite:",
	"mysql://",
	"mariadb://",
];

/// Validate that a database URL starts with a recognized scheme.
///
/// Returns `Ok(())` if the URL starts with one of the supported schemes,
/// or `Err` with a descriptive message listing the accepted schemes.
pub fn validate_database_url_scheme(url: &str) -> Result<(), String> {
	if VALID_DATABASE_SCHEMES.iter().any(|s| url.starts_with(s)) {
		Ok(())
	} else {
		Err(format!(
			"Invalid database URL: unrecognized scheme. Expected one of: {}",
			VALID_DATABASE_SCHEMES.join(", ")
		))
	}
}

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

	#[rstest]
	fn test_settings_db_config_sqlite() {
		// Arrange
		let db = DatabaseConfig::sqlite("test.db");

		// Assert
		assert_eq!(db.engine, "reinhardt.db.backends.sqlite3");
		assert_eq!(db.name, "test.db");
		assert!(db.user.is_none());
		assert!(db.password.is_none());
	}

	#[rstest]
	fn test_settings_db_config_postgresql() {
		// Arrange
		// codeql[rust/hard-coded-cryptographic-value] -- Test fixture credential, not a deployed secret.
		let db = DatabaseConfig::postgresql("testdb", "user", "pass", "localhost", 5432);

		// Assert
		assert_eq!(db.engine, "reinhardt.db.backends.postgresql");
		assert_eq!(db.name, "testdb");
		assert_eq!(db.user, Some("user".to_string()));
		assert_eq!(
			db.password.as_ref().map(|p| p.expose_secret()),
			// codeql[rust/hard-coded-cryptographic-value] -- Test fixture credential assertion.
			Some("pass")
		);
		assert_eq!(db.port, Some(5432));
	}

	#[rstest]
	fn test_debug_output_redacts_password() {
		// Arrange
		// codeql[rust/hard-coded-cryptographic-value] -- Test fixture credential, not a deployed secret.
		let db = DatabaseConfig::postgresql("testdb", "user", "s3cr3t!", "localhost", 5432);

		// Act
		let debug_output = format!("{:?}", db);

		// Assert
		assert!(!debug_output.contains("s3cr3t!"));
		assert!(debug_output.contains("[REDACTED]"));
	}

	#[rstest]
	fn test_debug_output_without_password() {
		// Arrange
		let db = DatabaseConfig::sqlite("test.db");

		// Act
		let debug_output = format!("{:?}", db);

		// Assert
		assert!(debug_output.contains("None"));
		assert!(debug_output.contains("DatabaseConfig"));
	}

	#[rstest]
	fn test_to_url_encodes_special_chars_in_username() {
		// Arrange
		// codeql[rust/hard-coded-cryptographic-value] -- Test fixture credential, not a deployed secret.
		let mut db = DatabaseConfig::postgresql("mydb", "user@domain", "pass", "localhost", 5432);
		db.user = Some("user@domain".to_string());

		// Act
		let url = db.to_url();

		// Assert
		assert!(url.contains("user%40domain"));
		assert!(!url.contains("user@domain:"));
	}

	#[rstest]
	fn test_to_url_encodes_special_chars_in_password() {
		// Arrange
		// codeql[rust/hard-coded-cryptographic-value] -- Test fixture credential, not a deployed secret.
		let db = DatabaseConfig::postgresql("mydb", "user", "p@ss:w/rd#", "localhost", 5432);

		// Act
		let url = db.to_url();

		// Assert
		assert!(url.contains("p%40ss%3Aw%2Frd%23"));
		assert!(!url.contains("p@ss:w/rd#"));
	}

	#[rstest]
	fn test_to_url_prevents_host_injection() {
		// Arrange - malicious username that attempts to redirect to a different host
		// codeql[rust/hard-coded-cryptographic-value] -- Test fixture credential, not a deployed secret.
		let db = DatabaseConfig::postgresql(
			"mydb",
			"admin@evil.com:9999/fake",
			"pass",
			"localhost",
			5432,
		);

		// Act
		let url = db.to_url();

		// Assert - the @ in username should be encoded, preventing host injection
		assert!(url.contains("admin%40evil.com%3A9999%2Ffake"));
		assert!(url.contains("@localhost:5432"));
	}

	#[rstest]
	fn test_to_url_encodes_query_parameter_values() {
		// Arrange
		// codeql[rust/hard-coded-cryptographic-value] -- Test fixture credential, not a deployed secret.
		let mut db = DatabaseConfig::postgresql("mydb", "user", "pass", "localhost", 5432);
		db.options
			.insert("sslmode".to_string(), "require&inject=true".to_string());

		// Act
		let url = db.to_url();

		// Assert
		assert!(url.contains("require%26inject%3Dtrue"));
		assert!(!url.contains("require&inject=true"));
	}

	#[rstest]
	fn test_to_url_simple_credentials() {
		// Arrange
		// codeql[rust/hard-coded-cryptographic-value] -- Test fixture credential, not a deployed secret.
		let db = DatabaseConfig::postgresql("mydb", "user", "pass", "localhost", 5432);

		// Act
		let url = db.to_url();

		// Assert
		assert_eq!(url, "postgresql://user:pass@localhost:5432/mydb");
	}

	#[rstest]
	fn test_display_output_masks_credentials() {
		// Arrange
		// codeql[rust/hard-coded-cryptographic-value] -- Test fixture credential, not a deployed secret.
		let db = DatabaseConfig::postgresql("mydb", "admin", "s3cr3t!", "db.example.com", 5432);

		// Act
		let display_output = format!("{}", db);

		// Assert
		assert!(!display_output.contains("admin"));
		assert!(!display_output.contains("s3cr3t!"));
		assert!(display_output.contains("***@"));
		assert!(display_output.contains("db.example.com"));
		assert!(display_output.contains("mydb"));
	}

	#[rstest]
	fn test_display_output_sqlite() {
		// Arrange
		let db = DatabaseConfig::sqlite("app.db");

		// Act
		let display_output = format!("{}", db);

		// Assert
		assert_eq!(display_output, "sqlite:app.db");
	}

	#[rstest]
	fn test_password_stored_as_secret_string() {
		// Arrange
		// codeql[rust/hard-coded-cryptographic-value] -- Test fixture credential, not a deployed secret.
		let db = DatabaseConfig::postgresql("mydb", "user", "my-secret-pw", "localhost", 5432);

		// Act
		let password = db.password.as_ref().unwrap();

		// Assert
		assert_eq!(password.expose_secret(), "my-secret-pw");
		// Display should not reveal the password
		assert_eq!(format!("{}", password), "[REDACTED]");
	}

	#[rstest]
	#[serial(env)]
	fn test_database_password_deserializes_from_secret_sources() {
		let temp_file = tempfile::NamedTempFile::new().unwrap();
		std::fs::write(temp_file.path(), "replica-secret\n").unwrap();
		// SAFETY: This test is serialized with other environment-mutating tests.
		unsafe { std::env::set_var("REINHARDT_DEFAULT_DB_PASSWORD", "default-secret") };
		let file_path = temp_file.path().to_string_lossy().replace('\\', "\\\\");
		let toml = format!(
			r#"
[default]
engine = "postgresql"
host = "localhost"
port = 5432
name = "app"
user = "app"
password = {{ env = "REINHARDT_DEFAULT_DB_PASSWORD" }}

[replica]
engine = "postgresql"
host = "replica.internal"
port = 5432
name = "app"
user = "readonly"
password = {{ file = "{}" }}
"#,
			file_path
		);

		let databases: HashMap<String, DatabaseConfig> = toml::from_str(&toml).unwrap();

		assert_eq!(
			databases["default"]
				.password
				.as_ref()
				.map(|password| password.expose_secret()),
			Some("default-secret")
		);
		assert_eq!(
			databases["replica"]
				.password
				.as_ref()
				.map(|password| password.expose_secret()),
			Some("replica-secret")
		);
		// SAFETY: This test is serialized with other environment-mutating tests.
		unsafe { std::env::remove_var("REINHARDT_DEFAULT_DB_PASSWORD") };
	}

	#[rstest]
	#[case("postgres://localhost/db")]
	#[case("postgresql://user:pass@localhost:5432/db")]
	#[case("sqlite::memory:")]
	#[case("sqlite:///path/to/db")]
	#[case("mysql://root@localhost/db")]
	#[case("mariadb://root@localhost/db")]
	fn test_valid_database_url_schemes(#[case] url: &str) {
		// Act / Assert
		assert!(validate_database_url_scheme(url).is_ok());
	}

	#[rstest]
	#[case("http://localhost/db")]
	#[case("ftp://localhost/db")]
	#[case("redis://localhost")]
	#[case("")]
	#[case("not-a-url")]
	fn test_invalid_database_url_schemes(#[case] url: &str) {
		// Act
		let result = validate_database_url_scheme(url);

		// Assert
		assert!(result.is_err());
		assert!(result.unwrap_err().contains("Invalid database URL"));
	}
}