1use 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;
12
13#[derive(Debug, Clone)]
19pub struct Normalizer {
20 name: String,
21 version: u32,
22 framing: Framing,
23 kinds: Vec<Kind>,
24}
25
26#[derive(Debug, Clone)]
27struct Kind {
28 name: String,
29 when: Vec<(SourcePath, Value)>,
30 class: Vec<(&'static str, Value)>,
32 fields: Vec<Field>,
34 unmapped: Vec<SourcePath>,
35}
36
37#[derive(Debug, Clone)]
38struct Field {
39 target: FieldPath,
40 source: Source,
41}
42
43#[derive(Debug, Clone)]
44enum Source {
45 Constant(Value),
46 Path {
47 path: SourcePath,
48 coercion: Option<Coercion>,
49 },
50 Translate {
51 path: SourcePath,
52 map: BTreeMap<String, Value>,
53 otherwise: Option<Value>,
54 },
55}
56
57#[derive(Debug, Clone, PartialEq, Eq)]
65struct SourcePath {
66 text: String,
67 segments: Vec<String>,
68}
69
70impl SourcePath {
71 fn parse(text: &str) -> Option<Self> {
72 let segments: Vec<String> = text.split('.').map(str::to_owned).collect();
73 segments
74 .iter()
75 .all(|segment| !segment.is_empty())
76 .then(|| Self {
77 text: text.to_owned(),
78 segments,
79 })
80 }
81
82 fn lookup<'a>(&self, record: &'a Value) -> Option<&'a Value> {
83 find(record, &self.segments)
84 }
85
86 fn member_of(&self, object: &Self) -> Option<String> {
89 (self.segments.len() > object.segments.len() && self.segments.starts_with(&object.segments))
90 .then(|| self.segments[object.segments.len()..].join("."))
91 }
92
93 fn is_member(&self, object: &Self, key: &str) -> bool {
95 self.member_of(object).is_some_and(|member| member == key)
96 }
97}
98
99fn find<'a>(value: &'a Value, segments: &[String]) -> Option<&'a Value> {
100 if segments.is_empty() {
101 return Some(value);
102 }
103 let object = value.as_object()?;
104 let mut name = String::new();
105 for (index, segment) in segments.iter().enumerate() {
106 if index > 0 {
107 name.push('.');
108 }
109 name.push_str(segment);
110 if let Some(found) = object
111 .get(&name)
112 .and_then(|member| find(member, &segments[index + 1..]))
113 {
114 return Some(found);
115 }
116 }
117 None
118}
119
120#[non_exhaustive]
122#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
123#[serde(rename_all = "snake_case")]
124pub enum Outcome {
125 Event(Normalized),
127 DeadLetter(DeadLetter),
129}
130
131#[non_exhaustive]
133#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
134pub struct Normalized {
135 pub id: EventId,
138 pub event: Value,
140 pub kind: String,
142 pub issues: Vec<Issue>,
146}
147
148#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
160pub struct EventId([u8; 16]);
161
162impl EventId {
163 const CONTEXT: &str = "goliath 2026-09-25 event id";
166
167 pub fn of(source: &str, raw: &[u8]) -> Self {
169 let mut hasher = blake3::Hasher::new_derive_key(Self::CONTEXT);
170 hasher.update(&(source.len() as u64).to_le_bytes());
173 hasher.update(source.as_bytes());
174 hasher.update(raw);
175 let mut id = [0; 16];
176 hasher.finalize_xof().fill(&mut id);
177 Self(id)
178 }
179
180 pub fn as_bytes(&self) -> &[u8; 16] {
182 &self.0
183 }
184}
185
186impl std::fmt::Display for EventId {
187 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
189 self.0.iter().try_for_each(|byte| write!(f, "{byte:02x}"))
190 }
191}
192
193impl std::str::FromStr for EventId {
194 type Err = String;
195
196 fn from_str(text: &str) -> Result<Self, Self::Err> {
200 let invalid = || format!("`{text}` is not 32 hexadecimal digits");
201 if text.len() != 32 {
202 return Err(invalid());
203 }
204 let mut id = [0; 16];
205 let (pairs, _) = text.as_bytes().as_chunks::<2>();
206 for (byte, pair) in id.iter_mut().zip(pairs) {
207 let pair = std::str::from_utf8(pair).map_err(|_| invalid())?;
208 *byte = u8::from_str_radix(pair, 16).map_err(|_| invalid())?;
209 }
210 Ok(Self(id))
211 }
212}
213
214impl Serialize for EventId {
216 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
217 serializer.collect_str(self)
218 }
219}
220
221impl<'de> Deserialize<'de> for EventId {
222 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
223 let text = String::deserialize(deserializer)?;
224 text.parse().map_err(serde::de::Error::custom)
225 }
226}
227
228impl std::fmt::Debug for EventId {
229 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
230 write!(f, "EventId({self})")
231 }
232}
233
234#[non_exhaustive]
236#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
237pub struct Issue {
238 pub target: String,
240 pub source: String,
242 pub reason: String,
244}
245
246#[non_exhaustive]
251#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
252pub struct DeadLetter {
253 pub stage: Stage,
255 pub error: String,
257 pub raw: Vec<u8>,
260}
261
262#[non_exhaustive]
264#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
265#[serde(rename_all = "snake_case")]
266pub enum Stage {
267 Framing,
269 Decoding,
271 Mapping,
273}
274
275impl Stage {
276 pub fn as_str(self) -> &'static str {
278 match self {
279 Self::Framing => "framing",
280 Self::Decoding => "decoding",
281 Self::Mapping => "mapping",
282 }
283 }
284}
285
286impl Normalizer {
287 pub fn from_yaml(text: &str) -> Result<Self, DefinitionError> {
293 let definition: SourceDefinition = goliath_sigma::yaml::from_str(text)?;
294 Self::new(&definition)
295 }
296
297 pub fn new(definition: &SourceDefinition) -> Result<Self, DefinitionError> {
307 if definition.kinds.is_empty() {
308 return Err(DefinitionError::NoKinds);
309 }
310 let common = compile_fields("common", &definition.common)?;
311 let mut kinds = Vec::with_capacity(definition.kinds.len());
312 for kind in &definition.kinds {
313 if kind.when.is_empty() {
314 return Err(DefinitionError::Unconditional {
315 kind: kind.name.clone(),
316 });
317 }
318 let when = kind
319 .when
320 .iter()
321 .map(|(path, value)| Ok((source_path(&kind.name, path)?, Value::from(value))))
322 .collect::<Result<_, DefinitionError>>()?;
323 let mut fields = common.clone();
324 fields.extend(compile_fields(&kind.name, &kind.fields)?);
325 check_overlaps(&kind.name, &fields)?;
326 check_schema(
327 &kind.name,
328 kind.class.class_uid,
329 kind.class.activity_id,
330 &fields,
331 )?;
332 let unmapped = kind
333 .unmapped
334 .iter()
335 .map(|path| source_path(&kind.name, path))
336 .collect::<Result<_, _>>()?;
337
338 let class_uid = kind.class.class_uid;
339 let activity_id = kind.class.activity_id;
340 let category_uid = goliath_ocsf::Event::derive_category_uid(class_uid);
341 let type_uid = goliath_ocsf::Event::derive_type_uid(class_uid, activity_id);
342 kinds.push(Kind {
343 name: kind.name.clone(),
344 when,
345 class: vec![
346 ("class_uid", Value::from(class_uid)),
347 ("category_uid", Value::from(category_uid)),
348 ("type_uid", Value::from(type_uid)),
349 ("activity_id", Value::from(activity_id)),
350 ],
351 fields,
352 unmapped,
353 });
354 }
355 match definition.decoding {
358 Decoding::Json => {}
359 }
360 Ok(Self {
361 name: definition.name.clone(),
362 version: definition.version,
363 framing: definition.framing,
364 kinds,
365 })
366 }
367
368 pub fn name(&self) -> &str {
370 &self.name
371 }
372
373 pub fn version(&self) -> u32 {
375 self.version
376 }
377
378 pub fn normalize(&self, bytes: &[u8], mut out: impl FnMut(Outcome)) {
381 match self.framing {
382 Framing::Lines => {
383 for line in bytes.split(|&byte| byte == b'\n') {
384 let line = line.strip_suffix(b"\r").unwrap_or(line);
385 if line.iter().all(u8::is_ascii_whitespace) {
386 continue;
387 }
388 out(match serde_json::from_slice::<Value>(line) {
389 Ok(record) => self.record(&record, line),
390 Err(error) => dead(Stage::Decoding, error.to_string(), line),
391 });
392 }
393 }
394 Framing::JsonValues => {
395 let mut stream = serde_json::Deserializer::from_slice(bytes).into_iter::<Value>();
396 let mut start = 0;
397 while let Some(next) = stream.next() {
398 match next {
399 Ok(record) => {
400 let end = stream.byte_offset();
401 out(self.record(&record, trim(&bytes[start..end])));
402 start = end;
403 }
404 Err(error) => {
405 out(dead(
408 Stage::Framing,
409 error.to_string(),
410 trim(&bytes[start..]),
411 ));
412 return;
413 }
414 }
415 }
416 }
417 }
418 }
419
420 fn record(&self, record: &Value, raw: &[u8]) -> Outcome {
422 if !record.is_object() {
423 return dead(
424 Stage::Decoding,
425 "the record is not a JSON object".to_owned(),
426 raw,
427 );
428 }
429 let Some(kind) = self.kinds.iter().find(|kind| {
430 kind.when
431 .iter()
432 .all(|(path, expected)| path.lookup(record) == Some(expected))
433 }) else {
434 return dead(
435 Stage::Mapping,
436 format!("no kind of source `{}` accepts the record", self.name),
437 raw,
438 );
439 };
440
441 let mut event = Map::new();
442 let mut unmapped = Map::new();
443 let mut issues = Vec::new();
444 let mut consumed: Vec<&SourcePath> = Vec::new();
445 for (name, value) in &kind.class {
446 event.insert((*name).to_owned(), value.clone());
447 }
448 for field in &kind.fields {
449 let path = match &field.source {
450 Source::Constant(value) => {
451 set(&mut event, field.target.segments(), value.clone());
452 continue;
453 }
454 Source::Path { path, .. } | Source::Translate { path, .. } => path,
455 };
456 let Some(found) = path.lookup(record).filter(|value| !value.is_null()) else {
457 continue;
458 };
459 consumed.push(path);
460 match field.source.convert(found) {
461 Ok(value) => set(&mut event, field.target.segments(), value),
462 Err(reason) => {
463 issues.push(Issue {
464 target: field.target.as_str().to_owned(),
465 source: path.text.clone(),
466 reason,
467 });
468 let name = kind
472 .unmapped
473 .iter()
474 .find_map(|object| path.member_of(object))
475 .unwrap_or_else(|| path.text.clone());
476 unmapped.insert(name, found.clone());
477 }
478 }
479 }
480 for object in &kind.unmapped {
481 let Some(Value::Object(members)) = object.lookup(record) else {
482 continue;
483 };
484 for (key, member) in members {
485 if member.is_null() || consumed.iter().any(|path| path.is_member(object, key)) {
486 continue;
487 }
488 unmapped
489 .entry(key.clone())
490 .or_insert_with(|| member.clone());
491 }
492 }
493 if !unmapped.is_empty() {
494 event.insert("unmapped".to_owned(), Value::Object(unmapped));
495 }
496 Outcome::Event(Normalized {
497 id: EventId::of(&self.name, raw),
498 event: Value::Object(event),
499 kind: kind.name.clone(),
500 issues,
501 })
502 }
503}
504
505fn dead(stage: Stage, error: String, raw: &[u8]) -> Outcome {
506 Outcome::DeadLetter(DeadLetter {
507 stage,
508 error,
509 raw: raw.to_vec(),
510 })
511}
512
513fn trim(bytes: &[u8]) -> &[u8] {
514 let start = bytes
515 .iter()
516 .position(|byte| !byte.is_ascii_whitespace())
517 .unwrap_or(bytes.len());
518 let end = bytes
519 .iter()
520 .rposition(|byte| !byte.is_ascii_whitespace())
521 .map_or(start, |position| position + 1);
522 &bytes[start..end]
523}
524
525fn source_path(kind: &str, text: &str) -> Result<SourcePath, DefinitionError> {
526 SourcePath::parse(text).ok_or_else(|| DefinitionError::SourcePath {
527 kind: kind.to_owned(),
528 path: text.to_owned(),
529 })
530}
531
532fn compile_fields(
533 kind: &str,
534 specs: &std::collections::BTreeMap<String, FieldSpec>,
535) -> Result<Vec<Field>, DefinitionError> {
536 specs
537 .iter()
538 .map(|(target, spec)| {
539 let path = FieldPath::parse(target).map_err(|source| DefinitionError::Target {
540 kind: kind.to_owned(),
541 target: target.clone(),
542 source,
543 })?;
544 let reserved = match path.segments()[0].as_str() {
545 "class_uid" | "category_uid" | "type_uid" | "activity_id" => {
546 Some("the kind's `class`")
547 }
548 "unmapped" => Some("the kind's `unmapped` list"),
549 _ => None,
550 };
551 if let Some(reason) = reserved {
552 return Err(DefinitionError::Reserved {
553 kind: kind.to_owned(),
554 target: target.clone(),
555 reason,
556 });
557 }
558 let source = match spec {
559 FieldSpec::Path(from) => Source::Path {
560 path: source_path(kind, from)?,
561 coercion: None,
562 },
563 FieldSpec::Converted { from, coercion } => Source::Path {
564 path: source_path(kind, from)?,
565 coercion: Some(*coercion),
566 },
567 FieldSpec::Translated {
568 from,
569 map,
570 otherwise,
571 } => {
572 let invalid = |reason| DefinitionError::Translation {
573 kind: kind.to_owned(),
574 target: target.clone(),
575 reason,
576 };
577 let mut values = map.values().chain(otherwise).map(Value::from);
578 let first = values.next().ok_or_else(|| invalid("is empty"))?;
579 if values.any(|value| Writes::of(&value) != Writes::of(&first)) {
580 return Err(invalid("mixes values of different types"));
581 }
582 Source::Translate {
583 path: source_path(kind, from)?,
584 map: map
585 .iter()
586 .map(|(key, value)| (key.clone(), Value::from(value)))
587 .collect(),
588 otherwise: otherwise.as_ref().map(Value::from),
589 }
590 }
591 FieldSpec::Value { value } => Source::Constant(Value::from(value)),
592 };
593 Ok(Field {
594 target: path,
595 source,
596 })
597 })
598 .collect()
599}
600
601fn check_overlaps(kind: &str, fields: &[Field]) -> Result<(), DefinitionError> {
604 for (index, first) in fields.iter().enumerate() {
605 for second in &fields[index + 1..] {
606 let (a, b) = (first.target.segments(), second.target.segments());
607 if a.starts_with(b) || b.starts_with(a) {
608 return Err(DefinitionError::Overlap {
609 kind: kind.to_owned(),
610 first: first.target.as_str().to_owned(),
611 second: second.target.as_str().to_owned(),
612 });
613 }
614 }
615 }
616 Ok(())
617}
618
619fn check_schema(
623 kind: &str,
624 class_uid: u32,
625 activity_id: u32,
626 fields: &[Field],
627) -> Result<(), DefinitionError> {
628 let class = schema::class(class_uid).ok_or_else(|| DefinitionError::UnknownClass {
629 kind: kind.to_owned(),
630 class_uid,
631 version: goliath_ocsf::SCHEMA_VERSION,
632 })?;
633 let activities = class
634 .attribute("activity_id")
635 .map(schema::Attribute::enum_values)
636 .unwrap_or_default();
637 if !activities.contains(&i64::from(activity_id)) {
638 return Err(DefinitionError::UnknownActivity {
639 kind: kind.to_owned(),
640 class: class.name(),
641 activity_id,
642 });
643 }
644 for field in fields {
645 let target = field.target.as_str();
646 let found = class
647 .resolve(target)
648 .map_err(|source| DefinitionError::Attribute {
649 kind: kind.to_owned(),
650 source,
651 })?;
652 if found.within_array {
653 return Err(DefinitionError::WithinArray {
654 kind: kind.to_owned(),
655 target: target.to_owned(),
656 });
657 }
658 let Some(writes) = field.source.writes() else {
661 continue;
662 };
663 if found.free_form {
664 continue;
665 }
666 let attribute = found.attribute;
667 let fits = !attribute.is_array()
668 && match writes {
669 Writes::Boolean => attribute.base() == Base::Boolean,
670 Writes::Integer => matches!(attribute.base(), Base::Integer | Base::Long),
671 Writes::Text => attribute.base() == Base::String,
672 Writes::Timestamp => attribute.type_name() == "timestamp_t",
673 };
674 if !fits {
675 let holds = match (attribute.is_array(), attribute.base()) {
676 (true, _) => format!("an array of `{}`", attribute.type_name()),
677 (false, Base::Object) => format!("an object `{}`", attribute.type_name()),
678 (false, _) => format!("`{}`", attribute.type_name()),
679 };
680 return Err(DefinitionError::Type {
681 kind: kind.to_owned(),
682 target: target.to_owned(),
683 holds,
684 writes: writes.describe(),
685 });
686 }
687 let values = attribute.enum_values();
688 let unknown = field
689 .source
690 .constants()
691 .filter_map(Value::as_i64)
692 .find(|value| !values.is_empty() && !values.contains(value));
693 if let Some(value) = unknown {
694 return Err(DefinitionError::UnknownValue {
695 kind: kind.to_owned(),
696 target: target.to_owned(),
697 value,
698 });
699 }
700 }
701 Ok(())
702}
703
704#[derive(Debug, Clone, Copy, PartialEq, Eq)]
706enum Writes {
707 Boolean,
708 Integer,
709 Text,
710 Timestamp,
711}
712
713impl Writes {
714 fn of(value: &Value) -> Option<Self> {
716 match value {
717 Value::Bool(_) => Some(Self::Boolean),
718 Value::Number(_) => Some(Self::Integer),
719 Value::String(_) => Some(Self::Text),
720 _ => None,
721 }
722 }
723
724 fn describe(self) -> &'static str {
725 match self {
726 Self::Boolean => "a boolean",
727 Self::Integer => "an integer",
728 Self::Text => "text",
729 Self::Timestamp => "a timestamp",
730 }
731 }
732}
733
734impl Source {
735 fn writes(&self) -> Option<Writes> {
736 match self {
737 Self::Constant(value) => Writes::of(value),
738 Self::Translate { map, .. } => map.values().next().and_then(Writes::of),
741 Self::Path { coercion: None, .. } => None,
742 Self::Path {
743 coercion: Some(coercion),
744 ..
745 } => Some(match coercion {
746 Coercion::String => Writes::Text,
747 Coercion::Integer => Writes::Integer,
748 Coercion::Timestamp => Writes::Timestamp,
749 }),
750 }
751 }
752}
753
754impl Source {
755 fn constants(&self) -> impl Iterator<Item = &Value> {
757 let (map, extra) = match self {
758 Self::Constant(value) => (None, Some(value)),
759 Self::Translate { map, otherwise, .. } => (Some(map), otherwise.as_ref()),
760 Self::Path { .. } => (None, None),
761 };
762 map.into_iter().flat_map(BTreeMap::values).chain(extra)
763 }
764
765 fn convert(&self, found: &Value) -> Result<Value, String> {
767 match self {
768 Self::Constant(value) => Ok(value.clone()),
769 Self::Path { coercion, .. } => coerce(found, *coercion),
770 Self::Translate { map, otherwise, .. } => {
771 let key = match found {
772 Value::String(text) => text.clone(),
773 Value::Number(_) | Value::Bool(_) => found.to_string(),
774 other => return Err(format!("cannot translate {}", describe(other))),
775 };
776 map.get(&key)
777 .or(otherwise.as_ref())
778 .cloned()
779 .ok_or_else(|| format!("`{key}` is not in the translation table"))
780 }
781 }
782 }
783}
784
785fn set(object: &mut Map<String, Value>, segments: &[String], value: Value) {
789 let Some((last, parents)) = segments.split_last() else {
790 return;
791 };
792 let mut object = object;
793 for segment in parents {
794 let child = object
795 .entry(segment.clone())
796 .or_insert_with(|| Value::Object(Map::new()));
797 let Value::Object(child) = child else {
798 return;
799 };
800 object = child;
801 }
802 object.insert(last.clone(), value);
803}
804
805fn coerce(value: &Value, coercion: Option<Coercion>) -> Result<Value, String> {
806 let Some(coercion) = coercion else {
807 return Ok(value.clone());
808 };
809 match (coercion, value) {
810 (Coercion::String, Value::String(_)) => Ok(value.clone()),
811 (Coercion::String, Value::Number(number)) => Ok(Value::String(number.to_string())),
812 (Coercion::Integer, Value::Number(number)) => number
813 .as_i64()
814 .map(Value::from)
815 .ok_or_else(|| format!("{number} is not a whole number")),
816 (Coercion::Integer, Value::String(text)) => text
817 .trim()
818 .parse::<i64>()
819 .map(Value::from)
820 .map_err(|_| format!("`{text}` is not a whole number")),
821 (Coercion::Timestamp, Value::String(text)) => text
822 .parse::<jiff::Timestamp>()
823 .map(|time| Value::from(time.as_millisecond()))
824 .map_err(|error| format!("`{text}` is not an RFC 3339 time: {error}")),
825 (coercion, other) => Err(format!(
826 "cannot convert {} to {coercion:?}",
827 describe(other)
828 )),
829 }
830}
831
832fn describe(value: &Value) -> &'static str {
833 match value {
834 Value::Null => "null",
835 Value::Bool(_) => "a boolean",
836 Value::Number(_) => "a number",
837 Value::String(_) => "text",
838 Value::Array(_) => "a list",
839 Value::Object(_) => "an object",
840 }
841}