mockforge_core/
conditions.rs

1//! Condition evaluation system for override rules
2//!
3//! This module provides support for conditional application of overrides based on
4//! JSONPath and XPath queries, as well as other conditional expressions.
5
6use jsonpath::Selector;
7use roxmltree::{Document, Node};
8use serde_json::Value;
9use std::collections::HashMap;
10use thiserror::Error;
11
12/// Errors that can occur during condition evaluation
13#[derive(Debug, Error)]
14pub enum ConditionError {
15    /// JSONPath expression is invalid or cannot be parsed
16    #[error("Invalid JSONPath expression: {0}")]
17    InvalidJsonPath(String),
18
19    /// XPath expression is invalid or cannot be parsed
20    #[error("Invalid XPath expression: {0}")]
21    InvalidXPath(String),
22
23    /// XML document is malformed or cannot be parsed
24    #[error("Invalid XML: {0}")]
25    InvalidXml(String),
26
27    /// Condition type is not supported by the evaluator
28    #[error("Unsupported condition type: {0}")]
29    UnsupportedCondition(String),
30
31    /// General condition evaluation failure with error message
32    #[error("Condition evaluation failed: {0}")]
33    EvaluationFailed(String),
34}
35
36/// Context for evaluating conditions
37#[derive(Debug, Clone)]
38pub struct ConditionContext {
39    /// Request body (JSON)
40    pub request_body: Option<Value>,
41    /// Response body (JSON)
42    pub response_body: Option<Value>,
43    /// Request body as XML string
44    pub request_xml: Option<String>,
45    /// Response body as XML string
46    pub response_xml: Option<String>,
47    /// Request headers
48    pub headers: HashMap<String, String>,
49    /// Query parameters
50    pub query_params: HashMap<String, String>,
51    /// Request path
52    pub path: String,
53    /// HTTP method
54    pub method: String,
55    /// Operation ID
56    pub operation_id: Option<String>,
57    /// Tags
58    pub tags: Vec<String>,
59}
60
61impl Default for ConditionContext {
62    fn default() -> Self {
63        Self::new()
64    }
65}
66
67impl ConditionContext {
68    /// Create a new empty condition context
69    pub fn new() -> Self {
70        Self {
71            request_body: None,
72            response_body: None,
73            request_xml: None,
74            response_xml: None,
75            headers: HashMap::new(),
76            query_params: HashMap::new(),
77            path: String::new(),
78            method: String::new(),
79            operation_id: None,
80            tags: Vec::new(),
81        }
82    }
83
84    /// Set the request body as JSON
85    pub fn with_request_body(mut self, body: Value) -> Self {
86        self.request_body = Some(body);
87        self
88    }
89
90    /// Set the response body as JSON
91    pub fn with_response_body(mut self, body: Value) -> Self {
92        self.response_body = Some(body);
93        self
94    }
95
96    /// Set the request body as XML string
97    pub fn with_request_xml(mut self, xml: String) -> Self {
98        self.request_xml = Some(xml);
99        self
100    }
101
102    /// Set the response body as XML string
103    pub fn with_response_xml(mut self, xml: String) -> Self {
104        self.response_xml = Some(xml);
105        self
106    }
107
108    /// Set the request headers
109    pub fn with_headers(mut self, headers: HashMap<String, String>) -> Self {
110        self.headers = headers;
111        self
112    }
113
114    /// Set the query parameters
115    pub fn with_query_params(mut self, params: HashMap<String, String>) -> Self {
116        self.query_params = params;
117        self
118    }
119
120    /// Set the request path
121    pub fn with_path(mut self, path: String) -> Self {
122        self.path = path;
123        self
124    }
125
126    /// Set the HTTP method
127    pub fn with_method(mut self, method: String) -> Self {
128        self.method = method;
129        self
130    }
131
132    /// Set the OpenAPI operation ID
133    pub fn with_operation_id(mut self, operation_id: String) -> Self {
134        self.operation_id = Some(operation_id);
135        self
136    }
137
138    /// Set the OpenAPI tags
139    pub fn with_tags(mut self, tags: Vec<String>) -> Self {
140        self.tags = tags;
141        self
142    }
143}
144
145/// Evaluate a condition expression
146pub fn evaluate_condition(
147    condition: &str,
148    context: &ConditionContext,
149) -> Result<bool, ConditionError> {
150    let condition = condition.trim();
151
152    if condition.is_empty() {
153        return Ok(true); // Empty condition always evaluates to true
154    }
155
156    // Handle logical operators
157    if let Some(and_conditions) = condition.strip_prefix("AND(") {
158        if let Some(inner) = and_conditions.strip_suffix(")") {
159            return evaluate_and_condition(inner, context);
160        }
161    }
162
163    if let Some(or_conditions) = condition.strip_prefix("OR(") {
164        if let Some(inner) = or_conditions.strip_suffix(")") {
165            return evaluate_or_condition(inner, context);
166        }
167    }
168
169    if let Some(not_condition) = condition.strip_prefix("NOT(") {
170        if let Some(inner) = not_condition.strip_suffix(")") {
171            return evaluate_not_condition(inner, context);
172        }
173    }
174
175    // Handle JSONPath queries
176    if condition.starts_with("$.") || condition.starts_with("$[") {
177        return evaluate_jsonpath(condition, context);
178    }
179
180    // Handle XPath queries
181    if condition.starts_with("/") || condition.starts_with("//") {
182        return evaluate_xpath(condition, context);
183    }
184
185    // Handle simple comparisons
186    evaluate_simple_condition(condition, context)
187}
188
189/// Evaluate AND condition with multiple sub-conditions
190fn evaluate_and_condition(
191    conditions: &str,
192    context: &ConditionContext,
193) -> Result<bool, ConditionError> {
194    let parts: Vec<&str> = conditions.split(',').map(|s| s.trim()).collect();
195
196    for part in parts {
197        if !evaluate_condition(part, context)? {
198            return Ok(false);
199        }
200    }
201
202    Ok(true)
203}
204
205/// Evaluate OR condition with multiple sub-conditions
206fn evaluate_or_condition(
207    conditions: &str,
208    context: &ConditionContext,
209) -> Result<bool, ConditionError> {
210    let parts: Vec<&str> = conditions.split(',').map(|s| s.trim()).collect();
211
212    for part in parts {
213        if evaluate_condition(part, context)? {
214            return Ok(true);
215        }
216    }
217
218    Ok(false)
219}
220
221/// Evaluate NOT condition
222fn evaluate_not_condition(
223    condition: &str,
224    context: &ConditionContext,
225) -> Result<bool, ConditionError> {
226    Ok(!evaluate_condition(condition, context)?)
227}
228
229/// Evaluate JSONPath query
230fn evaluate_jsonpath(query: &str, context: &ConditionContext) -> Result<bool, ConditionError> {
231    // Determine if this is a request or response query
232    let (_is_request, json_value) = if query.starts_with("$.request.") {
233        let _query = query.replace("$.request.", "$.");
234        (true, &context.request_body)
235    } else if query.starts_with("$.response.") {
236        let _query = query.replace("$.response.", "$.");
237        (false, &context.response_body)
238    } else {
239        // Default to response body if not specified
240        (false, &context.response_body)
241    };
242
243    let Some(json_value) = json_value else {
244        return Ok(false); // No body to query
245    };
246
247    match Selector::new(query) {
248        Ok(selector) => {
249            let results: Vec<_> = selector.find(json_value).collect();
250            Ok(!results.is_empty())
251        }
252        Err(_) => Err(ConditionError::InvalidJsonPath(query.to_string())),
253    }
254}
255
256/// Evaluate XPath query
257fn evaluate_xpath(query: &str, context: &ConditionContext) -> Result<bool, ConditionError> {
258    // Determine if this is a request or response query
259    let (_is_request, xml_content) = if query.starts_with("/request/") {
260        let _query = query.replace("/request/", "/");
261        (true, &context.request_xml)
262    } else if query.starts_with("/response/") {
263        let _query = query.replace("/response/", "/");
264        (false, &context.response_xml)
265    } else {
266        // Default to response XML if not specified
267        (false, &context.response_xml)
268    };
269
270    let Some(xml_content) = xml_content else {
271        println!("Debug - No XML content available for query: {}", query);
272        return Ok(false); // No XML content to query
273    };
274
275    println!("Debug - Evaluating XPath '{}' against XML content: {}", query, xml_content);
276
277    match Document::parse(xml_content) {
278        Ok(doc) => {
279            // Simple XPath evaluation - check if any nodes match
280            let root = doc.root_element();
281            println!("Debug - XML root element: {}", root.tag_name().name());
282            let matches = evaluate_xpath_simple(&root, query);
283            println!("Debug - XPath result: {}", matches);
284            Ok(matches)
285        }
286        Err(e) => {
287            println!("Debug - Failed to parse XML: {}", e);
288            Err(ConditionError::InvalidXml(xml_content.clone()))
289        }
290    }
291}
292
293/// Simple XPath evaluator (basic implementation)
294fn evaluate_xpath_simple(node: &Node, xpath: &str) -> bool {
295    // This is a simplified XPath implementation
296    // For production use, consider a more complete XPath library
297
298    // Handle descendant-or-self axis: //element (check this FIRST before stripping //)
299    if let Some(element_name) = xpath.strip_prefix("//") {
300        println!(
301            "Debug - Checking descendant-or-self for element '{}' on node '{}'",
302            element_name,
303            node.tag_name().name()
304        );
305        if node.tag_name().name() == element_name {
306            println!("Debug - Found match: {} == {}", node.tag_name().name(), element_name);
307            return true;
308        }
309        // Check descendants
310        for child in node.children() {
311            if child.is_element() {
312                println!("Debug - Checking child element: {}", child.tag_name().name());
313                if evaluate_xpath_simple(&child, &format!("//{}", element_name)) {
314                    return true;
315                }
316            }
317        }
318        return false; // If no descendant found, return false
319    }
320
321    let xpath = xpath.trim_start_matches('/');
322
323    if xpath.is_empty() {
324        return true;
325    }
326
327    // Handle attribute queries: element[@attribute='value']
328    if let Some((element_part, attr_part)) = xpath.split_once('[') {
329        if let Some(attr_query) = attr_part.strip_suffix(']') {
330            if let Some((attr_name, attr_value)) = attr_query.split_once("='") {
331                if let Some(expected_value) = attr_value.strip_suffix('\'') {
332                    if let Some(attr_val) = attr_name.strip_prefix('@') {
333                        if node.tag_name().name() == element_part {
334                            if let Some(attr) = node.attribute(attr_val) {
335                                return attr == expected_value;
336                            }
337                        }
338                    }
339                }
340            }
341        }
342        return false;
343    }
344
345    // Handle element name matching with optional predicates
346    if let Some((element_name, rest)) = xpath.split_once('/') {
347        if node.tag_name().name() == element_name {
348            if rest.is_empty() {
349                return true;
350            }
351            // Check child elements recursively
352            for child in node.children() {
353                if child.is_element() && evaluate_xpath_simple(&child, rest) {
354                    return true;
355                }
356            }
357        }
358    } else if node.tag_name().name() == xpath {
359        return true;
360    }
361
362    // Handle text content queries: element/text()
363    if let Some(text_query) = xpath.strip_suffix("/text()") {
364        if node.tag_name().name() == text_query {
365            return node.text().is_some_and(|t| !t.trim().is_empty());
366        }
367    }
368
369    false
370}
371
372/// Evaluate simple conditions like header checks, query param checks, etc.
373fn evaluate_simple_condition(
374    condition: &str,
375    context: &ConditionContext,
376) -> Result<bool, ConditionError> {
377    // Handle header conditions: header[name]=value
378    if let Some(header_condition) = condition.strip_prefix("header[") {
379        if let Some((header_name, expected_value)) = header_condition.split_once("]=") {
380            let expected_value = expected_value.trim();
381            if let Some(actual_value) = context.headers.get(header_name) {
382                return Ok(actual_value == expected_value);
383            }
384            return Ok(false);
385        }
386    }
387
388    // Handle query parameter conditions: query[name]=value
389    if let Some(query_condition) = condition.strip_prefix("query[") {
390        if let Some((param_name, expected_value)) = query_condition.split_once("]=") {
391            let expected_value = expected_value.trim();
392            if let Some(actual_value) = context.query_params.get(param_name) {
393                return Ok(actual_value == expected_value);
394            }
395            return Ok(false);
396        }
397    }
398
399    // Handle method conditions: method=POST
400    if let Some(method_condition) = condition.strip_prefix("method=") {
401        return Ok(context.method == method_condition);
402    }
403
404    // Handle path conditions: path=/api/users
405    if let Some(path_condition) = condition.strip_prefix("path=") {
406        return Ok(context.path == path_condition);
407    }
408
409    // Handle tag conditions: has_tag[admin]
410    if let Some(tag_condition) = condition.strip_prefix("has_tag[") {
411        if let Some(tag) = tag_condition.strip_suffix("]") {
412            return Ok(context.tags.contains(&tag.to_string()));
413        }
414    }
415
416    // Handle operation conditions: operation=getUser
417    if let Some(op_condition) = condition.strip_prefix("operation=") {
418        if let Some(operation_id) = &context.operation_id {
419            return Ok(operation_id == op_condition);
420        }
421        return Ok(false);
422    }
423
424    Err(ConditionError::UnsupportedCondition(condition.to_string()))
425}
426
427#[cfg(test)]
428mod tests {
429    use super::*;
430    use serde_json::json;
431
432    #[test]
433    fn test_jsonpath_condition() {
434        let context = ConditionContext::new().with_response_body(json!({
435            "user": {
436                "name": "John",
437                "role": "admin"
438            },
439            "items": [1, 2, 3]
440        }));
441
442        // Test simple path existence
443        assert!(evaluate_condition("$.user", &context).unwrap());
444
445        // Test specific value matching
446        assert!(evaluate_condition("$.user.role", &context).unwrap());
447
448        // Test array access
449        assert!(evaluate_condition("$.items[0]", &context).unwrap());
450
451        // Test non-existent path
452        assert!(!evaluate_condition("$.nonexistent", &context).unwrap());
453    }
454
455    #[test]
456    fn test_simple_conditions() {
457        let mut headers = HashMap::new();
458        headers.insert("authorization".to_string(), "Bearer token123".to_string());
459
460        let mut query_params = HashMap::new();
461        query_params.insert("limit".to_string(), "10".to_string());
462
463        let context = ConditionContext::new()
464            .with_headers(headers)
465            .with_query_params(query_params)
466            .with_method("POST".to_string())
467            .with_path("/api/users".to_string());
468
469        // Test header condition
470        assert!(evaluate_condition("header[authorization]=Bearer token123", &context).unwrap());
471        assert!(!evaluate_condition("header[authorization]=Bearer wrong", &context).unwrap());
472
473        // Test query parameter condition
474        assert!(evaluate_condition("query[limit]=10", &context).unwrap());
475        assert!(!evaluate_condition("query[limit]=20", &context).unwrap());
476
477        // Test method condition
478        assert!(evaluate_condition("method=POST", &context).unwrap());
479        assert!(!evaluate_condition("method=GET", &context).unwrap());
480
481        // Test path condition
482        assert!(evaluate_condition("path=/api/users", &context).unwrap());
483        assert!(!evaluate_condition("path=/api/posts", &context).unwrap());
484    }
485
486    #[test]
487    fn test_logical_conditions() {
488        let context = ConditionContext::new()
489            .with_method("POST".to_string())
490            .with_path("/api/users".to_string());
491
492        // Test AND condition
493        assert!(evaluate_condition("AND(method=POST,path=/api/users)", &context).unwrap());
494        assert!(!evaluate_condition("AND(method=GET,path=/api/users)", &context).unwrap());
495
496        // Test OR condition
497        assert!(evaluate_condition("OR(method=POST,path=/api/posts)", &context).unwrap());
498        assert!(!evaluate_condition("OR(method=GET,path=/api/posts)", &context).unwrap());
499
500        // Test NOT condition
501        assert!(!evaluate_condition("NOT(method=POST)", &context).unwrap());
502        assert!(evaluate_condition("NOT(method=GET)", &context).unwrap());
503    }
504
505    #[test]
506    fn test_xpath_condition() {
507        let xml_content = r#"
508            <user id="123">
509                <name>John Doe</name>
510                <role>admin</role>
511                <preferences>
512                    <theme>dark</theme>
513                    <notifications>true</notifications>
514                </preferences>
515            </user>
516        "#;
517
518        let context = ConditionContext::new().with_response_xml(xml_content.to_string());
519
520        // Test basic element existence
521        assert!(evaluate_condition("/user", &context).unwrap());
522
523        // Test nested element
524        assert!(evaluate_condition("/user/name", &context).unwrap());
525
526        // Test attribute query
527        assert!(evaluate_condition("/user[@id='123']", &context).unwrap());
528        assert!(!evaluate_condition("/user[@id='456']", &context).unwrap());
529
530        // Test text content
531        assert!(evaluate_condition("/user/name/text()", &context).unwrap());
532
533        // Test descendant axis
534        assert!(evaluate_condition("//theme", &context).unwrap());
535
536        // Test non-existent element
537        assert!(!evaluate_condition("/nonexistent", &context).unwrap());
538    }
539}