Skip to main content

goliath_normalize/
normalizer.rs

1//! Source definitions compiled for use, and records through them.
2
3use std::collections::BTreeMap;
4
5use goliath_ocsf::schema::{self, Base};
6use goliath_rule::FieldPath;
7use serde::{Deserialize, Deserializer, Serialize, Serializer};
8use serde_json::{Map, Value};
9
10use crate::definition::{Coercion, Decoding, FieldSpec, Framing, SourceDefinition};
11use crate::error::DefinitionError;
12use crate::{auditd, syslog};
13
14/// A source definition, checked and compiled.
15///
16/// Built once, then used for every record of the source. Normalizing is
17/// deterministic: the same bytes under the same definition version always give
18/// the same outcome.
19#[derive(Debug, Clone)]
20pub struct Normalizer {
21    name: String,
22    version: u32,
23    framing: Framing,
24    decoding: Decoding,
25    kinds: Vec<Kind>,
26    nil: Vec<Value>,
27    unwrap: Option<String>,
28    data_components: Vec<String>,
29}
30
31#[derive(Debug, Clone)]
32struct Kind {
33    name: String,
34    when: Vec<(SourcePath, Value)>,
35    /// `class_uid`, `category_uid`, `type_uid`, and `activity_id`.
36    class: Vec<(&'static str, Value)>,
37    /// The common fields, then the kind's own.
38    fields: Vec<Field>,
39    unmapped: Vec<SourcePath>,
40}
41
42#[derive(Debug, Clone)]
43struct Field {
44    target: FieldPath,
45    source: Source,
46}
47
48#[derive(Debug, Clone)]
49enum Source {
50    Constant(Value),
51    Path {
52        path: SourcePath,
53        coercion: Option<Coercion>,
54    },
55    Translate {
56        path: SourcePath,
57        map: BTreeMap<String, Value>,
58        otherwise: Option<Value>,
59    },
60}
61
62/// A dotted path into a decoded record. Unlike an OCSF path, it names exactly
63/// one value: records are read, not searched.
64///
65/// A member whose own name holds dots, as Falco's `proc.cmdline` does, is
66/// named by writing it out: `output_fields.proc.cmdline`. At each object a
67/// member named by the next segment alone is tried first, then by the next
68/// two joined with a dot, and so on.
69///
70/// In an array, a segment that is a number names the element at that index,
71/// counted from 0: `target.1.displayName` is the name of the second target.
72#[derive(Debug, Clone, PartialEq, Eq)]
73struct SourcePath {
74    text: String,
75    segments: Vec<String>,
76}
77
78impl SourcePath {
79    fn parse(text: &str) -> Option<Self> {
80        let segments: Vec<String> = text.split('.').map(str::to_owned).collect();
81        segments
82            .iter()
83            .all(|segment| !segment.is_empty())
84            .then(|| Self {
85                text: text.to_owned(),
86                segments,
87            })
88    }
89
90    fn lookup<'a>(&self, record: &'a Value) -> Option<&'a Value> {
91        find(record, &self.segments)
92    }
93
94    /// The name, within the object at `object`, of the member this path
95    /// names, if it is one.
96    fn member_of(&self, object: &Self) -> Option<String> {
97        (self.segments.len() > object.segments.len() && self.segments.starts_with(&object.segments))
98            .then(|| self.segments[object.segments.len()..].join("."))
99    }
100
101    /// Whether this path names the member `key` of the object at `object`.
102    fn is_member(&self, object: &Self, key: &str) -> bool {
103        self.member_of(object).is_some_and(|member| member == key)
104    }
105}
106
107fn find<'a>(value: &'a Value, segments: &[String]) -> Option<&'a Value> {
108    if segments.is_empty() {
109        return Some(value);
110    }
111    if let Some(items) = value.as_array() {
112        let index: usize = segments[0].parse().ok()?;
113        return find(items.get(index)?, &segments[1..]);
114    }
115    let object = value.as_object()?;
116    let mut name = String::new();
117    for (index, segment) in segments.iter().enumerate() {
118        if index > 0 {
119            name.push('.');
120        }
121        name.push_str(segment);
122        if let Some(found) = object
123            .get(&name)
124            .and_then(|member| find(member, &segments[index + 1..]))
125        {
126            return Some(found);
127        }
128    }
129    None
130}
131
132/// What became of one record.
133#[non_exhaustive]
134#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
135#[serde(rename_all = "snake_case")]
136pub enum Outcome {
137    /// The record became an OCSF event.
138    Event(Normalized),
139    /// The record could not become an event, and is kept whole.
140    DeadLetter(DeadLetter),
141}
142
143/// An OCSF event, and anything that did not convert on the way.
144#[non_exhaustive]
145#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
146pub struct Normalized {
147    /// Identifies the record the event came from, so that storage can drop
148    /// a record delivered twice.
149    pub id: EventId,
150    /// The event.
151    pub event: Value,
152    /// The kind of record it was.
153    pub kind: String,
154    /// Values that did not convert. Each is kept as written under
155    /// `unmapped`, and the event is still produced, so that a malformed field
156    /// cannot keep an event away from detection.
157    pub issues: Vec<Issue>,
158}
159
160impl Normalized {
161    /// An event made by the platform itself, such as a finding, with the
162    /// identity `id` and no issues.
163    pub fn new(id: EventId, event: Value, kind: impl Into<String>) -> Self {
164        Self {
165            id,
166            event,
167            kind: kind.into(),
168            issues: Vec::new(),
169        }
170    }
171}
172
173/// The identity of a record: 128 bits of the BLAKE3 hash of the source's
174/// name and the record's raw bytes.
175///
176/// It depends on nothing else, so a record delivered again, or collected
177/// again, gets the same identity and can be dropped as a duplicate. Two
178/// records with identical bytes from one source are the same record.
179///
180/// The hash is cryptographic on purpose. Whoever writes the logs chooses the
181/// bytes, and with a hash built only for speed they could craft a record
182/// whose identity equals that of another, and have storage drop one of the
183/// two as a duplicate.
184#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
185pub struct EventId([u8; 16]);
186
187impl EventId {
188    /// Keys the hash, so that identities cannot be confused with any other
189    /// use of BLAKE3. Changing it changes every identity.
190    const CONTEXT: &str = "goliath 2026-09-25 event id";
191
192    /// The identity of the record `raw` from the source `source`.
193    pub fn of(source: &str, raw: &[u8]) -> Self {
194        let mut hasher = blake3::Hasher::new_derive_key(Self::CONTEXT);
195        // The name's length first, so that no name and record pair can end
196        // where another pair's name does.
197        hasher.update(&(source.len() as u64).to_le_bytes());
198        hasher.update(source.as_bytes());
199        hasher.update(raw);
200        let mut id = [0; 16];
201        hasher.finalize_xof().fill(&mut id);
202        Self(id)
203    }
204
205    /// The identity's bytes.
206    pub fn as_bytes(&self) -> &[u8; 16] {
207        &self.0
208    }
209}
210
211impl std::fmt::Display for EventId {
212    /// Lowercase hexadecimal.
213    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
214        self.0.iter().try_for_each(|byte| write!(f, "{byte:02x}"))
215    }
216}
217
218impl std::str::FromStr for EventId {
219    type Err = String;
220
221    /// Parses the lowercase or uppercase hexadecimal [`Display`] writes.
222    ///
223    /// [`Display`]: std::fmt::Display
224    fn from_str(text: &str) -> Result<Self, Self::Err> {
225        let invalid = || format!("`{text}` is not 32 hexadecimal digits");
226        if text.len() != 32 {
227            return Err(invalid());
228        }
229        let mut id = [0; 16];
230        let (pairs, _) = text.as_bytes().as_chunks::<2>();
231        for (byte, pair) in id.iter_mut().zip(pairs) {
232            let pair = std::str::from_utf8(pair).map_err(|_| invalid())?;
233            *byte = u8::from_str_radix(pair, 16).map_err(|_| invalid())?;
234        }
235        Ok(Self(id))
236    }
237}
238
239/// As its hexadecimal text, so that it reads the same in JSON as in logs.
240impl Serialize for EventId {
241    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
242        serializer.collect_str(self)
243    }
244}
245
246impl<'de> Deserialize<'de> for EventId {
247    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
248        let text = String::deserialize(deserializer)?;
249        text.parse().map_err(serde::de::Error::custom)
250    }
251}
252
253impl std::fmt::Debug for EventId {
254    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
255        write!(f, "EventId({self})")
256    }
257}
258
259/// A value that did not convert.
260#[non_exhaustive]
261#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
262pub struct Issue {
263    /// The OCSF attribute it was meant for.
264    pub target: String,
265    /// Where it was read from.
266    pub source: String,
267    /// Why it did not convert.
268    pub reason: String,
269}
270
271/// A record that could not become an event.
272///
273/// The raw bytes are kept exactly, so the record can be processed again once
274/// the source definition is fixed. Nothing a source sends is dropped.
275#[non_exhaustive]
276#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
277pub struct DeadLetter {
278    /// The stage that failed.
279    pub stage: Stage,
280    /// Why.
281    pub error: String,
282    /// The record as received; for a stream that could not be framed, the
283    /// rest of the stream.
284    pub raw: Vec<u8>,
285}
286
287/// A stage of normalization, in order.
288#[non_exhaustive]
289#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
290#[serde(rename_all = "snake_case")]
291pub enum Stage {
292    /// Splitting the stream into records.
293    Framing,
294    /// Turning a record into a field map.
295    Decoding,
296    /// Choosing a kind and writing the OCSF event.
297    Mapping,
298}
299
300impl Stage {
301    /// The stage's name, as reports and metrics use it.
302    pub fn as_str(self) -> &'static str {
303        match self {
304            Self::Framing => "framing",
305            Self::Decoding => "decoding",
306            Self::Mapping => "mapping",
307        }
308    }
309}
310
311impl Normalizer {
312    /// Loads a source definition from YAML, as untrusted input.
313    ///
314    /// # Errors
315    ///
316    /// Returns [`DefinitionError`] if the YAML is not a valid definition.
317    pub fn from_yaml(text: &str) -> Result<Self, DefinitionError> {
318        let definition: SourceDefinition = goliath_sigma::yaml::from_str(text)?;
319        Self::new(&definition)
320    }
321
322    /// Checks and compiles a source definition.
323    ///
324    /// # Errors
325    ///
326    /// Returns [`DefinitionError`] if a path does not parse, two fields
327    /// would write over each other, a field writes an attribute that is set
328    /// otherwise, or a kind would accept every record; and if a class,
329    /// activity, or target is not in the OCSF schema, or a field writes a
330    /// value its attribute cannot hold.
331    pub fn new(definition: &SourceDefinition) -> Result<Self, DefinitionError> {
332        if definition.kinds.is_empty() {
333            return Err(DefinitionError::NoKinds);
334        }
335        let common = compile_fields("common", &definition.common)?;
336        let mut kinds = Vec::with_capacity(definition.kinds.len());
337        for kind in &definition.kinds {
338            if kind.when.is_empty() {
339                return Err(DefinitionError::Unconditional {
340                    kind: kind.name.clone(),
341                });
342            }
343            let when = kind
344                .when
345                .iter()
346                .map(|(path, value)| Ok((source_path(&kind.name, path)?, Value::from(value))))
347                .collect::<Result<_, DefinitionError>>()?;
348            let mut fields = common.clone();
349            fields.extend(compile_fields(&kind.name, &kind.fields)?);
350            check_overlaps(&kind.name, &fields)?;
351            check_schema(
352                &kind.name,
353                kind.class.class_uid,
354                kind.class.activity_id,
355                &fields,
356            )?;
357            let unmapped = kind
358                .unmapped
359                .iter()
360                .map(|path| {
361                    // `.` is the record itself, for sources that write every
362                    // field at its top level.
363                    if path == "." {
364                        Ok(SourcePath {
365                            text: path.clone(),
366                            segments: Vec::new(),
367                        })
368                    } else {
369                        source_path(&kind.name, path)
370                    }
371                })
372                .collect::<Result<_, _>>()?;
373
374            let class_uid = kind.class.class_uid;
375            let activity_id = kind.class.activity_id;
376            let category_uid = goliath_ocsf::Event::derive_category_uid(class_uid);
377            let type_uid = goliath_ocsf::Event::derive_type_uid(class_uid, activity_id);
378            kinds.push(Kind {
379                name: kind.name.clone(),
380                when,
381                class: vec![
382                    ("class_uid", Value::from(class_uid)),
383                    ("category_uid", Value::from(category_uid)),
384                    ("type_uid", Value::from(type_uid)),
385                    ("activity_id", Value::from(activity_id)),
386                ],
387                fields,
388                unmapped,
389            });
390        }
391        let fits = match definition.framing {
392            Framing::Lines => true,
393            Framing::JsonValues => definition.decoding == Decoding::Json,
394            Framing::AuditEvents => definition.decoding == Decoding::Auditd,
395            Framing::Syslog => {
396                matches!(definition.decoding, Decoding::Syslog | Decoding::SyslogJson)
397            }
398        };
399        if !fits {
400            return Err(DefinitionError::Decoding {
401                framing: match definition.framing {
402                    Framing::Lines => "lines",
403                    Framing::JsonValues => "json-values",
404                    Framing::AuditEvents => "audit-events",
405                    Framing::Syslog => "syslog",
406                },
407                decoding: match definition.decoding {
408                    Decoding::Json => "json",
409                    Decoding::Auditd => "auditd",
410                    Decoding::Syslog => "syslog",
411                    Decoding::SyslogJson => "syslog-json",
412                },
413            });
414        }
415        Ok(Self {
416            name: definition.name.clone(),
417            version: definition.version,
418            framing: definition.framing,
419            decoding: definition.decoding,
420            kinds,
421            nil: definition
422                .nil
423                .iter()
424                .map(|text| Value::from(text.as_str()))
425                .collect(),
426            unwrap: definition.unwrap.clone(),
427            data_components: definition.data_components.clone(),
428        })
429    }
430
431    /// The source's name.
432    pub fn name(&self) -> &str {
433        &self.name
434    }
435
436    /// The ATT&CK data components the definition says its records supply,
437    /// such as `Process Creation`.
438    pub fn data_components(&self) -> &[String] {
439        &self.data_components
440    }
441
442    /// How the source's bytes split into records.
443    pub fn framing(&self) -> Framing {
444        self.framing
445    }
446
447    /// The definition's version, to be stored with every event it produces.
448    pub fn version(&self) -> u32 {
449        self.version
450    }
451
452    /// Splits `bytes` into records and normalizes each, calling `out` with
453    /// every outcome in order.
454    pub fn normalize(&self, bytes: &[u8], mut out: impl FnMut(Outcome)) {
455        match self.framing {
456            Framing::Lines => {
457                for line in bytes.split(|&byte| byte == b'\n') {
458                    let line = line.strip_suffix(b"\r").unwrap_or(line);
459                    if line.iter().all(u8::is_ascii_whitespace) {
460                        continue;
461                    }
462                    self.decoded(line, &mut out);
463                }
464            }
465            Framing::AuditEvents => {
466                for event in auditd::events(bytes) {
467                    match event {
468                        Ok(raw) => self.decoded(&raw, &mut out),
469                        Err(line) => out(dead(
470                            Stage::Framing,
471                            "the line names no audit event".to_owned(),
472                            line,
473                        )),
474                    }
475                }
476            }
477            Framing::Syslog => {
478                for message in syslog::messages(bytes) {
479                    match message {
480                        Ok(raw) => self.decoded(raw, &mut out),
481                        Err(rest) => out(dead(
482                            Stage::Framing,
483                            "the message is shorter than its octet count".to_owned(),
484                            rest,
485                        )),
486                    }
487                }
488            }
489            Framing::JsonValues => {
490                let mut stream = serde_json::Deserializer::from_slice(bytes).into_iter::<Value>();
491                let mut start = 0;
492                while let Some(next) = stream.next() {
493                    match next {
494                        Ok(record) => {
495                            let end = stream.byte_offset();
496                            self.records(&record, trim(&bytes[start..end]), &mut out);
497                            start = end;
498                        }
499                        Err(error) => {
500                            // Where one value ends cannot be known once the
501                            // stream is broken, so the rest is kept together.
502                            out(dead(
503                                Stage::Framing,
504                                error.to_string(),
505                                trim(&bytes[start..]),
506                            ));
507                            return;
508                        }
509                    }
510                }
511            }
512        }
513    }
514
515    /// Decodes and normalizes one framed record.
516    fn decoded(&self, raw: &[u8], out: &mut impl FnMut(Outcome)) {
517        let record = match self.decoding {
518            Decoding::Json => {
519                serde_json::from_slice::<Value>(raw).map_err(|error| error.to_string())
520            }
521            Decoding::Auditd => auditd::decode(raw),
522            Decoding::Syslog => syslog::decode(raw, syslog::Message::Text, jiff::Timestamp::now),
523            Decoding::SyslogJson => {
524                syslog::decode(raw, syslog::Message::Json, jiff::Timestamp::now)
525            }
526        };
527        match record {
528            Ok(record) => self.records(&record, raw, out),
529            Err(error) => out(dead(Stage::Decoding, error, raw)),
530        }
531    }
532
533    /// Normalizes a decoded record, or each record of a batch the
534    /// definition unwraps.
535    fn records(&self, record: &Value, raw: &[u8], out: &mut impl FnMut(Outcome)) {
536        let batch = self.unwrap.as_ref().and_then(|member| {
537            if member == "." {
538                return record.as_array();
539            }
540            let object = record.as_object().filter(|object| object.len() == 1)?;
541            object.get(member)?.as_array()
542        });
543        match batch {
544            Some(items) => {
545                for item in items {
546                    let bytes = serde_json::to_vec(item).unwrap_or_default();
547                    out(self.record(item, &bytes));
548                }
549            }
550            None => out(self.record(record, raw)),
551        }
552    }
553
554    /// Normalizes one decoded record, whose raw bytes are `raw`.
555    fn record(&self, record: &Value, raw: &[u8]) -> Outcome {
556        if !record.is_object() {
557            return dead(
558                Stage::Decoding,
559                "the record is not a JSON object".to_owned(),
560                raw,
561            );
562        }
563        let Some(kind) = self.kinds.iter().find(|kind| {
564            kind.when
565                .iter()
566                .all(|(path, expected)| path.lookup(record) == Some(expected))
567        }) else {
568            return dead(
569                Stage::Mapping,
570                format!("no kind of source `{}` accepts the record", self.name),
571                raw,
572            );
573        };
574
575        let mut event = Map::new();
576        let mut unmapped = Map::new();
577        let mut issues = Vec::new();
578        let mut consumed: Vec<&SourcePath> = Vec::new();
579        for (name, value) in &kind.class {
580            event.insert((*name).to_owned(), value.clone());
581        }
582        for field in &kind.fields {
583            let path = match &field.source {
584                Source::Constant(value) => {
585                    set(&mut event, field.target.segments(), value.clone());
586                    continue;
587                }
588                Source::Path { path, .. } | Source::Translate { path, .. } => path,
589            };
590            let Some(found) = path
591                .lookup(record)
592                .filter(|value| !value.is_null() && !self.nil.contains(value))
593            else {
594                continue;
595            };
596            if !field.source.keeps_source() {
597                consumed.push(path);
598            }
599            match field.source.convert(found) {
600                Ok(value) => set(&mut event, field.target.segments(), value),
601                Err(reason) => {
602                    issues.push(Issue {
603                        target: field.target.as_str().to_owned(),
604                        source: path.text.clone(),
605                        reason,
606                    });
607                    // Kept by the name the `unmapped` lists would give it, or
608                    // by its whole path where they give none, so that it
609                    // cannot take another member's name.
610                    let name = kind
611                        .unmapped
612                        .iter()
613                        .find_map(|object| path.member_of(object))
614                        .unwrap_or_else(|| path.text.clone());
615                    unmapped.insert(name, found.clone());
616                }
617            }
618        }
619        for object in &kind.unmapped {
620            let Some(Value::Object(members)) = object.lookup(record) else {
621                continue;
622            };
623            for (key, member) in members {
624                if member.is_null() || consumed.iter().any(|path| path.is_member(object, key)) {
625                    continue;
626                }
627                // A name an earlier object already gave is qualified with
628                // this object's path, so that neither value is lost.
629                let name = if unmapped.contains_key(key) {
630                    format!("{}.{key}", object.text)
631                } else {
632                    key.clone()
633                };
634                unmapped.entry(name).or_insert_with(|| member.clone());
635            }
636        }
637        if !unmapped.is_empty() {
638            event.insert("unmapped".to_owned(), Value::Object(unmapped));
639        }
640        Outcome::Event(Normalized {
641            id: EventId::of(&self.name, raw),
642            event: Value::Object(event),
643            kind: kind.name.clone(),
644            issues,
645        })
646    }
647}
648
649fn dead(stage: Stage, error: String, raw: &[u8]) -> Outcome {
650    Outcome::DeadLetter(DeadLetter {
651        stage,
652        error,
653        raw: raw.to_vec(),
654    })
655}
656
657fn trim(bytes: &[u8]) -> &[u8] {
658    let start = bytes
659        .iter()
660        .position(|byte| !byte.is_ascii_whitespace())
661        .unwrap_or(bytes.len());
662    let end = bytes
663        .iter()
664        .rposition(|byte| !byte.is_ascii_whitespace())
665        .map_or(start, |position| position + 1);
666    &bytes[start..end]
667}
668
669fn source_path(kind: &str, text: &str) -> Result<SourcePath, DefinitionError> {
670    SourcePath::parse(text).ok_or_else(|| DefinitionError::SourcePath {
671        kind: kind.to_owned(),
672        path: text.to_owned(),
673    })
674}
675
676fn compile_fields(
677    kind: &str,
678    specs: &std::collections::BTreeMap<String, FieldSpec>,
679) -> Result<Vec<Field>, DefinitionError> {
680    specs
681        .iter()
682        .map(|(target, spec)| {
683            let path = FieldPath::parse(target).map_err(|source| DefinitionError::Target {
684                kind: kind.to_owned(),
685                target: target.clone(),
686                source,
687            })?;
688            let reserved = match path.segments()[0].as_str() {
689                "class_uid" | "category_uid" | "type_uid" | "activity_id" => {
690                    Some("the kind's `class`")
691                }
692                "unmapped" => Some("the kind's `unmapped` list"),
693                _ => None,
694            };
695            if let Some(reason) = reserved {
696                return Err(DefinitionError::Reserved {
697                    kind: kind.to_owned(),
698                    target: target.clone(),
699                    reason,
700                });
701            }
702            let source = match spec {
703                FieldSpec::Path(from) => Source::Path {
704                    path: source_path(kind, from)?,
705                    coercion: None,
706                },
707                FieldSpec::Converted { from, coercion } => Source::Path {
708                    path: source_path(kind, from)?,
709                    coercion: Some(*coercion),
710                },
711                FieldSpec::Translated {
712                    from,
713                    map,
714                    otherwise,
715                } => {
716                    let invalid = |reason| DefinitionError::Translation {
717                        kind: kind.to_owned(),
718                        target: target.clone(),
719                        reason,
720                    };
721                    let mut values = map.values().chain(otherwise).map(Value::from);
722                    let first = values.next().ok_or_else(|| invalid("is empty"))?;
723                    if values.any(|value| Writes::of(&value) != Writes::of(&first)) {
724                        return Err(invalid("mixes values of different types"));
725                    }
726                    Source::Translate {
727                        path: source_path(kind, from)?,
728                        map: map
729                            .iter()
730                            .map(|(key, value)| (key.clone(), Value::from(value)))
731                            .collect(),
732                        otherwise: otherwise.as_ref().map(Value::from),
733                    }
734                }
735                FieldSpec::Value { value } => Source::Constant(Value::from(value)),
736            };
737            Ok(Field {
738                target: path,
739                source,
740            })
741        })
742        .collect()
743}
744
745/// Rejects two fields writing the same attribute, or one inside another:
746/// the second write would replace or be lost under the first.
747fn check_overlaps(kind: &str, fields: &[Field]) -> Result<(), DefinitionError> {
748    for (index, first) in fields.iter().enumerate() {
749        for second in &fields[index + 1..] {
750            let (a, b) = (first.target.segments(), second.target.segments());
751            if a.starts_with(b) || b.starts_with(a) {
752                return Err(DefinitionError::Overlap {
753                    kind: kind.to_owned(),
754                    first: first.target.as_str().to_owned(),
755                    second: second.target.as_str().to_owned(),
756                });
757            }
758        }
759    }
760    Ok(())
761}
762
763/// Checks the class, the activity, and every field against the OCSF schema,
764/// so that a misspelled attribute fails here rather than produce events no
765/// rule reads.
766fn check_schema(
767    kind: &str,
768    class_uid: u32,
769    activity_id: u32,
770    fields: &[Field],
771) -> Result<(), DefinitionError> {
772    let class = schema::class(class_uid).ok_or_else(|| DefinitionError::UnknownClass {
773        kind: kind.to_owned(),
774        class_uid,
775        version: goliath_ocsf::SCHEMA_VERSION,
776    })?;
777    let activities = class
778        .attribute("activity_id")
779        .map(schema::Attribute::enum_values)
780        .unwrap_or_default();
781    if !activities.contains(&i64::from(activity_id)) {
782        return Err(DefinitionError::UnknownActivity {
783            kind: kind.to_owned(),
784            class: class.name(),
785            activity_id,
786        });
787    }
788    for field in fields {
789        let target = field.target.as_str();
790        let named = attribute_path(kind, class, field.target.segments())?;
791        let found = class
792            .resolve(&named)
793            .map_err(|source| DefinitionError::Attribute {
794                kind: kind.to_owned(),
795                source,
796            })?;
797        // A copy keeps whatever the source holds, and a free-form attribute
798        // takes anything, so neither has a type to check.
799        let Some(writes) = field.source.writes() else {
800            continue;
801        };
802        if found.free_form {
803            continue;
804        }
805        let attribute = found.attribute;
806        let fits = match writes {
807            Writes::Fingerprints => attribute.is_array() && attribute.type_name() == "fingerprint",
808            _ if attribute.is_array() => false,
809            Writes::Boolean => attribute.base() == Base::Boolean,
810            Writes::Integer => matches!(attribute.base(), Base::Integer | Base::Long),
811            Writes::Text => attribute.base() == Base::String,
812            Writes::Timestamp => attribute.type_name() == "timestamp_t",
813            Writes::Ip => attribute.type_name() == "ip_t",
814        };
815        if !fits {
816            let holds = match (attribute.is_array(), attribute.base()) {
817                (true, _) => format!("an array of `{}`", attribute.type_name()),
818                (false, Base::Object) => format!("an object `{}`", attribute.type_name()),
819                (false, _) => format!("`{}`", attribute.type_name()),
820            };
821            return Err(DefinitionError::Type {
822                kind: kind.to_owned(),
823                target: target.to_owned(),
824                holds,
825                writes: writes.describe(),
826            });
827        }
828        let values = attribute.enum_values();
829        let unknown = field
830            .source
831            .constants()
832            .filter_map(Value::as_i64)
833            .find(|value| !values.is_empty() && !values.contains(value));
834        if let Some(value) = unknown {
835            return Err(DefinitionError::UnknownValue {
836                kind: kind.to_owned(),
837                target: target.to_owned(),
838                value,
839            });
840        }
841    }
842    Ok(())
843}
844
845/// The attribute path of a target, without the indexes that name elements
846/// of arrays, such as `evidences.src_endpoint.ip` for
847/// `evidences.0.src_endpoint.ip`. Every array the target passes through
848/// must be followed by an index, and every index must follow an array.
849fn attribute_path(
850    kind: &str,
851    class: &schema::Class,
852    segments: &[String],
853) -> Result<String, DefinitionError> {
854    let target = || segments.join(".");
855    let is_index = |segment: &str| segment.bytes().all(|byte| byte.is_ascii_digit());
856    let mut named = String::new();
857    for (position, segment) in segments.iter().enumerate() {
858        // An index first is a name, which no class has.
859        if is_index(segment) && !named.is_empty() {
860            let array = class
861                .resolve(&named)
862                .is_ok_and(|found| found.attribute.is_array());
863            if !array {
864                return Err(DefinitionError::NotAnArray {
865                    kind: kind.to_owned(),
866                    target: target(),
867                    attribute: named,
868                });
869            }
870            continue;
871        }
872        if !named.is_empty() {
873            named.push('.');
874        }
875        named.push_str(segment);
876        let continues = segments
877            .get(position + 1)
878            .is_some_and(|next| !is_index(next));
879        if continues
880            && class
881                .resolve(&named)
882                .is_ok_and(|found| found.attribute.is_array() && !found.free_form)
883        {
884            return Err(DefinitionError::WithinArray {
885                kind: kind.to_owned(),
886                target: target(),
887            });
888        }
889    }
890    Ok(named)
891}
892
893/// What a field writes, where that is known before any record is read.
894#[derive(Debug, Clone, Copy, PartialEq, Eq)]
895enum Writes {
896    Boolean,
897    Integer,
898    Text,
899    Timestamp,
900    Ip,
901    Fingerprints,
902}
903
904impl Writes {
905    /// What writing `value` writes; nothing known for a list or an object.
906    fn of(value: &Value) -> Option<Self> {
907        match value {
908            Value::Bool(_) => Some(Self::Boolean),
909            Value::Number(_) => Some(Self::Integer),
910            Value::String(_) => Some(Self::Text),
911            _ => None,
912        }
913    }
914
915    fn describe(self) -> &'static str {
916        match self {
917            Self::Boolean => "a boolean",
918            Self::Integer => "an integer",
919            Self::Text => "text",
920            Self::Timestamp => "a timestamp",
921            Self::Ip => "an IP address",
922            Self::Fingerprints => "an array of fingerprints",
923        }
924    }
925}
926
927impl Source {
928    fn writes(&self) -> Option<Writes> {
929        match self {
930            Self::Constant(value) => Writes::of(value),
931            // Every value of a table has the same type, checked when it is
932            // compiled.
933            Self::Translate { map, .. } => map.values().next().and_then(Writes::of),
934            Self::Path { coercion: None, .. } => None,
935            Self::Path {
936                coercion: Some(coercion),
937                ..
938            } => Some(match coercion {
939                Coercion::String => Writes::Text,
940                Coercion::Integer => Writes::Integer,
941                Coercion::Timestamp | Coercion::UtcTimestamp | Coercion::UnixSeconds => {
942                    Writes::Timestamp
943                }
944                Coercion::Ip => Writes::Ip,
945                Coercion::Fingerprints => Writes::Fingerprints,
946            }),
947        }
948    }
949
950    /// Whether the source value also stays under `unmapped`, as written.
951    fn keeps_source(&self) -> bool {
952        matches!(
953            self,
954            Self::Path {
955                coercion: Some(Coercion::Fingerprints),
956                ..
957            }
958        )
959    }
960}
961
962impl Source {
963    /// Every value this source can write that is fixed by the definition.
964    fn constants(&self) -> impl Iterator<Item = &Value> {
965        let (map, extra) = match self {
966            Self::Constant(value) => (None, Some(value)),
967            Self::Translate { map, otherwise, .. } => (Some(map), otherwise.as_ref()),
968            Self::Path { .. } => (None, None),
969        };
970        map.into_iter().flat_map(BTreeMap::values).chain(extra)
971    }
972
973    /// The value to write for `found`, or why there is none.
974    fn convert(&self, found: &Value) -> Result<Value, String> {
975        match self {
976            Self::Constant(value) => Ok(value.clone()),
977            Self::Path { coercion, .. } => coerce(found, *coercion),
978            Self::Translate { map, otherwise, .. } => {
979                let key = match found {
980                    Value::String(text) => text.clone(),
981                    Value::Number(_) | Value::Bool(_) => found.to_string(),
982                    other => return Err(format!("cannot translate {}", describe(other))),
983                };
984                map.get(&key)
985                    .or(otherwise.as_ref())
986                    .cloned()
987                    .ok_or_else(|| format!("`{key}` is not in the translation table"))
988            }
989        }
990    }
991}
992
993/// Writes `value` at `segments`, creating objects on the way, and arrays
994/// where a segment is an index, such as `0` of `evidences.0.src_endpoint`,
995/// their elements before it empty objects. Overlapping targets are rejected
996/// when the definition is compiled, so the way is always clear.
997fn set(object: &mut Map<String, Value>, segments: &[String], value: Value) {
998    let Some((first, rest)) = segments.split_first() else {
999        return;
1000    };
1001    if rest.is_empty() {
1002        object.insert(first.clone(), value);
1003        return;
1004    }
1005    set_within(
1006        object.entry(first.clone()).or_insert(Value::Null),
1007        rest,
1008        value,
1009    );
1010}
1011
1012fn set_within(slot: &mut Value, segments: &[String], value: Value) {
1013    let Some((first, rest)) = segments.split_first() else {
1014        *slot = value;
1015        return;
1016    };
1017    if let Ok(index) = first.parse::<usize>() {
1018        if slot.is_null() {
1019            *slot = Value::Array(Vec::new());
1020        }
1021        let Value::Array(items) = slot else {
1022            return;
1023        };
1024        if items.len() <= index {
1025            items.resize(index + 1, Value::Object(Map::new()));
1026        }
1027        set_within(&mut items[index], rest, value);
1028    } else {
1029        if slot.is_null() {
1030            *slot = Value::Object(Map::new());
1031        }
1032        let Value::Object(object) = slot else {
1033            return;
1034        };
1035        set_within(
1036            object.entry(first.clone()).or_insert(Value::Null),
1037            rest,
1038            value,
1039        );
1040    }
1041}
1042
1043fn coerce(value: &Value, coercion: Option<Coercion>) -> Result<Value, String> {
1044    let Some(coercion) = coercion else {
1045        return Ok(value.clone());
1046    };
1047    match (coercion, value) {
1048        (Coercion::String, Value::String(_)) => Ok(value.clone()),
1049        (Coercion::String, Value::Number(number)) => Ok(Value::String(number.to_string())),
1050        (Coercion::Integer, Value::Number(number)) => number
1051            .as_i64()
1052            .map(Value::from)
1053            .ok_or_else(|| format!("{number} is not a whole number")),
1054        (Coercion::Integer, Value::String(text)) => {
1055            let trimmed = text.trim();
1056            match trimmed
1057                .strip_prefix("0x")
1058                .or_else(|| trimmed.strip_prefix("0X"))
1059            {
1060                Some(digits) => i64::from_str_radix(digits, 16),
1061                None => trimmed.parse::<i64>(),
1062            }
1063            .map(Value::from)
1064            .map_err(|_| format!("`{text}` is not a whole number"))
1065        }
1066        (Coercion::Timestamp, Value::String(text)) => text
1067            .parse::<jiff::Timestamp>()
1068            .map(|time| Value::from(time.as_millisecond()))
1069            .map_err(|error| format!("`{text}` is not an RFC 3339 time: {error}")),
1070        (Coercion::UtcTimestamp, Value::String(text)) => utc_timestamp(text),
1071        (Coercion::UnixSeconds, Value::String(text)) => unix_seconds(text),
1072        (Coercion::Ip, Value::String(text)) => text
1073            .trim()
1074            .parse::<std::net::IpAddr>()
1075            .map(|_| value.clone())
1076            .map_err(|_| format!("`{text}` is not an IP address")),
1077        (Coercion::UnixSeconds, Value::Number(number)) => unix_seconds(&number.to_string()),
1078        (Coercion::Fingerprints, Value::String(text)) => fingerprints(text),
1079        (coercion, other) => Err(format!(
1080            "cannot convert {} to {coercion:?}",
1081            describe(other)
1082        )),
1083    }
1084}
1085
1086/// File hashes written as `NAME=hash` joined by commas, as OCSF
1087/// fingerprints. A name OCSF has no algorithm for, such as `IMPHASH`, is
1088/// `Other`, with the name kept.
1089fn fingerprints(text: &str) -> Result<Value, String> {
1090    let mut found = Vec::new();
1091    for pair in text
1092        .split(',')
1093        .map(str::trim)
1094        .filter(|pair| !pair.is_empty())
1095    {
1096        let Some((name, hash)) = pair.split_once('=') else {
1097            return Err(format!("`{pair}` is not a hash written as NAME=hash"));
1098        };
1099        let name = name.trim().to_ascii_uppercase();
1100        let hash = hash.trim();
1101        if hash.is_empty() || !hash.bytes().all(|byte| byte.is_ascii_hexdigit()) {
1102            return Err(format!("`{pair}` does not hold a hexadecimal hash"));
1103        }
1104        let (algorithm, algorithm_id) = match name.as_str() {
1105            "MD5" => ("MD5", 1),
1106            "SHA1" | "SHA-1" => ("SHA-1", 2),
1107            "SHA256" | "SHA-256" => ("SHA-256", 3),
1108            "SHA512" | "SHA-512" => ("SHA-512", 4),
1109            other => (other, 99),
1110        };
1111        found.push(serde_json::json!({
1112            "algorithm": algorithm,
1113            "algorithm_id": algorithm_id,
1114            "value": hash,
1115        }));
1116    }
1117    if found.is_empty() {
1118        return Err("it holds no hash".to_owned());
1119    }
1120    Ok(Value::Array(found))
1121}
1122
1123/// An RFC 3339 time, with or without an offset, as milliseconds; one
1124/// without is UTC.
1125fn utc_timestamp(text: &str) -> Result<Value, String> {
1126    if let Ok(time) = text.parse::<jiff::Timestamp>() {
1127        return Ok(Value::from(time.as_millisecond()));
1128    }
1129    text.parse::<jiff::civil::DateTime>()
1130        .and_then(|time| time.to_zoned(jiff::tz::TimeZone::UTC))
1131        .map(|time| Value::from(time.timestamp().as_millisecond()))
1132        .map_err(|error| format!("`{text}` is not an RFC 3339 time: {error}"))
1133}
1134
1135/// Seconds since the epoch, such as `1727251200.123`, as milliseconds.
1136fn unix_seconds(text: &str) -> Result<Value, String> {
1137    let invalid = || format!("`{text}` is not a count of seconds since 1970");
1138    let (whole, fraction) = text.split_once('.').unwrap_or((text, ""));
1139    let digits = |part: &str| part.bytes().all(|byte| byte.is_ascii_digit());
1140    if whole.is_empty() || !digits(whole) || !digits(fraction) {
1141        return Err(invalid());
1142    }
1143    let seconds: i64 = whole.parse().map_err(|_| invalid())?;
1144    let millis: i64 = format!("{:0<3}", &fraction[..fraction.len().min(3)])
1145        .parse()
1146        .map_err(|_| invalid())?;
1147    seconds
1148        .checked_mul(1000)
1149        .and_then(|milliseconds| milliseconds.checked_add(millis))
1150        .map(Value::from)
1151        .ok_or_else(invalid)
1152}
1153
1154fn describe(value: &Value) -> &'static str {
1155    match value {
1156        Value::Null => "null",
1157        Value::Bool(_) => "a boolean",
1158        Value::Number(_) => "a number",
1159        Value::String(_) => "text",
1160        Value::Array(_) => "a list",
1161        Value::Object(_) => "an object",
1162    }
1163}