#![allow(
unused_imports,
dead_code,
reason = "each test sits behind its own feature"
)]
use crate::shared_tests::corpus::{Join, Record, Tally, for_each_record, for_each_record_of};
fn mutations(bytes: &[u8]) -> [Vec<u8>; 2] {
let mid = bytes.len() / 2;
let mut bad = bytes.to_vec();
bad.insert(mid, 0xff);
[bad, bytes[..mid].to_vec()]
}
#[cfg(feature = "parse")]
mod parsers {
use std::borrow::Cow;
use std::ops::Range;
use super::{Join, Record, Tally, for_each_record_of, mutations};
use crate::parse::{FieldValue, Fields, Parsed, Parser};
use crate::shared_tests::corpus::Unit;
struct Seen {
parsed: bool,
body: Option<Range<usize>>,
fields: Vec<(String, Vec<u8>, Option<Range<usize>>)>,
}
fn within(input: &[u8], value: &FieldValue<'_>) -> Option<Range<usize>> {
let Cow::Borrowed(v) = &value.bytes else {
return None;
};
let (outer, inner) = (input.as_ptr_range(), v.as_ptr_range());
(outer.start <= inner.start && inner.end <= outer.end).then(|| {
let start = inner.start as usize - outer.start as usize;
start..start + v.len()
})
}
fn read(parser: &dyn Parser, input: &[u8]) -> Seen {
let mut out = Fields::new();
let result = parser.parse(input, &mut out);
let (parsed, body) = match &result {
Ok(Parsed::Done | Parsed::Decoded(_)) => (true, None),
Ok(Parsed::Body { span, .. }) => (true, Some(span.clone())),
Ok(Parsed::NoMatch) | Err(_) => (false, None),
};
let fields = if parsed {
out.as_slice()
.iter()
.map(|(n, v)| (n.clone(), v.bytes.to_vec(), within(input, v)))
.collect()
} else {
Vec::new()
};
Seen {
parsed,
body,
fields,
}
}
fn round_trip(parser: &dyn Parser, input: &[u8], seen: &Seen) -> Result<(), String> {
let want: Vec<(&String, &Vec<u8>)> = seen.fields.iter().map(|(n, v, _)| (n, v)).collect();
for (i, (name, value, at)) in seen.fields.iter().enumerate().take(8) {
let Some(at) = at else { continue };
let mut text = Vec::new();
let Some(replaced) = parser.escape_value(input, i, at.clone(), value, &mut text) else {
continue;
};
let mut rewritten = input[..replaced.start].to_vec();
rewritten.extend_from_slice(&text);
rewritten.extend_from_slice(&input[replaced.end..]);
let again = read(parser, &rewritten);
let got: Vec<(&String, &Vec<u8>)> =
again.fields.iter().map(|(n, v, _)| (n, v)).collect();
if got != want {
let at = got
.iter()
.zip(&want)
.position(|(a, b)| a != b)
.unwrap_or_else(|| got.len().min(want.len()));
let show = |v: &[(&String, &Vec<u8>)]| {
v.get(at)
.map(|(n, b)| format!("{n}={:?}", String::from_utf8_lossy(b)))
};
return Err(format!(
"{name} written back as {:?} reads differently: {} fields for {}, first apart {:?} against {:?}",
String::from_utf8_lossy(&text),
got.len(),
want.len(),
show(&got),
show(&want)
));
}
}
Ok(())
}
pub(super) fn check(check: &str, parser: &dyn Parser, tags: &[&str]) {
let mut tally = Tally::default();
let mut join = Join::SPACE;
let n = for_each_record_of(tags, |r| {
if r.unit == Unit::File {
join = Join::LINES;
}
one(check, parser, r, &mut tally);
});
assert!(n > 0, "{check}: no records tagged {tags:?}");
tally.scales_longest(check, join, |input| {
read(parser, input);
});
tally.finish(check);
}
fn one(check: &str, parser: &dyn Parser, r: &Record<'_>, tally: &mut Tally) {
let Some(seen) = tally.caught(check, r, || read(parser, r.bytes)) else {
return;
};
tally.count(check, r, seen.parsed);
if seen.parsed && !parser.signature().may_match(r.bytes) {
tally.problem(check, r, "parsed, but its signature rules it out");
}
if let Some(span) = &seen.body
&& (span.start > span.end || span.end > r.bytes.len())
{
tally.problem(check, r, &format!("body {span:?} is outside the input"));
}
if seen.parsed
&& r.unit == Unit::Line
&& let Some(Err(e)) = tally.caught(check, r, || round_trip(parser, r.bytes, &seen))
{
tally.problem(check, r, &e);
}
for m in mutations(r.bytes) {
let mutated = Record { bytes: &m, ..*r };
tally.caught(check, &mutated, || read(parser, &m));
}
}
#[cfg(feature = "parse-syslog")]
#[test]
fn syslog_reads_real_lines() {
use crate::format::syslog::Syslog;
check("syslog", &Syslog::new(), &["syslog", "mixed", "leef"]);
check(
"syslog-no-pri",
&Syslog::pri_optional(),
&["syslog", "mixed"],
);
}
#[cfg(feature = "parse-cef")]
#[test]
fn cef_reads_real_lines() {
check("cef", &crate::format::cef::Cef::new(), &["cef", "mixed"]);
}
#[cfg(feature = "parse-leef")]
#[test]
fn leef_reads_real_lines() {
check(
"leef",
&crate::format::leef::Leef::new(),
&["leef", "mixed"],
);
}
#[cfg(feature = "parse-kv")]
#[test]
fn kv_reads_real_lines() {
use crate::format::kv::Kv;
check("kv", &Kv::default(), &["kv", "syslog", "mixed"]);
check("logfmt", &Kv::logfmt(), &["kv", "mixed"]);
}
#[cfg(feature = "parse-kv")]
#[test]
fn kv_writes_back_a_quoted_value_before_a_comma() {
use crate::format::kv::Kv;
let bytes = crate::shared_tests::corpus::file_bytes(
"logtriage",
"samples/f5-asm/benign/f5_asm_normal.log",
);
let line = crate::shared_tests::corpus::lines(&bytes)
.next()
.unwrap()
.1
.to_vec();
let parser = Kv::default();
let seen = read(&parser, &line);
assert!(seen.parsed);
assert_eq!(seen.fields.len(), 32);
round_trip(&parser, &line, &seen).unwrap();
}
#[cfg(feature = "parse-csv")]
#[test]
fn csv_reads_real_lines() {
use crate::format::csv::{Csv, CsvConfig};
check("csv", &Csv::new(CsvConfig::default()).unwrap(), &["csv"]);
let tab = CsvConfig {
delimiter: '\t',
..CsvConfig::default()
};
check("tsv", &Csv::new(tab).unwrap(), &["tsv"]);
}
#[cfg(feature = "parse-cri")]
#[test]
fn cri_reads_real_lines() {
check("cri", &crate::format::cri::Cri::new(), &["cri"]);
}
#[cfg(feature = "parse-ndjson")]
#[test]
fn ndjson_reads_real_records() {
use crate::format::ndjson::Ndjson;
check("ndjson", &Ndjson::new(), &["json", "ndjson", "json-suite"]);
}
#[cfg(feature = "parse-gelf")]
#[test]
fn gelf_reads_real_records() {
use crate::format::gelf::Gelf;
check("gelf", &Gelf::new(), &["json", "ndjson", "json-suite"]);
}
#[cfg(feature = "parse-xml")]
#[test]
fn xml_reads_real_documents() {
check(
"xml",
&crate::format::xml::Xml::new(),
&["xml", "xml-lines"],
);
}
#[cfg(feature = "parse-prometheus")]
#[test]
fn prometheus_reads_real_lines() {
use crate::format::prometheus::Prometheus;
check("prometheus", &Prometheus::new(), &["prometheus"]);
}
#[cfg(feature = "parse-cloud")]
#[test]
fn cloud_logs_read_real_lines() {
use crate::format::cloud::CloudLog;
check("aws-alb", &CloudLog::aws_alb(), &["cloud-alb"]);
check("aws-s3", &CloudLog::aws_s3(), &["cloud-s3"]);
check("aws-vpc-flow", &CloudLog::aws_vpc_flow(), &["cloud-vpc"]);
}
#[cfg(feature = "parse-access")]
#[test]
fn access_formats_read_real_lines() {
use crate::format::access::{apache, nginx};
let combined = r#"%h %l %u %t "%r" %>s %b "%{Referer}i" "%{User-agent}i""#;
check(
"apache-combined",
&apache(combined).unwrap(),
&["access", "mixed"],
);
check(
"apache-common",
&apache(r#"%h %l %u %t "%r" %>s %b"#).unwrap(),
&["access"],
);
let nginx_combined = r#"$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent""#;
check(
"nginx-combined",
&nginx(nginx_combined).unwrap(),
&["access", "mixed"],
);
}
#[cfg(feature = "parse-ini")]
#[test]
fn ini_reads_real_files() {
use crate::format::ini::{Dialect, Ini};
check("ini", &Ini::new(Dialect::Ini), &["ini"]);
check("dotenv", &Ini::new(Dialect::Dotenv), &["ini"]);
}
#[cfg(feature = "parse-toml")]
#[test]
fn toml_reads_real_files() {
use crate::format::toml::Toml;
check("toml", &Toml::new(), &["toml-valid", "toml-invalid"]);
}
#[cfg(feature = "parse-yaml")]
#[test]
fn yaml_reads_real_files() {
check("yaml", &crate::format::yaml::Yaml::new(), &["yaml"]);
}
#[cfg(feature = "parse-http")]
#[test]
fn http_reads_real_headers() {
use crate::format::http::{Http, HttpKind};
check("http-headers", &Http::new(HttpKind::Headers), &["http"]);
check("http-message", &Http::new(HttpKind::Message), &["http"]);
}
#[cfg(feature = "parse-msgpack")]
#[test]
fn msgpack_reads_the_test_suite() {
let parser = crate::format::msgpack::Msgpack::new();
let mut tally = Tally::default();
crate::shared_tests::corpus::for_each_record("msgpack", |r| {
let suite: serde_json::Value = serde_json::from_slice(r.bytes).unwrap();
let mut n = 0;
for cases in suite.as_object().unwrap().values() {
for case in cases.as_array().unwrap() {
for hex in case["msgpack"].as_array().unwrap() {
let bytes: Vec<u8> = hex
.as_str()
.unwrap()
.split('-')
.map(|b| u8::from_str_radix(b, 16).unwrap())
.collect();
n += 1;
let at = Record {
line: n,
bytes: &bytes,
..*r
};
one("msgpack", &parser, &at, &mut tally);
}
}
}
});
tally.scales_longest("msgpack", Join::NONE, |input| {
read(&parser, input);
});
tally.finish("msgpack");
}
#[cfg(feature = "parse-w3c")]
#[test]
fn w3c_reads_real_logs() {
use crate::format::w3c::{Line, W3c};
let mut tally = Tally::default();
let mut file = String::new();
let mut reader = W3c::new();
crate::shared_tests::corpus::for_each_record("w3c", |r| {
if r.file != file {
file = r.file.to_owned();
reader = W3c::new();
}
let got = tally.caught("w3c", r, || {
let mut out = Fields::new();
reader.line(r.bytes, &mut out).map(|l| (l, out.len()))
});
if let Some(got) = got {
tally.count("w3c", r, matches!(got, Ok((Line::Record(_), _))));
if let Ok((Line::Record(n), written)) = got
&& n != written
{
tally.problem("w3c", r, &format!("said {n} fields, wrote {written}"));
}
}
});
tally.scales_longest("w3c", Join::SPACE, |input| {
let _ = W3c::new().line(input, &mut Fields::new());
});
tally.finish("w3c");
}
#[cfg(feature = "parse-uri")]
#[test]
fn uri_and_query_parsers_read_real_urls() {
let urls = super::url_inputs();
let uri = crate::format::uri::Uri::new();
let mut tally = Tally::default();
for (r, _, url) in &urls {
let rec = Record {
bytes: url.as_bytes(),
..r.as_record()
};
one("uri", &uri, &rec, &mut tally);
#[cfg(feature = "parse-query")]
if let Some((_, q)) = url.split_once('?') {
let q = q.split('#').next().unwrap_or(q);
let query = crate::format::query::Query::new();
one(
"query",
&query,
&Record {
bytes: q.as_bytes(),
..rec
},
&mut tally,
);
}
}
tally.scales_longest("uri", Join::between(b"/"), |input| {
read(&uri, input);
});
tally.finish("uri");
}
#[cfg(all(
feature = "parse-syslog",
feature = "parse-cef",
feature = "parse-ndjson"
))]
#[test]
fn auto_star_reads_every_real_line_the_same_alone_and_mixed() {
use crate::parse::{ParsePlan, Parsers, Status};
let mut registry = Parsers::new();
crate::format::register_stock(&mut registry).unwrap();
let plan = ParsePlan::chain("auto*", ®istry).unwrap();
let mut mixed = plan.source_state();
let mut tally = Tally::default();
let tags = [
"syslog",
"cef",
"leef",
"kv",
"mixed",
"access",
"text",
"cri",
"ndjson",
"csv",
"tsv",
"prometheus",
"naughty",
"cloud-alb",
"cloud-s3",
"cloud-vpc",
"w3c",
];
for_each_record_of(&tags, |r| {
let Some(rows) = tally.caught("auto*", r, || {
let mut alone = Fields::new();
let a = plan.parse(r.bytes, &mut plan.source_state(), &mut alone);
let mut out = Fields::new();
let m = plan.parse(r.bytes, &mut mixed, &mut out);
let rows = |f: &Fields<'_>| -> Vec<(String, Vec<u8>)> {
f.as_slice()
.iter()
.map(|(n, v)| (n.clone(), v.bytes.to_vec()))
.collect()
};
(
(a.status, a.layers, rows(&alone)),
(m.status, m.layers, rows(&out)),
)
}) else {
return;
};
tally.count("auto*", r, rows.0.1 > 0);
if rows.0.0 == Status::Truncated {
tally.problem("auto*", r, "a real line used up the chain's work budget");
}
if rows.0 != rows.1 {
tally.problem("auto*", r, "reads differently alone and in a mixed stream");
}
});
tally.scales_longest("auto*", Join::SPACE, |input| {
let _ = plan.parse(input, &mut plan.source_state(), &mut Fields::new());
});
tally.finish("auto*");
}
}
#[cfg(any(feature = "parse-uri", feature = "uri", feature = "domain"))]
struct UrlRecord {
source: String,
file: String,
line: usize,
}
#[cfg(any(feature = "parse-uri", feature = "uri", feature = "domain"))]
impl UrlRecord {
fn as_record(&self) -> Record<'_> {
Record {
source: self.source.as_str(),
file: self.file.as_str(),
line: self.line,
bytes: b"",
unit: crate::shared_tests::corpus::Unit::Line,
}
}
}
#[cfg(any(feature = "parse-uri", feature = "uri", feature = "domain"))]
fn url_inputs() -> Vec<(UrlRecord, &'static str, String)> {
let mut out = Vec::new();
for_each_record("uri", |r| {
let cases: serde_json::Value = serde_json::from_slice(r.bytes).unwrap();
for (i, case) in cases.as_array().unwrap().iter().enumerate() {
for key in ["input", "href", "hostname"] {
if let Some(s) = case.get(key).and_then(serde_json::Value::as_str) {
let at = UrlRecord {
source: r.source.to_owned(),
file: r.file.to_owned(),
line: i + 1,
};
out.push((at, key, s.to_owned()));
}
}
}
});
assert!(!out.is_empty(), "no URL test data");
out
}
#[cfg(feature = "uri")]
#[test]
fn uri_split_reads_real_urls() {
let mut tally = Tally::default();
for (at, _, url) in url_inputs() {
let r = Record {
bytes: url.as_bytes(),
..at.as_record()
};
let Some(parts) = tally.caught("uri::split", &r, || crate::uri::split(&url)) else {
continue;
};
tally.count("uri::split", &r, parts.host.is_some());
let pieces = [
parts.scheme,
parts.user_info,
parts.host,
parts.port,
Some(parts.path),
parts.query,
parts.fragment,
];
let mut from = 0;
for piece in pieces.into_iter().flatten() {
let start = piece.as_ptr() as usize - url.as_ptr() as usize;
if start < from || start + piece.len() > url.len() {
tally.problem(
"uri::split",
&r,
"parts are out of order or outside the input",
);
break;
}
from = start + piece.len();
}
}
tally.scales_longest("uri::split", Join::between(b"/"), |input| {
if let Ok(url) = std::str::from_utf8(input) {
let _ = crate::uri::split(url);
}
});
tally.finish("uri::split");
}
#[cfg(feature = "domain")]
#[test]
fn domain_split_reads_real_hosts() {
use crate::domain::{Case, split};
let mut hosts: Vec<(UrlRecord, String)> = url_inputs()
.into_iter()
.filter(|(_, key, _)| *key == "hostname")
.map(|(at, _, host)| (at, host))
.collect();
for_each_record("domain", |r| {
let cases: serde_json::Value = serde_json::from_slice(r.bytes).unwrap();
for (i, case) in cases.as_array().unwrap().iter().enumerate() {
for key in ["input", "output"] {
if let Some(s) = case.get(key).and_then(serde_json::Value::as_str) {
let at = UrlRecord {
source: r.source.to_owned(),
file: r.file.to_owned(),
line: i + 1,
};
hosts.push((at, s.to_owned()));
}
}
}
});
let mut tally = Tally::default();
for (at, host) in &hosts {
let r = Record {
bytes: host.as_bytes(),
..at.as_record()
};
let Some(got) = tally.caught("domain", &r, || split(host, Case::Fold)) else {
continue;
};
tally.count(
"domain",
&r,
got.as_ref().is_some_and(|d| d.registrable.is_some()),
);
let Some(d) = got else { continue };
let name = host.strip_suffix('.').unwrap_or(host);
if !name.ends_with(d.suffix) {
tally.problem("domain", &r, "the suffix isn't the end of the name");
}
if let Some(reg) = d.registrable {
let rebuilt = d
.subdomain
.map_or_else(|| reg.to_owned(), |s| format!("{s}.{reg}"));
if !reg.ends_with(d.suffix) || rebuilt != name {
tally.problem("domain", &r, &format!("{d:?} doesn't rebuild the name"));
}
}
}
tally.scales_longest("domain", Join::between(b"."), |input| {
if let Ok(host) = std::str::from_utf8(input) {
let _ = split(host, Case::Fold);
}
});
tally.finish("domain");
}
#[cfg(feature = "strmatch")]
#[test]
fn strmatch_finds_what_the_regex_crate_finds_on_its_test_data() {
use crate::strmatch::StrMatcher;
let mut tally = Tally::default();
let mut widest: (Option<StrMatcher>, Vec<u8>) = (None, Vec::new());
for_each_record("regex", |r| {
let doc: toml::Table = std::str::from_utf8(r.bytes).unwrap().parse().unwrap();
let Some(cases) = doc.get("test").and_then(toml::Value::as_array) else {
return;
};
for (i, case) in cases.iter().enumerate() {
let case = case.as_table().unwrap();
let (Some(pattern), Some(hay)) = (
case.get("regex").and_then(toml::Value::as_str),
case.get("haystack").and_then(toml::Value::as_str),
) else {
continue;
};
let plain = ["name", "regex", "haystack", "matches", "match-limit"];
if case.keys().any(|k| !plain.contains(&k.as_str())) {
continue;
}
let at = Record {
line: i + 1,
bytes: pattern.as_bytes(),
..*r
};
let Ok(oracle) = regex::bytes::Regex::new(pattern) else {
continue;
};
let Some(Ok(ours)) = tally.caught("strmatch", &at, || StrMatcher::new(pattern)) else {
tally.count("strmatch", &at, false);
continue;
};
tally.count("strmatch", &at, true);
let want = oracle.find(hay.as_bytes()).map(|m| (m.start(), m.end()));
let got = tally.caught("strmatch", &at, || {
ours.find(hay.as_bytes()).map(|m| (m.start, m.end))
});
if let Some(got) = got
&& got != want
{
tally.problem(
"strmatch",
&at,
&format!("on {hay:?} found {got:?}, regex {want:?}"),
);
}
if hay.len() > widest.1.len() {
widest = (Some(ours), hay.as_bytes().to_vec());
}
}
});
tally.scales_longest("strmatch build", Join::NONE, |input| {
if let Ok(pattern) = std::str::from_utf8(input) {
let _ = StrMatcher::new(pattern);
}
});
if let (Some(ours), hay) = &widest {
tally.scales("strmatch find", hay, Join::SPACE, |input| {
let _ = ours.find(input);
});
}
tally.finish("strmatch");
}
#[cfg(feature = "scrub")]
#[test]
fn scrub_reads_real_lines_and_settles() {
use crate::scrub::Scrubber;
let scrubber = Scrubber::gitleaks().unwrap();
let mut scratch = scrubber.scratch();
let mut report = scrubber.report();
let mut tally = Tally::default();
let tags = [
"syslog", "cef", "leef", "kv", "mixed", "access", "text", "csv", "tsv", "json", "ndjson",
"naughty", "xml", "http",
];
for_each_record_of(&tags, |r| {
let Some(once) = tally.caught("scrub", r, || {
scrubber.scrub_text(r.bytes, &mut scratch, &mut report)
}) else {
return;
};
tally.count("scrub", r, once.is_some());
if let Some(once) = once {
let twice = tally.caught("scrub", r, || {
scrubber.scrub_text(&once, &mut scratch, &mut report)
});
if let Some(Some(changed)) = &twice
&& *changed == once
{
tally.problem(
"scrub",
r,
"said a scrubbed line changed though its bytes didn't",
);
} else if let Some(Some(changed)) = twice {
tally.problem(
"scrub",
r,
&format!(
"a second pass changed {:?} to {:?}",
String::from_utf8_lossy(&once),
String::from_utf8_lossy(&changed)
),
);
}
}
for m in mutations(r.bytes) {
let at = Record { bytes: &m, ..*r };
tally.caught("scrub", &at, || {
scrubber.scrub_text(&m, &mut scratch, &mut report)
});
}
});
tally.scales_longest("scrub", Join::SPACE, |input| {
let _ = scrubber.scrub_text(input, &mut scratch, &mut report);
});
tally.finish("scrub");
}
#[cfg(feature = "scrub")]
#[test]
fn scrubbing_scrubbed_lines_changes_nothing() {
use crate::scrub::Scrubber;
let scrubber = Scrubber::gitleaks().unwrap();
let (mut scratch, mut report) = (scrubber.scratch(), scrubber.report());
let files = [
("logtriage", "samples/auth-log/benign/authlog_normal.log"),
("logtriage", "samples/f5-asm/benign/f5_asm_normal.log"),
("logtriage", "samples/f5-asm/malicious/f5_asm_attacks.log"),
("logtriage", "samples/syslog/benign/syslog_normal.log"),
];
let mut changed = 0;
for (id, path) in files {
let bytes = crate::shared_tests::corpus::file_bytes(id, path);
for (n, line) in crate::shared_tests::corpus::lines(&bytes) {
let Some(once) = scrubber.scrub_text(line, &mut scratch, &mut report) else {
continue;
};
changed += 1;
let twice = scrubber.scrub_text(&once, &mut scratch, &mut report);
assert!(
twice.is_none(),
"{path}:{n} changed again: {}",
String::from_utf8_lossy(&twice.unwrap_or_default())
);
}
}
assert!(changed > 5, "{changed} lines changed on a first pass");
}
#[cfg(feature = "scrub")]
#[test]
fn scrub_keeps_sudos_working_directory_and_masks_a_pwd_password() {
use crate::scrub::Scrubber;
let scrubber = Scrubber::gitleaks().unwrap();
let (mut scratch, mut report) = (scrubber.scratch(), scrubber.report());
let mut sudo_lines = 0;
for_each_record_of(&["syslog", "text", "mixed"], |r| {
let line = String::from_utf8_lossy(r.bytes);
if !(line.contains(" sudo") && line.contains(" ; PWD=")) {
return;
}
sudo_lines += 1;
let out = scrubber.scrub_text(r.bytes, &mut scratch, &mut report);
assert_eq!(out, None, "{}: {line}", r.at());
});
assert!(sudo_lines >= 10, "{sudo_lines} real sudo lines");
let docs = "Driver={ODBC Driver 18 for SQL Server};Server=tcp:<server>;Database=<database>;UID=<user_id>;PWD=<password>;Encrypt=yes;TrustServerCertificate=no;MARS_Connection=Yes;WSID=app-node-01;";
let out = scrubber
.scrub_text(docs.as_bytes(), &mut scratch, &mut report)
.expect("a PWD password is masked");
let out = String::from_utf8(out).unwrap();
assert!(
out.contains("UID=<user_id>;PWD=[CREDENTIAL_FIELD_REDACTED]"),
"{out}"
);
assert!(!out.contains("<password>"), "{out}");
}
#[cfg(all(feature = "json-paths", feature = "record"))]
#[test]
fn json_readers_agree_with_serde_json_on_real_records() {
use crate::json::{MAX_DEPTH, Paths, Slot, Slots, depth_within};
use crate::path::Path;
use crate::record::{Json, Record as _};
let mut tally = Tally::default();
let mut slots = Slots::new();
let root = Paths::new([Path::from_pointer("").unwrap()]);
let mut roots = 0;
for_each_record_of(&["json", "ndjson", "json-suite"], |r| {
let parsed: Option<serde_json::Value> = serde_json::from_slice(r.bytes).ok();
let Some(within) = tally.caught("json", r, || depth_within(r.bytes, MAX_DEPTH)) else {
return;
};
tally.count("json", r, parsed.is_some());
if let Some(v) = &parsed
&& depth(v) <= MAX_DEPTH
&& !within
{
tally.problem("json", r, "valid JSON within the depth refused");
}
if let Some(v) = &parsed {
let whole = tally.caught("json", r, || {
root.read(r.bytes, &mut slots)
.get(0)
.and_then(Slot::found)
.and_then(|raw| serde_json::from_str::<serde_json::Value>(raw.text()).ok())
});
match whole {
Some(Some(got)) if got == *v => roots += 1,
Some(_) => tally.problem("json", r, "the root path read a different value"),
None => {}
}
}
let Some(serde_json::Value::Object(map)) = &parsed else {
tally.caught("record", r, || Json::new(r.bytes).find(&["a"]).is_ok());
return;
};
let keys: Vec<&String> = map.keys().take(16).collect();
let paths = Paths::new(
keys.iter()
.filter_map(|k| Path::from_keys([k.as_str()]).ok()),
);
let got = tally.caught("json", r, || {
paths
.read(r.bytes, &mut slots)
.iter()
.map(|s| match s {
Slot::Found(raw) => serde_json::from_str::<serde_json::Value>(raw.text()).ok(),
_ => None,
})
.collect::<Vec<_>>()
});
let json = Json::new(r.bytes);
let text = String::from_utf8_lossy(r.bytes);
for (i, key) in keys.iter().enumerate() {
let quoted = serde_json::to_string(key).unwrap();
if text.matches(quoted.as_str()).count() > 1 {
continue;
}
let want = map.get(*key);
if let Some(got) = &got
&& got.get(i).cloned().flatten().as_ref() != want
{
tally.problem("json", r, &format!("paths read {key} differently"));
}
let found = tally.caught("record", r, || json.find(&[key.as_str()]).is_ok());
if found == Some(false) {
tally.problem("record", r, &format!("record::Json missed {key}"));
}
}
});
assert!(roots > 0, "no real record read back whole by the root path");
tally.scales_longest("json depth", Join::ARRAY, |input| {
let _ = depth_within(input, MAX_DEPTH);
});
tally.scales_longest("json record", Join::ARRAY, |input| {
let _ = Json::new(input).find(&["a"]);
});
tally.finish("json");
}
#[cfg(all(feature = "json-paths", feature = "record"))]
fn depth(v: &serde_json::Value) -> usize {
match v {
serde_json::Value::Array(a) => 1 + a.iter().map(depth).max().unwrap_or(0),
serde_json::Value::Object(o) => 1 + o.values().map(depth).max().unwrap_or(0),
_ => 0,
}
}
#[cfg(feature = "time")]
#[test]
fn time_reads_real_date_strings() {
use crate::time::{TimeDefaults, TimeFormat, parse_stamp, parse_stamp_any};
let forms = [
TimeFormat::Iso8601,
TimeFormat::Rfc2822,
TimeFormat::HttpDate,
TimeFormat::Syslog,
];
let defaults = TimeDefaults {
year: Some(2026),
..TimeDefaults::default()
};
let mut tally = Tally::default();
for_each_record("time", |r| {
let Some(any) = tally.caught("time", r, || parse_stamp_any(&forms, r.bytes, &defaults))
else {
return;
};
tally.count("time", r, any.is_ok());
let iso = parse_stamp(&TimeFormat::Iso8601, r.bytes, &defaults);
let jiff: Option<jiff::Timestamp> = std::str::from_utf8(r.bytes)
.ok()
.and_then(|s| s.parse().ok());
if let (Ok(ours), Some(theirs)) = (iso, jiff)
&& ours.timestamp != theirs
{
tally.problem(
"time",
r,
&format!("ours {}, jiff {theirs}", ours.timestamp),
);
}
});
tally.scales_longest("time", Join::SPACE, |input| {
let _ = parse_stamp_any(&forms, input, &defaults);
});
tally.finish("time");
}
#[cfg(feature = "convert")]
#[test]
fn convert_reads_real_tokens_as_std_does() {
use crate::convert::{Width, parse_bool, parse_float, parse_int, parse_ip};
let mut tally = Tally::default();
for_each_record_of(
&["syslog", "access", "cloud-vpc", "cloud-alb", "tsv", "csv"],
|r| {
let Ok(line) = std::str::from_utf8(r.bytes) else {
return;
};
for token in line
.split([' ', '\t', ',', '=', '"', '[', ']'])
.filter(|t| !t.is_empty())
{
let at = Record {
bytes: token.as_bytes(),
..*r
};
let Some((int, float, ip)) = tally.caught("convert", &at, || {
let _ = parse_bool(token);
(
parse_int(token),
parse_float(token, Width::Double),
parse_ip(token),
)
}) else {
continue;
};
if let (Ok(ours), Ok(std)) = (&int, token.parse::<i64>())
&& *ours != std
{
tally.problem("convert", &at, &format!("int {ours}, std {std}"));
}
if token.parse::<std::net::IpAddr>().is_ok() && ip.is_err() {
tally.problem("convert", &at, "an IP std reads was refused");
}
if let (Ok(ours), Ok(std)) = (float, token.parse::<f64>())
&& ours.to_bits() != std.to_bits()
&& !(ours.is_nan() && std.is_nan())
{
tally.problem("convert", &at, &format!("float {ours}, std {std}"));
}
}
tally.count("convert", r, true);
},
);
tally.scales_longest("convert", Join::NONE, |input| {
if let Ok(token) = std::str::from_utf8(input) {
let _ = parse_bool(token);
let _ = (
parse_int(token),
parse_float(token, Width::Double),
parse_ip(token),
);
}
});
tally.finish("convert");
}
#[cfg(any(
feature = "decode-base64",
feature = "decode-hex",
feature = "decode-gzip"
))]
#[test]
fn decoders_give_back_real_lines() {
use crate::parse::{Fields, Parsed, Parser};
use base64::Engine;
fn encodings(bytes: &[u8]) -> [(&'static str, Vec<u8>); 5] {
let b64 = base64::engine::general_purpose::STANDARD.encode(bytes);
let url = base64::engine::general_purpose::URL_SAFE.encode(bytes);
let hex = bytes.iter().fold(String::new(), |mut s, b| {
let _ = std::fmt::Write::write_fmt(&mut s, format_args!("{b:02x}"));
s
});
let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
std::io::Write::write_all(&mut gz, bytes).unwrap();
let mut zlib = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());
std::io::Write::write_all(&mut zlib, bytes).unwrap();
[
("base64", b64.into_bytes()),
("base64url", url.into_bytes()),
("hex", hex.into_bytes()),
("gzip", gz.finish().unwrap()),
("zlib", zlib.finish().unwrap()),
]
}
let mut tally = Tally::default();
let decoders = crate::decode::stock();
for_each_record_of(&["syslog", "cef", "mixed", "json", "naughty"], |r| {
let encodings = encodings(r.bytes);
for d in &decoders {
let Some((_, encoded)) = encodings.iter().find(|(name, _)| *name == d.name()) else {
continue;
};
let got = tally.caught(d.name(), r, || match d.parse(encoded, &mut Fields::new()) {
Ok(Parsed::Decoded(out)) => Some(out.bytes().to_vec()),
_ => None,
});
if let Some(Some(bytes)) = got {
tally.count(d.name(), r, true);
if bytes != r.bytes {
tally.problem(d.name(), r, "decoded to other bytes");
}
}
}
});
tally.scales_longest("decode", Join::SPACE, |plain| {
let encodings = encodings(plain);
for d in &decoders {
if let Some((_, encoded)) = encodings.iter().find(|(name, _)| *name == d.name()) {
let _ = d.parse(encoded, &mut Fields::new());
}
}
});
tally.finish("decode");
}
#[cfg(feature = "framing")]
mod framing {
use std::io::{BufReader, Read};
use super::Record;
use crate::io::{Frame, Writer, frames};
use crate::parse::{StreamConfig, StreamSplit};
use crate::shared_tests::corpus::Tally;
struct Wobbly<'a> {
bytes: &'a [u8],
state: u64,
}
impl Read for Wobbly<'_> {
fn read(&mut self, out: &mut [u8]) -> std::io::Result<usize> {
self.state ^= self.state << 13;
self.state ^= self.state >> 7;
self.state ^= self.state << 17;
let n = usize::try_from(self.state % 97).unwrap_or(0) + 1;
let n = n.min(out.len()).min(self.bytes.len());
out[..n].copy_from_slice(&self.bytes[..n]);
self.bytes = &self.bytes[n..];
Ok(n)
}
}
pub(super) const SIZES: [usize; 5] = [usize::MAX, 1, 7, 4096, 0];
pub(super) fn read(c: &StreamConfig, bytes: &[u8], size: usize) -> Vec<Frame<Vec<u8>>> {
let got: Vec<Frame<Vec<u8>>> = if size == 0 {
let wobbly = Wobbly {
bytes,
state: 0x9e37_79b9_7f4a_7c15,
};
frames(BufReader::with_capacity(128, wobbly), c)
.map(Result::unwrap)
.collect()
} else {
let size = size.min(bytes.len()).max(1);
frames(BufReader::with_capacity(size, bytes), c)
.map(Result::unwrap)
.collect()
};
got.into_iter()
.map(|f| match f {
Frame::Oversize { head, .. } => Frame::Oversize { len: 0, head },
other => other,
})
.collect()
}
pub(super) fn apart(got: &[Frame<Vec<u8>>], want: &[Frame<Vec<u8>>]) -> String {
let at = got
.iter()
.zip(want)
.position(|(a, b)| a != b)
.unwrap_or_else(|| got.len().min(want.len()));
let show = |v: &[Frame<Vec<u8>>]| match v.get(at) {
Some(Frame::Record(r) | Frame::Oversize { head: r, .. }) => {
String::from_utf8_lossy(&r[..r.len().min(120)]).into_owned()
}
other => format!("{other:?}"),
};
format!(
"{} frames for {}, first apart at {at}: {:?} against {:?}",
got.len(),
want.len(),
show(got),
show(want)
)
}
pub(super) fn round_trip(
tally: &mut Tally,
r: &Record<'_>,
split: StreamSplit,
records: &[&[u8]],
) {
let c = StreamConfig {
split,
..StreamConfig::default()
};
let mut writer = Writer::new(&c);
let mut body = Vec::new();
let kept: Vec<&[u8]> = records
.iter()
.copied()
.filter(|record| writer.frame(record, &mut body).is_ok())
.collect();
writer.finish(&mut body);
for max in [c.max_bytes, 64] {
let c = StreamConfig {
max_bytes: max,
..c.clone()
};
let want: Vec<Frame<Vec<u8>>> = kept
.iter()
.map(|record| match record.get(..max) {
Some(head) if record.len() > max => Frame::Oversize {
len: 0,
head: head.to_vec(),
},
_ => Frame::Record(record.to_vec()),
})
.collect();
for size in SIZES {
let got = tally.caught("framing", r, || read(&c, &body, size));
if let Some(got) = got
&& got != want
{
let why = apart(&got, &want);
tally.problem(
"framing",
r,
&format!("{split:?} capped at {max}, read {size} at a time: {why}"),
);
}
}
}
}
}
#[cfg(feature = "framing")]
#[test]
fn framing_splits_real_streams_the_same_at_any_read_size() {
use crate::parse::{StreamConfig, StreamSplit};
let mut tally = Tally::default();
let tags = [
"syslog",
"cef",
"mixed",
"access",
"csv",
"tsv",
"prometheus",
"naughty",
];
let mut files = std::collections::BTreeSet::new();
for_each_record_of(&tags, |r| {
files.insert((r.source.to_owned(), r.file.to_owned()));
});
for (source, file) in files {
let bytes = crate::shared_tests::corpus::file_bytes(&source, &file);
let r = Record {
source: &source,
file: &file,
line: 0,
bytes: &bytes,
unit: crate::shared_tests::corpus::Unit::File,
};
let lf = StreamConfig::default();
let Some(whole) = tally.caught("framing", &r, || framing::read(&lf, &bytes, usize::MAX))
else {
continue;
};
tally.count("framing", &r, !whole.is_empty());
for size in framing::SIZES {
let got = tally.caught("framing", &r, || framing::read(&lf, &bytes, size));
if let Some(got) = got
&& got != whole
{
let why = framing::apart(&got, &whole);
tally.problem("framing", &r, &format!("read {size} at a time: {why}"));
}
}
let lines: Vec<&[u8]> = crate::shared_tests::corpus::lines(&bytes)
.map(|(_, l)| l)
.collect();
framing::round_trip(&mut tally, &r, StreamSplit::Lf, &lines);
framing::round_trip(&mut tally, &r, StreamSplit::Nul, &lines);
framing::round_trip(&mut tally, &r, StreamSplit::OctetCounted, &lines);
}
let mut json: Vec<Vec<u8>> = Vec::new();
for_each_record_of(&["json", "ndjson"], |r| {
let value = r.bytes.trim_ascii();
if serde_json::from_slice::<serde::de::IgnoredAny>(value).is_ok() {
json.push(value.to_vec());
}
});
let all: Vec<u8> = json.concat();
let r = Record {
source: "json and ndjson",
file: "every record",
line: 0,
bytes: &all,
unit: crate::shared_tests::corpus::Unit::File,
};
let records: Vec<&[u8]> = json.iter().map(Vec::as_slice).collect();
assert!(records.len() > 50, "{} JSON records", records.len());
for split in [
StreamSplit::JsonConcat,
StreamSplit::JsonSeq,
StreamSplit::JsonArray,
] {
framing::round_trip(&mut tally, &r, split, &records);
}
tally.scales_longest("framing", Join::LINES, |input| {
let _ = framing::read(&StreamConfig::default(), input, 4096);
});
tally.finish("framing");
}
#[cfg(feature = "xml")]
#[test]
fn xml_to_json_reads_real_documents() {
use crate::xml::{XmlConfig, to_json};
let config = XmlConfig::default();
let mut tally = Tally::default();
for_each_record_of(&["xml", "xml-lines"], |r| {
let Some(json) = tally.caught("xml::to_json", r, || to_json(r.bytes, &config)) else {
return;
};
tally.count("xml::to_json", r, json.is_ok());
if let Ok(json) = &json
&& serde_json::from_slice::<serde_json::Value>(json).is_err()
{
tally.problem("xml::to_json", r, "wrote JSON that doesn't read");
}
let well_formed =
std::str::from_utf8(r.bytes).is_ok_and(|s| roxmltree::Document::parse(s).is_ok());
if well_formed && json.is_err() {
tally.problem(
"xml::to_json",
r,
&format!("refused a document roxmltree reads: {json:?}"),
);
}
for m in mutations(r.bytes) {
let at = Record { bytes: &m, ..*r };
tally.caught("xml::to_json", &at, || to_json(&m, &config));
}
});
let wrapped = Join {
open: b"<r>",
sep: b"",
close: b"</r>",
};
tally.scales_longest("xml::to_json", wrapped, |input| {
let _ = to_json(input, &config);
});
tally.finish("xml::to_json");
}
#[cfg(feature = "xml")]
#[test]
fn xml_trim_text_off_adds_only_white_space_on_real_documents() {
use crate::xml::{XmlConfig, to_json};
use serde_json::Value as Json;
fn same(kept: &Json, trimmed: &Json, attribute: bool) -> bool {
let space = |c: char| matches!(c, ' ' | '\t' | '\r' | '\n');
match (kept, trimmed) {
(Json::String(k), Json::String(t)) if attribute => k == t,
(Json::String(k), Json::String(t)) => k.trim_matches(space) == t,
(Json::Array(k), Json::Array(t)) => {
k.len() == t.len() && k.iter().zip(t).all(|(k, t)| same(k, t, false))
}
(Json::Object(k), Json::Object(t)) => {
t.iter()
.all(|(key, t)| k.get(key).is_some_and(|k| same(k, t, key.starts_with('@'))))
&& k.iter().all(|(key, k)| {
t.contains_key(key)
|| (key == "#text"
&& matches!(k, Json::String(s) if s.trim_matches(space).is_empty()))
})
}
(k, t) => k == t,
}
}
let keep = XmlConfig {
trim_text: false,
..XmlConfig::default()
};
let trim = XmlConfig::default();
let mut tally = Tally::default();
for_each_record_of(&["xml", "xml-lines"], |r| {
let Some(kept) = tally.caught("xml::trim_text", r, || to_json(r.bytes, &keep)) else {
return;
};
let trimmed = to_json(r.bytes, &trim);
let (Ok(kept), Ok(trimmed)) = (kept, trimmed) else {
return;
};
let (Ok(k), Ok(t)) = (
serde_json::from_slice::<Json>(&kept),
serde_json::from_slice::<Json>(&trimmed),
) else {
tally.problem("xml::trim_text", r, "wrote JSON that doesn't read");
return;
};
let agree = same(&k, &t, false);
tally.count("xml::to_json", r, agree);
if !agree {
tally.problem("xml::trim_text", r, "kept text isn't the trimmed text");
}
});
tally.finish("xml::trim_text");
}
#[cfg(feature = "domain")]
#[test]
fn domain_split_passes_the_public_suffix_list_tests() {
use crate::domain::{Case, split};
let case = regex::Regex::new(r"^checkPublicSuffix\((null|'[^']*'), (null|'[^']*')\);").unwrap();
let unquote = |s: &str| (s != "null").then(|| s.trim_matches('\'').to_owned());
let mut tally = Tally::default();
for_each_record("domain-psl", |r| {
let Some(c) = std::str::from_utf8(r.bytes)
.ok()
.and_then(|l| case.captures(l))
else {
return;
};
let (Some(name), want) = (unquote(&c[1]), unquote(&c[2])) else {
return;
};
let Some(got) = tally.caught("domain-psl", r, || {
split(&name, Case::Fold).and_then(|d| d.registrable.map(str::to_ascii_lowercase))
}) else {
return;
};
tally.count("domain-psl", r, got == want);
if got != want {
tally.problem(
"domain-psl",
r,
&format!("{name}: {got:?}, the list expects {want:?}"),
);
}
});
tally.scales_longest("domain-psl", Join::between(b"."), |input| {
if let Ok(name) = std::str::from_utf8(input) {
let _ = split(name, Case::Fold);
}
});
tally.finish("domain-psl");
}