1use goliath_ocsf::schema::{self, Base};
4use goliath_rule::FieldPath;
5use serde_json::{Map, Value};
6
7use crate::definition::{Coercion, Decoding, FieldSpec, Framing, SourceDefinition};
8use crate::error::DefinitionError;
9
10#[derive(Debug, Clone)]
16pub struct Normalizer {
17 name: String,
18 version: u32,
19 framing: Framing,
20 kinds: Vec<Kind>,
21}
22
23#[derive(Debug, Clone)]
24struct Kind {
25 name: String,
26 when: Vec<(SourcePath, Value)>,
27 class: Vec<(&'static str, Value)>,
29 fields: Vec<Field>,
31 unmapped: Vec<SourcePath>,
32}
33
34#[derive(Debug, Clone)]
35struct Field {
36 target: FieldPath,
37 source: Source,
38}
39
40#[derive(Debug, Clone)]
41enum Source {
42 Constant(Value),
43 Path {
44 path: SourcePath,
45 coercion: Option<Coercion>,
46 },
47}
48
49#[derive(Debug, Clone, PartialEq, Eq)]
52struct SourcePath {
53 text: String,
54 segments: Vec<String>,
55}
56
57impl SourcePath {
58 fn parse(text: &str) -> Option<Self> {
59 let segments: Vec<String> = text.split('.').map(str::to_owned).collect();
60 segments
61 .iter()
62 .all(|segment| !segment.is_empty())
63 .then(|| Self {
64 text: text.to_owned(),
65 segments,
66 })
67 }
68
69 fn lookup<'a>(&self, record: &'a Value) -> Option<&'a Value> {
70 self.segments
71 .iter()
72 .try_fold(record, |value, segment| value.get(segment.as_str()))
73 }
74
75 fn is_member(&self, object: &Self, key: &str) -> bool {
77 self.segments.len() == object.segments.len() + 1
78 && self.segments.starts_with(&object.segments)
79 && self.segments.last().is_some_and(|last| last == key)
80 }
81
82 fn last(&self) -> &str {
83 self.segments.last().map_or("", String::as_str)
84 }
85}
86
87#[non_exhaustive]
89#[derive(Debug, Clone, PartialEq)]
90pub enum Outcome {
91 Event(Normalized),
93 DeadLetter(DeadLetter),
95}
96
97#[non_exhaustive]
99#[derive(Debug, Clone, PartialEq)]
100pub struct Normalized {
101 pub id: EventId,
104 pub event: Value,
106 pub kind: String,
108 pub issues: Vec<Issue>,
112}
113
114#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
126pub struct EventId([u8; 16]);
127
128impl EventId {
129 const CONTEXT: &str = "goliath 2026-09-25 event id";
132
133 pub fn of(source: &str, raw: &[u8]) -> Self {
135 let mut hasher = blake3::Hasher::new_derive_key(Self::CONTEXT);
136 hasher.update(&(source.len() as u64).to_le_bytes());
139 hasher.update(source.as_bytes());
140 hasher.update(raw);
141 let mut id = [0; 16];
142 hasher.finalize_xof().fill(&mut id);
143 Self(id)
144 }
145
146 pub fn as_bytes(&self) -> &[u8; 16] {
148 &self.0
149 }
150}
151
152impl std::fmt::Display for EventId {
153 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
155 self.0.iter().try_for_each(|byte| write!(f, "{byte:02x}"))
156 }
157}
158
159impl std::fmt::Debug for EventId {
160 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
161 write!(f, "EventId({self})")
162 }
163}
164
165#[non_exhaustive]
167#[derive(Debug, Clone, PartialEq, Eq)]
168pub struct Issue {
169 pub target: String,
171 pub source: String,
173 pub reason: String,
175}
176
177#[non_exhaustive]
182#[derive(Debug, Clone, PartialEq, Eq)]
183pub struct DeadLetter {
184 pub stage: Stage,
186 pub error: String,
188 pub raw: Vec<u8>,
191}
192
193#[non_exhaustive]
195#[derive(Debug, Clone, Copy, PartialEq, Eq)]
196pub enum Stage {
197 Framing,
199 Decoding,
201 Mapping,
203}
204
205impl Stage {
206 pub fn as_str(self) -> &'static str {
208 match self {
209 Self::Framing => "framing",
210 Self::Decoding => "decoding",
211 Self::Mapping => "mapping",
212 }
213 }
214}
215
216impl Normalizer {
217 pub fn from_yaml(text: &str) -> Result<Self, DefinitionError> {
223 let definition: SourceDefinition = goliath_sigma::yaml::from_str(text)?;
224 Self::new(&definition)
225 }
226
227 pub fn new(definition: &SourceDefinition) -> Result<Self, DefinitionError> {
237 if definition.kinds.is_empty() {
238 return Err(DefinitionError::NoKinds);
239 }
240 let common = compile_fields("common", &definition.common)?;
241 let mut kinds = Vec::with_capacity(definition.kinds.len());
242 for kind in &definition.kinds {
243 if kind.when.is_empty() {
244 return Err(DefinitionError::Unconditional {
245 kind: kind.name.clone(),
246 });
247 }
248 let when = kind
249 .when
250 .iter()
251 .map(|(path, value)| Ok((source_path(&kind.name, path)?, Value::from(value))))
252 .collect::<Result<_, DefinitionError>>()?;
253 let mut fields = common.clone();
254 fields.extend(compile_fields(&kind.name, &kind.fields)?);
255 check_overlaps(&kind.name, &fields)?;
256 check_schema(
257 &kind.name,
258 kind.class.class_uid,
259 kind.class.activity_id,
260 &fields,
261 )?;
262 let unmapped = kind
263 .unmapped
264 .iter()
265 .map(|path| source_path(&kind.name, path))
266 .collect::<Result<_, _>>()?;
267
268 let class_uid = kind.class.class_uid;
269 let activity_id = kind.class.activity_id;
270 let category_uid = goliath_ocsf::Event::derive_category_uid(class_uid);
271 let type_uid = goliath_ocsf::Event::derive_type_uid(class_uid, activity_id);
272 kinds.push(Kind {
273 name: kind.name.clone(),
274 when,
275 class: vec![
276 ("class_uid", Value::from(class_uid)),
277 ("category_uid", Value::from(category_uid)),
278 ("type_uid", Value::from(type_uid)),
279 ("activity_id", Value::from(activity_id)),
280 ],
281 fields,
282 unmapped,
283 });
284 }
285 match definition.decoding {
288 Decoding::Json => {}
289 }
290 Ok(Self {
291 name: definition.name.clone(),
292 version: definition.version,
293 framing: definition.framing,
294 kinds,
295 })
296 }
297
298 pub fn name(&self) -> &str {
300 &self.name
301 }
302
303 pub fn version(&self) -> u32 {
305 self.version
306 }
307
308 pub fn normalize(&self, bytes: &[u8], mut out: impl FnMut(Outcome)) {
311 match self.framing {
312 Framing::Lines => {
313 for line in bytes.split(|&byte| byte == b'\n') {
314 let line = line.strip_suffix(b"\r").unwrap_or(line);
315 if line.iter().all(u8::is_ascii_whitespace) {
316 continue;
317 }
318 out(match serde_json::from_slice::<Value>(line) {
319 Ok(record) => self.record(&record, line),
320 Err(error) => dead(Stage::Decoding, error.to_string(), line),
321 });
322 }
323 }
324 Framing::JsonValues => {
325 let mut stream = serde_json::Deserializer::from_slice(bytes).into_iter::<Value>();
326 let mut start = 0;
327 while let Some(next) = stream.next() {
328 match next {
329 Ok(record) => {
330 let end = stream.byte_offset();
331 out(self.record(&record, trim(&bytes[start..end])));
332 start = end;
333 }
334 Err(error) => {
335 out(dead(
338 Stage::Framing,
339 error.to_string(),
340 trim(&bytes[start..]),
341 ));
342 return;
343 }
344 }
345 }
346 }
347 }
348 }
349
350 fn record(&self, record: &Value, raw: &[u8]) -> Outcome {
352 if !record.is_object() {
353 return dead(
354 Stage::Decoding,
355 "the record is not a JSON object".to_owned(),
356 raw,
357 );
358 }
359 let Some(kind) = self.kinds.iter().find(|kind| {
360 kind.when
361 .iter()
362 .all(|(path, expected)| path.lookup(record) == Some(expected))
363 }) else {
364 return dead(
365 Stage::Mapping,
366 format!("no kind of source `{}` accepts the record", self.name),
367 raw,
368 );
369 };
370
371 let mut event = Map::new();
372 let mut unmapped = Map::new();
373 let mut issues = Vec::new();
374 let mut consumed: Vec<&SourcePath> = Vec::new();
375 for (name, value) in &kind.class {
376 event.insert((*name).to_owned(), value.clone());
377 }
378 for field in &kind.fields {
379 match &field.source {
380 Source::Constant(value) => set(&mut event, field.target.segments(), value.clone()),
381 Source::Path { path, coercion } => {
382 let Some(found) = path.lookup(record).filter(|value| !value.is_null()) else {
383 continue;
384 };
385 consumed.push(path);
386 match coerce(found, *coercion) {
387 Ok(value) => set(&mut event, field.target.segments(), value),
388 Err(reason) => {
389 issues.push(Issue {
390 target: field.target.as_str().to_owned(),
391 source: path.text.clone(),
392 reason,
393 });
394 let listed = kind
398 .unmapped
399 .iter()
400 .any(|object| path.is_member(object, path.last()));
401 let name = if listed { path.last() } else { &path.text };
402 unmapped.insert(name.to_owned(), found.clone());
403 }
404 }
405 }
406 }
407 }
408 for object in &kind.unmapped {
409 let Some(Value::Object(members)) = object.lookup(record) else {
410 continue;
411 };
412 for (key, member) in members {
413 if member.is_null() || consumed.iter().any(|path| path.is_member(object, key)) {
414 continue;
415 }
416 unmapped
417 .entry(key.clone())
418 .or_insert_with(|| member.clone());
419 }
420 }
421 if !unmapped.is_empty() {
422 event.insert("unmapped".to_owned(), Value::Object(unmapped));
423 }
424 Outcome::Event(Normalized {
425 id: EventId::of(&self.name, raw),
426 event: Value::Object(event),
427 kind: kind.name.clone(),
428 issues,
429 })
430 }
431}
432
433fn dead(stage: Stage, error: String, raw: &[u8]) -> Outcome {
434 Outcome::DeadLetter(DeadLetter {
435 stage,
436 error,
437 raw: raw.to_vec(),
438 })
439}
440
441fn trim(bytes: &[u8]) -> &[u8] {
442 let start = bytes
443 .iter()
444 .position(|byte| !byte.is_ascii_whitespace())
445 .unwrap_or(bytes.len());
446 let end = bytes
447 .iter()
448 .rposition(|byte| !byte.is_ascii_whitespace())
449 .map_or(start, |position| position + 1);
450 &bytes[start..end]
451}
452
453fn source_path(kind: &str, text: &str) -> Result<SourcePath, DefinitionError> {
454 SourcePath::parse(text).ok_or_else(|| DefinitionError::SourcePath {
455 kind: kind.to_owned(),
456 path: text.to_owned(),
457 })
458}
459
460fn compile_fields(
461 kind: &str,
462 specs: &std::collections::BTreeMap<String, FieldSpec>,
463) -> Result<Vec<Field>, DefinitionError> {
464 specs
465 .iter()
466 .map(|(target, spec)| {
467 let path = FieldPath::parse(target).map_err(|source| DefinitionError::Target {
468 kind: kind.to_owned(),
469 target: target.clone(),
470 source,
471 })?;
472 let reserved = match path.segments()[0].as_str() {
473 "class_uid" | "category_uid" | "type_uid" | "activity_id" => {
474 Some("the kind's `class`")
475 }
476 "unmapped" => Some("the kind's `unmapped` list"),
477 _ => None,
478 };
479 if let Some(reason) = reserved {
480 return Err(DefinitionError::Reserved {
481 kind: kind.to_owned(),
482 target: target.clone(),
483 reason,
484 });
485 }
486 let source = match spec {
487 FieldSpec::Path(from) => Source::Path {
488 path: source_path(kind, from)?,
489 coercion: None,
490 },
491 FieldSpec::Converted { from, coercion } => Source::Path {
492 path: source_path(kind, from)?,
493 coercion: Some(*coercion),
494 },
495 FieldSpec::Value { value } => Source::Constant(Value::from(value)),
496 };
497 Ok(Field {
498 target: path,
499 source,
500 })
501 })
502 .collect()
503}
504
505fn check_overlaps(kind: &str, fields: &[Field]) -> Result<(), DefinitionError> {
508 for (index, first) in fields.iter().enumerate() {
509 for second in &fields[index + 1..] {
510 let (a, b) = (first.target.segments(), second.target.segments());
511 if a.starts_with(b) || b.starts_with(a) {
512 return Err(DefinitionError::Overlap {
513 kind: kind.to_owned(),
514 first: first.target.as_str().to_owned(),
515 second: second.target.as_str().to_owned(),
516 });
517 }
518 }
519 }
520 Ok(())
521}
522
523fn check_schema(
527 kind: &str,
528 class_uid: u32,
529 activity_id: u32,
530 fields: &[Field],
531) -> Result<(), DefinitionError> {
532 let class = schema::class(class_uid).ok_or_else(|| DefinitionError::UnknownClass {
533 kind: kind.to_owned(),
534 class_uid,
535 version: goliath_ocsf::SCHEMA_VERSION,
536 })?;
537 let activities = class
538 .attribute("activity_id")
539 .map(schema::Attribute::enum_values)
540 .unwrap_or_default();
541 if !activities.contains(&i64::from(activity_id)) {
542 return Err(DefinitionError::UnknownActivity {
543 kind: kind.to_owned(),
544 class: class.name(),
545 activity_id,
546 });
547 }
548 for field in fields {
549 let target = field.target.as_str();
550 let found = class
551 .resolve(target)
552 .map_err(|source| DefinitionError::Attribute {
553 kind: kind.to_owned(),
554 source,
555 })?;
556 if found.within_array {
557 return Err(DefinitionError::WithinArray {
558 kind: kind.to_owned(),
559 target: target.to_owned(),
560 });
561 }
562 let Some(writes) = field.source.writes() else {
565 continue;
566 };
567 if found.free_form {
568 continue;
569 }
570 let attribute = found.attribute;
571 let fits = !attribute.is_array()
572 && match writes {
573 Writes::Boolean => attribute.base() == Base::Boolean,
574 Writes::Integer => matches!(attribute.base(), Base::Integer | Base::Long),
575 Writes::Text => attribute.base() == Base::String,
576 Writes::Timestamp => attribute.type_name() == "timestamp_t",
577 };
578 if !fits {
579 let holds = match (attribute.is_array(), attribute.base()) {
580 (true, _) => format!("an array of `{}`", attribute.type_name()),
581 (false, Base::Object) => format!("an object `{}`", attribute.type_name()),
582 (false, _) => format!("`{}`", attribute.type_name()),
583 };
584 return Err(DefinitionError::Type {
585 kind: kind.to_owned(),
586 target: target.to_owned(),
587 holds,
588 writes: writes.describe(),
589 });
590 }
591 let values = attribute.enum_values();
592 if let Source::Constant(Value::Number(number)) = &field.source
593 && let Some(value) = number.as_i64()
594 && !values.is_empty()
595 && !values.contains(&value)
596 {
597 return Err(DefinitionError::UnknownValue {
598 kind: kind.to_owned(),
599 target: target.to_owned(),
600 value,
601 });
602 }
603 }
604 Ok(())
605}
606
607#[derive(Debug, Clone, Copy)]
609enum Writes {
610 Boolean,
611 Integer,
612 Text,
613 Timestamp,
614}
615
616impl Writes {
617 fn describe(self) -> &'static str {
618 match self {
619 Self::Boolean => "a boolean",
620 Self::Integer => "an integer",
621 Self::Text => "text",
622 Self::Timestamp => "a timestamp",
623 }
624 }
625}
626
627impl Source {
628 fn writes(&self) -> Option<Writes> {
629 match self {
630 Self::Constant(Value::Bool(_)) => Some(Writes::Boolean),
631 Self::Constant(Value::Number(_)) => Some(Writes::Integer),
632 Self::Constant(Value::String(_)) => Some(Writes::Text),
633 Self::Constant(_) | Self::Path { coercion: None, .. } => None,
634 Self::Path {
635 coercion: Some(coercion),
636 ..
637 } => Some(match coercion {
638 Coercion::String => Writes::Text,
639 Coercion::Integer => Writes::Integer,
640 Coercion::Timestamp => Writes::Timestamp,
641 }),
642 }
643 }
644}
645
646fn set(object: &mut Map<String, Value>, segments: &[String], value: Value) {
650 let Some((last, parents)) = segments.split_last() else {
651 return;
652 };
653 let mut object = object;
654 for segment in parents {
655 let child = object
656 .entry(segment.clone())
657 .or_insert_with(|| Value::Object(Map::new()));
658 let Value::Object(child) = child else {
659 return;
660 };
661 object = child;
662 }
663 object.insert(last.clone(), value);
664}
665
666fn coerce(value: &Value, coercion: Option<Coercion>) -> Result<Value, String> {
667 let Some(coercion) = coercion else {
668 return Ok(value.clone());
669 };
670 match (coercion, value) {
671 (Coercion::String, Value::String(_)) => Ok(value.clone()),
672 (Coercion::String, Value::Number(number)) => Ok(Value::String(number.to_string())),
673 (Coercion::Integer, Value::Number(number)) => number
674 .as_i64()
675 .map(Value::from)
676 .ok_or_else(|| format!("{number} is not a whole number")),
677 (Coercion::Integer, Value::String(text)) => text
678 .trim()
679 .parse::<i64>()
680 .map(Value::from)
681 .map_err(|_| format!("`{text}` is not a whole number")),
682 (Coercion::Timestamp, Value::String(text)) => text
683 .parse::<jiff::Timestamp>()
684 .map(|time| Value::from(time.as_millisecond()))
685 .map_err(|error| format!("`{text}` is not an RFC 3339 time: {error}")),
686 (coercion, other) => Err(format!(
687 "cannot convert {} to {coercion:?}",
688 describe(other)
689 )),
690 }
691}
692
693fn describe(value: &Value) -> &'static str {
694 match value {
695 Value::Null => "null",
696 Value::Bool(_) => "a boolean",
697 Value::Number(_) => "a number",
698 Value::String(_) => "text",
699 Value::Array(_) => "a list",
700 Value::Object(_) => "an object",
701 }
702}