gene 0.7.2

Crate providing a log matching framework written in Rust
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
use std::{
    borrow::Cow,
    collections::HashMap,
    net::IpAddr,
    path::{Path, PathBuf},
};

use crate::{FieldValue, XPath};

/// An iterator over field names in an [`XPath`]-like path.
///
/// This iterator is used to traverse field names in structured data paths,
/// such as `.parent.child.field` in jq notation. It provides methods to
/// access the current field name and advance to the next one.
///
/// The iterator can be created from an [`XPath`] using the [`From`] trait,
/// or directly from a slice of field names.
///
/// # Examples
///
/// ```
/// use gene::{FieldNameIterator, XPath};
///
/// // From XPath
/// let path = XPath::parse(".parent.child.field").unwrap();
/// let mut iter = FieldNameIterator::from(&path);
///
/// assert_eq!(iter.next_field_name(), Some("parent"));
/// assert_eq!(iter.next_field_name(), Some("child"));
/// assert_eq!(iter.next_field_name(), Some("field"));
/// assert_eq!(iter.next_field_name(), None);
///
/// // From field names directly
/// let field_names = vec!["parent".to_string(), "child".to_string(), "field".to_string()];
/// let mut iter = FieldNameIterator::from(field_names.as_slice());
///
/// assert_eq!(iter.next_field_name(), Some("parent"));
/// assert_eq!(iter.next_field_name(), Some("child"));
/// assert_eq!(iter.next_field_name(), Some("field"));
/// assert_eq!(iter.next_field_name(), None);
/// ```
pub struct FieldNameIterator<'f> {
    i: Option<usize>,
    field_names: &'f [String],
}

impl<'f> From<&'f [String]> for FieldNameIterator<'f> {
    fn from(value: &'f [String]) -> Self {
        Self {
            i: None,
            field_names: value,
        }
    }
}

impl<'f> From<&'f XPath> for FieldNameIterator<'f> {
    fn from(value: &'f XPath) -> Self {
        value.segments().into()
    }
}

impl<'f> FieldNameIterator<'f> {
    /// Advances the iterator and returns the next field name.
    ///
    /// This method moves the iterator to the next position and returns the field name
    /// at that position. On the first call, it returns the first field name.
    /// When the iterator reaches the end, it returns `None`.
    ///
    /// # Examples
    ///
    /// ```
    /// use gene::FieldNameIterator;
    ///
    /// let field_names = vec!["field1".to_string(), "field2".to_string()];
    /// let mut iter = FieldNameIterator::from(field_names.as_slice());
    ///
    /// assert_eq!(iter.next_field_name(), Some("field1"));
    /// assert_eq!(iter.next_field_name(), Some("field2"));
    /// assert_eq!(iter.next_field_name(), None);
    /// ```
    #[inline]
    pub fn next_field_name(&mut self) -> Option<&str> {
        match self.i.as_mut() {
            Some(i) => {
                *i = i.checked_add(1)?;
                self.field_names.get(*i).map(|s| s.as_ref())
            }
            None => {
                self.i = Some(0);
                self.field_names.first().map(|s| s.as_ref())
            }
        }
    }

    /// Checks if the iterator is at the last field name.
    ///
    /// Returns `true` if the current position is at the last field name in the path,
    /// indicating that this is a terminal field access. Returns `false` otherwise.
    ///
    /// # Examples
    ///
    /// ```
    /// use gene::FieldNameIterator;
    ///
    /// let field_names = vec!["field1".to_string(), "field2".to_string()];
    /// let mut iter = FieldNameIterator::from(field_names.as_slice());
    ///
    /// assert_eq!(iter.next_field_name(), Some("field1"));
    /// assert!(!iter.is_terminal()); // At start, not terminal
    /// assert_eq!(iter.next_field_name(), Some("field2"));
    /// assert!(iter.is_terminal()); // After advancing once, at last field
    /// ```
    #[inline(always)]
    pub fn is_terminal(&self) -> bool {
        self.i.unwrap_or_default() == self.field_names.len() - 1
    }
}

/// Trait representing a log event that can be scanned by the engine.
///
/// Events provide access to their unique identifier, source, and field values
/// through the [`FieldGetter`] trait. This trait is typically derived using
/// the [`Event`] derive macro from `gene_derive`.
///
/// # Examples
///
/// ```
/// use gene::{FieldValue, Event, FieldGetter, FieldNameIterator};
/// use gene_derive::{Event, FieldGetter};
/// use std::borrow::Cow;
///
/// // Simple event with derive macro
/// #[derive(Event, FieldGetter)]
/// #[event(id = 42, source = "syslog".into())]
/// struct SyslogEvent {
///     message: String,
///     severity: u8,
/// }
/// ```
pub trait Event<'event>: FieldGetter<'event> {
    /// Returns the unique identifier for this event.
    ///
    /// The ID is used by rules to determine which events they apply to
    /// through the `match-on` directive.
    fn id(&self) -> i64;

    /// Returns the source of this event.
    ///
    /// The source is used by rules to determine which events they apply to
    /// through the `match-on` directive.
    fn source(&self) -> Cow<'_, str>;
}

/// Trait for fetching field values from structured data using XPath-like paths.
///
/// Implementors of this trait provide access to their fields through two methods:
/// - `get_from_path`: The primary interface using [`XPath`] expressions
/// - `get_from_iter`: A lower-level interface using path segment iterators
///
/// This trait is typically implemented automatically via the [`FieldGetter`] derive macro,
/// but can be implemented manually for custom data structures.
///
/// # Examples
///
/// ```
/// use gene::{FieldGetter, FieldValue, FieldNameIterator};
/// use std::net::IpAddr;
///
/// struct NetworkEvent {
///     source_ip: IpAddr,
///     destination_ip: IpAddr,
///     port: u16,
/// }
///
/// impl<'f> FieldGetter<'f> for NetworkEvent {
///     fn get_from_iter(
///         &'f self,
///         mut i: FieldNameIterator,
///     ) -> Option<FieldValue<'f>> {
///         match i.next_field_name() {
///             Some("source_ip") => Some(self.source_ip.to_string().into()),
///             Some("destination_ip") => Some(self.destination_ip.to_string().into()),
///             Some("port") => Some(self.port.into()),
///             _ => None,
///         }
///     }
/// }
/// ```
///
/// # Field Value Types
///
/// The trait returns [`FieldValue`] enum which can represent:
/// - Primitive types (numbers, booleans, strings)
/// - Complex types (IP addresses, paths, etc.)
/// - Collections (vectors, hash maps)
/// - Optional/nested values
///
/// Rules use these field values for pattern matching and condition evaluation.
pub trait FieldGetter<'field> {
    /// Gets a field value using an [`XPath`] expression.
    ///
    /// This is the primary method for field access and is called by the engine
    /// when evaluating rule conditions. The default implementation delegates
    /// to `get_from_iter` for convenience.
    ///
    /// # Arguments
    ///
    /// * `path` - The XPath expression identifying the field to retrieve
    ///
    /// # Returns
    ///
    /// * `Some(FieldValue)` if the field exists and can be accessed
    /// * `None` if the field does not exist or cannot be accessed
    ///
    /// # Notes
    ///
    /// Most implementations should rely on the default implementation and
    /// override [`Self::get_from_iter`] instead of overriding this method.
    #[inline]
    fn get_from_path(&'field self, path: &XPath) -> Option<FieldValue<'field>> {
        self.get_from_iter(FieldNameIterator::from(path))
    }

    /// Gets a field value using an iterator of path segments.
    ///
    /// This lower-level method provides direct access to path segments for
    /// implementors who need more control over path processing. It's called
    /// by the default implementation of `get_from_path`.
    ///
    /// # Arguments
    ///
    /// * `i` - An iterator over the path segments
    ///
    /// # Returns
    ///
    /// * `Some(FieldValue)` if the field exists and can be accessed
    /// * `None` if the field does not exist or cannot be accessed
    fn get_from_iter(&'field self, i: FieldNameIterator<'_>) -> Option<FieldValue<'field>>;
}

macro_rules! impl_with_getter {
    ($(($type:ty, $getter:tt)),*) => {
        $(
            impl<'f> FieldGetter<'f> for $type {
                #[inline]
                fn get_from_iter(&'f self, i: FieldNameIterator<'_>) -> Option<FieldValue<'f>> {
                    if !i.is_terminal() {
                        return None;
                    }
                    Some(self.$getter().into())
                }
            }
        )*
    };
}

macro_rules! impl_for_type {
    ($($type: ty),*) => {
        $(
            impl<'f> FieldGetter<'f>  for $type {
                #[inline]
                fn get_from_iter(&'f self, i: FieldNameIterator<'_>) -> Option<FieldValue<'f>> {
                    if !i.is_terminal() {
                        return None;
                    }
                    Some(self.into())
                }
            }
        )*
    };
}

impl_for_type!(
    Cow<'_, str>,
    Cow<'_, PathBuf>,
    &'_ str,
    str,
    String,
    i8,
    i16,
    i32,
    i64,
    isize,
    u8,
    u16,
    u32,
    u64,
    usize,
    f32,
    f64,
    bool
);

impl_with_getter!(
    (Path, to_string_lossy),
    (PathBuf, to_string_lossy),
    (IpAddr, to_string)
);

impl<'field, T> FieldGetter<'field> for Option<T>
where
    T: FieldGetter<'field>,
{
    #[inline]
    fn get_from_iter(&'field self, i: FieldNameIterator<'_>) -> Option<FieldValue<'field>> {
        match self {
            Some(v) => v.get_from_iter(i),
            None => Some(FieldValue::None),
        }
    }
}

impl<'f, T> FieldGetter<'f> for HashMap<String, T>
where
    T: FieldGetter<'f>,
{
    #[inline]
    fn get_from_iter(&'f self, mut i: FieldNameIterator<'_>) -> Option<FieldValue<'f>> {
        let k = match i.next_field_name() {
            Some(s) => s,
            None => {
                // No key to look up, return Some to indicate map existence
                return Some(FieldValue::Some);
            }
        };

        self.get(k)?.get_from_iter(i)
    }
}

macro_rules! impl_field_getter_for_vec {
    ($($ty:ty),*) => {
        $(
            impl<'f> FieldGetter<'f> for Vec<$ty>
            where
                $ty: Into<FieldValue<'f>>,
            {
                #[inline]
                fn get_from_iter(
                    &'f self,
                    i: FieldNameIterator<'_>,
                ) -> Option<FieldValue<'f>> {
                    if !i.is_terminal(){
                        return None;
                    }

                    Some(FieldValue::Vector(self.iter().map(|v| v.into()).collect()))
                }
            }
        )*
    };
}

// Apply the macro for common types
impl_field_getter_for_vec!(
    String,
    Cow<'f, str>,
    Cow<'f, PathBuf>,
    &'f str,
    i8,
    i16,
    i32,
    i64,
    u8,
    u16,
    u32,
    u64,
    f32,
    f64,
    bool
);

#[cfg(test)]
mod test {
    use std::str::FromStr;

    use gene_derive::{Event, FieldGetter};
    use serde::Deserialize;

    use super::*;

    macro_rules! path {
        ($p:literal) => {
            XPath::from_str($p).unwrap()
        };
    }

    #[derive(FieldGetter, Deserialize, Default)]
    #[getter(use_serde_rename)]
    struct LogData {
        some_float: f32,
        #[serde(rename = "serde_renamed")]
        some_string: String,
        #[getter(rename = "event_id")]
        id: i64,
        #[getter(skip)]
        #[allow(dead_code)]
        osef: u32,
        path: PathBuf,
    }

    // this is just a show case, it would be
    // shorter to set source = "test".into()
    #[inline]
    fn source() -> Cow<'static, str> {
        "test".into()
    }

    #[derive(Event, FieldGetter, Default)]
    #[event(id = self.data.id, source = source())]
    struct LogEntry<T>
    where
        T: Default,
    {
        name: String,
        data: LogData,
        t: T,
    }

    #[test]
    fn test_derive_event() {
        let entry = LogEntry::<i64> {
            name: "SomeLogEntry".into(),
            data: LogData {
                some_float: 4242.0,
                some_string: "some string".into(),
                id: 42,
                osef: 34,
                path: PathBuf::from("/absolute/path"),
            },
            t: 24,
        };

        assert_eq!(
            entry.get_from_path(&path!(".name")),
            Some("SomeLogEntry".into())
        );
        assert_eq!(
            entry.get_from_path(&path!(".data.some_float")),
            Some(4242.0.into())
        );

        // test that event id is generated correctly
        assert_eq!(entry.id(), 42);

        // check that #[event(rename)] worked
        assert_eq!(
            entry.get_from_path(&path!(".data.event_id")),
            Some(42i64.into())
        );
        // even if renamed we should still be able to reach via the real field name
        assert_eq!(entry.get_from_path(&path!(".data.id")), Some(42i64.into()));

        // check that #[serde(rename)] worked
        assert_eq!(
            entry.get_from_path(&path!(".data.serde_renamed")),
            Some("some string".into())
        );

        // check that #[event(skip)] worked
        assert_eq!(entry.get_from_path(&path!(".data.osef")), None,);

        assert_eq!(entry.get_from_path(&path!(".t")), Some(24.into()));

        // getting a PathBuf must return a FieldValue::String
        assert_eq!(
            entry.get_from_path(&path!(".data.path")),
            Some("/absolute/path".into())
        );

        // checking that source function got generated properly
        assert_eq!(entry.source(), "test");
    }

    #[test]
    // test reproducing https://github.com/0xrawsec/gene-rs/issues/1
    fn test_option_bug() {
        #[derive(FieldGetter, Debug)]
        pub struct SomeStruct {
            some_value: u64,
        }

        #[derive(Event, FieldGetter, Debug)]
        #[event(id = 1, source = "whatever".into())]
        pub struct SomeEvent {
            pub type_id: String,
            pub data: Option<SomeStruct>,
        }

        let event = SomeEvent {
            type_id: "some_id".to_string(),
            data: Some(SomeStruct { some_value: 1 }),
        };

        assert_eq!(
            event.get_from_path(&path!(".type_id")),
            Some("some_id".into())
        );

        assert_eq!(
            event.get_from_path(&path!(".data.some_value")),
            Some(1u64.into())
        );

        // if value is not known, it must at least return FieldValue::Some
        assert!(event.get_from_path(&path!(".data")).is_some());
        // None must be returned if trying to get a non existing field
        assert!(event.get_from_path(&path!(".unknown")).is_none());
    }

    #[test]
    fn test_vec_field_getter() {
        // Test in a struct context
        #[derive(FieldGetter)]
        struct TestStruct {
            items: Vec<String>,
            numbers: Vec<i32>,
        }

        let test_struct = TestStruct {
            items: vec!["first".into(), "second".into()],
            numbers: vec![10, 20, 30],
        };

        // Test accessing vec fields directly
        assert!(test_struct
            .get_from_path(&path!(".items"))
            .unwrap()
            .is_vector());

        assert!(test_struct
            .get_from_path(&path!(".numbers"))
            .unwrap()
            .is_vector());

        // Test that nested access returns None (as expected by the implementation)
        assert!(test_struct.get_from_path(&path!(".items.0")).is_none());
        assert!(test_struct
            .get_from_path(&path!(".numbers.first"))
            .is_none());
    }

    #[test]
    fn test_hashmap_field_getter() {
        use std::collections::HashMap;

        // Test direct HashMap implementation
        let mut map = HashMap::new();
        map.insert("name".to_string(), "test".to_string());

        // Test accessing existing keys
        assert_eq!(map.get_from_path(&path!(".name")), Some("test".into()));

        // Test accessing non-existing keys
        assert_eq!(map.get_from_path(&path!(".unknown")), None);

        // Test that nested access returns None (more than one segment)
        assert_eq!(map.get_from_path(&path!(".name.nested")), None);

        // Test in a struct context
        #[derive(FieldGetter)]
        struct TestStruct {
            data: HashMap<String, String>,
            metadata: HashMap<String, i32>,
        }

        let mut data_map = HashMap::new();
        data_map.insert("key1".to_string(), "value1".to_string());
        data_map.insert("key2".to_string(), "value2".to_string());

        let mut metadata_map = HashMap::new();
        metadata_map.insert("count".to_string(), 100);
        metadata_map.insert("size".to_string(), 200);

        let test_struct = TestStruct {
            data: data_map,
            metadata: metadata_map,
        };

        // Test accessing hashmap fields directly
        assert_eq!(
            test_struct.get_from_path(&path!(".data")),
            Some(FieldValue::Some)
        );
        assert_eq!(
            test_struct.get_from_path(&path!(".metadata")),
            Some(FieldValue::Some)
        );

        // Test accessing nested hashmap values
        assert_eq!(
            test_struct.get_from_path(&path!(".data.key1")),
            Some("value1".into())
        );
        assert_eq!(
            test_struct.get_from_path(&path!(".metadata.count")),
            Some(100i32.into())
        );

        // Test accessing non-existing nested keys
        assert_eq!(test_struct.get_from_path(&path!(".data.unknown")), None);
        assert_eq!(test_struct.get_from_path(&path!(".metadata.missing")), None);
    }
}