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