#![allow(clippy::expect_used, clippy::panic)]
use goliath_normalize::{DefinitionError, Normalizer, Outcome, Stage};
use serde_json::json;
const MINIMAL: &str = r"
name: test
version: 3
framing: lines
decoding: json
common:
metadata.product.name: { value: Test }
kinds:
- name: login
when: { type: login }
class: { class_uid: 3002, activity_id: 1 }
fields:
user.name: who
src_endpoint.port: { from: port, as: integer }
unmapped: [extra]
";
fn outcomes(definition: &str, input: &str) -> Vec<Outcome> {
let normalizer = Normalizer::from_yaml(definition).expect("definition loads");
let mut all = Vec::new();
normalizer.normalize(input.as_bytes(), |outcome| all.push(outcome));
all
}
fn one(definition: &str, input: &str) -> Outcome {
let mut all = outcomes(definition, input);
assert_eq!(all.len(), 1, "{all:?}");
all.remove(0)
}
fn error(definition: &str) -> DefinitionError {
Normalizer::from_yaml(definition).expect_err("definition is rejected")
}
#[test]
fn a_record_becomes_an_event_with_its_class() {
let Outcome::Event(normalized) = one(
MINIMAL,
r#"{"type": "login", "who": "adam", "port": "22", "extra": {"tty": "pts/1"}}"#,
) else {
panic!("not an event");
};
assert_eq!(normalized.kind, "login");
assert!(normalized.issues.is_empty());
assert_eq!(
normalized.event,
json!({
"class_uid": 3002,
"category_uid": 3,
"type_uid": 300_201,
"activity_id": 1,
"metadata": { "product": { "name": "Test" } },
"user": { "name": "adam" },
"src_endpoint": { "port": 22 },
"unmapped": { "tty": "pts/1" },
})
);
}
#[test]
fn lines_framing_skips_blank_lines_and_carriage_returns() {
let input = "\r\n{\"type\": \"login\"}\r\n \n{\"type\": \"login\"}";
let all = outcomes(MINIMAL, input);
assert_eq!(all.len(), 2);
assert!(
all.iter()
.all(|outcome| matches!(outcome, Outcome::Event(_)))
);
}
#[test]
fn a_line_that_is_not_json_is_a_dead_letter_with_its_bytes() {
let all = outcomes(MINIMAL, "{\"type\": \"login\"}\nnot json\n[1, 2]\n");
let [
Outcome::Event(_),
Outcome::DeadLetter(broken),
Outcome::DeadLetter(array),
] = all.as_slice()
else {
panic!("unexpected outcomes: {all:?}");
};
assert_eq!(broken.stage, Stage::Decoding);
assert_eq!(broken.raw, b"not json");
assert_eq!(array.stage, Stage::Decoding);
assert_eq!(array.raw, b"[1, 2]");
}
#[test]
fn a_record_no_kind_accepts_is_a_dead_letter() {
let Outcome::DeadLetter(dead) = one(MINIMAL, r#"{"type": "logout"}"#) else {
panic!("not a dead letter");
};
assert_eq!(dead.stage, Stage::Mapping);
assert_eq!(dead.raw, br#"{"type": "logout"}"#);
}
#[test]
fn conditions_compare_exactly() {
let definition = MINIMAL.replace("when: { type: login }", "when: { code: 1 }");
let all = outcomes(&definition, "{\"code\": 1}\n{\"code\": \"1\"}");
assert!(matches!(all[0], Outcome::Event(_)));
assert!(matches!(all[1], Outcome::DeadLetter(_)));
}
#[test]
fn a_value_that_does_not_convert_is_kept_and_reported() {
let Outcome::Event(normalized) = one(MINIMAL, r#"{"type": "login", "port": "ssh"}"#) else {
panic!("not an event");
};
assert_eq!(normalized.issues.len(), 1);
assert_eq!(normalized.issues[0].target, "src_endpoint.port");
assert_eq!(normalized.event["unmapped"]["port"], "ssh");
assert!(normalized.event.get("src_endpoint").is_none());
}
#[test]
fn nulls_and_missing_fields_are_left_out() {
let Outcome::Event(normalized) = one(
MINIMAL,
r#"{"type": "login", "who": null, "extra": {"gone": null}}"#,
) else {
panic!("not an event");
};
assert!(normalized.event.get("user").is_none());
assert!(normalized.event.get("unmapped").is_none());
assert!(normalized.issues.is_empty());
}
#[test]
fn a_broken_json_stream_keeps_its_remainder() {
let definition = MINIMAL.replace("framing: lines", "framing: json-values");
let all = outcomes(&definition, "{\"type\": \"login\"}\n {\"type\": \"log");
let [Outcome::Event(_), Outcome::DeadLetter(dead)] = all.as_slice() else {
panic!("unexpected outcomes: {all:?}");
};
assert_eq!(dead.stage, Stage::Framing);
assert_eq!(dead.raw, b"{\"type\": \"log");
}
#[test]
fn overlapping_targets_are_rejected() {
let definition = MINIMAL.replace(
" user.name: who\n",
" user.name: who\n user: who\n",
);
assert!(matches!(
error(&definition),
DefinitionError::Overlap { .. }
));
let definition = MINIMAL.replace("user.name: who", "metadata.product: who");
assert!(matches!(
error(&definition),
DefinitionError::Overlap { .. }
));
}
#[test]
fn class_and_unmapped_attributes_cannot_be_set_by_fields() {
for target in ["class_uid", "type_uid", "unmapped.x"] {
let definition = MINIMAL.replace("user.name: who", &format!("{target}: who"));
assert!(
matches!(error(&definition), DefinitionError::Reserved { .. }),
"{target}"
);
}
}
#[test]
fn a_kind_without_conditions_is_rejected() {
let definition = MINIMAL.replace("when: { type: login }", "when: {}");
assert!(matches!(
error(&definition),
DefinitionError::Unconditional { .. }
));
}
#[test]
fn malformed_definitions_are_rejected() {
assert!(matches!(
error(&MINIMAL.replace("user.name: who", "user..name: who")),
DefinitionError::Target { .. }
));
assert!(matches!(
error(&MINIMAL.replace("user.name: who", "user.name: a..b")),
DefinitionError::SourcePath { .. }
));
assert!(matches!(
error(&MINIMAL.replace("version: 3", "version: 3\nsurprise: 1")),
DefinitionError::Yaml(_)
));
assert!(matches!(
error(&MINIMAL.replace("as: integer", "as: float")),
DefinitionError::Yaml(_)
));
}
#[test]
fn classes_and_activities_must_exist_in_the_schema() {
assert_eq!(
error(&MINIMAL.replace("class_uid: 3002", "class_uid: 3999")).to_string(),
"kind `login`: OCSF 1.5.0 has no class 3999"
);
assert_eq!(
error(&MINIMAL.replace("activity_id: 1", "activity_id: 77")).to_string(),
"kind `login`: class `authentication` has no activity 77"
);
}
#[test]
fn targets_must_be_attributes_of_the_class() {
assert_eq!(
error(&MINIMAL.replace("user.name: who", "user.nmae: who")).to_string(),
"kind `login`: `user.nmae`: object `user` has no attribute `nmae`"
);
assert_eq!(
error(&MINIMAL.replace("metadata.product.name", "metadata.produce.name")).to_string(),
"kind `login`: `metadata.produce.name`: object `metadata` has no attribute `produce`"
);
assert_eq!(
error(&MINIMAL.replace("user.name: who", "attacks.technique.uid: who")).to_string(),
"kind `login`: `attacks.technique.uid` is inside an array; name an element by its index after the array, such as `0`"
);
}
#[test]
fn fields_must_write_what_their_attribute_holds() {
let cases = [
(
"user.name: { value: 5 }",
"`user.name` holds `username_t`, but the field writes an integer",
),
(
"user.name: { from: who, as: timestamp }",
"`user.name` holds `username_t`, but the field writes a timestamp",
),
(
"user: { value: adam }",
"`user` holds an object `user`, but the field writes text",
),
(
"metadata.labels: { value: test }",
"`metadata.labels` holds an array of `string_t`, but the field writes text",
),
("time: { from: who, as: integer }", ""),
(
"user.name: { value: true }",
"`user.name` holds `username_t`, but the field writes a boolean",
),
];
for (field, message) in cases {
let definition = MINIMAL.replace("user.name: who", field);
if message.is_empty() {
Normalizer::from_yaml(&definition).expect("an integer is a valid timestamp");
} else {
assert_eq!(
error(&definition).to_string(),
format!("kind `login`: {message}")
);
}
}
Normalizer::from_yaml(&MINIMAL.replace("user.name: who", "user: who")).expect("a copy fits");
}
#[test]
fn enumerated_constants_must_be_defined_values() {
let definition = MINIMAL.replace("user.name: who", "severity_id: { value: 42 }");
assert_eq!(
error(&definition).to_string(),
"kind `login`: 42 is not a defined value of `severity_id`"
);
let definition = MINIMAL.replace("user.name: who", "severity_id: { value: 99 }");
Normalizer::from_yaml(&definition).expect("99 is Other");
}
#[test]
fn seconds_since_the_epoch_become_milliseconds() {
let definition = MINIMAL.replace("user.name: who", "time: { from: at, as: unix-seconds }");
let time = |at: &str| match one(&definition, &format!(r#"{{"type": "login", "at": {at}}}"#)) {
Outcome::Event(normalized) => (normalized.event.get("time").cloned(), normalized.issues),
other => panic!("{other:?}"),
};
assert_eq!(
time(r#""1727251200.123""#).0,
Some(json!(1_727_251_200_123_i64))
);
assert_eq!(
time(r#""1727251200.1""#).0,
Some(json!(1_727_251_200_100_i64))
);
assert_eq!(
time(r#""1727251200.123456789""#).0,
Some(json!(1_727_251_200_123_i64))
);
assert_eq!(time("1727251200").0, Some(json!(1_727_251_200_000_i64)));
for bad in [r#""-1.5""#, r#""soon""#, r#""1.2.3""#, r#"".5""#] {
let (found, issues) = time(bad);
assert!(found.is_none(), "{bad}");
assert_eq!(issues.len(), 1, "{bad}");
}
}
#[test]
fn a_target_names_an_element_of_an_array_by_its_index() {
let definition = MINIMAL.replace(
"user.name: who",
"attacks.0.technique.uid: who
attacks.1.technique.uid: also",
);
match one(
&definition,
r#"{"type": "login", "who": "T1078", "also": "T1110"}"#,
) {
Outcome::Event(normalized) => assert_eq!(
normalized.event["attacks"],
json!([{ "technique": { "uid": "T1078" } }, { "technique": { "uid": "T1110" } }])
),
other => panic!("{other:?}"),
}
let definition = MINIMAL.replace("user.name: who", "attacks.1.technique.uid: who");
match one(&definition, r#"{"type": "login", "who": "T1078"}"#) {
Outcome::Event(normalized) => assert_eq!(
normalized.event["attacks"],
json!([{}, { "technique": { "uid": "T1078" } }])
),
other => panic!("{other:?}"),
}
assert_eq!(
error(&MINIMAL.replace("user.name: who", "user.0.name: who")).to_string(),
"kind `login`: `user.0.name` names an element of `user`, which is not an array"
);
assert_eq!(
error(&MINIMAL.replace("user.name: who", "0.name: who")).to_string(),
"kind `login`: `0.name`: class `authentication` has no attribute `0`"
);
}
#[test]
fn hashes_in_one_string_become_fingerprints_and_the_string_is_kept() {
let definition = MINIMAL.replace(
"user.name: who",
"certificate.fingerprints: { from: extra.Hashes, as: fingerprints }",
);
let event = |hashes: &str| match one(
&definition,
&format!(r#"{{"type": "login", "extra": {{"Hashes": "{hashes}", "Other": 1}}}}"#),
) {
Outcome::Event(normalized) => (normalized.event, normalized.issues),
other => panic!("{other:?}"),
};
let (found, issues) = event("MD5=AA11,SHA256=bb22, sha1=cc33,IMPHASH=dd44,SHA512=ee55");
assert_eq!(issues, []);
assert_eq!(
found["certificate"]["fingerprints"],
json!([
{ "algorithm": "MD5", "algorithm_id": 1, "value": "AA11" },
{ "algorithm": "SHA-256", "algorithm_id": 3, "value": "bb22" },
{ "algorithm": "SHA-1", "algorithm_id": 2, "value": "cc33" },
{ "algorithm": "IMPHASH", "algorithm_id": 99, "value": "dd44" },
{ "algorithm": "SHA-512", "algorithm_id": 4, "value": "ee55" }
])
);
assert_eq!(
found["unmapped"],
json!({ "Hashes": "MD5=AA11,SHA256=bb22, sha1=cc33,IMPHASH=dd44,SHA512=ee55", "Other": 1 })
);
for (hashes, reason) in [
("AA11", "`AA11` is not a hash written as NAME=hash"),
("MD5=xyz", "`MD5=xyz` does not hold a hexadecimal hash"),
("MD5=", "`MD5=` does not hold a hexadecimal hash"),
(",", "it holds no hash"),
] {
let (found, issues) = event(hashes);
assert!(found.get("certificate").is_none(), "{hashes}");
assert_eq!(issues.len(), 1, "{hashes}");
assert_eq!(issues[0].reason, reason);
assert_eq!(found["unmapped"]["Hashes"], hashes);
}
let wrong = MINIMAL.replace(
"user.name: who",
"user.name: { from: who, as: fingerprints }",
);
assert_eq!(
error(&wrong).to_string(),
"kind `login`: `user.name` holds `username_t`, but the field writes an array of fingerprints"
);
}
#[test]
fn a_time_without_an_offset_is_utc_when_the_definition_says_so() {
let definition = MINIMAL.replace("user.name: who", "time: { from: at, as: utc-timestamp }");
let time = |at: &str| match one(
&definition,
&format!(r#"{{"type": "login", "at": "{at}"}}"#),
) {
Outcome::Event(normalized) => (normalized.event.get("time").cloned(), normalized.issues),
other => panic!("{other:?}"),
};
let noon = Some(json!(1_790_596_801_000_i64));
assert_eq!(time("2026-09-28T12:00:01").0, noon);
assert_eq!(time("2026-09-28T12:00:01Z").0, noon);
assert_eq!(time("2026-09-28T15:00:01+03:00").0, noon);
assert_eq!(
time("2026-09-28T12:00:01.25").0,
Some(json!(1_790_596_801_250_i64))
);
let (found, issues) = time("yesterday");
assert!(found.is_none());
assert_eq!(issues.len(), 1);
let definition = MINIMAL.replace("user.name: who", "time: { from: at, as: timestamp }");
match one(
&definition,
r#"{"type": "login", "at": "2026-09-28T12:00:01"}"#,
) {
Outcome::Event(normalized) => {
assert!(normalized.event.get("time").is_none());
assert_eq!(normalized.issues.len(), 1);
}
other => panic!("{other:?}"),
}
}
#[test]
fn rows_need_the_names_of_their_columns_and_nothing_else_takes_them() {
let rows = MINIMAL.replace("decoding: json", "decoding: csv");
assert_eq!(
error(&rows).to_string(),
"`columns` is needed by decoding `csv`, and by no other"
);
let named = MINIMAL.replace(
"decoding: json",
"decoding: json
columns: [a, b]",
);
assert_eq!(error(&named), DefinitionError::Columns);
assert!(
Normalizer::from_yaml(&rows.replace(
"decoding: csv",
"decoding: csv
columns: [a, b]"
))
.is_ok()
);
}
#[test]
fn framing_and_decoding_must_fit_together() {
let audit_json = MINIMAL.replace("framing: lines", "framing: audit-events");
assert_eq!(
error(&audit_json).to_string(),
"framing `audit-events` cannot be used with decoding `json`"
);
let values_auditd = MINIMAL
.replace("framing: lines", "framing: json-values")
.replace("decoding: json", "decoding: auditd");
assert_eq!(
error(&values_auditd).to_string(),
"framing `json-values` cannot be used with decoding `auditd`"
);
}
#[test]
fn audit_lines_are_normalized_by_event() {
let definition = MINIMAL
.replace("framing: lines", "framing: audit-events")
.replace("decoding: json", "decoding: auditd")
.replace(
"when: { type: login }",
"when: { USER_LOGIN.msg.res: success }",
)
.replace("user.name: who", "user.name: USER_LOGIN.msg.acct")
.replace(
"src_endpoint.port: { from: port, as: integer }",
"time: { from: time, as: unix-seconds }",
)
.replace("unmapped: [extra]", "unmapped: [USER_LOGIN]");
let log = "type=USER_LOGIN msg=audit(1727251300.000:88): pid=4410 uid=0 msg='op=login acct=\"alice\" res=success'\n\
garbage\n\
type=USER_LOGIN msg=audit(1727251301.000:89): pid=4411 uid=0 msg='op=login acct=\"eve\" res=failed'\n";
let all = outcomes(&definition, log);
assert_eq!(all.len(), 3);
let Outcome::Event(alice) = &all[0] else {
panic!("{:?}", all[0]);
};
assert_eq!(alice.event["user"]["name"], "alice");
assert_eq!(alice.event["time"], 1_727_251_300_000_i64);
assert_eq!(alice.event["unmapped"]["pid"], "4410");
let Outcome::DeadLetter(garbage) = &all[1] else {
panic!("{:?}", all[1]);
};
assert_eq!(garbage.stage, Stage::Framing);
assert_eq!(garbage.raw, b"garbage");
assert!(matches!(&all[2], Outcome::DeadLetter(dead) if dead.stage == Stage::Mapping));
}
#[test]
fn a_name_two_unmapped_objects_share_keeps_both_values() {
let definition = MINIMAL.replace("unmapped: [extra]", "unmapped: [extra, more]");
let Outcome::Event(normalized) = one(
&definition,
r#"{"type": "login", "extra": {"a0": "id", "tty": "1"}, "more": {"a0": "55d5"}}"#,
) else {
panic!("not an event");
};
assert_eq!(
normalized.event["unmapped"],
json!({ "a0": "id", "tty": "1", "more.a0": "55d5" })
);
}
#[test]
fn members_with_dots_in_their_names_are_found() {
let definition = MINIMAL.replace("user.name: who", "user.name: extra.user.name");
let Outcome::Event(normalized) = one(
&definition,
r#"{"type": "login", "extra": {"user.name": "adam", "proc.pid": 7}}"#,
) else {
panic!("not an event");
};
assert_eq!(normalized.event["user"]["name"], "adam");
assert_eq!(normalized.event["unmapped"], json!({ "proc.pid": 7 }));
let Outcome::Event(normalized) = one(
&definition,
r#"{"type": "login", "extra": {"user": {"name": "eve"}, "user.name": "adam"}}"#,
) else {
panic!("not an event");
};
assert_eq!(normalized.event["user"]["name"], "eve");
}
#[test]
fn a_translation_turns_source_words_into_ocsf_values() {
let definition = MINIMAL.replace(
"user.name: who",
"severity_id: { from: level, map: { warn: 3, crit: 5, \"7\": 6 } }",
);
let severity = |input: &str| match one(&definition, input) {
Outcome::Event(normalized) => normalized,
other => panic!("{other:?}"),
};
assert_eq!(
severity(r#"{"type": "login", "level": "warn"}"#).event["severity_id"],
3
);
assert_eq!(
severity(r#"{"type": "login", "level": 7}"#).event["severity_id"],
6
);
let unlisted = severity(r#"{"type": "login", "level": "loud"}"#);
assert!(unlisted.event.get("severity_id").is_none());
assert_eq!(unlisted.event["unmapped"]["level"], "loud");
assert_eq!(unlisted.issues[0].target, "severity_id");
let definition = definition.replace("} }", "}, otherwise: 99 }");
let Outcome::Event(other) = one(&definition, r#"{"type": "login", "level": "loud"}"#) else {
panic!("not an event");
};
assert_eq!(other.event["severity_id"], 99);
assert!(other.issues.is_empty());
}
#[test]
fn translations_are_checked_when_they_load() {
let with = |table: &str| MINIMAL.replace("user.name: who", table);
assert_eq!(
error(&with(
"severity_id: { from: level, map: { warn: 3, crit: 42 } }"
))
.to_string(),
"kind `login`: 42 is not a defined value of `severity_id`"
);
assert_eq!(
error(&with(
"severity_id: { from: level, map: { warn: 3 }, otherwise: 42 }"
))
.to_string(),
"kind `login`: 42 is not a defined value of `severity_id`"
);
assert_eq!(
error(&with(
"severity_id: { from: level, map: { warn: 3, crit: high } }"
))
.to_string(),
"kind `login`: the translation for `severity_id` mixes values of different types"
);
assert_eq!(
error(&with("severity_id: { from: level, map: {} }")).to_string(),
"kind `login`: the translation for `severity_id` is empty"
);
assert!(matches!(
error(&with("severity_id: { from: level, map: { warn: high } }")),
DefinitionError::Type { .. }
));
}
#[test]
fn a_record_has_the_same_identity_every_time_it_arrives() {
let record = r#"{"type": "login", "who": "adam"}"#;
let id = |input: &str| match one(MINIMAL, input) {
Outcome::Event(normalized) => normalized.id,
other => panic!("{other:?}"),
};
assert_eq!(id(record), id(record));
assert_ne!(id(record), id(r#"{"type": "login", "who": "eve"}"#));
assert_ne!(id(record), id(r#"{"who": "adam", "type": "login"}"#));
}
#[test]
fn identities_separate_sources_and_print_as_hex() {
use goliath_normalize::EventId;
assert_ne!(EventId::of("a", b"bc"), EventId::of("ab", b"c"));
assert_ne!(EventId::of("sysmon", b"x"), EventId::of("auditd", b"x"));
let text = EventId::of("sysmon", b"x").to_string();
assert_eq!(text.len(), 32);
assert!(
text.bytes()
.all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
);
}
#[test]
fn outcomes_travel_between_roles_unchanged() {
use goliath_normalize::{Envelope, WireError};
let input = "{\"type\": \"login\", \"who\": \"adam\", \"port\": \"x\", \"extra\": {\"tty\": 1}}\nnot json\n";
for outcome in outcomes(MINIMAL, input) {
let envelope = Envelope::new("test", 3, outcome);
let bytes = envelope.encode();
assert_eq!(bytes[0], 1, "the format byte comes first");
assert_eq!(Envelope::decode(&bytes).expect("decodes"), envelope);
}
assert!(matches!(Envelope::decode(b""), Err(WireError { .. })));
assert!(
Envelope::decode(b"\x09{}")
.expect_err("unknown format")
.to_string()
.contains("unknown format 9")
);
assert!(Envelope::decode(b"\x01{").is_err());
let outcome = outcomes(MINIMAL, "{\"type\": \"login\", \"who\": \"adam\"}\n").remove(0);
let timed = Envelope::new("test", 3, outcome).received_at(1_790_294_400_000);
assert_eq!(Envelope::decode(&timed.encode()).expect("decodes"), timed);
let mut untimed = timed.clone();
untimed.received = None;
let old = untimed.encode();
assert!(!String::from_utf8_lossy(&old).contains("received"));
assert_eq!(Envelope::decode(&old).expect("decodes").received, None);
}
#[test]
fn identities_read_back_from_their_text() {
use goliath_normalize::EventId;
let id = EventId::of("sysmon", b"x");
assert_eq!(id.to_string().parse::<EventId>().expect("parses"), id);
assert_eq!(
id.to_string()
.to_uppercase()
.parse::<EventId>()
.expect("parses"),
id
);
for bad in ["", "abc", &"g".repeat(32), &"a".repeat(33)] {
assert!(bad.parse::<EventId>().is_err(), "{bad}");
}
}
const SYSLOG: &str = r"
name: test
version: 1
framing: syslog
decoding: syslog
common:
time: { from: timestamp, as: timestamp }
device.hostname: hostname
message: message
kinds:
- name: ssh
when: { app_name: sshd }
class: { class_uid: 3002, activity_id: 1 }
fields:
src_endpoint.port: { from: proc_id, as: integer }
";
#[test]
fn syslog_framing_reads_octet_counted_and_line_messages_alike() {
let counted = "<38>1 2026-09-28T10:00:00Z bastion sshd 22 - - two\nlines";
let input = format!(
"{} {counted}<38>Sep 28 10:00:00 bastion sshd[22]: one line\n40 <38>1 cut short",
counted.len()
);
let all = outcomes(SYSLOG, &input);
assert_eq!(all.len(), 3, "{all:?}");
let Outcome::Event(first) = &all[0] else {
panic!("not an event: {:?}", all[0]);
};
assert_eq!(first.event["message"], "two\nlines");
assert_eq!(first.event["device"]["hostname"], "bastion");
assert_eq!(first.event["time"], 1_790_589_600_000_i64);
let Outcome::Event(second) = &all[1] else {
panic!("not an event: {:?}", all[1]);
};
assert_eq!(second.event["message"], "one line");
assert_eq!(second.event["src_endpoint"]["port"], 22);
let Outcome::DeadLetter(dead) = &all[2] else {
panic!("not a dead letter: {:?}", all[2]);
};
assert_eq!(dead.stage, Stage::Framing);
assert_eq!(dead.raw, b"40 <38>1 cut short");
}
#[test]
fn syslog_framing_needs_a_syslog_decoding() {
assert!(matches!(
error(&SYSLOG.replace("decoding: syslog", "decoding: json")),
DefinitionError::Decoding { .. }
));
let json = SYSLOG.replace("decoding: syslog", "decoding: syslog-json");
let Outcome::Event(normalized) = one(
&json.replace("message: message", "message: message.text"),
r#"<38>1 - - sshd - - - {"text":"hi"}"#,
) else {
panic!("not an event");
};
assert_eq!(normalized.event["message"], "hi");
}
#[test]
fn integers_read_from_hexadecimal_text_as_windows_writes_them() {
let Outcome::Event(normalized) = one(MINIMAL, r#"{"type": "login", "port": "0x1F90"}"#) else {
panic!("not an event");
};
assert!(normalized.issues.is_empty(), "{:?}", normalized.issues);
assert_eq!(normalized.event["src_endpoint"]["port"], 8080);
let Outcome::Event(normalized) = one(MINIMAL, r#"{"type": "login", "port": "0xZZ"}"#) else {
panic!("not an event");
};
assert_eq!(normalized.issues.len(), 1);
}
#[test]
fn a_nil_value_leaves_its_field_out_and_is_kept_unmapped() {
let definition = MINIMAL.replace("common:", "nil: [\"-\"]\ncommon:");
let input = r#"{"type": "login", "who": "-", "port": "-", "extra": {"tty": "-"}}"#;
let Outcome::Event(normalized) = one(&definition, input) else {
panic!("not an event");
};
assert!(normalized.issues.is_empty(), "{:?}", normalized.issues);
assert!(normalized.event.get("user").is_none());
assert!(normalized.event.get("src_endpoint").is_none());
assert_eq!(normalized.event["unmapped"]["tty"], "-");
let Outcome::Event(normalized) = one(MINIMAL, input) else {
panic!("not an event");
};
assert_eq!(normalized.event["user"]["name"], "-");
assert_eq!(normalized.issues.len(), 1);
}
#[test]
fn a_batch_under_the_unwrap_member_becomes_one_record_per_element() {
let definition = MINIMAL
.replace("framing: lines", "framing: json-values")
.replace("common:", "unwrap: Records\ncommon:");
let input = r#"{"Records": [{"type": "login", "who": "adam"}, {"type": "login", "who": "eve"}, {"type": "other"}]}
{"type": "login", "who": "bob"}
{"Records": [{"type": "login"}], "extra": 1}"#;
let all = outcomes(&definition, input);
let names: Vec<_> = all
.iter()
.map(|outcome| match outcome {
Outcome::Event(normalized) => normalized.event["user"]["name"]
.as_str()
.unwrap_or("-")
.to_owned(),
Outcome::DeadLetter(dead) => format!("dead: {}", String::from_utf8_lossy(&dead.raw)),
other => panic!("{other:?}"),
})
.collect();
assert_eq!(
names,
[
"adam",
"eve",
r#"dead: {"type":"other"}"#,
"bob",
r#"dead: {"Records": [{"type": "login"}], "extra": 1}"#,
]
);
}
#[test]
fn an_ip_address_is_written_only_when_it_is_one() {
let definition = MINIMAL.replace(
"user.name: who",
"user.name: who\n src_endpoint.ip: { from: address, as: ip }",
);
let Outcome::Event(normalized) = one(
&definition,
r#"{"type": "login", "address": "fe80:0:0:0:1:2:3:4"}"#,
) else {
panic!("not an event");
};
assert!(normalized.issues.is_empty());
assert_eq!(
normalized.event["src_endpoint"]["ip"], "fe80:0:0:0:1:2:3:4",
"kept as written"
);
let Outcome::Event(normalized) = one(
&definition,
r#"{"type": "login", "address": "ec2.amazonaws.com"}"#,
) else {
panic!("not an event");
};
assert!(normalized.event["src_endpoint"].get("ip").is_none());
assert_eq!(normalized.issues.len(), 1);
assert_eq!(normalized.event["unmapped"]["address"], "ec2.amazonaws.com");
assert!(matches!(
error(&MINIMAL.replace("user.name: who", "user.name: { from: who, as: ip }")),
DefinitionError::Type { .. }
));
}
#[test]
fn a_number_in_a_path_names_an_element_of_an_array() {
let definition = MINIMAL
.replace(
"when: { type: login }",
"when: { type: login, targets.1.kind: group }",
)
.replace("user.name: who", "user.name: targets.0.name");
let Outcome::Event(normalized) = one(
&definition,
r#"{"type": "login", "targets": [{"kind": "user", "name": "adam"}, {"kind": "group", "name": "admins"}]}"#,
) else {
panic!("not an event");
};
assert_eq!(normalized.event["user"]["name"], "adam");
let Outcome::DeadLetter(_) = one(
&definition,
r#"{"type": "login", "targets": [{"name": "adam"}]}"#,
) else {
panic!("a missing element matches no kind");
};
}
#[test]
fn a_record_that_is_an_array_is_unwrapped_by_dot() {
let definition = MINIMAL
.replace("framing: lines", "framing: json-values")
.replace("common:", "unwrap: \".\"\ncommon:");
let all = outcomes(
&definition,
r#"[{"type": "login", "who": "adam"}, {"type": "login", "who": "eve"}] {"type": "login", "who": "bob"}"#,
);
let names: Vec<_> = all
.iter()
.map(|outcome| match outcome {
Outcome::Event(normalized) => normalized.event["user"]["name"].clone(),
other => panic!("{other:?}"),
})
.collect();
assert_eq!(names, ["adam", "eve", "bob"]);
}