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;
12use crate::{auditd, syslog};
13
14#[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: Vec<(&'static str, Value)>,
36 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#[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 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 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#[non_exhaustive]
133#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
134#[serde(rename_all = "snake_case")]
135pub enum Outcome {
136 Event(Normalized),
138 DeadLetter(DeadLetter),
140}
141
142#[non_exhaustive]
144#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
145pub struct Normalized {
146 pub id: EventId,
149 pub event: Value,
151 pub kind: String,
153 pub issues: Vec<Issue>,
157}
158
159#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
171pub struct EventId([u8; 16]);
172
173impl EventId {
174 const CONTEXT: &str = "goliath 2026-09-25 event id";
177
178 pub fn of(source: &str, raw: &[u8]) -> Self {
180 let mut hasher = blake3::Hasher::new_derive_key(Self::CONTEXT);
181 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 pub fn as_bytes(&self) -> &[u8; 16] {
193 &self.0
194 }
195}
196
197impl std::fmt::Display for EventId {
198 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 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
225impl 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#[non_exhaustive]
247#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
248pub struct Issue {
249 pub target: String,
251 pub source: String,
253 pub reason: String,
255}
256
257#[non_exhaustive]
262#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
263pub struct DeadLetter {
264 pub stage: Stage,
266 pub error: String,
268 pub raw: Vec<u8>,
271}
272
273#[non_exhaustive]
275#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
276#[serde(rename_all = "snake_case")]
277pub enum Stage {
278 Framing,
280 Decoding,
282 Mapping,
284}
285
286impl Stage {
287 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 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 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 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 pub fn name(&self) -> &str {
418 &self.name
419 }
420
421 pub fn framing(&self) -> Framing {
423 self.framing
424 }
425
426 pub fn version(&self) -> u32 {
428 self.version
429 }
430
431 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 out(dead(
482 Stage::Framing,
483 error.to_string(),
484 trim(&bytes[start..]),
485 ));
486 return;
487 }
488 }
489 }
490 }
491 }
492 }
493
494 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 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 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 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 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
722fn 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
740fn 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
828enum Writes {
829 Boolean,
830 Integer,
831 Text,
832 Timestamp,
833 Ip,
834}
835
836impl Writes {
837 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 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::UtcTimestamp | Coercion::UnixSeconds => {
873 Writes::Timestamp
874 }
875 Coercion::Ip => Writes::Ip,
876 }),
877 }
878 }
879}
880
881impl Source {
882 fn constants(&self) -> impl Iterator<Item = &Value> {
884 let (map, extra) = match self {
885 Self::Constant(value) => (None, Some(value)),
886 Self::Translate { map, otherwise, .. } => (Some(map), otherwise.as_ref()),
887 Self::Path { .. } => (None, None),
888 };
889 map.into_iter().flat_map(BTreeMap::values).chain(extra)
890 }
891
892 fn convert(&self, found: &Value) -> Result<Value, String> {
894 match self {
895 Self::Constant(value) => Ok(value.clone()),
896 Self::Path { coercion, .. } => coerce(found, *coercion),
897 Self::Translate { map, otherwise, .. } => {
898 let key = match found {
899 Value::String(text) => text.clone(),
900 Value::Number(_) | Value::Bool(_) => found.to_string(),
901 other => return Err(format!("cannot translate {}", describe(other))),
902 };
903 map.get(&key)
904 .or(otherwise.as_ref())
905 .cloned()
906 .ok_or_else(|| format!("`{key}` is not in the translation table"))
907 }
908 }
909 }
910}
911
912fn set(object: &mut Map<String, Value>, segments: &[String], value: Value) {
916 let Some((last, parents)) = segments.split_last() else {
917 return;
918 };
919 let mut object = object;
920 for segment in parents {
921 let child = object
922 .entry(segment.clone())
923 .or_insert_with(|| Value::Object(Map::new()));
924 let Value::Object(child) = child else {
925 return;
926 };
927 object = child;
928 }
929 object.insert(last.clone(), value);
930}
931
932fn coerce(value: &Value, coercion: Option<Coercion>) -> Result<Value, String> {
933 let Some(coercion) = coercion else {
934 return Ok(value.clone());
935 };
936 match (coercion, value) {
937 (Coercion::String, Value::String(_)) => Ok(value.clone()),
938 (Coercion::String, Value::Number(number)) => Ok(Value::String(number.to_string())),
939 (Coercion::Integer, Value::Number(number)) => number
940 .as_i64()
941 .map(Value::from)
942 .ok_or_else(|| format!("{number} is not a whole number")),
943 (Coercion::Integer, Value::String(text)) => {
944 let trimmed = text.trim();
945 match trimmed
946 .strip_prefix("0x")
947 .or_else(|| trimmed.strip_prefix("0X"))
948 {
949 Some(digits) => i64::from_str_radix(digits, 16),
950 None => trimmed.parse::<i64>(),
951 }
952 .map(Value::from)
953 .map_err(|_| format!("`{text}` is not a whole number"))
954 }
955 (Coercion::Timestamp, Value::String(text)) => text
956 .parse::<jiff::Timestamp>()
957 .map(|time| Value::from(time.as_millisecond()))
958 .map_err(|error| format!("`{text}` is not an RFC 3339 time: {error}")),
959 (Coercion::UtcTimestamp, Value::String(text)) => utc_timestamp(text),
960 (Coercion::UnixSeconds, Value::String(text)) => unix_seconds(text),
961 (Coercion::Ip, Value::String(text)) => text
962 .trim()
963 .parse::<std::net::IpAddr>()
964 .map(|_| value.clone())
965 .map_err(|_| format!("`{text}` is not an IP address")),
966 (Coercion::UnixSeconds, Value::Number(number)) => unix_seconds(&number.to_string()),
967 (coercion, other) => Err(format!(
968 "cannot convert {} to {coercion:?}",
969 describe(other)
970 )),
971 }
972}
973
974fn utc_timestamp(text: &str) -> Result<Value, String> {
977 if let Ok(time) = text.parse::<jiff::Timestamp>() {
978 return Ok(Value::from(time.as_millisecond()));
979 }
980 text.parse::<jiff::civil::DateTime>()
981 .and_then(|time| time.to_zoned(jiff::tz::TimeZone::UTC))
982 .map(|time| Value::from(time.timestamp().as_millisecond()))
983 .map_err(|error| format!("`{text}` is not an RFC 3339 time: {error}"))
984}
985
986fn unix_seconds(text: &str) -> Result<Value, String> {
988 let invalid = || format!("`{text}` is not a count of seconds since 1970");
989 let (whole, fraction) = text.split_once('.').unwrap_or((text, ""));
990 let digits = |part: &str| part.bytes().all(|byte| byte.is_ascii_digit());
991 if whole.is_empty() || !digits(whole) || !digits(fraction) {
992 return Err(invalid());
993 }
994 let seconds: i64 = whole.parse().map_err(|_| invalid())?;
995 let millis: i64 = format!("{:0<3}", &fraction[..fraction.len().min(3)])
996 .parse()
997 .map_err(|_| invalid())?;
998 seconds
999 .checked_mul(1000)
1000 .and_then(|milliseconds| milliseconds.checked_add(millis))
1001 .map(Value::from)
1002 .ok_or_else(invalid)
1003}
1004
1005fn describe(value: &Value) -> &'static str {
1006 match value {
1007 Value::Null => "null",
1008 Value::Bool(_) => "a boolean",
1009 Value::Number(_) => "a number",
1010 Value::String(_) => "text",
1011 Value::Array(_) => "a list",
1012 Value::Object(_) => "an object",
1013 }
1014}