Skip to main content

goliath_normalize/
normalizer.rs

1//! Source definitions compiled for use, and records through them.
2
3use goliath_rule::FieldPath;
4use serde_json::{Map, Value};
5
6use crate::definition::{Coercion, Decoding, FieldSpec, Framing, SourceDefinition};
7use crate::error::DefinitionError;
8
9/// A source definition, checked and compiled.
10///
11/// Built once, then used for every record of the source. Normalizing is
12/// deterministic: the same bytes under the same definition version always give
13/// the same outcome.
14#[derive(Debug, Clone)]
15pub struct Normalizer {
16    name: String,
17    version: u32,
18    framing: Framing,
19    kinds: Vec<Kind>,
20}
21
22#[derive(Debug, Clone)]
23struct Kind {
24    name: String,
25    when: Vec<(SourcePath, Value)>,
26    /// `class_uid`, `category_uid`, `type_uid`, and `activity_id`.
27    class: Vec<(&'static str, Value)>,
28    /// The common fields, then the kind's own.
29    fields: Vec<Field>,
30    unmapped: Vec<SourcePath>,
31}
32
33#[derive(Debug, Clone)]
34struct Field {
35    target: FieldPath,
36    source: Source,
37}
38
39#[derive(Debug, Clone)]
40enum Source {
41    Constant(Value),
42    Path {
43        path: SourcePath,
44        coercion: Option<Coercion>,
45    },
46}
47
48/// A dotted path into a decoded record. Unlike an OCSF path, it names exactly
49/// one value: records are read, not searched.
50#[derive(Debug, Clone, PartialEq, Eq)]
51struct SourcePath {
52    text: String,
53    segments: Vec<String>,
54}
55
56impl SourcePath {
57    fn parse(text: &str) -> Option<Self> {
58        let segments: Vec<String> = text.split('.').map(str::to_owned).collect();
59        segments
60            .iter()
61            .all(|segment| !segment.is_empty())
62            .then(|| Self {
63                text: text.to_owned(),
64                segments,
65            })
66    }
67
68    fn lookup<'a>(&self, record: &'a Value) -> Option<&'a Value> {
69        self.segments
70            .iter()
71            .try_fold(record, |value, segment| value.get(segment.as_str()))
72    }
73
74    /// Whether this path names the member `key` of the object at `object`.
75    fn is_member(&self, object: &Self, key: &str) -> bool {
76        self.segments.len() == object.segments.len() + 1
77            && self.segments.starts_with(&object.segments)
78            && self.segments.last().is_some_and(|last| last == key)
79    }
80
81    fn last(&self) -> &str {
82        self.segments.last().map_or("", String::as_str)
83    }
84}
85
86/// What became of one record.
87#[non_exhaustive]
88#[derive(Debug, Clone, PartialEq)]
89pub enum Outcome {
90    /// The record became an OCSF event.
91    Event(Normalized),
92    /// The record could not become an event, and is kept whole.
93    DeadLetter(DeadLetter),
94}
95
96/// An OCSF event, and anything that did not convert on the way.
97#[non_exhaustive]
98#[derive(Debug, Clone, PartialEq)]
99pub struct Normalized {
100    /// The event.
101    pub event: Value,
102    /// The kind of record it was.
103    pub kind: String,
104    /// Values that did not convert. Each is kept as written under
105    /// `unmapped`, and the event is still produced, so that a malformed field
106    /// cannot keep an event away from detection.
107    pub issues: Vec<Issue>,
108}
109
110/// A value that did not convert.
111#[non_exhaustive]
112#[derive(Debug, Clone, PartialEq, Eq)]
113pub struct Issue {
114    /// The OCSF attribute it was meant for.
115    pub target: String,
116    /// Where it was read from.
117    pub source: String,
118    /// Why it did not convert.
119    pub reason: String,
120}
121
122/// A record that could not become an event.
123///
124/// The raw bytes are kept exactly, so the record can be processed again once
125/// the source definition is fixed. Nothing a source sends is dropped.
126#[non_exhaustive]
127#[derive(Debug, Clone, PartialEq, Eq)]
128pub struct DeadLetter {
129    /// The stage that failed.
130    pub stage: Stage,
131    /// Why.
132    pub error: String,
133    /// The record as received; for a stream that could not be framed, the
134    /// rest of the stream.
135    pub raw: Vec<u8>,
136}
137
138/// A stage of normalization, in order.
139#[non_exhaustive]
140#[derive(Debug, Clone, Copy, PartialEq, Eq)]
141pub enum Stage {
142    /// Splitting the stream into records.
143    Framing,
144    /// Turning a record into a field map.
145    Decoding,
146    /// Choosing a kind and writing the OCSF event.
147    Mapping,
148}
149
150impl Stage {
151    /// The stage's name, as reports and metrics use it.
152    pub fn as_str(self) -> &'static str {
153        match self {
154            Self::Framing => "framing",
155            Self::Decoding => "decoding",
156            Self::Mapping => "mapping",
157        }
158    }
159}
160
161impl Normalizer {
162    /// Loads a source definition from YAML, as untrusted input.
163    ///
164    /// # Errors
165    ///
166    /// Returns [`DefinitionError`] if the YAML is not a valid definition.
167    pub fn from_yaml(text: &str) -> Result<Self, DefinitionError> {
168        let definition: SourceDefinition = goliath_sigma::yaml::from_str(text)?;
169        Self::new(&definition)
170    }
171
172    /// Checks and compiles a source definition.
173    ///
174    /// # Errors
175    ///
176    /// Returns [`DefinitionError`] if a path does not parse, two fields
177    /// would write over each other, a field writes an attribute that is set
178    /// otherwise, or a kind would accept every record.
179    pub fn new(definition: &SourceDefinition) -> Result<Self, DefinitionError> {
180        if definition.kinds.is_empty() {
181            return Err(DefinitionError::NoKinds);
182        }
183        let common = compile_fields("common", &definition.common)?;
184        let mut kinds = Vec::with_capacity(definition.kinds.len());
185        for kind in &definition.kinds {
186            if kind.when.is_empty() {
187                return Err(DefinitionError::Unconditional {
188                    kind: kind.name.clone(),
189                });
190            }
191            let when = kind
192                .when
193                .iter()
194                .map(|(path, value)| Ok((source_path(&kind.name, path)?, Value::from(value))))
195                .collect::<Result<_, DefinitionError>>()?;
196            let mut fields = common.clone();
197            fields.extend(compile_fields(&kind.name, &kind.fields)?);
198            check_overlaps(&kind.name, &fields)?;
199            let unmapped = kind
200                .unmapped
201                .iter()
202                .map(|path| source_path(&kind.name, path))
203                .collect::<Result<_, _>>()?;
204
205            let class_uid = kind.class.class_uid;
206            let activity_id = kind.class.activity_id;
207            let category_uid = goliath_ocsf::Event::derive_category_uid(class_uid);
208            let type_uid = goliath_ocsf::Event::derive_type_uid(class_uid, activity_id);
209            kinds.push(Kind {
210                name: kind.name.clone(),
211                when,
212                class: vec![
213                    ("class_uid", Value::from(class_uid)),
214                    ("category_uid", Value::from(category_uid)),
215                    ("type_uid", Value::from(type_uid)),
216                    ("activity_id", Value::from(activity_id)),
217                ],
218                fields,
219                unmapped,
220            });
221        }
222        // Only JSON exists so far; the match makes a new decoding a compile
223        // error here rather than a silent fallback.
224        match definition.decoding {
225            Decoding::Json => {}
226        }
227        Ok(Self {
228            name: definition.name.clone(),
229            version: definition.version,
230            framing: definition.framing,
231            kinds,
232        })
233    }
234
235    /// The source's name.
236    pub fn name(&self) -> &str {
237        &self.name
238    }
239
240    /// The definition's version, to be stored with every event it produces.
241    pub fn version(&self) -> u32 {
242        self.version
243    }
244
245    /// Splits `bytes` into records and normalizes each, calling `out` with
246    /// every outcome in order.
247    pub fn normalize(&self, bytes: &[u8], mut out: impl FnMut(Outcome)) {
248        match self.framing {
249            Framing::Lines => {
250                for line in bytes.split(|&byte| byte == b'\n') {
251                    let line = line.strip_suffix(b"\r").unwrap_or(line);
252                    if line.iter().all(u8::is_ascii_whitespace) {
253                        continue;
254                    }
255                    out(match serde_json::from_slice::<Value>(line) {
256                        Ok(record) => self.record(&record, line),
257                        Err(error) => dead(Stage::Decoding, error.to_string(), line),
258                    });
259                }
260            }
261            Framing::JsonValues => {
262                let mut stream = serde_json::Deserializer::from_slice(bytes).into_iter::<Value>();
263                let mut start = 0;
264                while let Some(next) = stream.next() {
265                    match next {
266                        Ok(record) => {
267                            let end = stream.byte_offset();
268                            out(self.record(&record, trim(&bytes[start..end])));
269                            start = end;
270                        }
271                        Err(error) => {
272                            // Where one value ends cannot be known once the
273                            // stream is broken, so the rest is kept together.
274                            out(dead(
275                                Stage::Framing,
276                                error.to_string(),
277                                trim(&bytes[start..]),
278                            ));
279                            return;
280                        }
281                    }
282                }
283            }
284        }
285    }
286
287    /// Normalizes one decoded record, whose raw bytes are `raw`.
288    fn record(&self, record: &Value, raw: &[u8]) -> Outcome {
289        if !record.is_object() {
290            return dead(
291                Stage::Decoding,
292                "the record is not a JSON object".to_owned(),
293                raw,
294            );
295        }
296        let Some(kind) = self.kinds.iter().find(|kind| {
297            kind.when
298                .iter()
299                .all(|(path, expected)| path.lookup(record) == Some(expected))
300        }) else {
301            return dead(
302                Stage::Mapping,
303                format!("no kind of source `{}` accepts the record", self.name),
304                raw,
305            );
306        };
307
308        let mut event = Map::new();
309        let mut unmapped = Map::new();
310        let mut issues = Vec::new();
311        let mut consumed: Vec<&SourcePath> = Vec::new();
312        for (name, value) in &kind.class {
313            event.insert((*name).to_owned(), value.clone());
314        }
315        for field in &kind.fields {
316            match &field.source {
317                Source::Constant(value) => set(&mut event, field.target.segments(), value.clone()),
318                Source::Path { path, coercion } => {
319                    let Some(found) = path.lookup(record).filter(|value| !value.is_null()) else {
320                        continue;
321                    };
322                    consumed.push(path);
323                    match coerce(found, *coercion) {
324                        Ok(value) => set(&mut event, field.target.segments(), value),
325                        Err(reason) => {
326                            issues.push(Issue {
327                                target: field.target.as_str().to_owned(),
328                                source: path.text.clone(),
329                                reason,
330                            });
331                            // Kept by the name the `unmapped` lists would give
332                            // it, or by its whole path where they give none,
333                            // so that it cannot take another member's name.
334                            let listed = kind
335                                .unmapped
336                                .iter()
337                                .any(|object| path.is_member(object, path.last()));
338                            let name = if listed { path.last() } else { &path.text };
339                            unmapped.insert(name.to_owned(), found.clone());
340                        }
341                    }
342                }
343            }
344        }
345        for object in &kind.unmapped {
346            let Some(Value::Object(members)) = object.lookup(record) else {
347                continue;
348            };
349            for (key, member) in members {
350                if member.is_null() || consumed.iter().any(|path| path.is_member(object, key)) {
351                    continue;
352                }
353                unmapped
354                    .entry(key.clone())
355                    .or_insert_with(|| member.clone());
356            }
357        }
358        if !unmapped.is_empty() {
359            event.insert("unmapped".to_owned(), Value::Object(unmapped));
360        }
361        Outcome::Event(Normalized {
362            event: Value::Object(event),
363            kind: kind.name.clone(),
364            issues,
365        })
366    }
367}
368
369fn dead(stage: Stage, error: String, raw: &[u8]) -> Outcome {
370    Outcome::DeadLetter(DeadLetter {
371        stage,
372        error,
373        raw: raw.to_vec(),
374    })
375}
376
377fn trim(bytes: &[u8]) -> &[u8] {
378    let start = bytes
379        .iter()
380        .position(|byte| !byte.is_ascii_whitespace())
381        .unwrap_or(bytes.len());
382    let end = bytes
383        .iter()
384        .rposition(|byte| !byte.is_ascii_whitespace())
385        .map_or(start, |position| position + 1);
386    &bytes[start..end]
387}
388
389fn source_path(kind: &str, text: &str) -> Result<SourcePath, DefinitionError> {
390    SourcePath::parse(text).ok_or_else(|| DefinitionError::SourcePath {
391        kind: kind.to_owned(),
392        path: text.to_owned(),
393    })
394}
395
396fn compile_fields(
397    kind: &str,
398    specs: &std::collections::BTreeMap<String, FieldSpec>,
399) -> Result<Vec<Field>, DefinitionError> {
400    specs
401        .iter()
402        .map(|(target, spec)| {
403            let path = FieldPath::parse(target).map_err(|source| DefinitionError::Target {
404                kind: kind.to_owned(),
405                target: target.clone(),
406                source,
407            })?;
408            let reserved = match path.segments()[0].as_str() {
409                "class_uid" | "category_uid" | "type_uid" | "activity_id" => {
410                    Some("the kind's `class`")
411                }
412                "unmapped" => Some("the kind's `unmapped` list"),
413                _ => None,
414            };
415            if let Some(reason) = reserved {
416                return Err(DefinitionError::Reserved {
417                    kind: kind.to_owned(),
418                    target: target.clone(),
419                    reason,
420                });
421            }
422            let source = match spec {
423                FieldSpec::Path(from) => Source::Path {
424                    path: source_path(kind, from)?,
425                    coercion: None,
426                },
427                FieldSpec::Converted { from, coercion } => Source::Path {
428                    path: source_path(kind, from)?,
429                    coercion: Some(*coercion),
430                },
431                FieldSpec::Value { value } => Source::Constant(Value::from(value)),
432            };
433            Ok(Field {
434                target: path,
435                source,
436            })
437        })
438        .collect()
439}
440
441/// Rejects two fields writing the same attribute, or one inside another:
442/// the second write would replace or be lost under the first.
443fn check_overlaps(kind: &str, fields: &[Field]) -> Result<(), DefinitionError> {
444    for (index, first) in fields.iter().enumerate() {
445        for second in &fields[index + 1..] {
446            let (a, b) = (first.target.segments(), second.target.segments());
447            if a.starts_with(b) || b.starts_with(a) {
448                return Err(DefinitionError::Overlap {
449                    kind: kind.to_owned(),
450                    first: first.target.as_str().to_owned(),
451                    second: second.target.as_str().to_owned(),
452                });
453            }
454        }
455    }
456    Ok(())
457}
458
459/// Writes `value` at `segments`, creating objects on the way. Overlapping
460/// targets are rejected when the definition is compiled, so the way is
461/// always clear.
462fn set(object: &mut Map<String, Value>, segments: &[String], value: Value) {
463    let Some((last, parents)) = segments.split_last() else {
464        return;
465    };
466    let mut object = object;
467    for segment in parents {
468        let child = object
469            .entry(segment.clone())
470            .or_insert_with(|| Value::Object(Map::new()));
471        let Value::Object(child) = child else {
472            return;
473        };
474        object = child;
475    }
476    object.insert(last.clone(), value);
477}
478
479fn coerce(value: &Value, coercion: Option<Coercion>) -> Result<Value, String> {
480    let Some(coercion) = coercion else {
481        return Ok(value.clone());
482    };
483    match (coercion, value) {
484        (Coercion::String, Value::String(_)) => Ok(value.clone()),
485        (Coercion::String, Value::Number(number)) => Ok(Value::String(number.to_string())),
486        (Coercion::Integer, Value::Number(number)) => number
487            .as_i64()
488            .map(Value::from)
489            .ok_or_else(|| format!("{number} is not a whole number")),
490        (Coercion::Integer, Value::String(text)) => text
491            .trim()
492            .parse::<i64>()
493            .map(Value::from)
494            .map_err(|_| format!("`{text}` is not a whole number")),
495        (Coercion::Timestamp, Value::String(text)) => text
496            .parse::<jiff::Timestamp>()
497            .map(|time| Value::from(time.as_millisecond()))
498            .map_err(|error| format!("`{text}` is not an RFC 3339 time: {error}")),
499        (coercion, other) => Err(format!(
500            "cannot convert {} to {coercion:?}",
501            describe(other)
502        )),
503    }
504}
505
506fn describe(value: &Value) -> &'static str {
507    match value {
508        Value::Null => "null",
509        Value::Bool(_) => "a boolean",
510        Value::Number(_) => "a number",
511        Value::String(_) => "text",
512        Value::Array(_) => "a list",
513        Value::Object(_) => "an object",
514    }
515}