goliath-normalize 0.1.0

Declarative source definitions that turn raw log records into OCSF events
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
//! Source definitions compiled for use, and records through them.

use goliath_rule::FieldPath;
use serde_json::{Map, Value};

use crate::definition::{Coercion, Decoding, FieldSpec, Framing, SourceDefinition};
use crate::error::DefinitionError;

/// A source definition, checked and compiled.
///
/// Built once, then used for every record of the source. Normalizing is
/// deterministic: the same bytes under the same definition version always give
/// the same outcome.
#[derive(Debug, Clone)]
pub struct Normalizer {
    name: String,
    version: u32,
    framing: Framing,
    kinds: Vec<Kind>,
}

#[derive(Debug, Clone)]
struct Kind {
    name: String,
    when: Vec<(SourcePath, Value)>,
    /// `class_uid`, `category_uid`, `type_uid`, and `activity_id`.
    class: Vec<(&'static str, Value)>,
    /// The common fields, then the kind's own.
    fields: Vec<Field>,
    unmapped: Vec<SourcePath>,
}

#[derive(Debug, Clone)]
struct Field {
    target: FieldPath,
    source: Source,
}

#[derive(Debug, Clone)]
enum Source {
    Constant(Value),
    Path {
        path: SourcePath,
        coercion: Option<Coercion>,
    },
}

/// A dotted path into a decoded record. Unlike an OCSF path, it names exactly
/// one value: records are read, not searched.
#[derive(Debug, Clone, PartialEq, Eq)]
struct SourcePath {
    text: String,
    segments: Vec<String>,
}

impl SourcePath {
    fn parse(text: &str) -> Option<Self> {
        let segments: Vec<String> = text.split('.').map(str::to_owned).collect();
        segments
            .iter()
            .all(|segment| !segment.is_empty())
            .then(|| Self {
                text: text.to_owned(),
                segments,
            })
    }

    fn lookup<'a>(&self, record: &'a Value) -> Option<&'a Value> {
        self.segments
            .iter()
            .try_fold(record, |value, segment| value.get(segment.as_str()))
    }

    /// Whether this path names the member `key` of the object at `object`.
    fn is_member(&self, object: &Self, key: &str) -> bool {
        self.segments.len() == object.segments.len() + 1
            && self.segments.starts_with(&object.segments)
            && self.segments.last().is_some_and(|last| last == key)
    }

    fn last(&self) -> &str {
        self.segments.last().map_or("", String::as_str)
    }
}

/// What became of one record.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq)]
pub enum Outcome {
    /// The record became an OCSF event.
    Event(Normalized),
    /// The record could not become an event, and is kept whole.
    DeadLetter(DeadLetter),
}

/// An OCSF event, and anything that did not convert on the way.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq)]
pub struct Normalized {
    /// The event.
    pub event: Value,
    /// The kind of record it was.
    pub kind: String,
    /// Values that did not convert. Each is kept as written under
    /// `unmapped`, and the event is still produced, so that a malformed field
    /// cannot keep an event away from detection.
    pub issues: Vec<Issue>,
}

/// A value that did not convert.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Issue {
    /// The OCSF attribute it was meant for.
    pub target: String,
    /// Where it was read from.
    pub source: String,
    /// Why it did not convert.
    pub reason: String,
}

/// A record that could not become an event.
///
/// The raw bytes are kept exactly, so the record can be processed again once
/// the source definition is fixed. Nothing a source sends is dropped.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DeadLetter {
    /// The stage that failed.
    pub stage: Stage,
    /// Why.
    pub error: String,
    /// The record as received; for a stream that could not be framed, the
    /// rest of the stream.
    pub raw: Vec<u8>,
}

/// A stage of normalization, in order.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Stage {
    /// Splitting the stream into records.
    Framing,
    /// Turning a record into a field map.
    Decoding,
    /// Choosing a kind and writing the OCSF event.
    Mapping,
}

impl Stage {
    /// The stage's name, as reports and metrics use it.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Framing => "framing",
            Self::Decoding => "decoding",
            Self::Mapping => "mapping",
        }
    }
}

impl Normalizer {
    /// Loads a source definition from YAML, as untrusted input.
    ///
    /// # Errors
    ///
    /// Returns [`DefinitionError`] if the YAML is not a valid definition.
    pub fn from_yaml(text: &str) -> Result<Self, DefinitionError> {
        let definition: SourceDefinition = goliath_sigma::yaml::from_str(text)?;
        Self::new(&definition)
    }

    /// Checks and compiles a source definition.
    ///
    /// # Errors
    ///
    /// Returns [`DefinitionError`] if a path does not parse, two fields
    /// would write over each other, a field writes an attribute that is set
    /// otherwise, or a kind would accept every record.
    pub fn new(definition: &SourceDefinition) -> Result<Self, DefinitionError> {
        if definition.kinds.is_empty() {
            return Err(DefinitionError::NoKinds);
        }
        let common = compile_fields("common", &definition.common)?;
        let mut kinds = Vec::with_capacity(definition.kinds.len());
        for kind in &definition.kinds {
            if kind.when.is_empty() {
                return Err(DefinitionError::Unconditional {
                    kind: kind.name.clone(),
                });
            }
            let when = kind
                .when
                .iter()
                .map(|(path, value)| Ok((source_path(&kind.name, path)?, Value::from(value))))
                .collect::<Result<_, DefinitionError>>()?;
            let mut fields = common.clone();
            fields.extend(compile_fields(&kind.name, &kind.fields)?);
            check_overlaps(&kind.name, &fields)?;
            let unmapped = kind
                .unmapped
                .iter()
                .map(|path| source_path(&kind.name, path))
                .collect::<Result<_, _>>()?;

            let class_uid = kind.class.class_uid;
            let activity_id = kind.class.activity_id;
            let category_uid = goliath_ocsf::Event::derive_category_uid(class_uid);
            let type_uid = goliath_ocsf::Event::derive_type_uid(class_uid, activity_id);
            kinds.push(Kind {
                name: kind.name.clone(),
                when,
                class: vec![
                    ("class_uid", Value::from(class_uid)),
                    ("category_uid", Value::from(category_uid)),
                    ("type_uid", Value::from(type_uid)),
                    ("activity_id", Value::from(activity_id)),
                ],
                fields,
                unmapped,
            });
        }
        // Only JSON exists so far; the match makes a new decoding a compile
        // error here rather than a silent fallback.
        match definition.decoding {
            Decoding::Json => {}
        }
        Ok(Self {
            name: definition.name.clone(),
            version: definition.version,
            framing: definition.framing,
            kinds,
        })
    }

    /// The source's name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// The definition's version, to be stored with every event it produces.
    pub fn version(&self) -> u32 {
        self.version
    }

    /// Splits `bytes` into records and normalizes each, calling `out` with
    /// every outcome in order.
    pub fn normalize(&self, bytes: &[u8], mut out: impl FnMut(Outcome)) {
        match self.framing {
            Framing::Lines => {
                for line in bytes.split(|&byte| byte == b'\n') {
                    let line = line.strip_suffix(b"\r").unwrap_or(line);
                    if line.iter().all(u8::is_ascii_whitespace) {
                        continue;
                    }
                    out(match serde_json::from_slice::<Value>(line) {
                        Ok(record) => self.record(&record, line),
                        Err(error) => dead(Stage::Decoding, error.to_string(), line),
                    });
                }
            }
            Framing::JsonValues => {
                let mut stream = serde_json::Deserializer::from_slice(bytes).into_iter::<Value>();
                let mut start = 0;
                while let Some(next) = stream.next() {
                    match next {
                        Ok(record) => {
                            let end = stream.byte_offset();
                            out(self.record(&record, trim(&bytes[start..end])));
                            start = end;
                        }
                        Err(error) => {
                            // Where one value ends cannot be known once the
                            // stream is broken, so the rest is kept together.
                            out(dead(
                                Stage::Framing,
                                error.to_string(),
                                trim(&bytes[start..]),
                            ));
                            return;
                        }
                    }
                }
            }
        }
    }

    /// Normalizes one decoded record, whose raw bytes are `raw`.
    fn record(&self, record: &Value, raw: &[u8]) -> Outcome {
        if !record.is_object() {
            return dead(
                Stage::Decoding,
                "the record is not a JSON object".to_owned(),
                raw,
            );
        }
        let Some(kind) = self.kinds.iter().find(|kind| {
            kind.when
                .iter()
                .all(|(path, expected)| path.lookup(record) == Some(expected))
        }) else {
            return dead(
                Stage::Mapping,
                format!("no kind of source `{}` accepts the record", self.name),
                raw,
            );
        };

        let mut event = Map::new();
        let mut unmapped = Map::new();
        let mut issues = Vec::new();
        let mut consumed: Vec<&SourcePath> = Vec::new();
        for (name, value) in &kind.class {
            event.insert((*name).to_owned(), value.clone());
        }
        for field in &kind.fields {
            match &field.source {
                Source::Constant(value) => set(&mut event, field.target.segments(), value.clone()),
                Source::Path { path, coercion } => {
                    let Some(found) = path.lookup(record).filter(|value| !value.is_null()) else {
                        continue;
                    };
                    consumed.push(path);
                    match coerce(found, *coercion) {
                        Ok(value) => set(&mut event, field.target.segments(), value),
                        Err(reason) => {
                            issues.push(Issue {
                                target: field.target.as_str().to_owned(),
                                source: path.text.clone(),
                                reason,
                            });
                            // Kept by the name the `unmapped` lists would give
                            // it, or by its whole path where they give none,
                            // so that it cannot take another member's name.
                            let listed = kind
                                .unmapped
                                .iter()
                                .any(|object| path.is_member(object, path.last()));
                            let name = if listed { path.last() } else { &path.text };
                            unmapped.insert(name.to_owned(), found.clone());
                        }
                    }
                }
            }
        }
        for object in &kind.unmapped {
            let Some(Value::Object(members)) = object.lookup(record) else {
                continue;
            };
            for (key, member) in members {
                if member.is_null() || consumed.iter().any(|path| path.is_member(object, key)) {
                    continue;
                }
                unmapped
                    .entry(key.clone())
                    .or_insert_with(|| member.clone());
            }
        }
        if !unmapped.is_empty() {
            event.insert("unmapped".to_owned(), Value::Object(unmapped));
        }
        Outcome::Event(Normalized {
            event: Value::Object(event),
            kind: kind.name.clone(),
            issues,
        })
    }
}

fn dead(stage: Stage, error: String, raw: &[u8]) -> Outcome {
    Outcome::DeadLetter(DeadLetter {
        stage,
        error,
        raw: raw.to_vec(),
    })
}

fn trim(bytes: &[u8]) -> &[u8] {
    let start = bytes
        .iter()
        .position(|byte| !byte.is_ascii_whitespace())
        .unwrap_or(bytes.len());
    let end = bytes
        .iter()
        .rposition(|byte| !byte.is_ascii_whitespace())
        .map_or(start, |position| position + 1);
    &bytes[start..end]
}

fn source_path(kind: &str, text: &str) -> Result<SourcePath, DefinitionError> {
    SourcePath::parse(text).ok_or_else(|| DefinitionError::SourcePath {
        kind: kind.to_owned(),
        path: text.to_owned(),
    })
}

fn compile_fields(
    kind: &str,
    specs: &std::collections::BTreeMap<String, FieldSpec>,
) -> Result<Vec<Field>, DefinitionError> {
    specs
        .iter()
        .map(|(target, spec)| {
            let path = FieldPath::parse(target).map_err(|source| DefinitionError::Target {
                kind: kind.to_owned(),
                target: target.clone(),
                source,
            })?;
            let reserved = match path.segments()[0].as_str() {
                "class_uid" | "category_uid" | "type_uid" | "activity_id" => {
                    Some("the kind's `class`")
                }
                "unmapped" => Some("the kind's `unmapped` list"),
                _ => None,
            };
            if let Some(reason) = reserved {
                return Err(DefinitionError::Reserved {
                    kind: kind.to_owned(),
                    target: target.clone(),
                    reason,
                });
            }
            let source = match spec {
                FieldSpec::Path(from) => Source::Path {
                    path: source_path(kind, from)?,
                    coercion: None,
                },
                FieldSpec::Converted { from, coercion } => Source::Path {
                    path: source_path(kind, from)?,
                    coercion: Some(*coercion),
                },
                FieldSpec::Value { value } => Source::Constant(Value::from(value)),
            };
            Ok(Field {
                target: path,
                source,
            })
        })
        .collect()
}

/// Rejects two fields writing the same attribute, or one inside another:
/// the second write would replace or be lost under the first.
fn check_overlaps(kind: &str, fields: &[Field]) -> Result<(), DefinitionError> {
    for (index, first) in fields.iter().enumerate() {
        for second in &fields[index + 1..] {
            let (a, b) = (first.target.segments(), second.target.segments());
            if a.starts_with(b) || b.starts_with(a) {
                return Err(DefinitionError::Overlap {
                    kind: kind.to_owned(),
                    first: first.target.as_str().to_owned(),
                    second: second.target.as_str().to_owned(),
                });
            }
        }
    }
    Ok(())
}

/// Writes `value` at `segments`, creating objects on the way. Overlapping
/// targets are rejected when the definition is compiled, so the way is
/// always clear.
fn set(object: &mut Map<String, Value>, segments: &[String], value: Value) {
    let Some((last, parents)) = segments.split_last() else {
        return;
    };
    let mut object = object;
    for segment in parents {
        let child = object
            .entry(segment.clone())
            .or_insert_with(|| Value::Object(Map::new()));
        let Value::Object(child) = child else {
            return;
        };
        object = child;
    }
    object.insert(last.clone(), value);
}

fn coerce(value: &Value, coercion: Option<Coercion>) -> Result<Value, String> {
    let Some(coercion) = coercion else {
        return Ok(value.clone());
    };
    match (coercion, value) {
        (Coercion::String, Value::String(_)) => Ok(value.clone()),
        (Coercion::String, Value::Number(number)) => Ok(Value::String(number.to_string())),
        (Coercion::Integer, Value::Number(number)) => number
            .as_i64()
            .map(Value::from)
            .ok_or_else(|| format!("{number} is not a whole number")),
        (Coercion::Integer, Value::String(text)) => text
            .trim()
            .parse::<i64>()
            .map(Value::from)
            .map_err(|_| format!("`{text}` is not a whole number")),
        (Coercion::Timestamp, Value::String(text)) => text
            .parse::<jiff::Timestamp>()
            .map(|time| Value::from(time.as_millisecond()))
            .map_err(|error| format!("`{text}` is not an RFC 3339 time: {error}")),
        (coercion, other) => Err(format!(
            "cannot convert {} to {coercion:?}",
            describe(other)
        )),
    }
}

fn describe(value: &Value) -> &'static str {
    match value {
        Value::Null => "null",
        Value::Bool(_) => "a boolean",
        Value::Number(_) => "a number",
        Value::String(_) => "text",
        Value::Array(_) => "a list",
        Value::Object(_) => "an object",
    }
}