1use super::input::{CharsetRule, FormatRule, InputValidationError, StringValidator};
33use crate::utils::error::Result;
34use std::collections::HashMap;
35
36#[derive(Debug, Clone)]
38pub enum RuleDefinition {
39 Length {
41 field: String,
42 min: usize,
43 max: usize,
44 },
45
46 Pattern { field: String, pattern: String },
48
49 Charset { field: String, charset: String },
51
52 Format { field: String, format: String },
54
55 Whitelist { field: String, allowed: Vec<String> },
57
58 Blacklist {
60 field: String,
61 forbidden: Vec<String>,
62 },
63
64 And {
66 left: Box<RuleDefinition>,
67 right: Box<RuleDefinition>,
68 },
69
70 Or {
72 left: Box<RuleDefinition>,
73 right: Box<RuleDefinition>,
74 },
75
76 Not { inner: Box<RuleDefinition> },
78}
79
80impl RuleDefinition {
81 pub fn length(field: &str, min: usize, max: usize) -> Self {
83 Self::Length {
84 field: field.to_string(),
85 min,
86 max,
87 }
88 }
89
90 pub fn pattern(field: &str, pattern: &str) -> Self {
92 Self::Pattern {
93 field: field.to_string(),
94 pattern: pattern.to_string(),
95 }
96 }
97
98 pub fn charset(field: &str, charset: &str) -> Self {
100 Self::Charset {
101 field: field.to_string(),
102 charset: charset.to_string(),
103 }
104 }
105
106 pub fn format(field: &str, format: &str) -> Self {
108 Self::Format {
109 field: field.to_string(),
110 format: format.to_string(),
111 }
112 }
113
114 pub fn whitelist(field: &str, allowed: Vec<String>) -> Self {
116 Self::Whitelist {
117 field: field.to_string(),
118 allowed,
119 }
120 }
121
122 pub fn blacklist(field: &str, forbidden: Vec<String>) -> Self {
124 Self::Blacklist {
125 field: field.to_string(),
126 forbidden,
127 }
128 }
129
130 pub fn and(self, other: RuleDefinition) -> Self {
132 Self::And {
133 left: Box::new(self),
134 right: Box::new(other),
135 }
136 }
137
138 pub fn or(self, other: RuleDefinition) -> Self {
140 Self::Or {
141 left: Box::new(self),
142 right: Box::new(other),
143 }
144 }
145
146 pub fn negate(self) -> Self {
148 Self::Not {
149 inner: Box::new(self),
150 }
151 }
152
153 pub fn field_name(&self) -> Option<&str> {
155 match self {
156 Self::Length { field, .. }
157 | Self::Pattern { field, .. }
158 | Self::Charset { field, .. }
159 | Self::Format { field, .. }
160 | Self::Whitelist { field, .. }
161 | Self::Blacklist { field, .. } => Some(field),
162 Self::And { left, .. } => left.field_name(),
163 Self::Or { left, .. } => left.field_name(),
164 Self::Not { inner } => inner.field_name(),
165 }
166 }
167}
168
169pub struct CompiledValidator {
171 validators: HashMap<String, StringValidator>,
172}
173
174impl CompiledValidator {
175 pub fn new(validators: HashMap<String, StringValidator>) -> Self {
177 Self { validators }
178 }
179
180 pub fn validate_field(&self, field: &str, value: &str) -> Result<String> {
182 if let Some(validator) = self.validators.get(field) {
183 validator.validate(value).map_err(|e| {
184 InputValidationError::FormatViolation {
185 field: field.to_string(),
186 reason: format!("Validation failed: {}", e),
187 }
188 .into()
189 })
190 } else {
191 Err(InputValidationError::EmptyInput {
192 field: format!("No validator defined for field: {}", field),
193 }
194 .into())
195 }
196 }
197
198 pub fn validate_fields(
200 &self, fields: &HashMap<String, String>,
201 ) -> Result<HashMap<String, String>> {
202 let mut validated = HashMap::new();
203
204 for (field, value) in fields {
205 let validated_value = self.validate_field(field, value)?;
206 validated.insert(field.clone(), validated_value);
207 }
208
209 Ok(validated)
210 }
211}
212
213pub struct RuleCompiler {
215 }
217
218impl RuleCompiler {
219 pub fn new() -> Self {
220 Self {}
221 }
222
223 pub fn compile(&self, rules: &[RuleDefinition]) -> Result<CompiledValidator> {
225 let mut validators: HashMap<String, StringValidator> = HashMap::new();
226
227 let mut rules_by_field: HashMap<String, Vec<&RuleDefinition>> = HashMap::new();
229 for rule in rules {
230 if let Some(field) = rule.field_name() {
231 rules_by_field
232 .entry(field.to_string())
233 .or_default()
234 .push(rule);
235 }
236 }
237
238 for (field, field_rules) in rules_by_field {
240 let mut validator = StringValidator::new();
241
242 for rule in field_rules {
243 validator = self.apply_rule(validator, rule)?;
244 }
245
246 validators.insert(field, validator);
247 }
248
249 Ok(CompiledValidator::new(validators))
250 }
251
252 fn apply_rule(
253 &self, mut validator: StringValidator, rule: &RuleDefinition,
254 ) -> Result<StringValidator> {
255 match rule {
256 RuleDefinition::Length { min, max, .. } => {
257 validator = validator.with_length(*min, *max);
258 }
259 RuleDefinition::Pattern { pattern, .. } => {
260 validator = validator.with_pattern(pattern);
261 }
262 RuleDefinition::Charset { charset, .. } => {
263 let charset_rule = match charset.as_str() {
264 "alphanumeric" => CharsetRule::alphanumeric(),
265 "identifier" => CharsetRule::identifier(),
266 "ascii_printable" => CharsetRule::ascii_printable(),
267 _ => {
268 return Err(InputValidationError::FormatViolation {
269 field: "charset".to_string(),
270 reason: format!("Unknown charset type: {}", charset),
271 }
272 .into())
273 }
274 };
275 validator = validator.with_charset(charset_rule);
276 }
277 RuleDefinition::Format { format, .. } => {
278 let format_rule = match format.as_str() {
279 "email" => FormatRule::Email,
280 "uuid" => FormatRule::Uuid,
281 "semver" => FormatRule::Semver,
282 "ip" => FormatRule::IpAddress,
283 "hostname" => FormatRule::Hostname,
284 _ => {
285 return Err(InputValidationError::FormatViolation {
286 field: "format".to_string(),
287 reason: format!("Unknown format type: {}", format),
288 }
289 .into())
290 }
291 };
292 validator = validator.with_format(format_rule);
293 }
294 RuleDefinition::Whitelist { allowed, .. } => {
295 validator = validator.with_whitelist(allowed.clone());
296 }
297 RuleDefinition::Blacklist { forbidden, .. } => {
298 validator = validator.with_blacklist(forbidden.clone());
299 }
300 RuleDefinition::And { .. } | RuleDefinition::Or { .. } | RuleDefinition::Not { .. } => {
301 return Err(InputValidationError::CompositeViolation {
304 reason: "Composite rules (AND/OR/NOT) not yet supported in compiler"
305 .to_string(),
306 }
307 .into());
308 }
309 }
310
311 Ok(validator)
312 }
313}
314
315impl Default for RuleCompiler {
316 fn default() -> Self {
317 Self::new()
318 }
319}
320
321#[cfg(test)]
322mod tests {
323 use super::*;
324
325 #[test]
326 fn test_rule_definition_length() {
327 let rule = RuleDefinition::length("username", 3, 32);
329
330 assert_eq!(rule.field_name(), Some("username"));
332 }
333
334 #[test]
335 fn test_rule_definition_pattern() {
336 let rule = RuleDefinition::pattern("email", r"^.+@.+$");
338
339 assert_eq!(rule.field_name(), Some("email"));
341 }
342
343 #[test]
344 fn test_rule_compiler_single_rule() {
345 let compiler = RuleCompiler::new();
347 let rules = vec![RuleDefinition::length("username", 3, 32)];
348
349 let validator = compiler.compile(&rules).expect("compilation succeeds");
351 let result = validator.validate_field("username", "alice");
352
353 assert!(result.is_ok());
355 }
356
357 #[test]
358 fn test_rule_compiler_multiple_rules_same_field() {
359 let compiler = RuleCompiler::new();
361 let rules = vec![
362 RuleDefinition::length("username", 3, 32),
363 RuleDefinition::charset("username", "identifier"),
364 ];
365
366 let validator = compiler.compile(&rules).expect("compilation succeeds");
368
369 assert!(validator.validate_field("username", "alice_123").is_ok());
371
372 assert!(validator.validate_field("username", "ab").is_err());
374
375 assert!(validator.validate_field("username", "alice@123").is_err());
377 }
378
379 #[test]
380 fn test_rule_compiler_multiple_fields() {
381 let compiler = RuleCompiler::new();
383 let rules = vec![
384 RuleDefinition::length("username", 3, 32),
385 RuleDefinition::length("email", 5, 254),
386 RuleDefinition::format("email", "email"),
387 ];
388
389 let validator = compiler.compile(&rules).expect("compilation succeeds");
391
392 assert!(validator.validate_field("username", "alice").is_ok());
394 assert!(validator
395 .validate_field("email", "alice@example.com")
396 .is_ok());
397 }
398
399 #[test]
400 fn test_rule_compiler_format_email() {
401 let compiler = RuleCompiler::new();
403 let rules = vec![RuleDefinition::format("email", "email")];
404
405 let validator = compiler.compile(&rules).expect("compilation succeeds");
407
408 assert!(validator
410 .validate_field("email", "alice@example.com")
411 .is_ok());
412 assert!(validator.validate_field("email", "not-an-email").is_err());
413 }
414
415 #[test]
416 fn test_rule_compiler_whitelist() {
417 let compiler = RuleCompiler::new();
419 let rules = vec![RuleDefinition::whitelist(
420 "role",
421 vec!["admin".to_string(), "user".to_string()],
422 )];
423
424 let validator = compiler.compile(&rules).expect("compilation succeeds");
426
427 assert!(validator.validate_field("role", "admin").is_ok());
429 assert!(validator.validate_field("role", "user").is_ok());
430 assert!(validator.validate_field("role", "guest").is_err());
431 }
432
433 #[test]
434 fn test_rule_compiler_blacklist() {
435 let compiler = RuleCompiler::new();
437 let rules = vec![RuleDefinition::blacklist(
438 "username",
439 vec!["admin".to_string(), "root".to_string()],
440 )];
441
442 let validator = compiler.compile(&rules).expect("compilation succeeds");
444
445 assert!(validator.validate_field("username", "alice").is_ok());
447 assert!(validator.validate_field("username", "admin").is_err());
448 assert!(validator.validate_field("username", "root").is_err());
449 }
450
451 #[test]
452 fn test_compiled_validator_validate_fields() {
453 let compiler = RuleCompiler::new();
455 let rules = vec![
456 RuleDefinition::length("username", 3, 32),
457 RuleDefinition::format("email", "email"),
458 ];
459
460 let validator = compiler.compile(&rules).expect("compilation succeeds");
461
462 let mut fields = HashMap::new();
463 fields.insert("username".to_string(), "alice".to_string());
464 fields.insert("email".to_string(), "alice@example.com".to_string());
465
466 let result = validator.validate_fields(&fields);
468
469 assert!(result.is_ok());
471 let validated = result.unwrap();
472 assert_eq!(validated.get("username"), Some(&"alice".to_string()));
473 assert_eq!(
474 validated.get("email"),
475 Some(&"alice@example.com".to_string())
476 );
477 }
478
479 #[test]
480 fn test_compiled_validator_unknown_field() {
481 let compiler = RuleCompiler::new();
483 let rules = vec![RuleDefinition::length("username", 3, 32)];
484
485 let validator = compiler.compile(&rules).expect("compilation succeeds");
486
487 let result = validator.validate_field("unknown", "value");
489
490 assert!(result.is_err());
492 }
493
494 #[test]
495 fn test_rule_definition_and() {
496 let rule = RuleDefinition::length("field", 5, 10)
498 .and(RuleDefinition::charset("field", "alphanumeric"));
499
500 assert_eq!(rule.field_name(), Some("field"));
502 }
503
504 #[test]
505 fn test_rule_definition_or() {
506 let rule =
508 RuleDefinition::length("field", 5, 10).or(RuleDefinition::length("field", 20, 30));
509
510 assert_eq!(rule.field_name(), Some("field"));
512 }
513
514 #[test]
515 fn test_rule_definition_negate() {
516 let rule = RuleDefinition::length("field", 5, 10).negate();
518
519 assert_eq!(rule.field_name(), Some("field"));
521 }
522}