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)]
69struct SourcePath {
70 text: String,
71 segments: Vec<String>,
72}
73
74impl SourcePath {
75 fn parse(text: &str) -> Option<Self> {
76 let segments: Vec<String> = text.split('.').map(str::to_owned).collect();
77 segments
78 .iter()
79 .all(|segment| !segment.is_empty())
80 .then(|| Self {
81 text: text.to_owned(),
82 segments,
83 })
84 }
85
86 fn lookup<'a>(&self, record: &'a Value) -> Option<&'a Value> {
87 find(record, &self.segments)
88 }
89
90 fn member_of(&self, object: &Self) -> Option<String> {
93 (self.segments.len() > object.segments.len() && self.segments.starts_with(&object.segments))
94 .then(|| self.segments[object.segments.len()..].join("."))
95 }
96
97 fn is_member(&self, object: &Self, key: &str) -> bool {
99 self.member_of(object).is_some_and(|member| member == key)
100 }
101}
102
103fn find<'a>(value: &'a Value, segments: &[String]) -> Option<&'a Value> {
104 if segments.is_empty() {
105 return Some(value);
106 }
107 let object = value.as_object()?;
108 let mut name = String::new();
109 for (index, segment) in segments.iter().enumerate() {
110 if index > 0 {
111 name.push('.');
112 }
113 name.push_str(segment);
114 if let Some(found) = object
115 .get(&name)
116 .and_then(|member| find(member, &segments[index + 1..]))
117 {
118 return Some(found);
119 }
120 }
121 None
122}
123
124#[non_exhaustive]
126#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
127#[serde(rename_all = "snake_case")]
128pub enum Outcome {
129 Event(Normalized),
131 DeadLetter(DeadLetter),
133}
134
135#[non_exhaustive]
137#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
138pub struct Normalized {
139 pub id: EventId,
142 pub event: Value,
144 pub kind: String,
146 pub issues: Vec<Issue>,
150}
151
152#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
164pub struct EventId([u8; 16]);
165
166impl EventId {
167 const CONTEXT: &str = "goliath 2026-09-25 event id";
170
171 pub fn of(source: &str, raw: &[u8]) -> Self {
173 let mut hasher = blake3::Hasher::new_derive_key(Self::CONTEXT);
174 hasher.update(&(source.len() as u64).to_le_bytes());
177 hasher.update(source.as_bytes());
178 hasher.update(raw);
179 let mut id = [0; 16];
180 hasher.finalize_xof().fill(&mut id);
181 Self(id)
182 }
183
184 pub fn as_bytes(&self) -> &[u8; 16] {
186 &self.0
187 }
188}
189
190impl std::fmt::Display for EventId {
191 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
193 self.0.iter().try_for_each(|byte| write!(f, "{byte:02x}"))
194 }
195}
196
197impl std::str::FromStr for EventId {
198 type Err = String;
199
200 fn from_str(text: &str) -> Result<Self, Self::Err> {
204 let invalid = || format!("`{text}` is not 32 hexadecimal digits");
205 if text.len() != 32 {
206 return Err(invalid());
207 }
208 let mut id = [0; 16];
209 let (pairs, _) = text.as_bytes().as_chunks::<2>();
210 for (byte, pair) in id.iter_mut().zip(pairs) {
211 let pair = std::str::from_utf8(pair).map_err(|_| invalid())?;
212 *byte = u8::from_str_radix(pair, 16).map_err(|_| invalid())?;
213 }
214 Ok(Self(id))
215 }
216}
217
218impl Serialize for EventId {
220 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
221 serializer.collect_str(self)
222 }
223}
224
225impl<'de> Deserialize<'de> for EventId {
226 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
227 let text = String::deserialize(deserializer)?;
228 text.parse().map_err(serde::de::Error::custom)
229 }
230}
231
232impl std::fmt::Debug for EventId {
233 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
234 write!(f, "EventId({self})")
235 }
236}
237
238#[non_exhaustive]
240#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
241pub struct Issue {
242 pub target: String,
244 pub source: String,
246 pub reason: String,
248}
249
250#[non_exhaustive]
255#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
256pub struct DeadLetter {
257 pub stage: Stage,
259 pub error: String,
261 pub raw: Vec<u8>,
264}
265
266#[non_exhaustive]
268#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
269#[serde(rename_all = "snake_case")]
270pub enum Stage {
271 Framing,
273 Decoding,
275 Mapping,
277}
278
279impl Stage {
280 pub fn as_str(self) -> &'static str {
282 match self {
283 Self::Framing => "framing",
284 Self::Decoding => "decoding",
285 Self::Mapping => "mapping",
286 }
287 }
288}
289
290impl Normalizer {
291 pub fn from_yaml(text: &str) -> Result<Self, DefinitionError> {
297 let definition: SourceDefinition = goliath_sigma::yaml::from_str(text)?;
298 Self::new(&definition)
299 }
300
301 pub fn new(definition: &SourceDefinition) -> Result<Self, DefinitionError> {
311 if definition.kinds.is_empty() {
312 return Err(DefinitionError::NoKinds);
313 }
314 let common = compile_fields("common", &definition.common)?;
315 let mut kinds = Vec::with_capacity(definition.kinds.len());
316 for kind in &definition.kinds {
317 if kind.when.is_empty() {
318 return Err(DefinitionError::Unconditional {
319 kind: kind.name.clone(),
320 });
321 }
322 let when = kind
323 .when
324 .iter()
325 .map(|(path, value)| Ok((source_path(&kind.name, path)?, Value::from(value))))
326 .collect::<Result<_, DefinitionError>>()?;
327 let mut fields = common.clone();
328 fields.extend(compile_fields(&kind.name, &kind.fields)?);
329 check_overlaps(&kind.name, &fields)?;
330 check_schema(
331 &kind.name,
332 kind.class.class_uid,
333 kind.class.activity_id,
334 &fields,
335 )?;
336 let unmapped = kind
337 .unmapped
338 .iter()
339 .map(|path| {
340 if path == "." {
343 Ok(SourcePath {
344 text: path.clone(),
345 segments: Vec::new(),
346 })
347 } else {
348 source_path(&kind.name, path)
349 }
350 })
351 .collect::<Result<_, _>>()?;
352
353 let class_uid = kind.class.class_uid;
354 let activity_id = kind.class.activity_id;
355 let category_uid = goliath_ocsf::Event::derive_category_uid(class_uid);
356 let type_uid = goliath_ocsf::Event::derive_type_uid(class_uid, activity_id);
357 kinds.push(Kind {
358 name: kind.name.clone(),
359 when,
360 class: vec![
361 ("class_uid", Value::from(class_uid)),
362 ("category_uid", Value::from(category_uid)),
363 ("type_uid", Value::from(type_uid)),
364 ("activity_id", Value::from(activity_id)),
365 ],
366 fields,
367 unmapped,
368 });
369 }
370 let fits = match definition.framing {
371 Framing::Lines => true,
372 Framing::JsonValues => definition.decoding == Decoding::Json,
373 Framing::AuditEvents => definition.decoding == Decoding::Auditd,
374 Framing::Syslog => {
375 matches!(definition.decoding, Decoding::Syslog | Decoding::SyslogJson)
376 }
377 };
378 if !fits {
379 return Err(DefinitionError::Decoding {
380 framing: match definition.framing {
381 Framing::Lines => "lines",
382 Framing::JsonValues => "json-values",
383 Framing::AuditEvents => "audit-events",
384 Framing::Syslog => "syslog",
385 },
386 decoding: match definition.decoding {
387 Decoding::Json => "json",
388 Decoding::Auditd => "auditd",
389 Decoding::Syslog => "syslog",
390 Decoding::SyslogJson => "syslog-json",
391 },
392 });
393 }
394 Ok(Self {
395 name: definition.name.clone(),
396 version: definition.version,
397 framing: definition.framing,
398 decoding: definition.decoding,
399 kinds,
400 nil: definition
401 .nil
402 .iter()
403 .map(|text| Value::from(text.as_str()))
404 .collect(),
405 unwrap: definition.unwrap.clone(),
406 })
407 }
408
409 pub fn name(&self) -> &str {
411 &self.name
412 }
413
414 pub fn framing(&self) -> Framing {
416 self.framing
417 }
418
419 pub fn version(&self) -> u32 {
421 self.version
422 }
423
424 pub fn normalize(&self, bytes: &[u8], mut out: impl FnMut(Outcome)) {
427 match self.framing {
428 Framing::Lines => {
429 for line in bytes.split(|&byte| byte == b'\n') {
430 let line = line.strip_suffix(b"\r").unwrap_or(line);
431 if line.iter().all(u8::is_ascii_whitespace) {
432 continue;
433 }
434 self.decoded(line, &mut out);
435 }
436 }
437 Framing::AuditEvents => {
438 for event in auditd::events(bytes) {
439 match event {
440 Ok(raw) => self.decoded(&raw, &mut out),
441 Err(line) => out(dead(
442 Stage::Framing,
443 "the line names no audit event".to_owned(),
444 line,
445 )),
446 }
447 }
448 }
449 Framing::Syslog => {
450 for message in syslog::messages(bytes) {
451 match message {
452 Ok(raw) => self.decoded(raw, &mut out),
453 Err(rest) => out(dead(
454 Stage::Framing,
455 "the message is shorter than its octet count".to_owned(),
456 rest,
457 )),
458 }
459 }
460 }
461 Framing::JsonValues => {
462 let mut stream = serde_json::Deserializer::from_slice(bytes).into_iter::<Value>();
463 let mut start = 0;
464 while let Some(next) = stream.next() {
465 match next {
466 Ok(record) => {
467 let end = stream.byte_offset();
468 self.records(&record, trim(&bytes[start..end]), &mut out);
469 start = end;
470 }
471 Err(error) => {
472 out(dead(
475 Stage::Framing,
476 error.to_string(),
477 trim(&bytes[start..]),
478 ));
479 return;
480 }
481 }
482 }
483 }
484 }
485 }
486
487 fn decoded(&self, raw: &[u8], out: &mut impl FnMut(Outcome)) {
489 let record = match self.decoding {
490 Decoding::Json => {
491 serde_json::from_slice::<Value>(raw).map_err(|error| error.to_string())
492 }
493 Decoding::Auditd => auditd::decode(raw),
494 Decoding::Syslog => syslog::decode(raw, syslog::Message::Text, jiff::Timestamp::now),
495 Decoding::SyslogJson => {
496 syslog::decode(raw, syslog::Message::Json, jiff::Timestamp::now)
497 }
498 };
499 match record {
500 Ok(record) => self.records(&record, raw, out),
501 Err(error) => out(dead(Stage::Decoding, error, raw)),
502 }
503 }
504
505 fn records(&self, record: &Value, raw: &[u8], out: &mut impl FnMut(Outcome)) {
508 let batch = self.unwrap.as_ref().and_then(|member| {
509 let object = record.as_object().filter(|object| object.len() == 1)?;
510 object.get(member)?.as_array()
511 });
512 match batch {
513 Some(items) => {
514 for item in items {
515 let bytes = serde_json::to_vec(item).unwrap_or_default();
516 out(self.record(item, &bytes));
517 }
518 }
519 None => out(self.record(record, raw)),
520 }
521 }
522
523 fn record(&self, record: &Value, raw: &[u8]) -> Outcome {
525 if !record.is_object() {
526 return dead(
527 Stage::Decoding,
528 "the record is not a JSON object".to_owned(),
529 raw,
530 );
531 }
532 let Some(kind) = self.kinds.iter().find(|kind| {
533 kind.when
534 .iter()
535 .all(|(path, expected)| path.lookup(record) == Some(expected))
536 }) else {
537 return dead(
538 Stage::Mapping,
539 format!("no kind of source `{}` accepts the record", self.name),
540 raw,
541 );
542 };
543
544 let mut event = Map::new();
545 let mut unmapped = Map::new();
546 let mut issues = Vec::new();
547 let mut consumed: Vec<&SourcePath> = Vec::new();
548 for (name, value) in &kind.class {
549 event.insert((*name).to_owned(), value.clone());
550 }
551 for field in &kind.fields {
552 let path = match &field.source {
553 Source::Constant(value) => {
554 set(&mut event, field.target.segments(), value.clone());
555 continue;
556 }
557 Source::Path { path, .. } | Source::Translate { path, .. } => path,
558 };
559 let Some(found) = path
560 .lookup(record)
561 .filter(|value| !value.is_null() && !self.nil.contains(value))
562 else {
563 continue;
564 };
565 consumed.push(path);
566 match field.source.convert(found) {
567 Ok(value) => set(&mut event, field.target.segments(), value),
568 Err(reason) => {
569 issues.push(Issue {
570 target: field.target.as_str().to_owned(),
571 source: path.text.clone(),
572 reason,
573 });
574 let name = kind
578 .unmapped
579 .iter()
580 .find_map(|object| path.member_of(object))
581 .unwrap_or_else(|| path.text.clone());
582 unmapped.insert(name, found.clone());
583 }
584 }
585 }
586 for object in &kind.unmapped {
587 let Some(Value::Object(members)) = object.lookup(record) else {
588 continue;
589 };
590 for (key, member) in members {
591 if member.is_null() || consumed.iter().any(|path| path.is_member(object, key)) {
592 continue;
593 }
594 let name = if unmapped.contains_key(key) {
597 format!("{}.{key}", object.text)
598 } else {
599 key.clone()
600 };
601 unmapped.entry(name).or_insert_with(|| member.clone());
602 }
603 }
604 if !unmapped.is_empty() {
605 event.insert("unmapped".to_owned(), Value::Object(unmapped));
606 }
607 Outcome::Event(Normalized {
608 id: EventId::of(&self.name, raw),
609 event: Value::Object(event),
610 kind: kind.name.clone(),
611 issues,
612 })
613 }
614}
615
616fn dead(stage: Stage, error: String, raw: &[u8]) -> Outcome {
617 Outcome::DeadLetter(DeadLetter {
618 stage,
619 error,
620 raw: raw.to_vec(),
621 })
622}
623
624fn trim(bytes: &[u8]) -> &[u8] {
625 let start = bytes
626 .iter()
627 .position(|byte| !byte.is_ascii_whitespace())
628 .unwrap_or(bytes.len());
629 let end = bytes
630 .iter()
631 .rposition(|byte| !byte.is_ascii_whitespace())
632 .map_or(start, |position| position + 1);
633 &bytes[start..end]
634}
635
636fn source_path(kind: &str, text: &str) -> Result<SourcePath, DefinitionError> {
637 SourcePath::parse(text).ok_or_else(|| DefinitionError::SourcePath {
638 kind: kind.to_owned(),
639 path: text.to_owned(),
640 })
641}
642
643fn compile_fields(
644 kind: &str,
645 specs: &std::collections::BTreeMap<String, FieldSpec>,
646) -> Result<Vec<Field>, DefinitionError> {
647 specs
648 .iter()
649 .map(|(target, spec)| {
650 let path = FieldPath::parse(target).map_err(|source| DefinitionError::Target {
651 kind: kind.to_owned(),
652 target: target.clone(),
653 source,
654 })?;
655 let reserved = match path.segments()[0].as_str() {
656 "class_uid" | "category_uid" | "type_uid" | "activity_id" => {
657 Some("the kind's `class`")
658 }
659 "unmapped" => Some("the kind's `unmapped` list"),
660 _ => None,
661 };
662 if let Some(reason) = reserved {
663 return Err(DefinitionError::Reserved {
664 kind: kind.to_owned(),
665 target: target.clone(),
666 reason,
667 });
668 }
669 let source = match spec {
670 FieldSpec::Path(from) => Source::Path {
671 path: source_path(kind, from)?,
672 coercion: None,
673 },
674 FieldSpec::Converted { from, coercion } => Source::Path {
675 path: source_path(kind, from)?,
676 coercion: Some(*coercion),
677 },
678 FieldSpec::Translated {
679 from,
680 map,
681 otherwise,
682 } => {
683 let invalid = |reason| DefinitionError::Translation {
684 kind: kind.to_owned(),
685 target: target.clone(),
686 reason,
687 };
688 let mut values = map.values().chain(otherwise).map(Value::from);
689 let first = values.next().ok_or_else(|| invalid("is empty"))?;
690 if values.any(|value| Writes::of(&value) != Writes::of(&first)) {
691 return Err(invalid("mixes values of different types"));
692 }
693 Source::Translate {
694 path: source_path(kind, from)?,
695 map: map
696 .iter()
697 .map(|(key, value)| (key.clone(), Value::from(value)))
698 .collect(),
699 otherwise: otherwise.as_ref().map(Value::from),
700 }
701 }
702 FieldSpec::Value { value } => Source::Constant(Value::from(value)),
703 };
704 Ok(Field {
705 target: path,
706 source,
707 })
708 })
709 .collect()
710}
711
712fn check_overlaps(kind: &str, fields: &[Field]) -> Result<(), DefinitionError> {
715 for (index, first) in fields.iter().enumerate() {
716 for second in &fields[index + 1..] {
717 let (a, b) = (first.target.segments(), second.target.segments());
718 if a.starts_with(b) || b.starts_with(a) {
719 return Err(DefinitionError::Overlap {
720 kind: kind.to_owned(),
721 first: first.target.as_str().to_owned(),
722 second: second.target.as_str().to_owned(),
723 });
724 }
725 }
726 }
727 Ok(())
728}
729
730fn check_schema(
734 kind: &str,
735 class_uid: u32,
736 activity_id: u32,
737 fields: &[Field],
738) -> Result<(), DefinitionError> {
739 let class = schema::class(class_uid).ok_or_else(|| DefinitionError::UnknownClass {
740 kind: kind.to_owned(),
741 class_uid,
742 version: goliath_ocsf::SCHEMA_VERSION,
743 })?;
744 let activities = class
745 .attribute("activity_id")
746 .map(schema::Attribute::enum_values)
747 .unwrap_or_default();
748 if !activities.contains(&i64::from(activity_id)) {
749 return Err(DefinitionError::UnknownActivity {
750 kind: kind.to_owned(),
751 class: class.name(),
752 activity_id,
753 });
754 }
755 for field in fields {
756 let target = field.target.as_str();
757 let found = class
758 .resolve(target)
759 .map_err(|source| DefinitionError::Attribute {
760 kind: kind.to_owned(),
761 source,
762 })?;
763 if found.within_array {
764 return Err(DefinitionError::WithinArray {
765 kind: kind.to_owned(),
766 target: target.to_owned(),
767 });
768 }
769 let Some(writes) = field.source.writes() else {
772 continue;
773 };
774 if found.free_form {
775 continue;
776 }
777 let attribute = found.attribute;
778 let fits = !attribute.is_array()
779 && match writes {
780 Writes::Boolean => attribute.base() == Base::Boolean,
781 Writes::Integer => matches!(attribute.base(), Base::Integer | Base::Long),
782 Writes::Text => attribute.base() == Base::String,
783 Writes::Timestamp => attribute.type_name() == "timestamp_t",
784 Writes::Ip => attribute.type_name() == "ip_t",
785 };
786 if !fits {
787 let holds = match (attribute.is_array(), attribute.base()) {
788 (true, _) => format!("an array of `{}`", attribute.type_name()),
789 (false, Base::Object) => format!("an object `{}`", attribute.type_name()),
790 (false, _) => format!("`{}`", attribute.type_name()),
791 };
792 return Err(DefinitionError::Type {
793 kind: kind.to_owned(),
794 target: target.to_owned(),
795 holds,
796 writes: writes.describe(),
797 });
798 }
799 let values = attribute.enum_values();
800 let unknown = field
801 .source
802 .constants()
803 .filter_map(Value::as_i64)
804 .find(|value| !values.is_empty() && !values.contains(value));
805 if let Some(value) = unknown {
806 return Err(DefinitionError::UnknownValue {
807 kind: kind.to_owned(),
808 target: target.to_owned(),
809 value,
810 });
811 }
812 }
813 Ok(())
814}
815
816#[derive(Debug, Clone, Copy, PartialEq, Eq)]
818enum Writes {
819 Boolean,
820 Integer,
821 Text,
822 Timestamp,
823 Ip,
824}
825
826impl Writes {
827 fn of(value: &Value) -> Option<Self> {
829 match value {
830 Value::Bool(_) => Some(Self::Boolean),
831 Value::Number(_) => Some(Self::Integer),
832 Value::String(_) => Some(Self::Text),
833 _ => None,
834 }
835 }
836
837 fn describe(self) -> &'static str {
838 match self {
839 Self::Boolean => "a boolean",
840 Self::Integer => "an integer",
841 Self::Text => "text",
842 Self::Timestamp => "a timestamp",
843 Self::Ip => "an IP address",
844 }
845 }
846}
847
848impl Source {
849 fn writes(&self) -> Option<Writes> {
850 match self {
851 Self::Constant(value) => Writes::of(value),
852 Self::Translate { map, .. } => map.values().next().and_then(Writes::of),
855 Self::Path { coercion: None, .. } => None,
856 Self::Path {
857 coercion: Some(coercion),
858 ..
859 } => Some(match coercion {
860 Coercion::String => Writes::Text,
861 Coercion::Integer => Writes::Integer,
862 Coercion::Timestamp | Coercion::UnixSeconds => Writes::Timestamp,
863 Coercion::Ip => Writes::Ip,
864 }),
865 }
866 }
867}
868
869impl Source {
870 fn constants(&self) -> impl Iterator<Item = &Value> {
872 let (map, extra) = match self {
873 Self::Constant(value) => (None, Some(value)),
874 Self::Translate { map, otherwise, .. } => (Some(map), otherwise.as_ref()),
875 Self::Path { .. } => (None, None),
876 };
877 map.into_iter().flat_map(BTreeMap::values).chain(extra)
878 }
879
880 fn convert(&self, found: &Value) -> Result<Value, String> {
882 match self {
883 Self::Constant(value) => Ok(value.clone()),
884 Self::Path { coercion, .. } => coerce(found, *coercion),
885 Self::Translate { map, otherwise, .. } => {
886 let key = match found {
887 Value::String(text) => text.clone(),
888 Value::Number(_) | Value::Bool(_) => found.to_string(),
889 other => return Err(format!("cannot translate {}", describe(other))),
890 };
891 map.get(&key)
892 .or(otherwise.as_ref())
893 .cloned()
894 .ok_or_else(|| format!("`{key}` is not in the translation table"))
895 }
896 }
897 }
898}
899
900fn set(object: &mut Map<String, Value>, segments: &[String], value: Value) {
904 let Some((last, parents)) = segments.split_last() else {
905 return;
906 };
907 let mut object = object;
908 for segment in parents {
909 let child = object
910 .entry(segment.clone())
911 .or_insert_with(|| Value::Object(Map::new()));
912 let Value::Object(child) = child else {
913 return;
914 };
915 object = child;
916 }
917 object.insert(last.clone(), value);
918}
919
920fn coerce(value: &Value, coercion: Option<Coercion>) -> Result<Value, String> {
921 let Some(coercion) = coercion else {
922 return Ok(value.clone());
923 };
924 match (coercion, value) {
925 (Coercion::String, Value::String(_)) => Ok(value.clone()),
926 (Coercion::String, Value::Number(number)) => Ok(Value::String(number.to_string())),
927 (Coercion::Integer, Value::Number(number)) => number
928 .as_i64()
929 .map(Value::from)
930 .ok_or_else(|| format!("{number} is not a whole number")),
931 (Coercion::Integer, Value::String(text)) => {
932 let trimmed = text.trim();
933 match trimmed
934 .strip_prefix("0x")
935 .or_else(|| trimmed.strip_prefix("0X"))
936 {
937 Some(digits) => i64::from_str_radix(digits, 16),
938 None => trimmed.parse::<i64>(),
939 }
940 .map(Value::from)
941 .map_err(|_| format!("`{text}` is not a whole number"))
942 }
943 (Coercion::Timestamp, Value::String(text)) => text
944 .parse::<jiff::Timestamp>()
945 .map(|time| Value::from(time.as_millisecond()))
946 .map_err(|error| format!("`{text}` is not an RFC 3339 time: {error}")),
947 (Coercion::UnixSeconds, Value::String(text)) => unix_seconds(text),
948 (Coercion::Ip, Value::String(text)) => text
949 .trim()
950 .parse::<std::net::IpAddr>()
951 .map(|_| value.clone())
952 .map_err(|_| format!("`{text}` is not an IP address")),
953 (Coercion::UnixSeconds, Value::Number(number)) => unix_seconds(&number.to_string()),
954 (coercion, other) => Err(format!(
955 "cannot convert {} to {coercion:?}",
956 describe(other)
957 )),
958 }
959}
960
961fn unix_seconds(text: &str) -> Result<Value, String> {
963 let invalid = || format!("`{text}` is not a count of seconds since 1970");
964 let (whole, fraction) = text.split_once('.').unwrap_or((text, ""));
965 let digits = |part: &str| part.bytes().all(|byte| byte.is_ascii_digit());
966 if whole.is_empty() || !digits(whole) || !digits(fraction) {
967 return Err(invalid());
968 }
969 let seconds: i64 = whole.parse().map_err(|_| invalid())?;
970 let millis: i64 = format!("{:0<3}", &fraction[..fraction.len().min(3)])
971 .parse()
972 .map_err(|_| invalid())?;
973 seconds
974 .checked_mul(1000)
975 .and_then(|milliseconds| milliseconds.checked_add(millis))
976 .map(Value::from)
977 .ok_or_else(invalid)
978}
979
980fn describe(value: &Value) -> &'static str {
981 match value {
982 Value::Null => "null",
983 Value::Bool(_) => "a boolean",
984 Value::Number(_) => "a number",
985 Value::String(_) => "text",
986 Value::Array(_) => "a list",
987 Value::Object(_) => "an object",
988 }
989}