Skip to main content

goliath_normalize/
normalizer.rs

1//! Source definitions compiled for use, and records through them.
2
3use goliath_ocsf::schema::{self, Base};
4use goliath_rule::FieldPath;
5use serde_json::{Map, Value};
6
7use crate::definition::{Coercion, Decoding, FieldSpec, Framing, SourceDefinition};
8use crate::error::DefinitionError;
9
10/// A source definition, checked and compiled.
11///
12/// Built once, then used for every record of the source. Normalizing is
13/// deterministic: the same bytes under the same definition version always give
14/// the same outcome.
15#[derive(Debug, Clone)]
16pub struct Normalizer {
17    name: String,
18    version: u32,
19    framing: Framing,
20    kinds: Vec<Kind>,
21}
22
23#[derive(Debug, Clone)]
24struct Kind {
25    name: String,
26    when: Vec<(SourcePath, Value)>,
27    /// `class_uid`, `category_uid`, `type_uid`, and `activity_id`.
28    class: Vec<(&'static str, Value)>,
29    /// The common fields, then the kind's own.
30    fields: Vec<Field>,
31    unmapped: Vec<SourcePath>,
32}
33
34#[derive(Debug, Clone)]
35struct Field {
36    target: FieldPath,
37    source: Source,
38}
39
40#[derive(Debug, Clone)]
41enum Source {
42    Constant(Value),
43    Path {
44        path: SourcePath,
45        coercion: Option<Coercion>,
46    },
47}
48
49/// A dotted path into a decoded record. Unlike an OCSF path, it names exactly
50/// one value: records are read, not searched.
51#[derive(Debug, Clone, PartialEq, Eq)]
52struct SourcePath {
53    text: String,
54    segments: Vec<String>,
55}
56
57impl SourcePath {
58    fn parse(text: &str) -> Option<Self> {
59        let segments: Vec<String> = text.split('.').map(str::to_owned).collect();
60        segments
61            .iter()
62            .all(|segment| !segment.is_empty())
63            .then(|| Self {
64                text: text.to_owned(),
65                segments,
66            })
67    }
68
69    fn lookup<'a>(&self, record: &'a Value) -> Option<&'a Value> {
70        self.segments
71            .iter()
72            .try_fold(record, |value, segment| value.get(segment.as_str()))
73    }
74
75    /// Whether this path names the member `key` of the object at `object`.
76    fn is_member(&self, object: &Self, key: &str) -> bool {
77        self.segments.len() == object.segments.len() + 1
78            && self.segments.starts_with(&object.segments)
79            && self.segments.last().is_some_and(|last| last == key)
80    }
81
82    fn last(&self) -> &str {
83        self.segments.last().map_or("", String::as_str)
84    }
85}
86
87/// What became of one record.
88#[non_exhaustive]
89#[derive(Debug, Clone, PartialEq)]
90pub enum Outcome {
91    /// The record became an OCSF event.
92    Event(Normalized),
93    /// The record could not become an event, and is kept whole.
94    DeadLetter(DeadLetter),
95}
96
97/// An OCSF event, and anything that did not convert on the way.
98#[non_exhaustive]
99#[derive(Debug, Clone, PartialEq)]
100pub struct Normalized {
101    /// Identifies the record the event came from, so that storage can drop
102    /// a record delivered twice.
103    pub id: EventId,
104    /// The event.
105    pub event: Value,
106    /// The kind of record it was.
107    pub kind: String,
108    /// Values that did not convert. Each is kept as written under
109    /// `unmapped`, and the event is still produced, so that a malformed field
110    /// cannot keep an event away from detection.
111    pub issues: Vec<Issue>,
112}
113
114/// The identity of a record: 128 bits of the BLAKE3 hash of the source's
115/// name and the record's raw bytes.
116///
117/// It depends on nothing else, so a record delivered again, or collected
118/// again, gets the same identity and can be dropped as a duplicate. Two
119/// records with identical bytes from one source are the same record.
120///
121/// The hash is cryptographic on purpose. Whoever writes the logs chooses the
122/// bytes, and with a hash built only for speed they could craft a record
123/// whose identity equals that of another, and have storage drop one of the
124/// two as a duplicate.
125#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
126pub struct EventId([u8; 16]);
127
128impl EventId {
129    /// Keys the hash, so that identities cannot be confused with any other
130    /// use of BLAKE3. Changing it changes every identity.
131    const CONTEXT: &str = "goliath 2026-09-25 event id";
132
133    /// The identity of the record `raw` from the source `source`.
134    pub fn of(source: &str, raw: &[u8]) -> Self {
135        let mut hasher = blake3::Hasher::new_derive_key(Self::CONTEXT);
136        // The name's length first, so that no name and record pair can end
137        // where another pair's name does.
138        hasher.update(&(source.len() as u64).to_le_bytes());
139        hasher.update(source.as_bytes());
140        hasher.update(raw);
141        let mut id = [0; 16];
142        hasher.finalize_xof().fill(&mut id);
143        Self(id)
144    }
145
146    /// The identity's bytes.
147    pub fn as_bytes(&self) -> &[u8; 16] {
148        &self.0
149    }
150}
151
152impl std::fmt::Display for EventId {
153    /// Lowercase hexadecimal.
154    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
155        self.0.iter().try_for_each(|byte| write!(f, "{byte:02x}"))
156    }
157}
158
159impl std::fmt::Debug for EventId {
160    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
161        write!(f, "EventId({self})")
162    }
163}
164
165/// A value that did not convert.
166#[non_exhaustive]
167#[derive(Debug, Clone, PartialEq, Eq)]
168pub struct Issue {
169    /// The OCSF attribute it was meant for.
170    pub target: String,
171    /// Where it was read from.
172    pub source: String,
173    /// Why it did not convert.
174    pub reason: String,
175}
176
177/// A record that could not become an event.
178///
179/// The raw bytes are kept exactly, so the record can be processed again once
180/// the source definition is fixed. Nothing a source sends is dropped.
181#[non_exhaustive]
182#[derive(Debug, Clone, PartialEq, Eq)]
183pub struct DeadLetter {
184    /// The stage that failed.
185    pub stage: Stage,
186    /// Why.
187    pub error: String,
188    /// The record as received; for a stream that could not be framed, the
189    /// rest of the stream.
190    pub raw: Vec<u8>,
191}
192
193/// A stage of normalization, in order.
194#[non_exhaustive]
195#[derive(Debug, Clone, Copy, PartialEq, Eq)]
196pub enum Stage {
197    /// Splitting the stream into records.
198    Framing,
199    /// Turning a record into a field map.
200    Decoding,
201    /// Choosing a kind and writing the OCSF event.
202    Mapping,
203}
204
205impl Stage {
206    /// The stage's name, as reports and metrics use it.
207    pub fn as_str(self) -> &'static str {
208        match self {
209            Self::Framing => "framing",
210            Self::Decoding => "decoding",
211            Self::Mapping => "mapping",
212        }
213    }
214}
215
216impl Normalizer {
217    /// Loads a source definition from YAML, as untrusted input.
218    ///
219    /// # Errors
220    ///
221    /// Returns [`DefinitionError`] if the YAML is not a valid definition.
222    pub fn from_yaml(text: &str) -> Result<Self, DefinitionError> {
223        let definition: SourceDefinition = goliath_sigma::yaml::from_str(text)?;
224        Self::new(&definition)
225    }
226
227    /// Checks and compiles a source definition.
228    ///
229    /// # Errors
230    ///
231    /// Returns [`DefinitionError`] if a path does not parse, two fields
232    /// would write over each other, a field writes an attribute that is set
233    /// otherwise, or a kind would accept every record; and if a class,
234    /// activity, or target is not in the OCSF schema, or a field writes a
235    /// value its attribute cannot hold.
236    pub fn new(definition: &SourceDefinition) -> Result<Self, DefinitionError> {
237        if definition.kinds.is_empty() {
238            return Err(DefinitionError::NoKinds);
239        }
240        let common = compile_fields("common", &definition.common)?;
241        let mut kinds = Vec::with_capacity(definition.kinds.len());
242        for kind in &definition.kinds {
243            if kind.when.is_empty() {
244                return Err(DefinitionError::Unconditional {
245                    kind: kind.name.clone(),
246                });
247            }
248            let when = kind
249                .when
250                .iter()
251                .map(|(path, value)| Ok((source_path(&kind.name, path)?, Value::from(value))))
252                .collect::<Result<_, DefinitionError>>()?;
253            let mut fields = common.clone();
254            fields.extend(compile_fields(&kind.name, &kind.fields)?);
255            check_overlaps(&kind.name, &fields)?;
256            check_schema(
257                &kind.name,
258                kind.class.class_uid,
259                kind.class.activity_id,
260                &fields,
261            )?;
262            let unmapped = kind
263                .unmapped
264                .iter()
265                .map(|path| source_path(&kind.name, path))
266                .collect::<Result<_, _>>()?;
267
268            let class_uid = kind.class.class_uid;
269            let activity_id = kind.class.activity_id;
270            let category_uid = goliath_ocsf::Event::derive_category_uid(class_uid);
271            let type_uid = goliath_ocsf::Event::derive_type_uid(class_uid, activity_id);
272            kinds.push(Kind {
273                name: kind.name.clone(),
274                when,
275                class: vec![
276                    ("class_uid", Value::from(class_uid)),
277                    ("category_uid", Value::from(category_uid)),
278                    ("type_uid", Value::from(type_uid)),
279                    ("activity_id", Value::from(activity_id)),
280                ],
281                fields,
282                unmapped,
283            });
284        }
285        // Only JSON exists so far; the match makes a new decoding a compile
286        // error here rather than a silent fallback.
287        match definition.decoding {
288            Decoding::Json => {}
289        }
290        Ok(Self {
291            name: definition.name.clone(),
292            version: definition.version,
293            framing: definition.framing,
294            kinds,
295        })
296    }
297
298    /// The source's name.
299    pub fn name(&self) -> &str {
300        &self.name
301    }
302
303    /// The definition's version, to be stored with every event it produces.
304    pub fn version(&self) -> u32 {
305        self.version
306    }
307
308    /// Splits `bytes` into records and normalizes each, calling `out` with
309    /// every outcome in order.
310    pub fn normalize(&self, bytes: &[u8], mut out: impl FnMut(Outcome)) {
311        match self.framing {
312            Framing::Lines => {
313                for line in bytes.split(|&byte| byte == b'\n') {
314                    let line = line.strip_suffix(b"\r").unwrap_or(line);
315                    if line.iter().all(u8::is_ascii_whitespace) {
316                        continue;
317                    }
318                    out(match serde_json::from_slice::<Value>(line) {
319                        Ok(record) => self.record(&record, line),
320                        Err(error) => dead(Stage::Decoding, error.to_string(), line),
321                    });
322                }
323            }
324            Framing::JsonValues => {
325                let mut stream = serde_json::Deserializer::from_slice(bytes).into_iter::<Value>();
326                let mut start = 0;
327                while let Some(next) = stream.next() {
328                    match next {
329                        Ok(record) => {
330                            let end = stream.byte_offset();
331                            out(self.record(&record, trim(&bytes[start..end])));
332                            start = end;
333                        }
334                        Err(error) => {
335                            // Where one value ends cannot be known once the
336                            // stream is broken, so the rest is kept together.
337                            out(dead(
338                                Stage::Framing,
339                                error.to_string(),
340                                trim(&bytes[start..]),
341                            ));
342                            return;
343                        }
344                    }
345                }
346            }
347        }
348    }
349
350    /// Normalizes one decoded record, whose raw bytes are `raw`.
351    fn record(&self, record: &Value, raw: &[u8]) -> Outcome {
352        if !record.is_object() {
353            return dead(
354                Stage::Decoding,
355                "the record is not a JSON object".to_owned(),
356                raw,
357            );
358        }
359        let Some(kind) = self.kinds.iter().find(|kind| {
360            kind.when
361                .iter()
362                .all(|(path, expected)| path.lookup(record) == Some(expected))
363        }) else {
364            return dead(
365                Stage::Mapping,
366                format!("no kind of source `{}` accepts the record", self.name),
367                raw,
368            );
369        };
370
371        let mut event = Map::new();
372        let mut unmapped = Map::new();
373        let mut issues = Vec::new();
374        let mut consumed: Vec<&SourcePath> = Vec::new();
375        for (name, value) in &kind.class {
376            event.insert((*name).to_owned(), value.clone());
377        }
378        for field in &kind.fields {
379            match &field.source {
380                Source::Constant(value) => set(&mut event, field.target.segments(), value.clone()),
381                Source::Path { path, coercion } => {
382                    let Some(found) = path.lookup(record).filter(|value| !value.is_null()) else {
383                        continue;
384                    };
385                    consumed.push(path);
386                    match coerce(found, *coercion) {
387                        Ok(value) => set(&mut event, field.target.segments(), value),
388                        Err(reason) => {
389                            issues.push(Issue {
390                                target: field.target.as_str().to_owned(),
391                                source: path.text.clone(),
392                                reason,
393                            });
394                            // Kept by the name the `unmapped` lists would give
395                            // it, or by its whole path where they give none,
396                            // so that it cannot take another member's name.
397                            let listed = kind
398                                .unmapped
399                                .iter()
400                                .any(|object| path.is_member(object, path.last()));
401                            let name = if listed { path.last() } else { &path.text };
402                            unmapped.insert(name.to_owned(), found.clone());
403                        }
404                    }
405                }
406            }
407        }
408        for object in &kind.unmapped {
409            let Some(Value::Object(members)) = object.lookup(record) else {
410                continue;
411            };
412            for (key, member) in members {
413                if member.is_null() || consumed.iter().any(|path| path.is_member(object, key)) {
414                    continue;
415                }
416                unmapped
417                    .entry(key.clone())
418                    .or_insert_with(|| member.clone());
419            }
420        }
421        if !unmapped.is_empty() {
422            event.insert("unmapped".to_owned(), Value::Object(unmapped));
423        }
424        Outcome::Event(Normalized {
425            id: EventId::of(&self.name, raw),
426            event: Value::Object(event),
427            kind: kind.name.clone(),
428            issues,
429        })
430    }
431}
432
433fn dead(stage: Stage, error: String, raw: &[u8]) -> Outcome {
434    Outcome::DeadLetter(DeadLetter {
435        stage,
436        error,
437        raw: raw.to_vec(),
438    })
439}
440
441fn trim(bytes: &[u8]) -> &[u8] {
442    let start = bytes
443        .iter()
444        .position(|byte| !byte.is_ascii_whitespace())
445        .unwrap_or(bytes.len());
446    let end = bytes
447        .iter()
448        .rposition(|byte| !byte.is_ascii_whitespace())
449        .map_or(start, |position| position + 1);
450    &bytes[start..end]
451}
452
453fn source_path(kind: &str, text: &str) -> Result<SourcePath, DefinitionError> {
454    SourcePath::parse(text).ok_or_else(|| DefinitionError::SourcePath {
455        kind: kind.to_owned(),
456        path: text.to_owned(),
457    })
458}
459
460fn compile_fields(
461    kind: &str,
462    specs: &std::collections::BTreeMap<String, FieldSpec>,
463) -> Result<Vec<Field>, DefinitionError> {
464    specs
465        .iter()
466        .map(|(target, spec)| {
467            let path = FieldPath::parse(target).map_err(|source| DefinitionError::Target {
468                kind: kind.to_owned(),
469                target: target.clone(),
470                source,
471            })?;
472            let reserved = match path.segments()[0].as_str() {
473                "class_uid" | "category_uid" | "type_uid" | "activity_id" => {
474                    Some("the kind's `class`")
475                }
476                "unmapped" => Some("the kind's `unmapped` list"),
477                _ => None,
478            };
479            if let Some(reason) = reserved {
480                return Err(DefinitionError::Reserved {
481                    kind: kind.to_owned(),
482                    target: target.clone(),
483                    reason,
484                });
485            }
486            let source = match spec {
487                FieldSpec::Path(from) => Source::Path {
488                    path: source_path(kind, from)?,
489                    coercion: None,
490                },
491                FieldSpec::Converted { from, coercion } => Source::Path {
492                    path: source_path(kind, from)?,
493                    coercion: Some(*coercion),
494                },
495                FieldSpec::Value { value } => Source::Constant(Value::from(value)),
496            };
497            Ok(Field {
498                target: path,
499                source,
500            })
501        })
502        .collect()
503}
504
505/// Rejects two fields writing the same attribute, or one inside another:
506/// the second write would replace or be lost under the first.
507fn check_overlaps(kind: &str, fields: &[Field]) -> Result<(), DefinitionError> {
508    for (index, first) in fields.iter().enumerate() {
509        for second in &fields[index + 1..] {
510            let (a, b) = (first.target.segments(), second.target.segments());
511            if a.starts_with(b) || b.starts_with(a) {
512                return Err(DefinitionError::Overlap {
513                    kind: kind.to_owned(),
514                    first: first.target.as_str().to_owned(),
515                    second: second.target.as_str().to_owned(),
516                });
517            }
518        }
519    }
520    Ok(())
521}
522
523/// Checks the class, the activity, and every field against the OCSF schema,
524/// so that a misspelled attribute fails here rather than produce events no
525/// rule reads.
526fn check_schema(
527    kind: &str,
528    class_uid: u32,
529    activity_id: u32,
530    fields: &[Field],
531) -> Result<(), DefinitionError> {
532    let class = schema::class(class_uid).ok_or_else(|| DefinitionError::UnknownClass {
533        kind: kind.to_owned(),
534        class_uid,
535        version: goliath_ocsf::SCHEMA_VERSION,
536    })?;
537    let activities = class
538        .attribute("activity_id")
539        .map(schema::Attribute::enum_values)
540        .unwrap_or_default();
541    if !activities.contains(&i64::from(activity_id)) {
542        return Err(DefinitionError::UnknownActivity {
543            kind: kind.to_owned(),
544            class: class.name(),
545            activity_id,
546        });
547    }
548    for field in fields {
549        let target = field.target.as_str();
550        let found = class
551            .resolve(target)
552            .map_err(|source| DefinitionError::Attribute {
553                kind: kind.to_owned(),
554                source,
555            })?;
556        if found.within_array {
557            return Err(DefinitionError::WithinArray {
558                kind: kind.to_owned(),
559                target: target.to_owned(),
560            });
561        }
562        // A copy keeps whatever the source holds, and a free-form attribute
563        // takes anything, so neither has a type to check.
564        let Some(writes) = field.source.writes() else {
565            continue;
566        };
567        if found.free_form {
568            continue;
569        }
570        let attribute = found.attribute;
571        let fits = !attribute.is_array()
572            && match writes {
573                Writes::Boolean => attribute.base() == Base::Boolean,
574                Writes::Integer => matches!(attribute.base(), Base::Integer | Base::Long),
575                Writes::Text => attribute.base() == Base::String,
576                Writes::Timestamp => attribute.type_name() == "timestamp_t",
577            };
578        if !fits {
579            let holds = match (attribute.is_array(), attribute.base()) {
580                (true, _) => format!("an array of `{}`", attribute.type_name()),
581                (false, Base::Object) => format!("an object `{}`", attribute.type_name()),
582                (false, _) => format!("`{}`", attribute.type_name()),
583            };
584            return Err(DefinitionError::Type {
585                kind: kind.to_owned(),
586                target: target.to_owned(),
587                holds,
588                writes: writes.describe(),
589            });
590        }
591        let values = attribute.enum_values();
592        if let Source::Constant(Value::Number(number)) = &field.source
593            && let Some(value) = number.as_i64()
594            && !values.is_empty()
595            && !values.contains(&value)
596        {
597            return Err(DefinitionError::UnknownValue {
598                kind: kind.to_owned(),
599                target: target.to_owned(),
600                value,
601            });
602        }
603    }
604    Ok(())
605}
606
607/// What a field writes, where that is known before any record is read.
608#[derive(Debug, Clone, Copy)]
609enum Writes {
610    Boolean,
611    Integer,
612    Text,
613    Timestamp,
614}
615
616impl Writes {
617    fn describe(self) -> &'static str {
618        match self {
619            Self::Boolean => "a boolean",
620            Self::Integer => "an integer",
621            Self::Text => "text",
622            Self::Timestamp => "a timestamp",
623        }
624    }
625}
626
627impl Source {
628    fn writes(&self) -> Option<Writes> {
629        match self {
630            Self::Constant(Value::Bool(_)) => Some(Writes::Boolean),
631            Self::Constant(Value::Number(_)) => Some(Writes::Integer),
632            Self::Constant(Value::String(_)) => Some(Writes::Text),
633            Self::Constant(_) | Self::Path { coercion: None, .. } => None,
634            Self::Path {
635                coercion: Some(coercion),
636                ..
637            } => Some(match coercion {
638                Coercion::String => Writes::Text,
639                Coercion::Integer => Writes::Integer,
640                Coercion::Timestamp => Writes::Timestamp,
641            }),
642        }
643    }
644}
645
646/// Writes `value` at `segments`, creating objects on the way. Overlapping
647/// targets are rejected when the definition is compiled, so the way is
648/// always clear.
649fn set(object: &mut Map<String, Value>, segments: &[String], value: Value) {
650    let Some((last, parents)) = segments.split_last() else {
651        return;
652    };
653    let mut object = object;
654    for segment in parents {
655        let child = object
656            .entry(segment.clone())
657            .or_insert_with(|| Value::Object(Map::new()));
658        let Value::Object(child) = child else {
659            return;
660        };
661        object = child;
662    }
663    object.insert(last.clone(), value);
664}
665
666fn coerce(value: &Value, coercion: Option<Coercion>) -> Result<Value, String> {
667    let Some(coercion) = coercion else {
668        return Ok(value.clone());
669    };
670    match (coercion, value) {
671        (Coercion::String, Value::String(_)) => Ok(value.clone()),
672        (Coercion::String, Value::Number(number)) => Ok(Value::String(number.to_string())),
673        (Coercion::Integer, Value::Number(number)) => number
674            .as_i64()
675            .map(Value::from)
676            .ok_or_else(|| format!("{number} is not a whole number")),
677        (Coercion::Integer, Value::String(text)) => text
678            .trim()
679            .parse::<i64>()
680            .map(Value::from)
681            .map_err(|_| format!("`{text}` is not a whole number")),
682        (Coercion::Timestamp, Value::String(text)) => text
683            .parse::<jiff::Timestamp>()
684            .map(|time| Value::from(time.as_millisecond()))
685            .map_err(|error| format!("`{text}` is not an RFC 3339 time: {error}")),
686        (coercion, other) => Err(format!(
687            "cannot convert {} to {coercion:?}",
688            describe(other)
689        )),
690    }
691}
692
693fn describe(value: &Value) -> &'static str {
694    match value {
695        Value::Null => "null",
696        Value::Bool(_) => "a boolean",
697        Value::Number(_) => "a number",
698        Value::String(_) => "text",
699        Value::Array(_) => "a list",
700        Value::Object(_) => "an object",
701    }
702}