tellaro-query-language 0.2.23

A flexible, human-friendly query language for searching and filtering structured data
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
//! TQL AST to OpenSearch Query DSL translator.
//!
//! This module translates TQL abstract syntax trees into OpenSearch Query DSL.

use super::error::{OpenSearchError, Result};
use super::field_mappings::FieldMappings;
use crate::parser::{AstNode, CollectionOpNode, NslookupExprNode, Value as AstValue};
use serde_json::{json, Value as JsonValue};

/// Query builder for translating TQL to OpenSearch DSL
pub struct QueryBuilder {
    field_mappings: Option<FieldMappings>,
}

impl QueryBuilder {
    /// Create a new query builder
    ///
    /// # Arguments
    ///
    /// * `field_mappings` - Optional field mappings for intelligent query generation
    pub fn new(field_mappings: Option<FieldMappings>) -> Self {
        Self { field_mappings }
    }

    /// Convert AstValue to JsonValue
    fn ast_value_to_json(value: &AstValue) -> JsonValue {
        match value {
            AstValue::String(s) => json!(s),
            AstValue::Integer(i) => json!(i),
            AstValue::Float(f) => json!(f),
            AstValue::Boolean(b) => json!(b),
            AstValue::List(list) => {
                json!(list.iter().map(Self::ast_value_to_json).collect::<Vec<_>>())
            }
            AstValue::Null => json!(null),
        }
    }

    /// Build an OpenSearch query from a TQL AST
    ///
    /// # Arguments
    ///
    /// * `ast` - The TQL abstract syntax tree
    ///
    /// # Returns
    ///
    /// OpenSearch Query DSL as JSON
    ///
    /// # Example
    ///
    /// ```ignore
    /// use tql::parser::TqlParser;
    /// use tql::opensearch::QueryBuilder;
    ///
    /// let parser = TqlParser::new();
    /// let ast = parser.parse("age > 25 AND status eq 'active'").unwrap();
    /// let builder = QueryBuilder::new(None);
    /// let query = builder.build_query(&ast).unwrap();
    /// ```
    pub fn build_query(&self, ast: &AstNode) -> Result<JsonValue> {
        // Handle stats and query-with-stats AST nodes
        match ast {
            AstNode::StatsExpr(stats) => {
                // Pure stats query (no filter): match_all + aggregations
                let mut dsl = json!({ "query": { "match_all": {} }, "size": 0 });
                let aggs =
                    super::stats_translator::translate_stats(stats, self.field_mappings.as_ref())
                        .map_err(OpenSearchError::TranslationError)?;
                if let Some(aggs_obj) = aggs.get("aggs") {
                    dsl["aggs"] = aggs_obj.clone();
                }
                return Ok(dsl);
            }
            AstNode::QueryWithStats(qws) => {
                // Filter + stats: build filter query + aggregations, size=0
                let query_clause = self.build_query_clause(&qws.filter)?;
                let mut dsl = json!({ "query": query_clause, "size": 0 });
                let aggs = super::stats_translator::translate_stats(
                    &qws.stats,
                    self.field_mappings.as_ref(),
                )
                .map_err(OpenSearchError::TranslationError)?;
                if let Some(aggs_obj) = aggs.get("aggs") {
                    dsl["aggs"] = aggs_obj.clone();
                }
                return Ok(dsl);
            }
            _ => {}
        }

        let query_clause = self.build_query_clause(ast)?;
        Ok(json!({
            "query": query_clause
        }))
    }

    /// Check if mutators require post-processing (cannot be pushed to OpenSearch)
    fn has_post_processing_mutators(mutators: &Option<Vec<crate::parser::Mutator>>) -> bool {
        mutators.as_ref().is_some_and(|mutators| {
            mutators.iter().any(|m| {
                let name = m.name.to_lowercase();
                // These mutators require post-processing - they transform values
                // and cannot be evaluated by OpenSearch
                matches!(
                    name.as_str(),
                    "is_global"
                        | "is_private"
                        | "is_multicast"
                        | "is_loopback"
                        | "is_link_local"
                        | "nslookup"
                        | "geoip"
                        | "geoip_lookup"
                        | "geo"
                        | "lowercase"
                        | "uppercase"
                        | "trim"
                        | "length"
                        | "split"
                        | "replace"
                        | "b64encode"
                        | "b64decode"
                        | "urldecode"
                        | "hexencode"
                        | "hexdecode"
                        | "md5"
                        | "sha256"
                        | "refang"
                        | "defang"
                )
            })
        })
    }

    fn build_query_clause(&self, node: &AstNode) -> Result<JsonValue> {
        match node {
            AstNode::Comparison(comp) => {
                // Check if there are post-processing mutators on the field
                // If so, we can only check that the field exists - the actual
                // filtering will be done in post-processing
                if Self::has_post_processing_mutators(&comp.field_mutators) {
                    // For mutators that require post-processing, return exists query
                    // The actual filtering (is_global eq true, etc.) happens after
                    // results are fetched from OpenSearch
                    return Ok(json!({
                        "exists": {
                            "field": &comp.field
                        }
                    }));
                }

                // Handle "exists" operator with no value (field-only expressions like `field | nslookup`)
                if comp.operator == "exists" && comp.value.is_none() {
                    // Check if there are enrichment mutators (nslookup, geoip, etc.)
                    // These require post-processing, so we return match_all to fetch all docs
                    let has_enrichment_mutator =
                        comp.field_mutators.as_ref().is_some_and(|mutators| {
                            mutators.iter().any(|m| {
                                let name = m.name.to_lowercase();
                                name == "nslookup" || name == "geoip" || name == "geoip_lookup"
                            })
                        });

                    if has_enrichment_mutator {
                        // Enrichment-only expression - return match_all for post-processing
                        return Ok(json!({
                            "match_all": {}
                        }));
                    } else {
                        // Regular exists check
                        return Ok(json!({
                            "exists": {
                                "field": &comp.field
                            }
                        }));
                    }
                }

                let value = comp.value.as_ref().ok_or_else(|| {
                    OpenSearchError::TranslationError("Comparison requires a value".to_string())
                })?;
                self.build_comparison(&comp.field, &comp.operator, value)
            }
            AstNode::LogicalOp(logical) => {
                self.build_logical(&logical.operator, &logical.left, &logical.right)
            }
            AstNode::UnaryOp(unary) => {
                let inner = self.build_query_clause(&unary.operand)?;
                Ok(json!({
                    "bool": {
                        "must_not": inner
                    }
                }))
            }
            AstNode::MatchAll => Ok(json!({
                "match_all": {}
            })),
            AstNode::CollectionOp(collection) => self.build_collection_op(collection),
            AstNode::NslookupExpr(nslookup) => self.build_nslookup_expr(nslookup),
            AstNode::GeoExpr(geo) => {
                // Geo expressions require post-processing, similar to nslookup
                // If there are conditions, use exists query on the field
                // If no conditions, return match_all
                if geo.conditions.is_some() {
                    Ok(json!({
                        "exists": {
                            "field": &geo.field
                        }
                    }))
                } else {
                    Ok(json!({
                        "match_all": {}
                    }))
                }
            }
            _ => Err(OpenSearchError::TranslationError(format!(
                "Unsupported AST node type: {:?}",
                node
            ))),
        }
    }

    /// Check if a field is a text type (needs lowercasing for wildcard queries).
    fn is_text_field(&self, field: &str) -> bool {
        self.field_mappings
            .as_ref()
            .and_then(|m| m.get_field_type(field))
            .is_some_and(|ft| *ft == super::field_mappings::FieldType::Text)
    }

    fn build_comparison(&self, field: &str, operator: &str, value: &AstValue) -> Result<JsonValue> {
        // Convert AstValue to JsonValue
        let json_value = Self::ast_value_to_json(value);

        // Determine the actual field name to use (may include .keyword suffix)
        let query_field = self
            .field_mappings
            .as_ref()
            .map(|m| m.get_query_field(field, operator))
            .unwrap_or_else(|| field.to_string());

        match operator {
            "eq" => {
                // Use term for exact match
                Ok(json!({
                    "term": {
                        query_field: json_value
                    }
                }))
            }
            "ne" => {
                // Use bool must_not with term
                Ok(json!({
                    "bool": {
                        "must_not": {
                            "term": {
                                query_field: json_value
                            }
                        }
                    }
                }))
            }
            "gt" => Ok(json!({
                "range": {
                    query_field: {
                        "gt": json_value
                    }
                }
            })),
            "gte" => Ok(json!({
                "range": {
                    query_field: {
                        "gte": json_value
                    }
                }
            })),
            "lt" => Ok(json!({
                "range": {
                    query_field: {
                        "lt": json_value
                    }
                }
            })),
            "lte" => Ok(json!({
                "range": {
                    query_field: {
                        "lte": json_value
                    }
                }
            })),
            "contains" => {
                // Lowercase the value only for text fields (OpenSearch text analysis
                // lowercases indexed tokens). Keyword fields and unknown fields preserve case.
                let is_text = self.is_text_field(field);
                let raw = json_value.as_str().unwrap_or("");
                let val = if is_text {
                    raw.to_lowercase()
                } else {
                    raw.to_string()
                };
                Ok(json!({
                    "wildcard": {
                        query_field: format!("*{}*", val)
                    }
                }))
            }
            "startswith" => {
                let is_text = self.is_text_field(field);
                let raw = json_value.as_str().unwrap_or("");
                let val = if is_text {
                    raw.to_lowercase()
                } else {
                    raw.to_string()
                };
                Ok(json!({
                    "prefix": {
                        query_field: val
                    }
                }))
            }
            "endswith" => {
                let is_text = self.is_text_field(field);
                let raw = json_value.as_str().unwrap_or("");
                let val = if is_text {
                    raw.to_lowercase()
                } else {
                    raw.to_string()
                };
                Ok(json!({
                    "wildcard": {
                        query_field: format!("*{}", val)
                    }
                }))
            }
            "matches" => {
                // Use regexp query
                Ok(json!({
                    "regexp": {
                        query_field: json_value
                    }
                }))
            }
            "in" => {
                // Use terms query
                let values = if let JsonValue::Array(arr) = &json_value {
                    arr.clone()
                } else {
                    vec![json_value.clone()]
                };
                Ok(json!({
                    "terms": {
                        query_field: values
                    }
                }))
            }
            "between" => {
                // Use range query with gte and lte
                if let JsonValue::Array(arr) = &json_value {
                    if arr.len() == 2 {
                        Ok(json!({
                            "range": {
                                query_field: {
                                    "gte": arr[0],
                                    "lte": arr[1]
                                }
                            }
                        }))
                    } else {
                        Err(OpenSearchError::TranslationError(
                            "between operator requires array of 2 values".to_string(),
                        ))
                    }
                } else {
                    Err(OpenSearchError::TranslationError(
                        "between operator requires array value".to_string(),
                    ))
                }
            }
            _ => Err(OpenSearchError::TranslationError(format!(
                "Unsupported operator: {}",
                operator
            ))),
        }
    }

    fn build_logical(&self, operator: &str, left: &AstNode, right: &AstNode) -> Result<JsonValue> {
        let left_clause = self.build_query_clause(left)?;
        let right_clause = self.build_query_clause(right)?;

        match operator.to_lowercase().as_str() {
            "and" => Ok(json!({
                "bool": {
                    "must": [left_clause, right_clause]
                }
            })),
            "or" => Ok(json!({
                "bool": {
                    "should": [left_clause, right_clause],
                    "minimum_should_match": 1
                }
            })),
            _ => Err(OpenSearchError::TranslationError(format!(
                "Unsupported logical operator: {}",
                operator
            ))),
        }
    }

    fn build_collection_op(&self, collection: &CollectionOpNode) -> Result<JsonValue> {
        let json_value = Self::ast_value_to_json(&collection.value);
        let operator = collection.operator.to_lowercase();
        let comparison_op = &collection.comparison_operator;

        // Build the inner comparison query
        let inner_query = match comparison_op.as_str() {
            "eq" => json!({
                "term": {
                    collection.field.clone(): json_value
                }
            }),
            "ne" => json!({
                "bool": {
                    "must_not": {
                        "term": {
                            collection.field.clone(): json_value
                        }
                    }
                }
            }),
            "gt" => json!({
                "range": {
                    collection.field.clone(): {
                        "gt": json_value
                    }
                }
            }),
            "gte" => json!({
                "range": {
                    collection.field.clone(): {
                        "gte": json_value
                    }
                }
            }),
            "lt" => json!({
                "range": {
                    collection.field.clone(): {
                        "lt": json_value
                    }
                }
            }),
            "lte" => json!({
                "range": {
                    collection.field.clone(): {
                        "lte": json_value
                    }
                }
            }),
            "contains" => json!({
                "wildcard": {
                    collection.field.clone(): format!("*{}*", json_value.as_str().unwrap_or(""))
                }
            }),
            _ => {
                return Err(OpenSearchError::TranslationError(format!(
                    "Unsupported collection comparison operator: {}",
                    comparison_op
                )));
            }
        };

        // Wrap in appropriate collection operator
        match operator.as_str() {
            "any" => {
                // ANY: At least one element matches (OpenSearch handles arrays automatically)
                Ok(inner_query)
            }
            "all" => {
                // ALL: All elements match - requires script query or post-processing
                // For now, we'll return a placeholder that indicates post-processing is needed
                Err(OpenSearchError::TranslationError(
                    "ALL collection operator requires post-processing".to_string(),
                ))
            }
            "none" => {
                // NONE: No elements match
                Ok(json!({
                    "bool": {
                        "must_not": inner_query
                    }
                }))
            }
            _ => Err(OpenSearchError::TranslationError(format!(
                "Unsupported collection operator: {}",
                operator
            ))),
        }
    }

    fn build_nslookup_expr(&self, nslookup: &NslookupExprNode) -> Result<JsonValue> {
        // Nslookup expressions are enrichment operations that require post-processing
        // If there are conditions (filters on the nslookup results), use exists query
        // If no conditions (just enrichment), return match_all to fetch all documents
        if nslookup.conditions.is_some() {
            Ok(json!({
                "exists": {
                    "field": &nslookup.field
                }
            }))
        } else {
            Ok(json!({
                "match_all": {}
            }))
        }
    }
}

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

    #[test]
    fn test_simple_equality() {
        let parser = TqlParser::new();
        let ast = parser.parse("status eq 'active'").unwrap();
        let builder = QueryBuilder::new(None);
        let query = builder.build_query(&ast).unwrap();

        assert_eq!(
            query,
            json!({
                "query": {
                    "term": {
                        "status": "active"
                    }
                }
            })
        );
    }

    #[test]
    fn test_range_query() {
        let parser = TqlParser::new();
        let ast = parser.parse("age > 25").unwrap();
        let builder = QueryBuilder::new(None);
        let query = builder.build_query(&ast).unwrap();

        assert_eq!(
            query,
            json!({
                "query": {
                    "range": {
                        "age": {
                            "gt": 25
                        }
                    }
                }
            })
        );
    }

    #[test]
    fn test_and_query() {
        let parser = TqlParser::new();
        let ast = parser.parse("age > 25 AND status eq 'active'").unwrap();
        let builder = QueryBuilder::new(None);
        let query = builder.build_query(&ast).unwrap();

        // Verify it's a bool/must query
        assert!(query["query"]["bool"]["must"].is_array());
        assert_eq!(query["query"]["bool"]["must"].as_array().unwrap().len(), 2);
    }

    #[test]
    fn test_or_query() {
        let parser = TqlParser::new();
        let ast = parser
            .parse("status eq 'active' OR status eq 'pending'")
            .unwrap();
        let builder = QueryBuilder::new(None);
        let query = builder.build_query(&ast).unwrap();

        // Verify it's a bool/should query
        assert!(query["query"]["bool"]["should"].is_array());
        assert_eq!(
            query["query"]["bool"]["should"].as_array().unwrap().len(),
            2
        );
        assert_eq!(query["query"]["bool"]["minimum_should_match"], 1);
    }

    #[test]
    fn test_not_query() {
        let parser = TqlParser::new();
        let ast = parser.parse("NOT (age < 18)").unwrap();
        let builder = QueryBuilder::new(None);
        let query = builder.build_query(&ast).unwrap();

        // Verify it's a bool/must_not query
        assert!(query["query"]["bool"]["must_not"]["range"].is_object());
    }

    #[test]
    fn test_detection_rule_with_is_global_and_nslookup() {
        let parser = TqlParser::new();
        let query_str =
            "event.code = 3 AND destination.ip | is_global eq true AND destination.ip | nslookup";
        let ast = parser.parse(query_str).unwrap();

        // Print the AST for debugging
        eprintln!("AST for detection rule query:\n{:#?}", ast);

        let builder = QueryBuilder::new(None);
        let query = builder.build_query(&ast).unwrap();

        // Print the generated DSL
        eprintln!(
            "Generated OpenSearch DSL:\n{}",
            serde_json::to_string_pretty(&query).unwrap()
        );

        // The query should have a bool with must clauses
        assert!(
            query["query"]["bool"]["must"].is_array(),
            "Expected bool/must query, got: {}",
            serde_json::to_string_pretty(&query).unwrap()
        );

        let must_clauses = query["query"]["bool"]["must"].as_array().unwrap();

        // Should have 3 clauses: event.code=3, is_global, nslookup
        // Actually, the structure depends on how AND is parsed
        eprintln!("Number of must clauses: {}", must_clauses.len());
    }
}