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
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
656
657
658
659
660
661
662
663
664
665
666
667
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Escapes special HTML characters to prevent XSS attacks.
///
/// This function converts the following characters to their HTML entity equivalents:
/// - `&` → `&`
/// - `<` → `&lt;`
/// - `>` → `&gt;`
/// - `"` → `&quot;`
/// - `'` → `&#x27;`
///
/// # Examples
///
/// ```
/// use reinhardt_forms::field::html_escape;
///
/// assert_eq!(html_escape("<script>"), "&lt;script&gt;");
/// assert_eq!(html_escape("a & b"), "a &amp; b");
/// assert_eq!(html_escape("\"quoted\""), "&quot;quoted&quot;");
/// ```
pub fn html_escape(s: &str) -> String {
	s.replace('&', "&amp;")
		.replace('<', "&lt;")
		.replace('>', "&gt;")
		.replace('"', "&quot;")
		.replace('\'', "&#x27;")
}

/// Escapes a value for use in an HTML attribute context.
/// This is an alias for [`html_escape`] as the escaping rules are the same.
///
/// # Examples
///
/// ```
/// use reinhardt_forms::field::escape_attribute;
///
/// assert_eq!(escape_attribute("on\"click"), "on&quot;click");
/// ```
pub fn escape_attribute(s: &str) -> String {
	html_escape(s)
}

/// Categories of validation errors that can occur during field cleaning.
///
/// Used as keys in custom error message maps to override default messages.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ErrorType {
	/// The field value is missing but required.
	Required,
	/// The field value has an invalid format or type.
	Invalid,
	/// The field value is shorter than the minimum length.
	MinLength,
	/// The field value exceeds the maximum length.
	MaxLength,
	/// The field value is below the minimum allowed value.
	MinValue,
	/// The field value exceeds the maximum allowed value.
	MaxValue,
	/// A custom application-defined error category.
	Custom(String),
}

/// Error type returned when field validation fails.
#[derive(Debug, thiserror::Error)]
pub enum FieldError {
	/// The field is required but no value was provided.
	#[error("{0}")]
	Required(String),
	/// The field value has an invalid format or type.
	#[error("{0}")]
	Invalid(String),
	/// The field value failed a validation constraint (e.g., length, range).
	#[error("{0}")]
	Validation(String),
}

/// Result type alias for field validation operations.
pub type FieldResult<T> = Result<T, FieldError>;

impl FieldError {
	/// Creates a required field error
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_forms::FieldError;
	///
	/// let error = FieldError::required(None);
	/// assert_eq!(error.to_string(), "This field is required.");
	///
	/// let custom_error = FieldError::required(Some("Name is mandatory"));
	/// assert_eq!(custom_error.to_string(), "Name is mandatory");
	/// ```
	pub fn required(custom_msg: Option<&str>) -> Self {
		FieldError::Required(custom_msg.unwrap_or("This field is required.").to_string())
	}
	/// Creates an invalid field error
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_forms::FieldError;
	///
	/// let error = FieldError::invalid(None, "Invalid input format");
	/// assert_eq!(error.to_string(), "Invalid input format");
	///
	/// let custom_error = FieldError::invalid(Some("Must be a number"), "Invalid");
	/// assert_eq!(custom_error.to_string(), "Must be a number");
	/// ```
	pub fn invalid(custom_msg: Option<&str>, default_msg: &str) -> Self {
		FieldError::Invalid(custom_msg.unwrap_or(default_msg).to_string())
	}
	/// Creates a validation field error
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_forms::FieldError;
	///
	/// let error = FieldError::validation(None, "Value out of range");
	/// assert_eq!(error.to_string(), "Value out of range");
	///
	/// let custom_error = FieldError::validation(Some("Too long"), "Length exceeded");
	/// assert_eq!(custom_error.to_string(), "Too long");
	/// ```
	pub fn validation(custom_msg: Option<&str>, default_msg: &str) -> Self {
		FieldError::Validation(custom_msg.unwrap_or(default_msg).to_string())
	}
}

/// Field widget type that determines HTML rendering.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Widget {
	/// Single-line text input (`<input type="text">`).
	TextInput,
	/// Password input that never renders its value (`<input type="password">`).
	PasswordInput,
	/// Email address input (`<input type="email">`).
	EmailInput,
	/// Numeric input (`<input type="number">`).
	NumberInput,
	/// Multi-line text area (`<textarea>`).
	TextArea,
	/// Dropdown select with predefined (value, label) choices (`<select>`).
	Select {
		/// Available (value, label) pairs for the dropdown.
		choices: Vec<(String, String)>,
	},
	/// Checkbox input (`<input type="checkbox">`).
	CheckboxInput,
	/// Radio button group with predefined (value, label) choices.
	RadioSelect {
		/// Available (value, label) pairs for the radio group.
		choices: Vec<(String, String)>,
	},
	/// Date picker input (`<input type="date">`).
	DateInput,
	/// Date and time picker input (`<input type="datetime-local">`).
	DateTimeInput,
	/// File upload input (`<input type="file">`).
	FileInput,
	/// Hidden input for passing data without display (`<input type="hidden">`).
	HiddenInput,
}

impl Widget {
	/// Renders the widget as HTML with XSS protection.
	///
	/// All user-controlled values (name, value, attributes, choices) are
	/// HTML-escaped to prevent Cross-Site Scripting (XSS) attacks.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_forms::Widget;
	///
	/// let widget = Widget::TextInput;
	/// let html = widget.render_html("username", Some("john_doe"), None);
	/// assert!(html.contains("<input"));
	/// assert!(html.contains("type=\"text\""));
	/// assert!(html.contains("name=\"username\""));
	/// assert!(html.contains("value=\"john_doe\""));
	/// ```
	///
	/// # XSS Protection
	///
	/// ```
	/// use reinhardt_forms::Widget;
	///
	/// let widget = Widget::TextInput;
	/// // Malicious input is escaped
	/// let html = widget.render_html("field", Some("<script>alert('xss')</script>"), None);
	/// assert!(!html.contains("<script>"));
	/// assert!(html.contains("&lt;script&gt;"));
	/// ```
	pub fn render_html(
		&self,
		name: &str,
		value: Option<&str>,
		attrs: Option<&HashMap<String, String>>,
	) -> String {
		let mut html = String::new();
		let default_attrs = HashMap::new();
		let attrs = attrs.unwrap_or(&default_attrs);

		// Escape name for use in attributes
		let escaped_name = escape_attribute(name);

		// Build common attributes with escaping
		let mut common_attrs = String::new();
		for (key, val) in attrs {
			common_attrs.push_str(&format!(
				" {}=\"{}\"",
				escape_attribute(key),
				escape_attribute(val)
			));
		}

		match self {
			Widget::TextInput => {
				html.push_str(&format!(
					"<input type=\"text\" name=\"{}\" value=\"{}\"{}",
					escaped_name,
					escape_attribute(value.unwrap_or("")),
					common_attrs
				));
				if !attrs.contains_key("id") {
					html.push_str(&format!(" id=\"id_{}\"", escaped_name));
				}
				html.push_str(" />");
			}
			Widget::PasswordInput => {
				// Security: Password fields NEVER render the value attribute
				// to prevent password leakage in HTML source
				html.push_str(&format!(
					"<input type=\"password\" name=\"{}\"{}",
					escaped_name, common_attrs
				));
				if !attrs.contains_key("id") {
					html.push_str(&format!(" id=\"id_{}\"", escaped_name));
				}
				html.push_str(" />");
			}
			Widget::EmailInput => {
				html.push_str(&format!(
					"<input type=\"email\" name=\"{}\" value=\"{}\"{}",
					escaped_name,
					escape_attribute(value.unwrap_or("")),
					common_attrs
				));
				if !attrs.contains_key("id") {
					html.push_str(&format!(" id=\"id_{}\"", escaped_name));
				}
				html.push_str(" />");
			}
			Widget::NumberInput => {
				html.push_str(&format!(
					"<input type=\"number\" name=\"{}\" value=\"{}\"{}",
					escaped_name,
					escape_attribute(value.unwrap_or("")),
					common_attrs
				));
				if !attrs.contains_key("id") {
					html.push_str(&format!(" id=\"id_{}\"", escaped_name));
				}
				html.push_str(" />");
			}
			Widget::TextArea => {
				html.push_str(&format!(
					"<textarea name=\"{}\"{}",
					escaped_name, common_attrs
				));
				if !attrs.contains_key("id") {
					html.push_str(&format!(" id=\"id_{}\"", escaped_name));
				}
				html.push('>');
				// TextArea content is in HTML body context - must escape
				html.push_str(&html_escape(value.unwrap_or("")));
				html.push_str("</textarea>");
			}
			Widget::Select { choices } => {
				html.push_str(&format!(
					"<select name=\"{}\"{}",
					escaped_name, common_attrs
				));
				if !attrs.contains_key("id") {
					html.push_str(&format!(" id=\"id_{}\"", escaped_name));
				}
				html.push('>');
				for (choice_value, choice_label) in choices {
					let selected = if Some(choice_value.as_str()) == value {
						" selected"
					} else {
						""
					};
					html.push_str(&format!(
						"<option value=\"{}\"{}>{}</option>",
						escape_attribute(choice_value),
						selected,
						html_escape(choice_label)
					));
				}
				html.push_str("</select>");
			}
			Widget::CheckboxInput => {
				html.push_str(&format!(
					"<input type=\"checkbox\" name=\"{}\"",
					escaped_name
				));
				if value == Some("true") || value == Some("on") {
					html.push_str(" checked");
				}
				html.push_str(&common_attrs);
				if !attrs.contains_key("id") {
					html.push_str(&format!(" id=\"id_{}\"", escaped_name));
				}
				html.push_str(" />");
			}
			Widget::RadioSelect { choices } => {
				for (i, (choice_value, choice_label)) in choices.iter().enumerate() {
					let checked = if Some(choice_value.as_str()) == value {
						" checked"
					} else {
						""
					};
					html.push_str(&format!(
						"<input type=\"radio\" name=\"{}\" value=\"{}\" id=\"id_{}_{}\"{}{} />",
						escaped_name,
						escape_attribute(choice_value),
						escaped_name,
						i,
						checked,
						common_attrs
					));
					html.push_str(&format!(
						"<label for=\"id_{}_{}\">{}</label>",
						escaped_name,
						i,
						html_escape(choice_label)
					));
				}
			}
			Widget::DateInput => {
				html.push_str(&format!(
					"<input type=\"date\" name=\"{}\" value=\"{}\"{}",
					escaped_name,
					escape_attribute(value.unwrap_or("")),
					common_attrs
				));
				if !attrs.contains_key("id") {
					html.push_str(&format!(" id=\"id_{}\"", escaped_name));
				}
				html.push_str(" />");
			}
			Widget::DateTimeInput => {
				html.push_str(&format!(
					"<input type=\"datetime-local\" name=\"{}\" value=\"{}\"{}",
					escaped_name,
					escape_attribute(value.unwrap_or("")),
					common_attrs
				));
				if !attrs.contains_key("id") {
					html.push_str(&format!(" id=\"id_{}\"", escaped_name));
				}
				html.push_str(" />");
			}
			Widget::FileInput => {
				html.push_str(&format!(
					"<input type=\"file\" name=\"{}\"{}",
					escaped_name, common_attrs
				));
				if !attrs.contains_key("id") {
					html.push_str(&format!(" id=\"id_{}\"", escaped_name));
				}
				html.push_str(" />");
			}
			Widget::HiddenInput => {
				html.push_str(&format!(
					"<input type=\"hidden\" name=\"{}\" value=\"{}\" />",
					escaped_name,
					escape_attribute(value.unwrap_or(""))
				));
			}
		}

		html
	}
}

/// Base field trait for forms
///
/// This trait is specifically for form fields. For ORM fields, use `reinhardt_db::orm::Field`.
pub trait FormField: Send + Sync {
	/// Returns the field's name used as the form data key.
	fn name(&self) -> &str;
	/// Returns the human-readable label, if set.
	fn label(&self) -> Option<&str>;
	/// Returns whether this field must have a non-empty value.
	fn required(&self) -> bool;
	/// Returns optional help text displayed alongside the field.
	fn help_text(&self) -> Option<&str>;
	/// Returns the widget type used for HTML rendering.
	fn widget(&self) -> &Widget;
	/// Returns the initial (default) value for this field, if any.
	fn initial(&self) -> Option<&serde_json::Value>;

	/// Validates and cleans the submitted value, returning the cleaned result.
	fn clean(&self, value: Option<&serde_json::Value>) -> FieldResult<serde_json::Value>;

	/// Check if the field value has changed from its initial value
	fn has_changed(
		&self,
		initial: Option<&serde_json::Value>,
		data: Option<&serde_json::Value>,
	) -> bool {
		// Default implementation: compare values directly
		match (initial, data) {
			(None, None) => false,
			(Some(_), None) | (None, Some(_)) => true,
			(Some(i), Some(d)) => i != d,
		}
	}

	/// Get custom error messages for this field
	fn error_messages(&self) -> HashMap<ErrorType, String> {
		HashMap::new()
	}
}

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

	// Note: Field-specific tests have been moved to their respective field modules
	// in the fields/ directory. Only FormField trait tests remain here.

	#[test]
	fn test_field_has_changed() {
		use crate::fields::CharField;

		let field = CharField::new("name".to_string());

		// No change: both None
		assert!(!field.has_changed(None, None));

		// Change: initial None, data Some
		assert!(field.has_changed(None, Some(&serde_json::json!("John"))));

		// Change: initial Some, data None
		assert!(field.has_changed(Some(&serde_json::json!("John")), None));

		// No change: same value
		assert!(!field.has_changed(
			Some(&serde_json::json!("John")),
			Some(&serde_json::json!("John"))
		));

		// Change: different value
		assert!(field.has_changed(
			Some(&serde_json::json!("John")),
			Some(&serde_json::json!("Jane"))
		));
	}

	#[test]
	fn test_field_error_messages() {
		use crate::fields::CharField;

		let field = CharField::new("name".to_string());

		// Default implementation returns empty HashMap
		assert!(field.error_messages().is_empty());
	}

	// ============================================================================
	// XSS Prevention Tests (Issue #547)
	// ============================================================================

	#[test]
	fn test_html_escape_basic() {
		assert_eq!(html_escape("<script>"), "&lt;script&gt;");
		assert_eq!(html_escape("a & b"), "a &amp; b");
		assert_eq!(html_escape("\"quoted\""), "&quot;quoted&quot;");
		assert_eq!(html_escape("'single'"), "&#x27;single&#x27;");
	}

	#[test]
	fn test_html_escape_all_special_chars() {
		let input = "<script>alert('xss')&\"</script>";
		let expected = "&lt;script&gt;alert(&#x27;xss&#x27;)&amp;&quot;&lt;/script&gt;";
		assert_eq!(html_escape(input), expected);
	}

	#[test]
	fn test_html_escape_no_special_chars() {
		assert_eq!(html_escape("normal text"), "normal text");
		assert_eq!(html_escape(""), "");
	}

	#[test]
	fn test_escape_attribute() {
		assert_eq!(escape_attribute("on\"click"), "on&quot;click");
		assert_eq!(
			escape_attribute("javascript:alert('xss')"),
			"javascript:alert(&#x27;xss&#x27;)"
		);
	}

	#[test]
	fn test_widget_render_html_escapes_value_in_text_input() {
		let widget = Widget::TextInput;
		let xss_payload = "\"><script>alert('xss')</script>";
		let html = widget.render_html("field", Some(xss_payload), None);

		// Should NOT contain raw script tag
		assert!(!html.contains("<script>"));
		// Should contain escaped version
		assert!(html.contains("&lt;script&gt;"));
		assert!(html.contains("&quot;"));
	}

	#[test]
	fn test_widget_render_html_escapes_name() {
		let widget = Widget::TextInput;
		let xss_name = "field\"><script>alert('xss')</script>";
		let html = widget.render_html(xss_name, Some("value"), None);

		// Should NOT contain raw script tag
		assert!(!html.contains("<script>"));
		// Should contain escaped version
		assert!(html.contains("&lt;script&gt;"));
	}

	#[test]
	fn test_widget_render_html_escapes_textarea_content() {
		let widget = Widget::TextArea;
		let xss_content = "</textarea><script>alert('xss')</script>";
		let html = widget.render_html("comment", Some(xss_content), None);

		// Should NOT contain raw script tag
		assert!(!html.contains("<script>"));
		// Should contain escaped version
		assert!(html.contains("&lt;script&gt;"));
		// Raw </textarea> should be escaped
		assert!(!html.contains("</textarea><"));
	}

	#[test]
	fn test_widget_render_html_escapes_select_choices() {
		let widget = Widget::Select {
			choices: vec![
				(
					"value\"><script>alert('xss')</script>".to_string(),
					"Label".to_string(),
				),
				(
					"safe_value".to_string(),
					"</option><script>alert('xss')</script>".to_string(),
				),
			],
		};

		let html = widget.render_html("choice", Some("safe_value"), None);

		// Should NOT contain raw script tags
		assert!(!html.contains("<script>"));
		// Should contain escaped versions
		assert!(html.contains("&lt;script&gt;"));
		// The malicious </option> in the label should be escaped
		assert!(html.contains("&lt;/option&gt;"));
	}

	#[test]
	fn test_widget_render_html_escapes_radio_choices() {
		let widget = Widget::RadioSelect {
			choices: vec![(
				"value\"><script>alert('xss')</script>".to_string(),
				"</label><script>alert('xss')</script>".to_string(),
			)],
		};

		let html = widget.render_html("radio", None, None);

		// Should NOT contain raw script tags
		assert!(!html.contains("<script>"));
		// Should contain escaped versions
		assert!(html.contains("&lt;script&gt;"));
	}

	#[test]
	fn test_widget_render_html_escapes_attributes() {
		let widget = Widget::TextInput;
		let mut attrs = HashMap::new();
		attrs.insert("class".to_string(), "\" onclick=\"alert('xss')".to_string());
		attrs.insert(
			"data-evil".to_string(),
			"\"><script>alert('xss')</script>".to_string(),
		);

		let html = widget.render_html("field", Some("value"), Some(&attrs));

		// Should NOT contain raw script tags or unescaped quotes that could break out
		assert!(!html.contains("<script>"));
		assert!(html.contains("&lt;script&gt;"));
		assert!(html.contains("&quot;"));
	}

	#[test]
	fn test_widget_render_html_all_widget_types_escape_value() {
		let xss_payload = "\"><script>alert('xss')</script>";

		// Test widget types that render a value attribute
		let widgets_with_value: Vec<Widget> = vec![
			Widget::TextInput,
			Widget::EmailInput,
			Widget::NumberInput,
			Widget::TextArea,
			Widget::DateInput,
			Widget::DateTimeInput,
			Widget::HiddenInput,
		];

		for widget in widgets_with_value {
			let html = widget.render_html("field", Some(xss_payload), None);
			assert!(
				!html.contains("<script>"),
				"Widget {:?} did not escape XSS payload",
				widget
			);
			assert!(
				html.contains("&lt;script&gt;"),
				"Widget {:?} did not encode < and > characters",
				widget
			);
		}

		// PasswordInput intentionally does not render the value attribute
		let password_html = Widget::PasswordInput.render_html("field", Some(xss_payload), None);
		assert!(
			!password_html.contains("value="),
			"PasswordInput should never render the value attribute"
		);
	}

	#[test]
	fn test_widget_render_html_normal_values_preserved() {
		let widget = Widget::TextInput;
		let html = widget.render_html("username", Some("john_doe"), None);

		// Normal values should work correctly
		assert!(html.contains("name=\"username\""));
		assert!(html.contains("value=\"john_doe\""));
	}

	#[test]
	fn test_widget_render_html_ampersand_escaped_first() {
		// Critical test: & must be escaped FIRST to prevent double-encoding
		// e.g., if we escape < first, & becomes &amp;, then if we escape & again,
		// it becomes &amp;amp;
		let input = "&lt;"; // This is already an entity
		let result = html_escape(input);
		// Should become &amp;lt; (the & is escaped, not the <)
		assert_eq!(result, "&amp;lt;");
	}
}