1use crate::utils::error::{Error, Result as GgenResult};
42use regex::Regex;
43use std::fmt;
44use std::path::{Path, PathBuf};
45use url::Url;
46
47#[derive(Debug, thiserror::Error)]
49pub enum InputValidationError {
50 #[error("Length validation failed: {field} has length {actual}, expected {constraint}")]
51 LengthViolation {
52 field: String,
53 actual: usize,
54 constraint: String,
55 },
56
57 #[error("Pattern validation failed: {field} does not match pattern {pattern}")]
58 PatternViolation { field: String, pattern: String },
59
60 #[error("Charset validation failed: {field} contains invalid characters")]
61 CharsetViolation { field: String },
62
63 #[error("Format validation failed: {field} has invalid format: {reason}")]
64 FormatViolation { field: String, reason: String },
65
66 #[error("Range validation failed: {field} value {actual} not in range {constraint}")]
67 RangeViolation {
68 field: String,
69 actual: String,
70 constraint: String,
71 },
72
73 #[error("Whitelist validation failed: {field} value '{value}' not in whitelist")]
74 WhitelistViolation { field: String, value: String },
75
76 #[error("Blacklist validation failed: {field} value '{value}' is blacklisted")]
77 BlacklistViolation { field: String, value: String },
78
79 #[error("Path validation failed: {reason}")]
80 PathViolation { reason: String },
81
82 #[error("URL validation failed: {reason}")]
83 UrlViolation { reason: String },
84
85 #[error("Empty input: {field} cannot be empty")]
86 EmptyInput { field: String },
87
88 #[error("Composite validation failed: {reason}")]
89 CompositeViolation { reason: String },
90
91 #[error("Regex compilation failed: {0}")]
92 RegexError(String),
93}
94
95impl From<InputValidationError> for Error {
96 fn from(err: InputValidationError) -> Self {
97 Error::new(&err.to_string())
98 }
99}
100
101pub trait ValidationRule<T>: Send + Sync {
105 fn validate(&self, input: &T, field_name: &str) -> GgenResult<T>;
107
108 fn and<R: ValidationRule<T> + 'static>(self, other: R) -> AndRule<T>
110 where
111 Self: Sized + 'static,
112 {
113 AndRule {
114 left: Box::new(self),
115 right: Box::new(other),
116 }
117 }
118
119 fn or<R: ValidationRule<T> + 'static>(self, other: R) -> OrRule<T>
121 where
122 Self: Sized + 'static,
123 {
124 OrRule {
125 left: Box::new(self),
126 right: Box::new(other),
127 }
128 }
129
130 fn not(self) -> NotRule<T>
132 where
133 Self: Sized + 'static,
134 {
135 NotRule {
136 inner: Box::new(self),
137 }
138 }
139}
140
141pub struct AndRule<T> {
147 left: Box<dyn ValidationRule<T>>,
148 right: Box<dyn ValidationRule<T>>,
149}
150
151impl<T: Clone> ValidationRule<T> for AndRule<T> {
152 fn validate(&self, input: &T, field_name: &str) -> GgenResult<T> {
153 let validated_left = self.left.validate(input, field_name)?;
154 self.right.validate(&validated_left, field_name)
155 }
156}
157
158pub struct OrRule<T> {
160 left: Box<dyn ValidationRule<T>>,
161 right: Box<dyn ValidationRule<T>>,
162}
163
164impl<T: Clone> ValidationRule<T> for OrRule<T> {
165 fn validate(&self, input: &T, field_name: &str) -> GgenResult<T> {
166 match self.left.validate(input, field_name) {
167 Ok(validated) => Ok(validated),
168 Err(left_err) => match self.right.validate(input, field_name) {
169 Ok(validated) => Ok(validated),
170 Err(right_err) => Err(InputValidationError::CompositeViolation {
171 reason: format!("OR failed: {} AND {}", left_err, right_err),
172 }
173 .into()),
174 },
175 }
176 }
177}
178
179pub struct NotRule<T> {
181 inner: Box<dyn ValidationRule<T>>,
182}
183
184impl<T: Clone> ValidationRule<T> for NotRule<T> {
185 fn validate(&self, input: &T, field_name: &str) -> GgenResult<T> {
186 match self.inner.validate(input, field_name) {
187 Ok(_) => Err(InputValidationError::CompositeViolation {
188 reason: "NOT validation failed: inner validation succeeded".to_string(),
189 }
190 .into()),
191 Err(_) => Ok(input.clone()),
192 }
193 }
194}
195
196#[derive(Clone)]
202pub struct LengthRule {
203 min: Option<usize>,
204 max: Option<usize>,
205}
206
207impl LengthRule {
208 pub fn new(min: Option<usize>, max: Option<usize>) -> Self {
209 Self { min, max }
210 }
211
212 pub fn exact(length: usize) -> Self {
213 Self {
214 min: Some(length),
215 max: Some(length),
216 }
217 }
218
219 pub fn min(min: usize) -> Self {
220 Self {
221 min: Some(min),
222 max: None,
223 }
224 }
225
226 pub fn max(max: usize) -> Self {
227 Self {
228 min: None,
229 max: Some(max),
230 }
231 }
232
233 pub fn range(min: usize, max: usize) -> Self {
234 Self {
235 min: Some(min),
236 max: Some(max),
237 }
238 }
239}
240
241impl ValidationRule<String> for LengthRule {
242 fn validate(&self, input: &String, field_name: &str) -> GgenResult<String> {
243 let len = input.len();
244
245 if let Some(min) = self.min {
246 if len < min {
247 return Err(InputValidationError::LengthViolation {
248 field: field_name.to_string(),
249 actual: len,
250 constraint: format!("min {}", min),
251 }
252 .into());
253 }
254 }
255
256 if let Some(max) = self.max {
257 if len > max {
258 return Err(InputValidationError::LengthViolation {
259 field: field_name.to_string(),
260 actual: len,
261 constraint: format!("max {}", max),
262 }
263 .into());
264 }
265 }
266
267 Ok(input.clone())
268 }
269}
270
271#[derive(Clone)]
273pub struct PatternRule {
274 pattern: String,
275 regex: Regex,
276}
277
278impl PatternRule {
279 pub fn new(pattern: &str) -> GgenResult<Self> {
280 let regex =
281 Regex::new(pattern).map_err(|e| InputValidationError::RegexError(e.to_string()))?;
282
283 Ok(Self {
284 pattern: pattern.to_string(),
285 regex,
286 })
287 }
288}
289
290impl ValidationRule<String> for PatternRule {
291 fn validate(&self, input: &String, field_name: &str) -> GgenResult<String> {
292 if !self.regex.is_match(input) {
293 return Err(InputValidationError::PatternViolation {
294 field: field_name.to_string(),
295 pattern: self.pattern.clone(),
296 }
297 .into());
298 }
299
300 Ok(input.clone())
301 }
302}
303
304#[derive(Clone)]
306pub struct CharsetRule {
307 allowed_chars: fn(char) -> bool,
308 description: String,
309}
310
311impl CharsetRule {
312 pub fn new(allowed_chars: fn(char) -> bool, description: &str) -> Self {
313 Self {
314 allowed_chars,
315 description: description.to_string(),
316 }
317 }
318
319 pub fn alphanumeric() -> Self {
320 Self::new(|c| c.is_alphanumeric(), "alphanumeric")
321 }
322
323 pub fn alphanumeric_with_underscore() -> Self {
324 Self::new(
325 |c| c.is_alphanumeric() || c == '_',
326 "alphanumeric with underscore",
327 )
328 }
329
330 pub fn alphanumeric_with_hyphen() -> Self {
331 Self::new(
332 |c| c.is_alphanumeric() || c == '-',
333 "alphanumeric with hyphen",
334 )
335 }
336
337 pub fn identifier() -> Self {
338 Self::new(
339 |c| c.is_alphanumeric() || c == '_' || c == '-',
340 "identifier (alphanumeric, underscore, hyphen)",
341 )
342 }
343
344 pub fn ascii_printable() -> Self {
345 Self::new(|c| c.is_ascii() && !c.is_control(), "ASCII printable")
346 }
347}
348
349impl ValidationRule<String> for CharsetRule {
350 fn validate(&self, input: &String, field_name: &str) -> GgenResult<String> {
351 if !input.chars().all(self.allowed_chars) {
352 return Err(InputValidationError::CharsetViolation {
353 field: field_name.to_string(),
354 }
355 .into());
356 }
357
358 Ok(input.clone())
359 }
360}
361
362#[derive(Clone)]
364pub enum FormatRule {
365 Email,
366 Uuid,
367 Semver,
368 IpAddress,
369 Hostname,
370}
371
372impl FormatRule {
373 fn email_pattern() -> &'static str {
374 r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
375 }
376
377 fn uuid_pattern() -> &'static str {
378 r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"
379 }
380
381 fn semver_pattern() -> &'static str {
382 r"^\d+\.\d+\.\d+(-[a-zA-Z0-9.-]+)?(\+[a-zA-Z0-9.-]+)?$"
383 }
384
385 fn ip_pattern() -> &'static str {
386 r"^(\d{1,3}\.){3}\d{1,3}$"
387 }
388
389 fn hostname_pattern() -> &'static str {
390 r"^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$"
391 }
392}
393
394impl ValidationRule<String> for FormatRule {
395 fn validate(&self, input: &String, field_name: &str) -> GgenResult<String> {
396 let (pattern, format_name) = match self {
397 FormatRule::Email => (Self::email_pattern(), "email"),
398 FormatRule::Uuid => (Self::uuid_pattern(), "UUID"),
399 FormatRule::Semver => (Self::semver_pattern(), "semver"),
400 FormatRule::IpAddress => (Self::ip_pattern(), "IP address"),
401 FormatRule::Hostname => (Self::hostname_pattern(), "hostname"),
402 };
403
404 let regex =
405 Regex::new(pattern).map_err(|e| InputValidationError::RegexError(e.to_string()))?;
406
407 if !regex.is_match(input) {
408 return Err(InputValidationError::FormatViolation {
409 field: field_name.to_string(),
410 reason: format!("does not match {} format", format_name),
411 }
412 .into());
413 }
414
415 Ok(input.clone())
416 }
417}
418
419#[derive(Clone)]
421pub struct WhitelistRule {
422 allowed: Vec<String>,
423}
424
425impl WhitelistRule {
426 pub fn new(allowed: Vec<String>) -> Self {
427 Self { allowed }
428 }
429}
430
431impl ValidationRule<String> for WhitelistRule {
432 fn validate(&self, input: &String, field_name: &str) -> GgenResult<String> {
433 if !self.allowed.contains(input) {
434 return Err(InputValidationError::WhitelistViolation {
435 field: field_name.to_string(),
436 value: input.clone(),
437 }
438 .into());
439 }
440
441 Ok(input.clone())
442 }
443}
444
445#[derive(Clone)]
447pub struct BlacklistRule {
448 forbidden: Vec<String>,
449}
450
451impl BlacklistRule {
452 pub fn new(forbidden: Vec<String>) -> Self {
453 Self { forbidden }
454 }
455}
456
457impl ValidationRule<String> for BlacklistRule {
458 fn validate(&self, input: &String, field_name: &str) -> GgenResult<String> {
459 if self.forbidden.contains(input) {
460 return Err(InputValidationError::BlacklistViolation {
461 field: field_name.to_string(),
462 value: input.clone(),
463 }
464 .into());
465 }
466
467 Ok(input.clone())
468 }
469}
470
471pub struct StringValidator {
473 rules: Vec<Box<dyn ValidationRule<String>>>,
474}
475
476impl StringValidator {
477 pub fn new() -> Self {
478 Self { rules: Vec::new() }
479 }
480
481 pub fn with_length(mut self, min: usize, max: usize) -> Self {
482 self.rules.push(Box::new(LengthRule::range(min, max)));
483 self
484 }
485
486 pub fn with_min_length(mut self, min: usize) -> Self {
487 self.rules.push(Box::new(LengthRule::min(min)));
488 self
489 }
490
491 pub fn with_max_length(mut self, max: usize) -> Self {
492 self.rules.push(Box::new(LengthRule::max(max)));
493 self
494 }
495
496 pub fn with_pattern(mut self, pattern: &str) -> Self {
497 if let Ok(rule) = PatternRule::new(pattern) {
498 self.rules.push(Box::new(rule));
499 }
500 self
501 }
502
503 pub fn with_charset(mut self, rule: CharsetRule) -> Self {
504 self.rules.push(Box::new(rule));
505 self
506 }
507
508 pub fn with_format(mut self, format: FormatRule) -> Self {
509 self.rules.push(Box::new(format));
510 self
511 }
512
513 pub fn with_whitelist(mut self, allowed: Vec<String>) -> Self {
514 self.rules.push(Box::new(WhitelistRule::new(allowed)));
515 self
516 }
517
518 pub fn with_blacklist(mut self, forbidden: Vec<String>) -> Self {
519 self.rules.push(Box::new(BlacklistRule::new(forbidden)));
520 self
521 }
522
523 pub fn validate(&self, input: &str) -> GgenResult<String> {
524 let mut validated = input.to_string();
525
526 for rule in &self.rules {
527 validated = rule.validate(&validated, "input")?;
528 }
529
530 Ok(validated)
531 }
532}
533
534impl Default for StringValidator {
535 fn default() -> Self {
536 Self::new()
537 }
538}
539
540pub struct PathValidatorRule {
546 allowed_extensions: Option<Vec<String>>,
547 prevent_traversal: bool,
548 base_dir: Option<PathBuf>,
549 max_length: usize,
550}
551
552impl PathValidatorRule {
553 pub fn new() -> Self {
554 Self {
555 allowed_extensions: None,
556 prevent_traversal: true,
557 base_dir: None,
558 max_length: 4096,
559 }
560 }
561
562 pub fn with_extensions(mut self, extensions: Vec<String>) -> Self {
563 self.allowed_extensions = Some(extensions);
564 self
565 }
566
567 pub fn with_base_dir(mut self, base: PathBuf) -> Self {
568 self.base_dir = Some(base);
569 self
570 }
571
572 pub fn allow_traversal(mut self) -> Self {
573 self.prevent_traversal = false;
574 self
575 }
576
577 pub fn with_max_length(mut self, max_length: usize) -> Self {
578 self.max_length = max_length;
579 self
580 }
581
582 pub fn validate(&self, path: &Path) -> GgenResult<PathBuf> {
583 let path_str = path.to_string_lossy();
584
585 if path_str.len() > self.max_length {
587 return Err(InputValidationError::PathViolation {
588 reason: format!(
589 "Path length {} exceeds maximum {}",
590 path_str.len(),
591 self.max_length
592 ),
593 }
594 .into());
595 }
596
597 if self.prevent_traversal {
599 for component in path.components() {
600 let component_str = component.as_os_str().to_string_lossy();
601 if component_str == ".." {
602 return Err(InputValidationError::PathViolation {
603 reason: "Path traversal detected (..)".to_string(),
604 }
605 .into());
606 }
607 }
608 }
609
610 if let Some(ref allowed_exts) = self.allowed_extensions {
612 if let Some(ext) = path.extension() {
613 let ext_str = ext.to_string_lossy().to_string();
614 if !allowed_exts.contains(&ext_str) {
615 return Err(InputValidationError::PathViolation {
616 reason: format!("Extension '{}' not in whitelist", ext_str),
617 }
618 .into());
619 }
620 } else {
621 return Err(InputValidationError::PathViolation {
622 reason: "No file extension found".to_string(),
623 }
624 .into());
625 }
626 }
627
628 if let Some(ref base) = self.base_dir {
630 let abs_path = if path.is_relative() {
631 base.join(path)
632 } else {
633 path.to_path_buf()
634 };
635
636 if !abs_path.starts_with(base) {
637 return Err(InputValidationError::PathViolation {
638 reason: format!(
639 "Path '{}' escapes base directory '{}'",
640 abs_path.display(),
641 base.display()
642 ),
643 }
644 .into());
645 }
646 }
647
648 Ok(path.to_path_buf())
649 }
650}
651
652impl Default for PathValidatorRule {
653 fn default() -> Self {
654 Self::new()
655 }
656}
657
658pub struct UrlValidator {
664 allowed_schemes: Option<Vec<String>>,
665 allowed_domains: Option<Vec<String>>,
666 require_https: bool,
667}
668
669impl UrlValidator {
670 pub fn new() -> Self {
671 Self {
672 allowed_schemes: None,
673 allowed_domains: None,
674 require_https: false,
675 }
676 }
677
678 pub fn with_schemes(mut self, schemes: Vec<String>) -> Self {
679 self.allowed_schemes = Some(schemes);
680 self
681 }
682
683 pub fn with_domains(mut self, domains: Vec<String>) -> Self {
684 self.allowed_domains = Some(domains);
685 self
686 }
687
688 pub fn require_https(mut self) -> Self {
689 self.require_https = true;
690 self
691 }
692
693 pub fn validate(&self, url_str: &str) -> GgenResult<Url> {
694 let url = Url::parse(url_str).map_err(|e| InputValidationError::UrlViolation {
695 reason: format!("Invalid URL: {}", e),
696 })?;
697
698 if self.require_https && url.scheme() != "https" {
700 return Err(InputValidationError::UrlViolation {
701 reason: "HTTPS required".to_string(),
702 }
703 .into());
704 }
705
706 if let Some(ref allowed_schemes) = self.allowed_schemes {
707 if !allowed_schemes.contains(&url.scheme().to_string()) {
708 return Err(InputValidationError::UrlViolation {
709 reason: format!("Scheme '{}' not in whitelist", url.scheme()),
710 }
711 .into());
712 }
713 }
714
715 if let Some(ref allowed_domains) = self.allowed_domains {
717 if let Some(host) = url.host_str() {
718 if !allowed_domains.iter().any(|d| host.ends_with(d)) {
719 return Err(InputValidationError::UrlViolation {
720 reason: format!("Domain '{}' not in whitelist", host),
721 }
722 .into());
723 }
724 } else {
725 return Err(InputValidationError::UrlViolation {
726 reason: "No host found in URL".to_string(),
727 }
728 .into());
729 }
730 }
731
732 Ok(url)
733 }
734}
735
736impl Default for UrlValidator {
737 fn default() -> Self {
738 Self::new()
739 }
740}
741
742#[derive(Clone)]
748pub struct RangeRule<T: PartialOrd + fmt::Display + Clone> {
749 min: Option<T>,
750 max: Option<T>,
751}
752
753impl<T: PartialOrd + fmt::Display + Clone> RangeRule<T> {
754 pub fn new(min: Option<T>, max: Option<T>) -> Self {
755 Self { min, max }
756 }
757
758 pub fn min(min: T) -> Self {
759 Self {
760 min: Some(min),
761 max: None,
762 }
763 }
764
765 pub fn max(max: T) -> Self {
766 Self {
767 min: None,
768 max: Some(max),
769 }
770 }
771
772 pub fn between(min: T, max: T) -> Self {
773 Self {
774 min: Some(min),
775 max: Some(max),
776 }
777 }
778}
779
780impl<T: PartialOrd + fmt::Display + Clone + Send + Sync + 'static> ValidationRule<T>
781 for RangeRule<T>
782{
783 fn validate(&self, input: &T, field_name: &str) -> GgenResult<T> {
784 if let Some(ref min) = self.min {
785 if input < min {
786 return Err(InputValidationError::RangeViolation {
787 field: field_name.to_string(),
788 actual: format!("{}", input),
789 constraint: format!(">= {}", min),
790 }
791 .into());
792 }
793 }
794
795 if let Some(ref max) = self.max {
796 if input > max {
797 return Err(InputValidationError::RangeViolation {
798 field: field_name.to_string(),
799 actual: format!("{}", input),
800 constraint: format!("<= {}", max),
801 }
802 .into());
803 }
804 }
805
806 Ok(input.clone())
807 }
808}
809
810#[derive(Clone)]
812pub struct PositiveRule;
813
814impl ValidationRule<i64> for PositiveRule {
815 fn validate(&self, input: &i64, field_name: &str) -> GgenResult<i64> {
816 if *input <= 0 {
817 return Err(InputValidationError::RangeViolation {
818 field: field_name.to_string(),
819 actual: input.to_string(),
820 constraint: "> 0".to_string(),
821 }
822 .into());
823 }
824 Ok(*input)
825 }
826}
827
828impl ValidationRule<f64> for PositiveRule {
829 fn validate(&self, input: &f64, field_name: &str) -> GgenResult<f64> {
830 if *input <= 0.0 {
831 return Err(InputValidationError::RangeViolation {
832 field: field_name.to_string(),
833 actual: input.to_string(),
834 constraint: "> 0".to_string(),
835 }
836 .into());
837 }
838 Ok(*input)
839 }
840}
841
842#[derive(Clone)]
844pub struct NegativeRule;
845
846impl ValidationRule<i64> for NegativeRule {
847 fn validate(&self, input: &i64, field_name: &str) -> GgenResult<i64> {
848 if *input >= 0 {
849 return Err(InputValidationError::RangeViolation {
850 field: field_name.to_string(),
851 actual: input.to_string(),
852 constraint: "< 0".to_string(),
853 }
854 .into());
855 }
856 Ok(*input)
857 }
858}
859
860impl ValidationRule<f64> for NegativeRule {
861 fn validate(&self, input: &f64, field_name: &str) -> GgenResult<f64> {
862 if *input >= 0.0 {
863 return Err(InputValidationError::RangeViolation {
864 field: field_name.to_string(),
865 actual: input.to_string(),
866 constraint: "< 0".to_string(),
867 }
868 .into());
869 }
870 Ok(*input)
871 }
872}
873
874#[derive(Clone)]
876pub struct PrecisionRule {
877 max_decimal_places: usize,
878}
879
880impl PrecisionRule {
881 pub fn new(max_decimal_places: usize) -> Self {
882 Self { max_decimal_places }
883 }
884}
885
886impl ValidationRule<f64> for PrecisionRule {
887 fn validate(&self, input: &f64, field_name: &str) -> GgenResult<f64> {
888 let s = format!("{}", input);
889 if let Some(decimal_pos) = s.find('.') {
890 let decimal_places = s.len() - decimal_pos - 1;
891 if decimal_places > self.max_decimal_places {
892 return Err(InputValidationError::FormatViolation {
893 field: field_name.to_string(),
894 reason: format!(
895 "Precision {} exceeds maximum {}",
896 decimal_places, self.max_decimal_places
897 ),
898 }
899 .into());
900 }
901 }
902 Ok(*input)
903 }
904}
905
906#[cfg(test)]
907mod tests {
908 use super::*;
909
910 #[test]
912 fn test_length_rule_valid() {
913 let rule = LengthRule::range(3, 10);
914 assert!(rule.validate(&"hello".to_string(), "test").is_ok());
915 }
916
917 #[test]
918 fn test_length_rule_too_short() {
919 let rule = LengthRule::range(5, 10);
920 assert!(rule.validate(&"hi".to_string(), "test").is_err());
921 }
922
923 #[test]
924 fn test_length_rule_too_long() {
925 let rule = LengthRule::range(3, 5);
926 assert!(rule.validate(&"toolong".to_string(), "test").is_err());
927 }
928
929 #[test]
930 fn test_pattern_rule_valid() {
931 let rule = PatternRule::new(r"^\d{3}-\d{4}$").expect("valid regex");
932 assert!(rule.validate(&"123-4567".to_string(), "test").is_ok());
933 }
934
935 #[test]
936 fn test_pattern_rule_invalid() {
937 let rule = PatternRule::new(r"^\d{3}-\d{4}$").expect("valid regex");
938 assert!(rule.validate(&"invalid".to_string(), "test").is_err());
939 }
940
941 #[test]
942 fn test_charset_rule_alphanumeric() {
943 let rule = CharsetRule::alphanumeric();
944 assert!(rule.validate(&"abc123".to_string(), "test").is_ok());
945 assert!(rule.validate(&"abc-123".to_string(), "test").is_err());
946 }
947
948 #[test]
949 fn test_format_rule_email_valid() {
950 let rule = FormatRule::Email;
951 assert!(rule
952 .validate(&"alice@example.com".to_string(), "test")
953 .is_ok());
954 }
955
956 #[test]
957 fn test_format_rule_email_invalid() {
958 let rule = FormatRule::Email;
959 assert!(rule.validate(&"not-an-email".to_string(), "test").is_err());
960 }
961
962 #[test]
963 fn test_whitelist_rule_valid() {
964 let rule = WhitelistRule::new(vec!["foo".to_string(), "bar".to_string()]);
965 assert!(rule.validate(&"foo".to_string(), "test").is_ok());
966 }
967
968 #[test]
969 fn test_whitelist_rule_invalid() {
970 let rule = WhitelistRule::new(vec!["foo".to_string(), "bar".to_string()]);
971 assert!(rule.validate(&"baz".to_string(), "test").is_err());
972 }
973
974 #[test]
975 fn test_blacklist_rule_valid() {
976 let rule = BlacklistRule::new(vec!["bad".to_string(), "evil".to_string()]);
977 assert!(rule.validate(&"good".to_string(), "test").is_ok());
978 }
979
980 #[test]
981 fn test_blacklist_rule_invalid() {
982 let rule = BlacklistRule::new(vec!["bad".to_string(), "evil".to_string()]);
983 assert!(rule.validate(&"bad".to_string(), "test").is_err());
984 }
985
986 #[test]
987 fn test_string_validator_builder() {
988 let validator = StringValidator::new()
989 .with_length(3, 32)
990 .with_charset(CharsetRule::identifier());
991
992 assert!(validator.validate("user_name-123").is_ok());
993 assert!(validator.validate("ab").is_err()); assert!(validator.validate("a".repeat(33).as_str()).is_err()); }
996
997 #[test]
999 fn test_and_rule() {
1000 let rule1 = LengthRule::min(3);
1001 let rule2 = LengthRule::max(10);
1002 let composite = rule1.and(rule2);
1003
1004 assert!(composite.validate(&"hello".to_string(), "test").is_ok());
1005 assert!(composite.validate(&"hi".to_string(), "test").is_err());
1006 }
1007
1008 #[test]
1009 fn test_or_rule() {
1010 let rule1 = PatternRule::new(r"^\d+$").expect("valid regex");
1011 let rule2 = PatternRule::new(r"^[a-z]+$").expect("valid regex");
1012 let composite = rule1.or(rule2);
1013
1014 assert!(composite.validate(&"123".to_string(), "test").is_ok());
1015 assert!(composite.validate(&"abc".to_string(), "test").is_ok());
1016 assert!(composite.validate(&"abc123".to_string(), "test").is_err());
1017 }
1018
1019 #[test]
1021 fn test_path_validator_basic() {
1022 let validator = PathValidatorRule::new();
1023 assert!(validator.validate(Path::new("src/main.rs")).is_ok());
1024 }
1025
1026 #[test]
1027 fn test_path_validator_traversal() {
1028 let validator = PathValidatorRule::new();
1029 assert!(validator.validate(Path::new("../etc/passwd")).is_err());
1030 }
1031
1032 #[test]
1033 fn test_path_validator_extension_whitelist() {
1034 let validator =
1035 PathValidatorRule::new().with_extensions(vec!["rs".to_string(), "toml".to_string()]);
1036
1037 assert!(validator.validate(Path::new("main.rs")).is_ok());
1038 assert!(validator.validate(Path::new("config.toml")).is_ok());
1039 assert!(validator.validate(Path::new("script.sh")).is_err());
1040 }
1041
1042 #[test]
1044 fn test_url_validator_basic() {
1045 let validator = UrlValidator::new();
1046 assert!(validator.validate("https://example.com").is_ok());
1047 }
1048
1049 #[test]
1050 fn test_url_validator_require_https() {
1051 let validator = UrlValidator::new().require_https();
1052 assert!(validator.validate("https://example.com").is_ok());
1053 assert!(validator.validate("http://example.com").is_err());
1054 }
1055
1056 #[test]
1057 fn test_url_validator_scheme_whitelist() {
1058 let validator =
1059 UrlValidator::new().with_schemes(vec!["https".to_string(), "wss".to_string()]);
1060
1061 assert!(validator.validate("https://example.com").is_ok());
1062 assert!(validator.validate("wss://example.com").is_ok());
1063 assert!(validator.validate("http://example.com").is_err());
1064 }
1065
1066 #[test]
1067 fn test_url_validator_domain_whitelist() {
1068 let validator = UrlValidator::new()
1069 .with_domains(vec!["example.com".to_string(), "trusted.org".to_string()]);
1070
1071 assert!(validator.validate("https://example.com/path").is_ok());
1072 assert!(validator.validate("https://api.example.com").is_ok());
1073 assert!(validator.validate("https://untrusted.com").is_err());
1074 }
1075
1076 #[test]
1078 fn test_range_rule_int() {
1079 let rule = RangeRule::between(0, 100);
1080 assert!(rule.validate(&50, "test").is_ok());
1081 assert!(rule.validate(&-1, "test").is_err());
1082 assert!(rule.validate(&101, "test").is_err());
1083 }
1084
1085 #[test]
1086 fn test_range_rule_float() {
1087 let rule = RangeRule::between(0.0, 1.0);
1088 assert!(rule.validate(&0.5, "test").is_ok());
1089 assert!(rule.validate(&-0.1, "test").is_err());
1090 assert!(rule.validate(&1.1, "test").is_err());
1091 }
1092
1093 #[test]
1094 fn test_positive_rule_int() {
1095 let rule = PositiveRule;
1096 assert!(rule.validate(&10, "test").is_ok());
1097 assert!(rule.validate(&0, "test").is_err());
1098 assert!(rule.validate(&-10, "test").is_err());
1099 }
1100
1101 #[test]
1102 fn test_negative_rule_int() {
1103 let rule = NegativeRule;
1104 assert!(rule.validate(&-10, "test").is_ok());
1105 assert!(rule.validate(&0, "test").is_err());
1106 assert!(rule.validate(&10, "test").is_err());
1107 }
1108
1109 #[test]
1110 fn test_precision_rule() {
1111 let rule = PrecisionRule::new(2);
1112 #[allow(clippy::approx_constant)]
1114 let two_decimal = 3.14_f64;
1115 assert!(rule.validate(&two_decimal, "test").is_ok());
1116 assert!(rule.validate(&std::f64::consts::PI, "test").is_err());
1118 }
1119}