1use anyhow::Result;
4use regex::Regex;
5use serde::{Deserialize, Serialize};
6
7#[derive(Debug, Clone, Serialize, Deserialize)]
9pub struct ValidationResult {
10 pub is_valid: bool,
11 pub sanitized_input: String,
12 pub violations: Vec<ValidationViolation>,
13 pub risk_score: f64,
14}
15
16impl ValidationResult {
17 pub fn valid(sanitized: String) -> Self {
18 Self {
19 is_valid: true,
20 sanitized_input: sanitized,
21 violations: vec![],
22 risk_score: 0.0,
23 }
24 }
25
26 pub fn invalid(violations: Vec<ValidationViolation>, risk_score: f64) -> Self {
27 Self {
28 is_valid: false,
29 sanitized_input: String::new(),
30 violations,
31 risk_score,
32 }
33 }
34}
35
36#[derive(Debug, Clone, Serialize, Deserialize)]
38pub struct ValidationViolation {
39 pub violation_type: ViolationType,
40 pub description: String,
41 pub severity: Severity,
42}
43
44#[derive(Debug, Clone, Serialize, Deserialize)]
45pub enum ViolationType {
46 SqlInjection,
47 XssAttempt,
48 CommandInjection,
49 PathTraversal,
50 ExcessiveLength,
51 MalformedInput,
52 SuspiciousPattern,
53 ProhibitedContent,
54}
55
56#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
57pub enum Severity {
58 Low,
59 Medium,
60 High,
61 Critical,
62}
63
64pub struct InputValidator {
66 max_input_size: usize,
67 max_tokens: usize,
68 sql_injection_patterns: Vec<Regex>,
69 xss_patterns: Vec<Regex>,
70 command_injection_patterns: Vec<Regex>,
71 path_traversal_patterns: Vec<Regex>,
72}
73
74impl InputValidator {
75 pub fn new(max_input_size: usize, max_tokens: usize) -> Self {
76 Self {
77 max_input_size,
78 max_tokens,
79 sql_injection_patterns: Self::build_sql_patterns(),
80 xss_patterns: Self::build_xss_patterns(),
81 command_injection_patterns: Self::build_command_patterns(),
82 path_traversal_patterns: Self::build_path_patterns(),
83 }
84 }
85
86 pub fn validate(&self, input: &str) -> Result<ValidationResult> {
88 let mut violations = Vec::new();
89 let mut risk_score = 0.0;
90
91 if input.len() > self.max_input_size {
93 violations.push(ValidationViolation {
94 violation_type: ViolationType::ExcessiveLength,
95 description: format!(
96 "Input exceeds maximum size of {} bytes",
97 self.max_input_size
98 ),
99 severity: Severity::High,
100 });
101 risk_score += 0.5;
102 }
103
104 if let Some(violation) = self.check_sql_injection(input) {
106 violations.push(violation);
107 risk_score += 0.8;
108 }
109
110 if let Some(violation) = self.check_xss(input) {
112 violations.push(violation);
113 risk_score += 0.7;
114 }
115
116 if let Some(violation) = self.check_command_injection(input) {
118 violations.push(violation);
119 risk_score += 0.9;
120 }
121
122 if let Some(violation) = self.check_path_traversal(input) {
124 violations.push(violation);
125 risk_score += 0.6;
126 }
127
128 if violations.iter().any(|v| v.severity == Severity::Critical) {
130 return Ok(ValidationResult::invalid(violations, risk_score));
131 }
132
133 let sanitized = self.sanitize(input);
135
136 if violations.is_empty() {
137 Ok(ValidationResult::valid(sanitized))
138 } else {
139 Ok(ValidationResult {
140 is_valid: risk_score < 0.5,
141 sanitized_input: sanitized,
142 violations,
143 risk_score,
144 })
145 }
146 }
147
148 fn check_sql_injection(&self, input: &str) -> Option<ValidationViolation> {
149 for pattern in &self.sql_injection_patterns {
150 if pattern.is_match(input) {
151 return Some(ValidationViolation {
152 violation_type: ViolationType::SqlInjection,
153 description: "Potential SQL injection detected".to_string(),
154 severity: Severity::Critical,
155 });
156 }
157 }
158 None
159 }
160
161 fn check_xss(&self, input: &str) -> Option<ValidationViolation> {
162 for pattern in &self.xss_patterns {
163 if pattern.is_match(input) {
164 return Some(ValidationViolation {
165 violation_type: ViolationType::XssAttempt,
166 description: "Potential XSS attack detected".to_string(),
167 severity: Severity::High,
168 });
169 }
170 }
171 None
172 }
173
174 fn check_command_injection(&self, input: &str) -> Option<ValidationViolation> {
175 for pattern in &self.command_injection_patterns {
176 if pattern.is_match(input) {
177 return Some(ValidationViolation {
178 violation_type: ViolationType::CommandInjection,
179 description: "Potential command injection detected".to_string(),
180 severity: Severity::Critical,
181 });
182 }
183 }
184 None
185 }
186
187 fn check_path_traversal(&self, input: &str) -> Option<ValidationViolation> {
188 for pattern in &self.path_traversal_patterns {
189 if pattern.is_match(input) {
190 return Some(ValidationViolation {
191 violation_type: ViolationType::PathTraversal,
192 description: "Potential path traversal detected".to_string(),
193 severity: Severity::High,
194 });
195 }
196 }
197 None
198 }
199
200 fn sanitize(&self, input: &str) -> String {
201 input
203 .chars()
204 .filter(|c| !c.is_control() || c.is_whitespace())
205 .collect()
206 }
207
208 fn build_sql_patterns() -> Vec<Regex> {
209 vec![
210 Regex::new(r"(?i)(union\s+select)").expect("valid regex pattern"),
211 Regex::new(r"(?i)(drop\s+table)").expect("valid regex pattern"),
212 Regex::new(r"(?i)(delete\s+from)").expect("valid regex pattern"),
213 Regex::new(r"(?i)(insert\s+into)").expect("valid regex pattern"),
214 Regex::new(r"(?i)(--\s*$)").expect("valid regex pattern"),
215 Regex::new(r"(?i)(;\s*drop)").expect("valid regex pattern"),
216 ]
217 }
218
219 fn build_xss_patterns() -> Vec<Regex> {
220 vec![
221 Regex::new(r"(?i)(<script.*?>)").expect("valid regex pattern"),
222 Regex::new(r"(?i)(javascript:)").expect("valid regex pattern"),
223 Regex::new(r"(?i)(onerror\s*=)").expect("valid regex pattern"),
224 Regex::new(r"(?i)(onload\s*=)").expect("valid regex pattern"),
225 ]
226 }
227
228 fn build_command_patterns() -> Vec<Regex> {
229 vec![
230 Regex::new(r"[;&|`$]").expect("valid regex pattern"),
231 Regex::new(r"(?i)(rm\s+-rf)").expect("valid regex pattern"),
232 Regex::new(r"(?i)(wget|curl)\s+http").expect("valid regex pattern"),
233 ]
234 }
235
236 fn build_path_patterns() -> Vec<Regex> {
237 vec![
238 Regex::new(r"\.\.\/").expect("valid regex pattern"),
239 Regex::new(r"\.\.\\").expect("valid regex pattern"),
240 Regex::new(r"(?i)(\/etc\/passwd)").expect("valid regex pattern"),
241 ]
242 }
243}
244
245#[cfg(test)]
246mod tests {
247 use super::*;
248
249 #[test]
250 fn test_valid_input() {
251 let validator = InputValidator::new(1024 * 1024, 4096);
252 let result = validator
253 .validate("SELECT ?s ?p ?o WHERE { ?s ?p ?o }")
254 .expect("should succeed");
255 assert!(result.is_valid);
256 }
257
258 #[test]
259 fn test_sql_injection_detection() {
260 let validator = InputValidator::new(1024 * 1024, 4096);
261 let result = validator
262 .validate("'; DROP TABLE users; --")
263 .expect("should succeed");
264 assert!(!result.is_valid);
265 assert!(!result.violations.is_empty());
266 }
267
268 #[test]
269 fn test_xss_detection() {
270 let validator = InputValidator::new(1024 * 1024, 4096);
271 let result = validator
272 .validate("<script>alert('xss')</script>")
273 .expect("should succeed");
274 assert!(!result.is_valid);
275 }
276
277 #[test]
278 fn test_command_injection_detection() {
279 let validator = InputValidator::new(1024 * 1024, 4096);
280 let result = validator
281 .validate("test; rm -rf /")
282 .expect("should succeed");
283 assert!(!result.is_valid);
284 }
285
286 #[test]
287 fn test_excessive_length() {
288 let validator = InputValidator::new(100, 4096);
289 let long_input = "a".repeat(200);
290 let result = validator.validate(&long_input).expect("should succeed");
291 assert!(!result.violations.is_empty());
292 }
293}