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