grippo 0.1.3

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 std::borrow::Cow;
use std::ops::Range;

use crate::parse::{FieldSink, FieldValue, Hint, ParseError, Parsed, Parser};
use crate::path::key_part;
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,
    }
}

/// The separator between a record's attributes: a tab, or LEEF 2.0's own.
fn attribute_separator(input: &[u8]) -> Option<u8> {
    let ends = pipes::<5>(input)?;
    if !input[5..ends[0]].starts_with(b"2") {
        return Some(b'\t');
    }
    let ends = pipes::<6>(input)?;
    separator(&input[ends[4] + 1..ends[5]])
}

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

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

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

    /// The reader undoes no escape, so a value goes in as it is, and is
    /// refused where it would end its field early: a header field holding an
    /// unescaped `|` or ending in a lone `\`, an attribute holding the
    /// separator or ending in a line end.
    fn escape_value(
        &self,
        input: &[u8],
        field: usize,
        at: Range<usize>,
        value: &[u8],
        out: &mut Vec<u8>,
    ) -> Option<Range<usize>> {
        if field < HEADER.len() {
            let mut i = 0;
            while i < value.len() {
                match value[i] {
                    b'\\' => i += 2,
                    b'|' => return None,
                    _ => i += 1,
                }
            }
            if i > value.len() {
                return None;
            }
        } else {
            let sep = if input.is_empty() {
                b'\t'
            } else {
                attribute_separator(input)?
            };
            if value.contains(&sep) || matches!(value.last(), Some(b'\n' | b'\r')) {
                return None;
            }
        }
        out.extend_from_slice(value);
        Some(at)
    }

    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_part(Cow::Borrowed(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 a_dotted_attribute_key_is_written_quoted_and_reads_back_whole() {
        for (name, value) in [(r#"["a.b"]"#, "1"), ("c", "2")] {
            let mut out = Fields::new();
            Leef::new()
                .parse(
                    b"LEEF:1.0|Microsoft|MSExchange|4.0 SP1|15345|a.b=1\tc=2\n",
                    &mut out,
                )
                .unwrap();
            let got = out
                .get(name)
                .map(|v| String::from_utf8_lossy(&v.bytes).into_owned());
            assert_eq!(got.as_deref(), Some(value), "{name}");
            #[cfg(feature = "record")]
            {
                use crate::record::Record;
                let keys: Vec<_> = crate::path::keys(name).collect();
                let at = (&out).find(&keys[..]).unwrap();
                assert_eq!((&out).text(at).unwrap(), value, "{name}");
            }
        }
    }

    #[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"));
    }

    /// `value` written as field `field` of `record`, `None` when refused.
    fn escaped(record: &str, field: usize, value: &str) -> Option<String> {
        let mut out = Vec::new();
        let at = 0..0;
        let span =
            Leef::new().escape_value(record.as_bytes(), field, at, value.as_bytes(), &mut out);
        span.map(|_| String::from_utf8(out).unwrap())
    }

    #[test]
    fn values_go_in_as_they_are_or_are_refused() {
        let v1 = "LEEF:1.0|V|P|1|E|a=1";
        let v2 = "LEEF:2.0|V|P|1|E|^|a=1";
        let cases: &[(&str, usize, &str, Option<&str>)] = &[
            (v1, 1, r"a\|b", Some(r"a\|b")),
            (v1, 1, "a|b", None),
            (v1, 1, "ends\\", None),
            (v1, 1, r"a\\", Some(r"a\\")),
            (v1, 5, "a=b|c ^", Some("a=b|c ^")),
            (v1, 5, "a\tb", None),
            (v1, 5, "ends\n", None),
            (v2, 5, "a\tb", Some("a\tb")),
            (v2, 5, "a^b", None),
            ("LEEF:2.0|V|P|1|E|bad|a=1", 5, "a", None),
            ("", 5, "a=b", Some("a=b")),
        ];
        for &(record, field, value, want) in cases {
            let got = escaped(record, field, value);
            assert_eq!(got.as_deref(), want, "{record} {field} {value:?}");
        }
    }

    proptest::proptest! {
        /// A header field and an attribute the escaper takes read back as
        /// written, in LEEF 1.0 and 2.0.
        #[test]
        fn a_written_value_reads_back(
            vendor in r"[a-z|\\= ^\t]{0,12}",
            value in r"[a-z|\\= ^\t\n]{0,12}",
            v2 in proptest::bool::ANY,
        ) {
            let head = if v2 { "LEEF:2.0|V|P|1|E|^|" } else { "LEEF:1.0|V|P|1|E|" };
            let sep = if v2 { "^" } else { "\t" };
            let record = format!("{head}a=1{sep}z=2");
            let (Some(vendor_out), Some(value_out)) =
                (escaped(&record, 1, &vendor), escaped(&record, 5, &value))
            else {
                return Ok(());
            };
            let head = head.replacen("|V|", &format!("|{vendor_out}|"), 1);
            let (p, f) = parse(&format!("{head}a={value_out}{sep}z=2"));
            proptest::prop_assert!(matches!(p, Ok(Parsed::Done)));
            proptest::prop_assert_eq!(get(&f, "vendor"), Some(vendor.as_str()));
            proptest::prop_assert_eq!(get(&f, "a"), Some(value.as_str()));
            proptest::prop_assert_eq!(get(&f, "z"), Some("2"));
        }
    }
}