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 found = class
768            .resolve(target)
769            .map_err(|source| DefinitionError::Attribute {
770                kind: kind.to_owned(),
771                source,
772            })?;
773        if found.within_array {
774            return Err(DefinitionError::WithinArray {
775                kind: kind.to_owned(),
776                target: target.to_owned(),
777            });
778        }
779        // A copy keeps whatever the source holds, and a free-form attribute
780        // takes anything, so neither has a type to check.
781        let Some(writes) = field.source.writes() else {
782            continue;
783        };
784        if found.free_form {
785            continue;
786        }
787        let attribute = found.attribute;
788        let fits = !attribute.is_array()
789            && match writes {
790                Writes::Boolean => attribute.base() == Base::Boolean,
791                Writes::Integer => matches!(attribute.base(), Base::Integer | Base::Long),
792                Writes::Text => attribute.base() == Base::String,
793                Writes::Timestamp => attribute.type_name() == "timestamp_t",
794                Writes::Ip => attribute.type_name() == "ip_t",
795            };
796        if !fits {
797            let holds = match (attribute.is_array(), attribute.base()) {
798                (true, _) => format!("an array of `{}`", attribute.type_name()),
799                (false, Base::Object) => format!("an object `{}`", attribute.type_name()),
800                (false, _) => format!("`{}`", attribute.type_name()),
801            };
802            return Err(DefinitionError::Type {
803                kind: kind.to_owned(),
804                target: target.to_owned(),
805                holds,
806                writes: writes.describe(),
807            });
808        }
809        let values = attribute.enum_values();
810        let unknown = field
811            .source
812            .constants()
813            .filter_map(Value::as_i64)
814            .find(|value| !values.is_empty() && !values.contains(value));
815        if let Some(value) = unknown {
816            return Err(DefinitionError::UnknownValue {
817                kind: kind.to_owned(),
818                target: target.to_owned(),
819                value,
820            });
821        }
822    }
823    Ok(())
824}
825
826/// What a field writes, where that is known before any record is read.
827#[derive(Debug, Clone, Copy, PartialEq, Eq)]
828enum Writes {
829    Boolean,
830    Integer,
831    Text,
832    Timestamp,
833    Ip,
834}
835
836impl Writes {
837    /// What writing `value` writes; nothing known for a list or an object.
838    fn of(value: &Value) -> Option<Self> {
839        match value {
840            Value::Bool(_) => Some(Self::Boolean),
841            Value::Number(_) => Some(Self::Integer),
842            Value::String(_) => Some(Self::Text),
843            _ => None,
844        }
845    }
846
847    fn describe(self) -> &'static str {
848        match self {
849            Self::Boolean => "a boolean",
850            Self::Integer => "an integer",
851            Self::Text => "text",
852            Self::Timestamp => "a timestamp",
853            Self::Ip => "an IP address",
854        }
855    }
856}
857
858impl Source {
859    fn writes(&self) -> Option<Writes> {
860        match self {
861            Self::Constant(value) => Writes::of(value),
862            // Every value of a table has the same type, checked when it is
863            // compiled.
864            Self::Translate { map, .. } => map.values().next().and_then(Writes::of),
865            Self::Path { coercion: None, .. } => None,
866            Self::Path {
867                coercion: Some(coercion),
868                ..
869            } => Some(match coercion {
870                Coercion::String => Writes::Text,
871                Coercion::Integer => Writes::Integer,
872                Coercion::Timestamp | Coercion::UnixSeconds => Writes::Timestamp,
873                Coercion::Ip => Writes::Ip,
874            }),
875        }
876    }
877}
878
879impl Source {
880    /// Every value this source can write that is fixed by the definition.
881    fn constants(&self) -> impl Iterator<Item = &Value> {
882        let (map, extra) = match self {
883            Self::Constant(value) => (None, Some(value)),
884            Self::Translate { map, otherwise, .. } => (Some(map), otherwise.as_ref()),
885            Self::Path { .. } => (None, None),
886        };
887        map.into_iter().flat_map(BTreeMap::values).chain(extra)
888    }
889
890    /// The value to write for `found`, or why there is none.
891    fn convert(&self, found: &Value) -> Result<Value, String> {
892        match self {
893            Self::Constant(value) => Ok(value.clone()),
894            Self::Path { coercion, .. } => coerce(found, *coercion),
895            Self::Translate { map, otherwise, .. } => {
896                let key = match found {
897                    Value::String(text) => text.clone(),
898                    Value::Number(_) | Value::Bool(_) => found.to_string(),
899                    other => return Err(format!("cannot translate {}", describe(other))),
900                };
901                map.get(&key)
902                    .or(otherwise.as_ref())
903                    .cloned()
904                    .ok_or_else(|| format!("`{key}` is not in the translation table"))
905            }
906        }
907    }
908}
909
910/// Writes `value` at `segments`, creating objects on the way. Overlapping
911/// targets are rejected when the definition is compiled, so the way is
912/// always clear.
913fn set(object: &mut Map<String, Value>, segments: &[String], value: Value) {
914    let Some((last, parents)) = segments.split_last() else {
915        return;
916    };
917    let mut object = object;
918    for segment in parents {
919        let child = object
920            .entry(segment.clone())
921            .or_insert_with(|| Value::Object(Map::new()));
922        let Value::Object(child) = child else {
923            return;
924        };
925        object = child;
926    }
927    object.insert(last.clone(), value);
928}
929
930fn coerce(value: &Value, coercion: Option<Coercion>) -> Result<Value, String> {
931    let Some(coercion) = coercion else {
932        return Ok(value.clone());
933    };
934    match (coercion, value) {
935        (Coercion::String, Value::String(_)) => Ok(value.clone()),
936        (Coercion::String, Value::Number(number)) => Ok(Value::String(number.to_string())),
937        (Coercion::Integer, Value::Number(number)) => number
938            .as_i64()
939            .map(Value::from)
940            .ok_or_else(|| format!("{number} is not a whole number")),
941        (Coercion::Integer, Value::String(text)) => {
942            let trimmed = text.trim();
943            match trimmed
944                .strip_prefix("0x")
945                .or_else(|| trimmed.strip_prefix("0X"))
946            {
947                Some(digits) => i64::from_str_radix(digits, 16),
948                None => trimmed.parse::<i64>(),
949            }
950            .map(Value::from)
951            .map_err(|_| format!("`{text}` is not a whole number"))
952        }
953        (Coercion::Timestamp, Value::String(text)) => text
954            .parse::<jiff::Timestamp>()
955            .map(|time| Value::from(time.as_millisecond()))
956            .map_err(|error| format!("`{text}` is not an RFC 3339 time: {error}")),
957        (Coercion::UnixSeconds, Value::String(text)) => unix_seconds(text),
958        (Coercion::Ip, Value::String(text)) => text
959            .trim()
960            .parse::<std::net::IpAddr>()
961            .map(|_| value.clone())
962            .map_err(|_| format!("`{text}` is not an IP address")),
963        (Coercion::UnixSeconds, Value::Number(number)) => unix_seconds(&number.to_string()),
964        (coercion, other) => Err(format!(
965            "cannot convert {} to {coercion:?}",
966            describe(other)
967        )),
968    }
969}
970
971/// Seconds since the epoch, such as `1727251200.123`, as milliseconds.
972fn unix_seconds(text: &str) -> Result<Value, String> {
973    let invalid = || format!("`{text}` is not a count of seconds since 1970");
974    let (whole, fraction) = text.split_once('.').unwrap_or((text, ""));
975    let digits = |part: &str| part.bytes().all(|byte| byte.is_ascii_digit());
976    if whole.is_empty() || !digits(whole) || !digits(fraction) {
977        return Err(invalid());
978    }
979    let seconds: i64 = whole.parse().map_err(|_| invalid())?;
980    let millis: i64 = format!("{:0<3}", &fraction[..fraction.len().min(3)])
981        .parse()
982        .map_err(|_| invalid())?;
983    seconds
984        .checked_mul(1000)
985        .and_then(|milliseconds| milliseconds.checked_add(millis))
986        .map(Value::from)
987        .ok_or_else(invalid)
988}
989
990fn describe(value: &Value) -> &'static str {
991    match value {
992        Value::Null => "null",
993        Value::Bool(_) => "a boolean",
994        Value::Number(_) => "a number",
995        Value::String(_) => "text",
996        Value::Array(_) => "a list",
997        Value::Object(_) => "an object",
998    }
999}