reinhardt-utils 0.1.0-rc.22

Utility functions aggregator for Reinhardt
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
//! Input validation and sanitization utilities
//!
//! Provides helpers for validating and sanitizing user input to prevent
//! common security vulnerabilities such as open redirects, log injection,
//! and identifier-based attacks.

/// Errors returned by [`validate_identifier`].
#[derive(Debug, thiserror::Error)]
pub enum IdentifierError {
	/// The identifier is an empty string.
	#[error("Identifier is empty")]
	Empty,
	/// The identifier exceeds the allowed maximum length.
	#[error("Identifier exceeds maximum length of {max_length} characters")]
	TooLong {
		/// The maximum allowed length.
		max_length: usize,
	},
	/// The identifier contains a character that is not alphanumeric, hyphen, or underscore.
	#[error("Identifier contains invalid character: '{ch}'")]
	InvalidCharacter {
		/// The invalid character found.
		ch: char,
	},
	/// The identifier starts with a character that is not alphanumeric or underscore.
	#[error("Identifier must start with alphanumeric or underscore, got: '{ch}'")]
	InvalidStartCharacter {
		/// The invalid starting character.
		ch: char,
	},
}

/// Validates a URL for safe redirect usage.
///
/// Allows:
/// - Relative paths starting with `/` (absolute paths on same origin)
/// - Same-origin relative paths starting with `./`
/// - Anchor links starting with `#`
/// - `http://` and `https://` URLs
///
/// Rejects:
/// - Path traversal (`../`)
/// - Dangerous protocols (`javascript:`, `data:`, `vbscript:`)
/// - Unknown URL schemes
/// - URLs with embedded credentials (`http://user:pass@host`)
///
/// # Examples
///
/// ```
/// use reinhardt_utils::utils_core::input_validation::validate_redirect_url;
///
/// assert!(validate_redirect_url("/dashboard"));
/// assert!(validate_redirect_url("https://example.com/page"));
/// assert!(!validate_redirect_url("javascript:alert(1)"));
/// assert!(!validate_redirect_url("../secret"));
/// ```
pub fn validate_redirect_url(url: &str) -> bool {
	let trimmed = url.trim();

	if trimmed.is_empty() {
		return false;
	}

	// Reject path traversal
	if trimmed.starts_with("../") || trimmed.contains("/../") || trimmed.ends_with("/..") {
		return false;
	}

	// Allow anchor links
	if trimmed.starts_with('#') {
		return true;
	}

	// Allow same-origin relative paths
	if trimmed.starts_with("./") {
		return true;
	}

	// Allow absolute paths on same origin (must start with single /)
	// Reject protocol-relative URLs (//) to prevent open redirect
	if trimmed.starts_with('/') {
		return !trimmed.starts_with("//");
	}

	let lower = trimmed.to_lowercase();

	// Reject dangerous protocols
	let dangerous_protocols = ["javascript:", "data:", "vbscript:"];
	for proto in &dangerous_protocols {
		if lower.starts_with(proto) {
			return false;
		}
	}

	// Allow only http:// and https://
	if lower.starts_with("http://") || lower.starts_with("https://") {
		// Reject URLs with embedded credentials (user:pass@host)
		let after_scheme = if lower.starts_with("https://") {
			&trimmed[8..]
		} else {
			&trimmed[7..]
		};

		// Check for @ before the first / (indicates credentials)
		if let Some(path_start) = after_scheme.find('/') {
			let authority = &after_scheme[..path_start];
			if authority.contains('@') {
				return false;
			}
		} else if after_scheme.contains('@') {
			return false;
		}

		return true;
	}

	// Reject all other schemes / unknown formats
	false
}

/// Sanitizes user input for safe inclusion in log messages.
///
/// Replaces control characters, newlines, and other characters
/// that could be used for log injection attacks. Truncates
/// the result to `max_length` characters.
///
/// # Examples
///
/// ```
/// use reinhardt_utils::utils_core::input_validation::sanitize_log_input;
///
/// let input = "normal text\ninjected line";
/// let sanitized = sanitize_log_input(input, 100);
/// assert!(!sanitized.contains('\n'));
/// ```
pub fn sanitize_log_input(input: &str, max_length: usize) -> String {
	let mut result = String::with_capacity(input.len().min(max_length));

	for (char_count, ch) in input.chars().enumerate() {
		if char_count >= max_length {
			break;
		}

		match ch {
			// Replace newlines and carriage returns with spaces
			'\n' | '\r' => result.push(' '),
			// Replace tabs with spaces
			'\t' => result.push(' '),
			// Replace other control characters with Unicode replacement character
			c if c.is_control() => result.push('\u{FFFD}'),
			// Keep printable characters as-is
			c => result.push(c),
		}
	}

	result
}

/// Validates that a string is a safe identifier.
///
/// Allows: ASCII alphanumeric, hyphens, underscores.
/// First character must be alphanumeric or underscore.
/// Max length is enforced.
///
/// # Errors
///
/// Returns [`IdentifierError`] if the identifier is empty, too long,
/// starts with an invalid character, or contains invalid characters.
///
/// # Examples
///
/// ```
/// use reinhardt_utils::utils_core::input_validation::validate_identifier;
///
/// assert!(validate_identifier("my-plugin", 64).is_ok());
/// assert!(validate_identifier("_internal", 64).is_ok());
/// assert!(validate_identifier("", 64).is_err());
/// assert!(validate_identifier("-invalid", 64).is_err());
/// ```
pub fn validate_identifier(input: &str, max_length: usize) -> Result<(), IdentifierError> {
	if input.is_empty() {
		return Err(IdentifierError::Empty);
	}

	if input.len() > max_length {
		return Err(IdentifierError::TooLong { max_length });
	}

	// First character must be alphanumeric or underscore
	let first = input.chars().next().expect("non-empty string");
	if !first.is_ascii_alphanumeric() && first != '_' {
		return Err(IdentifierError::InvalidStartCharacter { ch: first });
	}

	// Remaining characters: alphanumeric, hyphens, underscores
	for ch in input.chars() {
		if !ch.is_ascii_alphanumeric() && ch != '-' && ch != '_' {
			return Err(IdentifierError::InvalidCharacter { ch });
		}
	}

	Ok(())
}

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

	// ===================================================================
	// validate_redirect_url tests
	// ===================================================================

	#[rstest]
	#[case("/dashboard", true)]
	#[case("/path/to/page", true)]
	#[case("./relative", true)]
	#[case("#section", true)]
	#[case("#", true)]
	#[case("https://example.com", true)]
	#[case("http://example.com/page", true)]
	#[case("https://example.com/path?q=1", true)]
	fn test_validate_redirect_url_allows_safe_urls(#[case] url: &str, #[case] expected: bool) {
		// Act
		let result = validate_redirect_url(url);

		// Assert
		assert_eq!(result, expected, "URL {:?} should be allowed", url);
	}

	#[rstest]
	#[case("javascript:alert(1)", false)]
	#[case("JAVASCRIPT:alert(1)", false)]
	#[case("data:text/html,<script>", false)]
	#[case("vbscript:msgbox", false)]
	#[case("../secret", false)]
	#[case("/path/../secret", false)]
	#[case("/path/..", false)]
	#[case("//evil.com", false)]
	#[case("", false)]
	#[case("   ", false)]
	#[case("ftp://files.example.com", false)]
	#[case("http://user:pass@host.com", false)]
	#[case("https://admin:secret@host.com/path", false)]
	fn test_validate_redirect_url_rejects_unsafe_urls(#[case] url: &str, #[case] expected: bool) {
		// Act
		let result = validate_redirect_url(url);

		// Assert
		assert_eq!(result, expected, "URL {:?} should be rejected", url);
	}

	#[rstest]
	fn test_validate_redirect_url_trims_whitespace() {
		// Arrange
		let url = "  /dashboard  ";

		// Act
		let result = validate_redirect_url(url);

		// Assert
		assert!(result);
	}

	// ===================================================================
	// sanitize_log_input tests
	// ===================================================================

	#[rstest]
	fn test_sanitize_log_input_replaces_newlines() {
		// Arrange
		let input = "line1\nline2\rline3\r\nline4";

		// Act
		let result = sanitize_log_input(input, 100);

		// Assert
		assert_eq!(result, "line1 line2 line3  line4");
	}

	#[rstest]
	fn test_sanitize_log_input_replaces_tabs() {
		// Arrange
		let input = "col1\tcol2\tcol3";

		// Act
		let result = sanitize_log_input(input, 100);

		// Assert
		assert_eq!(result, "col1 col2 col3");
	}

	#[rstest]
	fn test_sanitize_log_input_replaces_control_characters() {
		// Arrange
		let input = "before\x00\x01\x07after";

		// Act
		let result = sanitize_log_input(input, 100);

		// Assert
		assert_eq!(result, "before\u{FFFD}\u{FFFD}\u{FFFD}after");
	}

	#[rstest]
	fn test_sanitize_log_input_truncates_to_max_length() {
		// Arrange
		let input = "a".repeat(200);

		// Act
		let result = sanitize_log_input(&input, 50);

		// Assert
		assert_eq!(result.len(), 50);
	}

	#[rstest]
	fn test_sanitize_log_input_preserves_normal_text() {
		// Arrange
		let input = "Hello, World! 123 @#$";

		// Act
		let result = sanitize_log_input(input, 100);

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

	#[rstest]
	fn test_sanitize_log_input_empty_input() {
		// Act
		let result = sanitize_log_input("", 100);

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

	#[rstest]
	fn test_sanitize_log_input_zero_max_length() {
		// Act
		let result = sanitize_log_input("some text", 0);

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

	// ===================================================================
	// validate_identifier tests
	// ===================================================================

	#[rstest]
	#[case("my-plugin", 64)]
	#[case("MyPlugin", 64)]
	#[case("plugin_v2", 64)]
	#[case("_internal", 64)]
	#[case("a", 64)]
	#[case("A123-test_name", 64)]
	fn test_validate_identifier_accepts_valid(#[case] input: &str, #[case] max_len: usize) {
		// Act
		let result = validate_identifier(input, max_len);

		// Assert
		assert!(result.is_ok(), "Identifier {:?} should be valid", input);
	}

	#[rstest]
	fn test_validate_identifier_rejects_empty() {
		// Act
		let result = validate_identifier("", 64);

		// Assert
		assert!(matches!(result, Err(IdentifierError::Empty)));
	}

	#[rstest]
	fn test_validate_identifier_rejects_too_long() {
		// Arrange
		let input = "a".repeat(65);

		// Act
		let result = validate_identifier(&input, 64);

		// Assert
		assert!(matches!(
			result,
			Err(IdentifierError::TooLong { max_length: 64 })
		));
	}

	#[rstest]
	#[case("-starts-with-hyphen")]
	fn test_validate_identifier_rejects_invalid_start(#[case] input: &str) {
		// Act
		let result = validate_identifier(input, 64);

		// Assert
		assert!(matches!(
			result,
			Err(IdentifierError::InvalidStartCharacter { .. })
		));
	}

	#[rstest]
	#[case("has space", ' ')]
	#[case("has.dot", '.')]
	#[case("has/slash", '/')]
	#[case("has@at", '@')]
	fn test_validate_identifier_rejects_invalid_characters(
		#[case] input: &str,
		#[case] expected_ch: char,
	) {
		// Act
		let result = validate_identifier(input, 64);

		// Assert
		match result {
			Err(IdentifierError::InvalidCharacter { ch }) => {
				assert_eq!(ch, expected_ch);
			}
			other => panic!("Expected InvalidCharacter, got {:?}", other),
		}
	}

	// ===================================================================
	// IdentifierError Display tests
	// ===================================================================

	#[rstest]
	fn test_sanitize_log_input_multibyte_truncation_does_not_panic() {
		// Fixes #762: Use character count instead of byte length for truncation
		// to prevent cutting in the middle of multi-byte UTF-8 characters.
		let input = "あいうえおかきくけこ"; // 10 chars, 30 bytes

		// Act
		let result = sanitize_log_input(input, 5);

		// Assert
		assert_eq!(result.chars().count(), 5);
		assert_eq!(result, "あいうえお");
	}

	#[rstest]
	fn test_sanitize_log_input_mixed_multibyte_truncation() {
		// Fixes #762: Mixed ASCII and multibyte characters
		let input = "aあbいcうdえeお";

		// Act
		let result = sanitize_log_input(input, 6);

		// Assert
		assert_eq!(result.chars().count(), 6);
		assert_eq!(result, "aあbいcう");
	}

	#[rstest]
	fn test_identifier_error_display_messages() {
		// Assert
		assert_eq!(IdentifierError::Empty.to_string(), "Identifier is empty");
		assert_eq!(
			IdentifierError::TooLong { max_length: 32 }.to_string(),
			"Identifier exceeds maximum length of 32 characters"
		);
		assert_eq!(
			IdentifierError::InvalidCharacter { ch: '@' }.to_string(),
			"Identifier contains invalid character: '@'"
		);
		assert_eq!(
			IdentifierError::InvalidStartCharacter { ch: '-' }.to_string(),
			"Identifier must start with alphanumeric or underscore, got: '-'"
		);
	}
}