grippo 0.1.0

Parse, match and scrub data at scale.
Documentation
// Project:   grippo
// File:      src/format/leef.rs
// Purpose:   The Log Event Extended Format parser, versions 1.0 and 2.0
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! `LEEF:Version|Vendor|Product|ProductVersion|EventID|` then attributes.
//!
//! LEEF 1.0 separates attributes with a tab. LEEF 2.0 adds a header field
//! naming the separator, as one character or as hex (`x5E`, `0x5E`), with a
//! tab when it is empty. Each attribute is `key=value`, split at its first `=`.

use crate::parse::{FieldSink, FieldValue, Hint, ParseError, Parsed, Parser};
use crate::strmatch::Signature;
use crate::tier::MatcherTier;

/// The header field names, in order.
pub const HEADER: [&str; 5] = [
    "version",
    "vendor",
    "product",
    "product_version",
    "event_id",
];

/// The LEEF parser, registered as `leef`.
#[derive(Debug, Clone)]
pub struct Leef {
    signature: Signature,
}

impl Default for Leef {
    fn default() -> Self {
        Self::new()
    }
}

impl Leef {
    /// A LEEF parser.
    ///
    /// # Panics
    ///
    /// Never: the signature's literal is fixed and non-empty.
    #[must_use]
    pub fn new() -> Self {
        let signature = Signature::builder()
            .anchored(["LEEF:"])
            .verify(|span, _| pipes::<5>(span).is_some())
            .build()
            .unwrap_or_else(|_| unreachable!("invariant: `LEEF:` is a non-empty literal"));
        Self { signature }
    }
}

/// The first `N` unescaped `|` after `LEEF:`, or `None` with fewer.
fn pipes<const N: usize>(span: &[u8]) -> Option<[usize; N]> {
    let mut ends = [0; N];
    let mut found = 0;
    let mut i = 5;
    while found < N {
        match span.get(i)? {
            b'\\' => i += 2,
            b'|' => {
                ends[found] = i;
                found += 1;
                i += 1;
            }
            _ => i += 1,
        }
    }
    Some(ends)
}

/// LEEF 2.0's separator field: one byte, or `xHH` / `0xHH`. Empty is a tab.
fn separator(field: &[u8]) -> Option<u8> {
    let hex = field
        .strip_prefix(b"0x")
        .or_else(|| field.strip_prefix(b"x"))
        .filter(|h| h.len() == 2);
    match (field, hex) {
        ([], _) => Some(b'\t'),
        (_, Some(h)) => u8::from_str_radix(std::str::from_utf8(h).ok()?, 16).ok(),
        ([one], None) => Some(*one),
        _ => None,
    }
}

impl Parser for Leef {
    fn name(&self) -> &'static str {
        "leef"
    }

    fn tier(&self) -> MatcherTier {
        MatcherTier::Field
    }

    fn signature(&self) -> &Signature {
        &self.signature
    }

    fn parse<'a>(
        &self,
        input: &'a [u8],
        out: &mut dyn FieldSink<'a>,
    ) -> Result<Parsed, ParseError> {
        if !input.starts_with(b"LEEF:") {
            return Ok(Parsed::NoMatch);
        }
        let Some(ends) = pipes::<6>(input)
            .or_else(|| pipes::<5>(input).map(|e| [e[0], e[1], e[2], e[3], e[4], usize::MAX]))
        else {
            return Ok(Parsed::NoMatch);
        };
        let v2 = input[5..ends[0]].starts_with(b"2");
        let (sep, attrs_at) = if v2 {
            if ends[5] == usize::MAX {
                return Ok(Parsed::NoMatch);
            }
            let Some(sep) = separator(&input[ends[4] + 1..ends[5]]) else {
                return Err(ParseError::Malformed {
                    offset: ends[4] + 1,
                    reason: "a LEEF 2.0 separator that is not one character or xHH",
                });
            };
            (sep, ends[5] + 1)
        } else {
            (b'\t', ends[4] + 1)
        };
        let mut start = 5;
        for (name, end) in HEADER.iter().zip(ends) {
            out.field(name, FieldValue::borrowed(&input[start..end], Hint::Text));
            start = end + 1;
        }
        let trail = input
            .iter()
            .rev()
            .take_while(|&&b| matches!(b, b'\n' | b'\r'))
            .count();
        let attrs = &input[attrs_at.min(input.len() - trail)..input.len() - trail];
        for pair in attrs.split(|&b| b == sep) {
            let Some(eq) = pair.iter().position(|&b| b == b'=') else {
                continue;
            };
            let Ok(key) = std::str::from_utf8(&pair[..eq]) else {
                continue;
            };
            if !key.is_empty() {
                out.field(key, FieldValue::borrowed(&pair[eq + 1..], Hint::Text));
            }
        }
        Ok(Parsed::Done)
    }
}

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

    fn parse(line: &str) -> (Result<Parsed, ParseError>, Vec<(String, String)>) {
        let mut out = Fields::new();
        let p = Leef::new().parse(line.as_bytes(), &mut out);
        let fields = out
            .as_slice()
            .iter()
            .map(|(n, v)| (n.clone(), String::from_utf8_lossy(&v.bytes).into_owned()))
            .collect();
        (p, fields)
    }

    fn get<'f>(fields: &'f [(String, String)], name: &str) -> Option<&'f str> {
        fields
            .iter()
            .find(|(n, _)| n == name)
            .map(|(_, v)| v.as_str())
    }

    #[test]
    fn leef_1_uses_tabs() {
        let (p, f) = parse(
            "LEEF:1.0|Microsoft|MSExchange|4.0 SP1|15345|src=10.50.1.1\tdst=2.10.20.20\tsev=5\n",
        );
        assert!(matches!(p, Ok(Parsed::Done)));
        assert_eq!(get(&f, "vendor"), Some("Microsoft"));
        assert_eq!(get(&f, "product_version"), Some("4.0 SP1"));
        assert_eq!(get(&f, "event_id"), Some("15345"));
        assert_eq!(get(&f, "src"), Some("10.50.1.1"));
        assert_eq!(get(&f, "sev"), Some("5"));
    }

    #[test]
    fn leef_2_names_its_separator() {
        let (_, f) =
            parse("LEEF:2.0|Lancope|StealthWatch|1.0|41|^|src=10.0.1.8^dst=10.0.0.5^msg=a=b c");
        assert_eq!(get(&f, "dst"), Some("10.0.0.5"));
        assert_eq!(
            get(&f, "msg"),
            Some("a=b c"),
            "a value keeps every = after the first"
        );
        let (_, f) = parse("LEEF:2.0|V|P|1|E|x7C|a=1|b=2");
        assert_eq!(get(&f, "b"), Some("2"), "x7C is |");
        let (_, f) = parse("LEEF:2.0|V|P|1|E|0x5E|a=1^b=2");
        assert_eq!(get(&f, "b"), Some("2"));
        let (_, f) = parse("LEEF:2.0|V|P|1|E||a=1\tb=2");
        assert_eq!(get(&f, "b"), Some("2"), "an empty separator field is a tab");
    }

    #[test]
    fn short_or_bad_records() {
        assert!(matches!(parse("LEEF:1.0|V|P|1").0, Ok(Parsed::NoMatch)));
        assert!(matches!(
            parse("LEEF:2.0|V|P|1|E|ab|x=1").0,
            Err(ParseError::Malformed { .. })
        ));
        let (p, f) = parse("LEEF:2.0|V|P|1|E|");
        assert!(matches!(p, Ok(Parsed::NoMatch)));
        assert_eq!(f, Vec::<(String, String)>::new());
        assert!(!Leef::new().signature().may_match(b"LEEF:1.0|V|P"));
    }
}