reinhardt-core 0.1.0

Core components for Reinhardt framework
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
//! IP Address validator using std::net::IpAddr for type-safe validation

use super::{ValidationError, ValidationResult, Validator};
use std::net::IpAddr;

/// IP Address validator - validates IPv4 and IPv6 addresses using std::net::IpAddr
///
/// This validator provides type-safe IP address validation by leveraging Rust's
/// standard library. It supports both IPv4 and IPv6 addresses with configurable
/// validation rules and custom error messages.
///
/// # Examples
///
/// ## Basic usage (accepts both IPv4 and IPv6)
///
/// ```
/// use reinhardt_core::validators::{IPAddressValidator, Validator};
///
/// let validator = IPAddressValidator::new();
/// assert!(validator.validate("192.168.1.1").is_ok());
/// assert!(validator.validate("2001:0db8:85a3:0000:0000:8a2e:0370:7334").is_ok());
/// assert!(validator.validate("::1").is_ok());
/// assert!(validator.validate("invalid-ip").is_err());
/// ```
///
/// ## IPv4 only
///
/// ```
/// use reinhardt_core::validators::{IPAddressValidator, Validator};
///
/// let validator = IPAddressValidator::ipv4_only();
/// assert!(validator.validate("192.168.1.1").is_ok());
/// assert!(validator.validate("2001:0db8:85a3::8a2e:0370:7334").is_err());
/// ```
///
/// ## IPv6 only
///
/// ```
/// use reinhardt_core::validators::{IPAddressValidator, Validator};
///
/// let validator = IPAddressValidator::ipv6_only();
/// assert!(validator.validate("2001:0db8:85a3::8a2e:0370:7334").is_ok());
/// assert!(validator.validate("192.168.1.1").is_err());
/// ```
///
/// ## Custom error message
///
/// ```
/// use reinhardt_core::validators::{IPAddressValidator, Validator};
///
/// let validator = IPAddressValidator::new()
///     .with_message("Please provide a valid IP address");
///
/// match validator.validate("invalid") {
///     Err(e) => {
///         // Error message will include the custom message
///     }
///     _ => panic!("Expected validation error"),
/// }
/// ```
pub struct IPAddressValidator {
	allow_ipv4: bool,
	allow_ipv6: bool,
	message: Option<String>,
}

impl IPAddressValidator {
	/// Creates a new IPAddressValidator that accepts both IPv4 and IPv6 addresses.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_core::validators::{IPAddressValidator, Validator};
	///
	/// let validator = IPAddressValidator::new();
	/// assert!(validator.validate("192.168.1.1").is_ok());
	/// assert!(validator.validate("2001:db8::1").is_ok());
	/// ```
	pub fn new() -> Self {
		Self {
			allow_ipv4: true,
			allow_ipv6: true,
			message: None,
		}
	}

	/// Creates a validator that only accepts IPv4 addresses.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_core::validators::{IPAddressValidator, Validator};
	///
	/// let validator = IPAddressValidator::ipv4_only();
	/// assert!(validator.validate("192.168.1.1").is_ok());
	/// assert!(validator.validate("10.0.0.0").is_ok());
	/// assert!(validator.validate("2001:db8::1").is_err());
	/// ```
	pub fn ipv4_only() -> Self {
		Self {
			allow_ipv4: true,
			allow_ipv6: false,
			message: None,
		}
	}

	/// Creates a validator that only accepts IPv6 addresses.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_core::validators::{IPAddressValidator, Validator};
	///
	/// let validator = IPAddressValidator::ipv6_only();
	/// assert!(validator.validate("2001:db8::1").is_ok());
	/// assert!(validator.validate("::1").is_ok());
	/// assert!(validator.validate("192.168.1.1").is_err());
	/// ```
	pub fn ipv6_only() -> Self {
		Self {
			allow_ipv4: false,
			allow_ipv6: true,
			message: None,
		}
	}

	/// Sets a custom error message for validation failures.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_core::validators::{IPAddressValidator, Validator};
	///
	/// let validator = IPAddressValidator::new()
	///     .with_message("Invalid IP address format");
	///
	/// assert!(validator.validate("192.168.1.1").is_ok());
	/// ```
	pub fn with_message(mut self, message: impl Into<String>) -> Self {
		self.message = Some(message.into());
		self
	}

	/// Internal validation logic using std::net::IpAddr for type-safe parsing
	fn validate_ip(&self, value: &str) -> ValidationResult<()> {
		// Parse the IP address using std::net::IpAddr
		let ip_addr = value.parse::<IpAddr>().map_err(|_| {
			ValidationError::InvalidIPAddress(
				self.message
					.clone()
					.unwrap_or_else(|| "Invalid IP address format".to_string()),
			)
		})?;

		// Check if the parsed IP address type is allowed
		match ip_addr {
			IpAddr::V4(_) if !self.allow_ipv4 => Err(ValidationError::InvalidIPAddress(
				self.message
					.clone()
					.unwrap_or_else(|| "IPv4 addresses are not allowed".to_string()),
			)),
			IpAddr::V6(_) if !self.allow_ipv6 => Err(ValidationError::InvalidIPAddress(
				self.message
					.clone()
					.unwrap_or_else(|| "IPv6 addresses are not allowed".to_string()),
			)),
			_ => Ok(()),
		}
	}
}

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

impl Validator<String> for IPAddressValidator {
	fn validate(&self, value: &String) -> ValidationResult<()> {
		self.validate_ip(value.as_str())
	}
}

impl Validator<str> for IPAddressValidator {
	fn validate(&self, value: &str) -> ValidationResult<()> {
		self.validate_ip(value)
	}
}

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

	// Basic IPv4 validation tests
	#[test]
	fn test_ipv4_valid_addresses() {
		let validator = IPAddressValidator::new();
		let valid_ipv4 = vec![
			"0.0.0.0",
			"127.0.0.1",
			"192.168.1.1",
			"10.0.0.1",
			"172.16.0.1",
			"255.255.255.255",
			"8.8.8.8",
			"1.1.1.1",
		];

		for ip in valid_ipv4 {
			assert!(
				validator.validate(ip).is_ok(),
				"Expected {} to be valid IPv4",
				ip
			);
		}
	}

	#[test]
	fn test_ipv4_invalid_addresses() {
		let validator = IPAddressValidator::new();
		let invalid_ipv4 = vec![
			"256.1.1.1",      // Octet out of range
			"192.168.1.256",  // Octet out of range
			"192.168.1",      // Missing octet
			"192.168.1.1.1",  // Too many octets
			"192.168.-1.1",   // Negative number
			"192.168.1.a",    // Non-numeric
			"192.168..1",     // Empty octet
			"...",            // All empty
			"",               // Empty string
			"192.168.1.1/24", // CIDR notation not supported
		];

		for ip in invalid_ipv4 {
			assert!(
				validator.validate(ip).is_err(),
				"Expected {} to be invalid",
				ip
			);
		}
	}

	// Basic IPv6 validation tests
	#[test]
	fn test_ipv6_valid_addresses() {
		let validator = IPAddressValidator::new();
		let valid_ipv6 = vec![
			"::1",                                     // Loopback
			"::",                                      // All zeros
			"2001:db8::1",                             // Compressed
			"2001:0db8:85a3:0000:0000:8a2e:0370:7334", // Full form
			"2001:db8:85a3::8a2e:370:7334",            // Compressed middle
			"fe80::1",                                 // Link-local
			"::ffff:192.0.2.1",                        // IPv4-mapped IPv6
			"2001:db8::8a2e:370:7334",
			"2001:db8:0:0:1:0:0:1",
			"2001:0db8:0001:0000:0000:0ab9:C0A8:0102",
		];

		for ip in valid_ipv6 {
			assert!(
				validator.validate(ip).is_ok(),
				"Expected {} to be valid IPv6",
				ip
			);
		}
	}

	#[test]
	fn test_ipv6_invalid_addresses() {
		let validator = IPAddressValidator::new();
		let invalid_ipv6 = vec![
			"02001:db8::1",                        // Too many digits
			"2001:db8::1::2",                      // Double ::
			"gggg::1",                             // Invalid hex
			"2001:db8:85a3::8a2e:370k:7334",       // Invalid character
			"::1::2",                              // Multiple ::
			"2001:db8:85a3:8a2e:370:7334",         // Too few groups
			"2001:db8:85a3:0:0:8a2e:0:0:370:7334", // Too many groups
		];

		for ip in invalid_ipv6 {
			assert!(
				validator.validate(ip).is_err(),
				"Expected {} to be invalid",
				ip
			);
		}
	}

	// IPv4-only validator tests
	#[test]
	fn test_ipv4_only_validator() {
		let validator = IPAddressValidator::ipv4_only();

		// Should accept IPv4
		assert!(validator.validate("192.168.1.1").is_ok());
		assert!(validator.validate("10.0.0.1").is_ok());
		assert!(validator.validate("127.0.0.1").is_ok());

		// Should reject IPv6
		assert!(validator.validate("::1").is_err());
		assert!(validator.validate("2001:db8::1").is_err());
		assert!(validator.validate("fe80::1").is_err());
	}

	// IPv6-only validator tests
	#[test]
	fn test_ipv6_only_validator() {
		let validator = IPAddressValidator::ipv6_only();

		// Should accept IPv6
		assert!(validator.validate("::1").is_ok());
		assert!(validator.validate("2001:db8::1").is_ok());
		assert!(validator.validate("fe80::1").is_ok());

		// Should reject IPv4
		assert!(validator.validate("192.168.1.1").is_err());
		assert!(validator.validate("10.0.0.1").is_err());
		assert!(validator.validate("127.0.0.1").is_err());
	}

	// Custom message tests
	#[test]
	fn test_custom_error_message() {
		let custom_msg = "Please provide a valid IP address";
		let validator = IPAddressValidator::new().with_message(custom_msg);

		match validator.validate("invalid-ip") {
			Err(ValidationError::InvalidIPAddress(msg)) => {
				assert_eq!(msg, custom_msg);
			}
			_ => panic!("Expected InvalidIPAddress error with custom message"),
		}
	}

	#[test]
	fn test_custom_error_message_ipv4_only() {
		let custom_msg = "Only IPv4 addresses are allowed";
		let validator = IPAddressValidator::ipv4_only().with_message(custom_msg);

		match validator.validate("2001:db8::1") {
			Err(ValidationError::InvalidIPAddress(_)) => {
				// Custom message is used when IPv6 is not allowed
			}
			_ => panic!("Expected InvalidIPAddress error"),
		}
	}

	#[test]
	fn test_custom_error_message_ipv6_only() {
		let custom_msg = "Only IPv6 addresses are allowed";
		let validator = IPAddressValidator::ipv6_only().with_message(custom_msg);

		match validator.validate("192.168.1.1") {
			Err(ValidationError::InvalidIPAddress(_)) => {
				// Custom message is used when IPv4 is not allowed
			}
			_ => panic!("Expected InvalidIPAddress error"),
		}
	}

	// String type tests
	#[test]
	fn test_validator_with_string_type() {
		let validator = IPAddressValidator::new();

		let valid_ip = String::from("192.168.1.1");
		assert!(validator.validate(&valid_ip).is_ok());

		let invalid_ip = String::from("invalid");
		assert!(validator.validate(&invalid_ip).is_err());
	}

	#[test]
	fn test_validator_with_str_type() {
		let validator = IPAddressValidator::new();

		assert!(validator.validate("192.168.1.1").is_ok());
		assert!(validator.validate("2001:db8::1").is_ok());
		assert!(validator.validate("invalid").is_err());
	}

	// Edge cases
	#[test]
	fn test_empty_string() {
		let validator = IPAddressValidator::new();
		assert!(validator.validate("").is_err());
	}

	#[test]
	fn test_whitespace() {
		let validator = IPAddressValidator::new();
		assert!(validator.validate(" ").is_err());
		assert!(validator.validate("192.168.1.1 ").is_err());
		assert!(validator.validate(" 192.168.1.1").is_err());
	}

	#[test]
	fn test_special_ipv4_addresses() {
		let validator = IPAddressValidator::new();

		// Loopback
		assert!(validator.validate("127.0.0.1").is_ok());

		// Broadcast
		assert!(validator.validate("255.255.255.255").is_ok());

		// Network address
		assert!(validator.validate("0.0.0.0").is_ok());
	}

	#[test]
	fn test_special_ipv6_addresses() {
		let validator = IPAddressValidator::new();

		// Loopback
		assert!(validator.validate("::1").is_ok());

		// All zeros
		assert!(validator.validate("::").is_ok());

		// IPv4-mapped IPv6
		assert!(validator.validate("::ffff:192.0.2.1").is_ok());
	}

	#[test]
	fn test_ipv6_compression() {
		let validator = IPAddressValidator::new();

		// Various compression forms
		assert!(validator.validate("2001:db8::1").is_ok());
		assert!(validator.validate("2001:db8::").is_ok());
		assert!(validator.validate("::2001:db8:1").is_ok());
		assert!(validator.validate("2001:db8:0:0:0:0:0:1").is_ok());
	}

	#[test]
	fn test_default_implementation() {
		let validator = IPAddressValidator::default();
		assert!(validator.validate("192.168.1.1").is_ok());
		assert!(validator.validate("2001:db8::1").is_ok());
	}

	// Error type tests
	#[test]
	fn test_error_type_for_invalid_format() {
		let validator = IPAddressValidator::new();

		match validator.validate("not-an-ip") {
			Err(ValidationError::InvalidIPAddress(_)) => {}
			_ => panic!("Expected InvalidIPAddress error"),
		}
	}

	#[test]
	fn test_error_type_for_wrong_version() {
		let ipv4_validator = IPAddressValidator::ipv4_only();
		match ipv4_validator.validate("::1") {
			Err(ValidationError::InvalidIPAddress(_)) => {}
			_ => panic!("Expected InvalidIPAddress error"),
		}

		let ipv6_validator = IPAddressValidator::ipv6_only();
		match ipv6_validator.validate("192.168.1.1") {
			Err(ValidationError::InvalidIPAddress(_)) => {}
			_ => panic!("Expected InvalidIPAddress error"),
		}
	}

	// Real-world IP addresses
	#[test]
	fn test_real_world_ipv4_addresses() {
		let validator = IPAddressValidator::new();

		// Public DNS servers
		assert!(validator.validate("8.8.8.8").is_ok()); // Google DNS
		assert!(validator.validate("1.1.1.1").is_ok()); // Cloudflare DNS
		assert!(validator.validate("208.67.222.222").is_ok()); // OpenDNS

		// Private networks
		assert!(validator.validate("192.168.0.1").is_ok()); // Home router
		assert!(validator.validate("10.0.0.1").is_ok()); // Private network
		assert!(validator.validate("172.16.0.1").is_ok()); // Private network
	}

	#[test]
	fn test_real_world_ipv6_addresses() {
		let validator = IPAddressValidator::new();

		// Public IPv6 addresses
		assert!(validator.validate("2001:4860:4860::8888").is_ok()); // Google DNS
		assert!(validator.validate("2606:4700:4700::1111").is_ok()); // Cloudflare DNS

		// Link-local
		assert!(validator.validate("fe80::1").is_ok());
	}
}