reinhardt-forms 0.1.0-rc.15

Form handling and validation
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
use crate::field::{FieldError, FieldResult, FormField, Widget};
use regex::Regex;
use std::net::Ipv6Addr;
use std::sync::OnceLock;

/// RegexField for pattern-based validation
///
/// Compiled regex is cached using `OnceLock` to avoid repeated
/// compilation which could lead to ReDoS via allocation overhead.
pub struct RegexField {
	/// The field name used as the form data key.
	pub name: String,
	/// Optional human-readable label for display.
	pub label: Option<String>,
	/// Whether this field must be filled in.
	pub required: bool,
	/// Optional help text displayed alongside the field.
	pub help_text: Option<String>,
	/// The widget type used for rendering this field.
	pub widget: Widget,
	/// Optional initial (default) value for the field.
	pub initial: Option<serde_json::Value>,
	/// Cached compiled regex to prevent repeated compilation (ReDoS mitigation)
	regex_cache: OnceLock<Regex>,
	/// Raw pattern string stored for lazy compilation
	pattern: String,
	/// The error message shown when the regex does not match.
	pub error_message: String,
	/// Maximum allowed character count.
	pub max_length: Option<usize>,
	/// Minimum required character count.
	pub min_length: Option<usize>,
}

impl RegexField {
	/// Create a new RegexField
	///
	/// The regex is compiled lazily on first use and cached for subsequent calls.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_forms::fields::RegexField;
	///
	/// let field = RegexField::new("pattern".to_string(), r"^\d+$").unwrap();
	/// assert_eq!(field.name, "pattern");
	/// ```
	pub fn new(name: String, pattern: &str) -> Result<Self, regex::Error> {
		// Validate the pattern eagerly so callers get errors at construction time
		let compiled = Regex::new(pattern)?;
		let cache = OnceLock::new();
		let _ = cache.set(compiled);
		Ok(Self {
			name,
			label: None,
			required: true,
			help_text: None,
			widget: Widget::TextInput,
			initial: None,
			regex_cache: cache,
			pattern: pattern.to_string(),
			error_message: "Enter a valid value".to_string(),
			max_length: None,
			min_length: None,
		})
	}

	/// Get the cached compiled regex
	fn regex(&self) -> &Regex {
		self.regex_cache.get_or_init(|| {
			Regex::new(&self.pattern).expect("Pattern was validated at construction")
		})
	}
	/// Overrides the default error message for validation failures.
	pub fn with_error_message(mut self, message: String) -> Self {
		self.error_message = message;
		self
	}
}

impl std::fmt::Debug for RegexField {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		f.debug_struct("RegexField")
			.field("name", &self.name)
			.field("label", &self.label)
			.field("required", &self.required)
			.field("help_text", &self.help_text)
			.field("widget", &self.widget)
			.field("initial", &self.initial)
			.field("pattern", &self.pattern)
			.field("error_message", &self.error_message)
			.field("max_length", &self.max_length)
			.field("min_length", &self.min_length)
			.finish()
	}
}

impl Clone for RegexField {
	fn clone(&self) -> Self {
		let cache = OnceLock::new();
		if let Some(regex) = self.regex_cache.get() {
			let _ = cache.set(regex.clone());
		}
		Self {
			name: self.name.clone(),
			label: self.label.clone(),
			required: self.required,
			help_text: self.help_text.clone(),
			widget: self.widget.clone(),
			initial: self.initial.clone(),
			regex_cache: cache,
			pattern: self.pattern.clone(),
			error_message: self.error_message.clone(),
			max_length: self.max_length,
			min_length: self.min_length,
		}
	}
}

impl FormField for RegexField {
	fn name(&self) -> &str {
		&self.name
	}

	fn label(&self) -> Option<&str> {
		self.label.as_deref()
	}

	fn required(&self) -> bool {
		self.required
	}

	fn help_text(&self) -> Option<&str> {
		self.help_text.as_deref()
	}

	fn widget(&self) -> &Widget {
		&self.widget
	}

	fn initial(&self) -> Option<&serde_json::Value> {
		self.initial.as_ref()
	}

	fn clean(&self, value: Option<&serde_json::Value>) -> FieldResult<serde_json::Value> {
		match value {
			None if self.required => Err(FieldError::required(None)),
			None => Ok(serde_json::Value::Null),
			Some(v) => {
				let s = v
					.as_str()
					.ok_or_else(|| FieldError::invalid(None, "Expected string"))?;

				if s.is_empty() {
					if self.required {
						return Err(FieldError::required(None));
					}
					return Ok(serde_json::Value::Null);
				}

				// Length validation using character count (not byte count)
				// for correct multi-byte character handling
				let char_count = s.chars().count();
				if let Some(max) = self.max_length
					&& char_count > max
				{
					return Err(FieldError::validation(
						None,
						&format!("Ensure this value has at most {} characters", max),
					));
				}

				if let Some(min) = self.min_length
					&& char_count < min
				{
					return Err(FieldError::validation(
						None,
						&format!("Ensure this value has at least {} characters", min),
					));
				}

				// Regex validation (uses cached compiled regex)
				if !self.regex().is_match(s) {
					return Err(FieldError::validation(None, &self.error_message));
				}

				Ok(serde_json::Value::String(s.to_string()))
			}
		}
	}
}

/// SlugField for URL-safe slugs
#[derive(Debug, Clone)]
pub struct SlugField {
	/// The field name used as the form data key.
	pub name: String,
	/// Optional human-readable label for display.
	pub label: Option<String>,
	/// Whether this field must be filled in.
	pub required: bool,
	/// Optional help text displayed alongside the field.
	pub help_text: Option<String>,
	/// The widget type used for rendering this field.
	pub widget: Widget,
	/// Optional initial (default) value for the field.
	pub initial: Option<serde_json::Value>,
	/// Maximum allowed character count (defaults to 50).
	pub max_length: Option<usize>,
	/// Whether to allow Unicode characters in the slug.
	pub allow_unicode: bool,
}

impl SlugField {
	/// Creates a new `SlugField` with a default max length of 50.
	pub fn new(name: String) -> Self {
		Self {
			name,
			label: None,
			required: true,
			help_text: None,
			widget: Widget::TextInput,
			initial: None,
			max_length: Some(50),
			allow_unicode: false,
		}
	}

	fn is_valid_slug(&self, s: &str) -> bool {
		if self.allow_unicode {
			s.chars().all(|c| {
				c.is_alphanumeric() || c == '-' || c == '_' || (!c.is_ascii() && c.is_alphabetic())
			})
		} else {
			s.chars()
				.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
		}
	}
}

impl FormField for SlugField {
	fn name(&self) -> &str {
		&self.name
	}

	fn label(&self) -> Option<&str> {
		self.label.as_deref()
	}

	fn required(&self) -> bool {
		self.required
	}

	fn help_text(&self) -> Option<&str> {
		self.help_text.as_deref()
	}

	fn widget(&self) -> &Widget {
		&self.widget
	}

	fn initial(&self) -> Option<&serde_json::Value> {
		self.initial.as_ref()
	}

	fn clean(&self, value: Option<&serde_json::Value>) -> FieldResult<serde_json::Value> {
		match value {
			None if self.required => Err(FieldError::required(None)),
			None => Ok(serde_json::Value::Null),
			Some(v) => {
				let s = v
					.as_str()
					.ok_or_else(|| FieldError::invalid(None, "Expected string"))?;

				if s.is_empty() {
					if self.required {
						return Err(FieldError::required(None));
					}
					return Ok(serde_json::Value::Null);
				}

				// Use character count for correct multi-byte handling
				if let Some(max) = self.max_length
					&& s.chars().count() > max
				{
					return Err(FieldError::validation(
						None,
						&format!("Ensure this value has at most {} characters", max),
					));
				}

				if !self.is_valid_slug(s) {
					let msg = if self.allow_unicode {
						"Enter a valid slug consisting of Unicode letters, numbers, underscores, or hyphens"
					} else {
						"Enter a valid slug consisting of letters, numbers, underscores or hyphens"
					};
					return Err(FieldError::validation(None, msg));
				}

				Ok(serde_json::Value::String(s.to_string()))
			}
		}
	}
}

/// GenericIPAddressField for IPv4 and IPv6 addresses
#[derive(Debug, Clone)]
pub struct GenericIPAddressField {
	/// The field name used as the form data key.
	pub name: String,
	/// Optional human-readable label for display.
	pub label: Option<String>,
	/// Whether this field must be filled in.
	pub required: bool,
	/// Optional help text displayed alongside the field.
	pub help_text: Option<String>,
	/// The widget type used for rendering this field.
	pub widget: Widget,
	/// Optional initial (default) value for the field.
	pub initial: Option<serde_json::Value>,
	/// Which IP protocol versions to accept.
	pub protocol: IPProtocol,
}

/// Specifies which IP address protocol versions are accepted.
#[derive(Debug, Clone, Copy)]
pub enum IPProtocol {
	/// Accept both IPv4 and IPv6 addresses.
	Both,
	/// Accept only IPv4 addresses.
	IPv4,
	/// Accept only IPv6 addresses.
	IPv6,
}

impl GenericIPAddressField {
	/// Creates a new `GenericIPAddressField` that accepts both IPv4 and IPv6.
	pub fn new(name: String) -> Self {
		Self {
			name,
			label: None,
			required: true,
			help_text: None,
			widget: Widget::TextInput,
			initial: None,
			protocol: IPProtocol::Both,
		}
	}

	fn is_valid_ipv4(&self, s: &str) -> bool {
		let parts: Vec<&str> = s.split('.').collect();
		if parts.len() != 4 {
			return false;
		}

		parts.iter().all(|part| {
			part.parse::<u8>()
				.map(|_| !part.starts_with('0') || part.len() == 1)
				.unwrap_or(false)
		})
	}

	fn is_valid_ipv6(&self, s: &str) -> bool {
		// Use std::net::Ipv6Addr for comprehensive IPv6 validation,
		// covering compressed (::1), IPv4-mapped (::ffff:192.0.2.1),
		// and all other valid IPv6 address formats.
		s.parse::<Ipv6Addr>().is_ok()
	}
}

impl FormField for GenericIPAddressField {
	fn name(&self) -> &str {
		&self.name
	}

	fn label(&self) -> Option<&str> {
		self.label.as_deref()
	}

	fn required(&self) -> bool {
		self.required
	}

	fn help_text(&self) -> Option<&str> {
		self.help_text.as_deref()
	}

	fn widget(&self) -> &Widget {
		&self.widget
	}

	fn initial(&self) -> Option<&serde_json::Value> {
		self.initial.as_ref()
	}

	fn clean(&self, value: Option<&serde_json::Value>) -> FieldResult<serde_json::Value> {
		match value {
			None if self.required => Err(FieldError::required(None)),
			None => Ok(serde_json::Value::Null),
			Some(v) => {
				let s = v
					.as_str()
					.ok_or_else(|| FieldError::invalid(None, "Expected string"))?;

				if s.is_empty() {
					if self.required {
						return Err(FieldError::required(None));
					}
					return Ok(serde_json::Value::Null);
				}

				let is_valid = match self.protocol {
					IPProtocol::IPv4 => self.is_valid_ipv4(s),
					IPProtocol::IPv6 => self.is_valid_ipv6(s),
					IPProtocol::Both => self.is_valid_ipv4(s) || self.is_valid_ipv6(s),
				};

				if !is_valid {
					return Err(FieldError::validation(None, "Enter a valid IP address"));
				}

				Ok(serde_json::Value::String(s.to_string()))
			}
		}
	}
}

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

	#[test]
	fn test_regex_field() {
		let field = RegexField::new("code".to_string(), r"^[A-Z]{3}\d{3}$").unwrap();

		assert!(field.clean(Some(&serde_json::json!("ABC123"))).is_ok());
		assert!(matches!(
			field.clean(Some(&serde_json::json!("abc123"))),
			Err(FieldError::Validation(_))
		));
	}

	#[test]
	fn test_forms_regex_field_slug() {
		let field = SlugField::new("slug".to_string());

		assert!(field.clean(Some(&serde_json::json!("my-slug"))).is_ok());
		assert!(field.clean(Some(&serde_json::json!("my_slug"))).is_ok());
		assert!(matches!(
			field.clean(Some(&serde_json::json!("my slug"))),
			Err(FieldError::Validation(_))
		));
	}

	#[test]
	fn test_ip_field_ipv4() {
		let mut field = GenericIPAddressField::new("ip".to_string());
		field.protocol = IPProtocol::IPv4;

		assert!(field.clean(Some(&serde_json::json!("192.168.1.1"))).is_ok());
		assert!(matches!(
			field.clean(Some(&serde_json::json!("999.999.999.999"))),
			Err(FieldError::Validation(_))
		));
	}

	#[test]
	fn test_ip_field_ipv6() {
		let mut field = GenericIPAddressField::new("ip".to_string());
		field.protocol = IPProtocol::IPv6;

		assert!(
			field
				.clean(Some(&serde_json::json!(
					"2001:0db8:85a3:0000:0000:8a2e:0370:7334"
				)))
				.is_ok()
		);
		assert!(field.clean(Some(&serde_json::json!("::1"))).is_ok());
	}

	#[rstest]
	#[case("::1", true)]
	#[case("::", true)]
	#[case("::ffff:192.0.2.1", true)]
	#[case("2001:db8::1", true)]
	#[case("fe80::1%eth0", false)]
	#[case("2001:db8:85a3::8a2e:370:7334", true)]
	#[case("::ffff:10.0.0.1", true)]
	#[case("2001:db8::", true)]
	#[case("::192.168.1.1", true)]
	#[case("not-an-ip", false)]
	#[case("2001:db8::g1", false)]
	#[case("12345::1", false)]
	fn test_ipv6_comprehensive_validation(#[case] input: &str, #[case] should_accept: bool) {
		// Arrange
		let mut field = GenericIPAddressField::new("ip".to_string());
		field.protocol = IPProtocol::IPv6;

		// Act
		let result = field.clean(Some(&serde_json::json!(input)));

		// Assert
		if should_accept {
			assert!(
				result.is_ok(),
				"Expected valid IPv6 '{}' to be accepted, got: {:?}",
				input,
				result,
			);
		} else {
			assert!(
				result.is_err(),
				"Expected invalid IPv6 '{}' to be rejected, got: {:?}",
				input,
				result,
			);
		}
	}
}