feat: implement Pillars 2-4 and fix a production false-positive in Pillar 1

Pillar 1 v1.1 (shipped earlier) flagged benign browsing bursts as
beaconing: on short captures, grid periods longer than the observed
span never complete a cycle, so significance saturates to 1 and the
score sticks at exactly 0.5. v1.2 caps the grid at a third of the
observed span, requires a minimum number of completed cycles, and
excludes protocols that are periodic by nature (NTP, DNS, mDNS,
ICMP). Validated against 300 seeds per scenario: false positives on
bursty traffic drop from the 290-300/300 that v1.1 produced to 0/300,
with every beacon-detection scenario scoring unchanged.

Add Pillar 2 (persistent/long-lived sessions, with Zeek's fragmented
TCP sessions rejoined after a 5-minute gap), Pillar 3 (DNS tunneling
via Shannon-entropy information volume per subdomain per hour; the
Jensen-Shannon divergence was measured and does not separate tunnels
from benign CDN subdomains, so it stays in the evidence at zero
weight instead of in the score), and Pillar 4 (deterministic
noisy-OR fusion across the three pillars).

The fusion formula was validated against 8 labeled real-traffic
vectors (IoT-23, CTU-Normal) with tolerance <= 1e-4. A known
limitation is kept, not hidden: a benign Philips HUE bulb's strict
periodic polling and a 21.9h session score it above three real C2
hosts. No weight or threshold was tuned to mask this; it is
documented in the architecture docs instead.

Also fixes real bugs found along the way: ingest_dir's partition
count summed file names instead of distinct dates, DuckDB errors
were counted as bad rows, /api/alerts always returned an empty list
regardless of the last analysis, and the dashboard still claimed
every pillar was unimplemented.

Restores four design corrections that were missing from
docs/architecture.md (KL to Jensen-Shannon, the persistent-session
detector, the JA4 licensing boundary, and deterministic reduction
order), and catalogs the public datasets used for validation
(IoT-23, CTU-Normal, Mendeley DTQBC) with their licenses and SHA-256
checksums under research/validation/.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VAyr8d7HuAdUGB6aA5xmDD
This commit is contained in:
Lucas RayanandClaude Sonnet 5 committed 2026-11-01 00:28:54 -03:00
1 parent 8a80504c45
commit c64bbbf775
41 files changed
+4034 -348

No files matched your search

+472 -75
View File
@@ -1,8 +1,8 @@
use crate::error::{AcauaError, Result};
use chrono::NaiveDate;
use serde::Serialize;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::HashSet;
use std::collections::{HashMap, HashSet};
use std::fs;
use std::path::{Path, PathBuf};
@@ -27,12 +27,14 @@ impl DatasetSummary {
}
}
#[derive(Debug, Clone, Default)]
#[derive(Debug, Clone, Default, Serialize)]
pub struct IngestionStats {
pub files_seen: usize,
pub records_ingested: u64,
pub lines_skipped: u64,
pub partitions_affected: usize,
pub files_failed: usize,
pub failed_errors: Vec<String>,
}
#[derive(Debug, Clone)]
@@ -40,9 +42,35 @@ pub struct TupleTimestamps {
pub orig_h: String,
pub resp_h: String,
pub resp_p: u16,
pub proto: String,
pub timestamps: Vec<f64>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChainedSession {
pub orig_h: String,
pub orig_p: u16,
pub resp_h: String,
pub resp_p: u16,
pub proto: String,
pub start_ts: f64,
pub end_ts: f64,
pub duration: f64,
pub parts: usize,
pub orig_bytes: u64,
pub resp_bytes: u64,
}
#[derive(Debug, Clone)]
pub struct TupleSessions {
pub orig_h: String,
pub resp_h: String,
pub resp_p: u16,
pub proto: String,
pub sessions: Vec<ChainedSession>,
pub failed_attempts: usize,
}
#[derive(Debug, Clone)]
pub struct Storage {
root: PathBuf,
@@ -59,6 +87,12 @@ pub struct ConnRecord {
pub proto: String,
pub service: Option<String>,
pub duration: Option<f64>,
pub orig_bytes: Option<u64>,
pub resp_bytes: Option<u64>,
pub conn_state: Option<String>,
pub history: Option<String>,
pub orig_pkts: Option<u64>,
pub resp_pkts: Option<u64>,
}
impl Storage {
@@ -133,7 +167,7 @@ impl Storage {
let query = format!(
"SELECT count(*)::BIGINT, count(DISTINCT date)::BIGINT
FROM read_parquet('{parquet_glob}', hive_partitioning = true);"
FROM read_parquet('{parquet_glob}', hive_partitioning = true, union_by_name = true);"
);
let row = conn.query_row(&query, [], |r| {
@@ -193,6 +227,26 @@ impl Storage {
}
}
// Also prune raw/dns if exists
let dns_dir = self.root.join("raw").join("dns");
if let Ok(dns_entries) = fs::read_dir(&dns_dir) {
for entry in dns_entries.flatten() {
let path = entry.path();
if !path.is_dir() {
continue;
}
if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
if let Some(date_str) = name.strip_prefix("date=") {
if let Ok(d) = NaiveDate::parse_from_str(date_str, "%Y-%m-%d") {
if d <= cutoff && fs::remove_dir_all(&path).is_ok() {
pruned += 1;
}
}
}
}
}
}
Ok(pruned)
}
@@ -203,6 +257,7 @@ impl Storage {
let mut separator = '\t';
let mut unset_field = String::from("-");
let mut empty_field = String::from("(empty)");
let mut fields: Vec<String> = Vec::new();
let mut idx_ts = None;
@@ -214,6 +269,12 @@ impl Storage {
let mut idx_proto = None;
let mut idx_service = None;
let mut idx_duration = None;
let mut idx_orig_bytes = None;
let mut idx_resp_bytes = None;
let mut idx_conn_state = None;
let mut idx_history = None;
let mut idx_orig_pkts = None;
let mut idx_resp_pkts = None;
let text = String::from_utf8_lossy(content);
@@ -235,6 +296,8 @@ impl Storage {
}
} else if let Some(rest) = line.strip_prefix("#unset_field") {
unset_field = rest.trim().to_string();
} else if let Some(rest) = line.strip_prefix("#empty_field") {
empty_field = rest.trim().to_string();
} else if let Some(rest) = line.strip_prefix("#fields") {
let rest = rest.trim();
fields = rest
@@ -251,11 +314,16 @@ impl Storage {
idx_proto = fields.iter().position(|s| s == "proto");
idx_service = fields.iter().position(|s| s == "service");
idx_duration = fields.iter().position(|s| s == "duration");
idx_orig_bytes = fields.iter().position(|s| s == "orig_bytes");
idx_resp_bytes = fields.iter().position(|s| s == "resp_bytes");
idx_conn_state = fields.iter().position(|s| s == "conn_state");
idx_history = fields.iter().position(|s| s == "history");
idx_orig_pkts = fields.iter().position(|s| s == "orig_pkts");
idx_resp_pkts = fields.iter().position(|s| s == "resp_pkts");
}
continue;
}
// Must have fields mapped
let (i_ts, i_uid, i_oh, i_op, i_rh, i_rp, i_pr) = match (
idx_ts, idx_uid, idx_orig_h, idx_orig_p, idx_resp_h, idx_resp_p, idx_proto,
) {
@@ -298,25 +366,29 @@ impl Storage {
}
};
let service = idx_service.and_then(|idx| {
let val = parts.get(idx)?;
if *val == unset_field.as_str() || *val == "-" {
let get_val = |idx: Option<usize>| -> Option<&str> {
let i = idx?;
let val = parts.get(i)?;
if *val == unset_field.as_str()
|| *val == "-"
|| *val == empty_field.as_str()
|| *val == "(empty)"
{
None
} else {
Some(val.to_string())
Some(*val)
}
});
};
let duration = idx_duration.and_then(|idx| {
let val = parts.get(idx)?;
if *val == unset_field.as_str() || *val == "-" {
None
} else {
val.parse::<f64>().ok()
}
});
let service = get_val(idx_service).map(|s| s.to_string());
let duration = get_val(idx_duration).and_then(|s| s.parse::<f64>().ok());
let orig_bytes = get_val(idx_orig_bytes).and_then(|s| s.parse::<u64>().ok());
let resp_bytes = get_val(idx_resp_bytes).and_then(|s| s.parse::<u64>().ok());
let conn_state = get_val(idx_conn_state).map(|s| s.to_string());
let history = get_val(idx_history).map(|s| s.to_string());
let orig_pkts = get_val(idx_orig_pkts).and_then(|s| s.parse::<u64>().ok());
let resp_pkts = get_val(idx_resp_pkts).and_then(|s| s.parse::<u64>().ok());
// Track day partition (UTC)
let date_ts = chrono::DateTime::from_timestamp(ts.floor() as i64, 0);
if let Some(dt) = date_ts {
dates.insert(dt.format("%Y-%m-%d").to_string());
@@ -332,13 +404,19 @@ impl Storage {
proto: parts[i_pr].to_string(),
service,
duration,
orig_bytes,
resp_bytes,
conn_state,
history,
orig_pkts,
resp_pkts,
});
}
(records, skipped, dates)
}
pub fn ingest_file(&self, path: impl AsRef<Path>) -> Result<(u64, u64, usize)> {
pub fn ingest_file(&self, path: impl AsRef<Path>) -> Result<(u64, u64, HashSet<String>)> {
let path = path.as_ref();
let content = fs::read(path)?;
let mut hasher = Sha256::new();
@@ -352,7 +430,7 @@ impl Storage {
let (records, skipped, dates) = Self::parse_conn_log(&content);
if records.is_empty() {
return Ok((0, skipped, 0));
return Ok((0, skipped, dates));
}
let conn = self.open_connection()?;
@@ -366,7 +444,13 @@ impl Storage {
resp_p USMALLINT,
proto VARCHAR,
service VARCHAR,
duration DOUBLE
duration DOUBLE,
orig_bytes UBIGINT,
resp_bytes UBIGINT,
conn_state VARCHAR,
history VARCHAR,
orig_pkts UBIGINT,
resp_pkts UBIGINT
);",
)?;
@@ -374,8 +458,21 @@ impl Storage {
let mut appender = conn.appender("t")?;
for r in &records {
appender.append_row(duckdb::params![
r.ts, r.uid, r.orig_h, r.orig_p, r.resp_h, r.resp_p, r.proto, r.service,
r.duration
r.ts,
r.uid,
r.orig_h,
r.orig_p,
r.resp_h,
r.resp_p,
r.proto,
r.service,
r.duration,
r.orig_bytes,
r.resp_bytes,
r.conn_state,
r.history,
r.orig_pkts,
r.resp_pkts
])?;
}
}
@@ -401,7 +498,7 @@ impl Storage {
conn.execute_batch(&copy_sql)?;
conn.execute_batch("DROP TABLE t;")?;
Ok((records.len() as u64, skipped, dates.len()))
Ok((records.len() as u64, skipped, dates))
}
pub fn ingest_dir(&self, directory: impl AsRef<Path>) -> Result<IngestionStats> {
@@ -421,7 +518,6 @@ impl Storage {
let entries = fs::read_dir(&canonical_dir)?;
for entry in entries.flatten() {
let path = entry.path();
// Path confinement: do not follow symlink to outside directory
if let Ok(canon) = fs::canonicalize(&path) {
if !canon.starts_with(&canonical_dir) {
continue;
@@ -435,27 +531,26 @@ impl Storage {
None => continue,
};
// Skip .gz archives with note
if file_name.ends_with(".gz") {
continue;
}
// Only conn.log and conn.*.log directly in directory
let is_conn = file_name == "conn.log"
|| (file_name.starts_with("conn.") && file_name.ends_with(".log"));
if is_conn && path.is_file() {
stats.files_seen += 1;
match self.ingest_file(&path) {
Ok((recs, sk, affected)) => {
Ok((recs, sk, dates)) => {
stats.records_ingested += recs;
stats.lines_skipped += sk;
for _ in 0..affected {
all_dates.insert(file_name.to_string());
}
all_dates.extend(dates);
}
Err(_) => {
stats.lines_skipped += 1;
Err(e) => {
stats.files_failed += 1;
if stats.failed_errors.len() < 10 {
stats.failed_errors.push(e.to_string());
}
}
}
}
@@ -465,7 +560,7 @@ impl Storage {
Ok(stats)
}
pub fn query_7day_tuples(&self) -> Result<Vec<TupleTimestamps>> {
pub fn query_7day_sessions(&self) -> Result<Vec<TupleSessions>> {
if !self.has_parquet_files() {
return Ok(Vec::new());
}
@@ -483,7 +578,7 @@ impl Storage {
// Find max date present in data
let max_date_query = format!(
"SELECT max(date)::VARCHAR
FROM read_parquet('{parquet_glob}', hive_partitioning = true);"
FROM read_parquet('{parquet_glob}', hive_partitioning = true, union_by_name = true);"
);
let max_date: Option<String> = conn
@@ -495,47 +590,193 @@ impl Storage {
_ => return Ok(Vec::new()),
};
// Query all conn rows in 7-day window ordered by orig_h, orig_p, resp_h, resp_p, ts
let query = format!(
"WITH daily AS (
SELECT date, orig_h, resp_h, resp_p, list(ts ORDER BY ts) AS tss
FROM read_parquet('{parquet_glob}', hive_partitioning = true)
WHERE date > CAST('{max_date_str}' AS DATE) - INTERVAL 7 DAY
GROUP BY ALL
)
SELECT orig_h, resp_h, resp_p, list_sort(flatten(list(tss))) AS timestamps
FROM daily
GROUP BY ALL
ORDER BY orig_h, resp_h, resp_p;"
"SELECT ts, orig_h, orig_p, resp_h, resp_p, proto, duration, orig_bytes, resp_bytes, conn_state, history
FROM read_parquet('{parquet_glob}', hive_partitioning = true, union_by_name = true)
WHERE date > CAST('{max_date_str}' AS DATE) - INTERVAL 7 DAY
ORDER BY orig_h, orig_p, resp_h, resp_p, ts;"
);
struct RawRow {
ts: f64,
orig_h: String,
orig_p: u16,
resp_h: String,
resp_p: u16,
proto: String,
duration: Option<f64>,
orig_bytes: Option<u64>,
resp_bytes: Option<u64>,
conn_state: Option<String>,
history: Option<String>,
}
let mut stmt = conn.prepare(&query)?;
let rows = stmt.query_map([], |row| {
let orig_h: String = row.get(0)?;
let resp_h: String = row.get(1)?;
let resp_p: u16 = row.get(2)?;
let timestamps_val: duckdb::types::Value = row.get(3)?;
let mut timestamps = Vec::new();
if let duckdb::types::Value::List(items) = timestamps_val {
for item in items {
if let duckdb::types::Value::Double(t) = item {
timestamps.push(t);
}
}
}
Ok(TupleTimestamps {
orig_h,
resp_h,
resp_p,
timestamps,
Ok(RawRow {
ts: row.get(0)?,
orig_h: row.get(1)?,
orig_p: row.get(2)?,
resp_h: row.get(3)?,
resp_p: row.get(4)?,
proto: row.get(5)?,
duration: row.get(6)?,
orig_bytes: row.get(7)?,
resp_bytes: row.get(8)?,
conn_state: row.get(9)?,
history: row.get(10)?,
})
})?;
let mut result = Vec::new();
let mut raw_rows = Vec::new();
let mut failed_map: HashMap<(String, String, u16), usize> = HashMap::new();
for r in rows {
result.push(r?);
let row = r?;
if row.proto == "tcp" {
if let Some(cs) = &row.conn_state {
if cs == "S0" || cs == "REJ" || cs == "RSTOS0" || cs == "SH" {
*failed_map
.entry((row.orig_h.clone(), row.resp_h.clone(), row.resp_p))
.or_insert(0) += 1;
}
}
}
raw_rows.push(row);
}
// Group rows by 4-tuple (orig_h, orig_p, resp_h, resp_p, proto)
// Since rows are already ordered by (orig_h, orig_p, resp_h, resp_p, ts),
// we can chain sequentially.
let mut all_sessions: Vec<ChainedSession> = Vec::new();
let mut current_chain: Option<ChainedSession> = None;
for r in raw_rows {
let row_end = r.ts + r.duration.unwrap_or(0.0);
if r.proto == "tcp" {
let matches_current_4tuple = match &current_chain {
Some(curr) => {
curr.orig_h == r.orig_h
&& curr.orig_p == r.orig_p
&& curr.resp_h == r.resp_h
&& curr.resp_p == r.resp_p
&& curr.proto == r.proto
}
None => false,
};
let is_continuation = if matches_current_4tuple {
let curr = current_chain.as_ref().unwrap();
match &r.history {
Some(h) => !h.contains('S') && (r.ts - curr.end_ts <= 3600.0),
None => false,
}
} else {
false
};
if is_continuation {
let curr = current_chain.as_mut().unwrap();
if row_end > curr.end_ts {
curr.end_ts = row_end;
}
curr.duration = curr.end_ts - curr.start_ts;
curr.parts += 1;
curr.orig_bytes += r.orig_bytes.unwrap_or(0);
curr.resp_bytes += r.resp_bytes.unwrap_or(0);
} else {
if let Some(finished) = current_chain.take() {
all_sessions.push(finished);
}
current_chain = Some(ChainedSession {
orig_h: r.orig_h,
orig_p: r.orig_p,
resp_h: r.resp_h,
resp_p: r.resp_p,
proto: r.proto,
start_ts: r.ts,
end_ts: row_end,
duration: row_end - r.ts,
parts: 1,
orig_bytes: r.orig_bytes.unwrap_or(0),
resp_bytes: r.resp_bytes.unwrap_or(0),
});
}
} else {
if let Some(finished) = current_chain.take() {
all_sessions.push(finished);
}
all_sessions.push(ChainedSession {
orig_h: r.orig_h,
orig_p: r.orig_p,
resp_h: r.resp_h,
resp_p: r.resp_p,
proto: r.proto,
start_ts: r.ts,
end_ts: row_end,
duration: row_end - r.ts,
parts: 1,
orig_bytes: r.orig_bytes.unwrap_or(0),
resp_bytes: r.resp_bytes.unwrap_or(0),
});
}
}
if let Some(finished) = current_chain {
all_sessions.push(finished);
}
// Group sessions by (orig_h, resp_h, resp_p, proto)
let mut grouped: HashMap<(String, String, u16, String), Vec<ChainedSession>> =
HashMap::new();
for session in all_sessions {
let key = (
session.orig_h.clone(),
session.resp_h.clone(),
session.resp_p,
session.proto.clone(),
);
grouped.entry(key).or_default().push(session);
}
let mut result = Vec::new();
for ((orig_h, resp_h, resp_p, proto), mut sessions) in grouped {
sessions.sort_by(|a, b| a.start_ts.partial_cmp(&b.start_ts).unwrap());
let failed_attempts = failed_map
.get(&(orig_h.clone(), resp_h.clone(), resp_p))
.copied()
.unwrap_or(0);
result.push(TupleSessions {
orig_h,
resp_h,
resp_p,
proto,
sessions,
failed_attempts,
});
}
result.sort_by(|a, b| {
(&a.orig_h, &a.resp_h, a.resp_p, &a.proto)
.cmp(&(&b.orig_h, &b.resp_h, b.resp_p, &b.proto))
});
Ok(result)
}
pub fn query_7day_tuples(&self) -> Result<Vec<TupleTimestamps>> {
let tuple_sessions = self.query_7day_sessions()?;
Ok(tuple_sessions
.into_iter()
.map(|ts| TupleTimestamps {
orig_h: ts.orig_h,
resp_h: ts.resp_h,
resp_p: ts.resp_p,
proto: ts.proto,
timestamps: ts.sessions.into_iter().map(|s| s.start_ts).collect(),
})
.collect())
}
}
#[cfg(test)]
@@ -548,15 +789,15 @@ mod tests {
#unset_field\t-\n\
#path\tconn\n\
#open\t2026-10-31-12-00-00\n\
#fields\tts\tuid\tid.orig_h\tid.orig_p\tid.resp_h\tid.resp_p\tproto\tservice\tduration\tip_proto\n\
#types\ttime\tstring\taddr\tport\taddr\tport\tenum\tstring\tinterval\tcount\n\
1793461200.000000\tCuid1\t192.168.1.10\t45000\t10.0.0.1\t443\ttcp\tssl\t1.234\t6\n\
1793461205.000000\tCuid2\t192.168.1.10\t45001\t10.0.0.1\t443\ttcp\t-\t-\t6\n\
#fields\tts\tuid\tid.orig_h\tid.orig_p\tid.resp_h\tid.resp_p\tproto\tservice\tduration\torig_bytes\tresp_bytes\tconn_state\thistory\torig_pkts\tresp_pkts\n\
#types\ttime\tstring\taddr\tport\taddr\tport\tenum\tstring\tinterval\tcount\tcount\tstring\tstring\tcount\tcount\n\
1793461200.000000\tCuid1\t192.168.1.10\t45000\t10.0.0.1\t443\ttcp\tssl\t1.234\t100\t200\tSF\tShADadFf\t10\t12\n\
1793461205.000000\tCuid2\t192.168.1.10\t45001\t10.0.0.1\t443\ttcp\t-\t-\t-\t-\tS0\tS\t1\t0\n\
#close\t2026-10-31-12-01-00\n";
const CONN_LOG_PERMUTED_COLS: &str = "#separator \\x09\n\
#fields\tid.resp_p\tid.orig_h\tservice\tuid\tduration\tproto\tts\tid.resp_h\tid.orig_p\n\
443\t192.168.1.10\thttp\tCuid3\t0.5\ttcp\t1793461210.000000\t10.0.0.1\t45002\n";
#fields\tid.resp_p\tid.orig_h\tservice\tuid\tduration\tproto\tts\tid.resp_h\tid.orig_p\tconn_state\thistory\n\
443\t192.168.1.10\thttp\tCuid3\t0.5\ttcp\t1793461210.000000\t10.0.0.1\t45002\tSF\tShAD\n";
#[test]
fn test_parser_extracts_correct_fields_and_unset_as_none() {
@@ -573,10 +814,19 @@ mod tests {
assert_eq!(records[0].proto, "tcp");
assert_eq!(records[0].service.as_deref(), Some("ssl"));
assert_eq!(records[0].duration, Some(1.234));
assert_eq!(records[0].orig_bytes, Some(100));
assert_eq!(records[0].resp_bytes, Some(200));
assert_eq!(records[0].conn_state.as_deref(), Some("SF"));
assert_eq!(records[0].history.as_deref(), Some("ShADadFf"));
assert_eq!(records[0].orig_pkts, Some(10));
assert_eq!(records[0].resp_pkts, Some(12));
assert_eq!(records[1].uid, "Cuid2");
assert_eq!(records[1].service, None);
assert_eq!(records[1].duration, None);
assert_eq!(records[1].orig_bytes, None);
assert_eq!(records[1].conn_state.as_deref(), Some("S0"));
assert_eq!(records[1].history.as_deref(), Some("S"));
}
#[test]
@@ -611,7 +861,6 @@ mod tests {
assert_eq!(summary1.records, 2);
assert_eq!(summary1.partitions, 1);
// Idempotence: re-ingesting the exact same file does not duplicate records
let (ingested2, skipped2, _) = store.ingest_file(&log_file).unwrap();
assert_eq!(ingested2, 2);
assert_eq!(skipped2, 0);
@@ -619,7 +868,6 @@ mod tests {
let summary2 = store.summary().unwrap();
assert_eq!(summary2.records, 2);
// Ingesting a different file for the same tuple/day adds to it
let log_file_2 = temp_dir.path().join("conn.extra.log");
fs::write(&log_file_2, CONN_LOG_PERMUTED_COLS).unwrap();
store.ingest_file(&log_file_2).unwrap();
@@ -632,6 +880,7 @@ mod tests {
assert_eq!(tuples[0].orig_h, "192.168.1.10");
assert_eq!(tuples[0].resp_h, "10.0.0.1");
assert_eq!(tuples[0].resp_p, 443);
assert_eq!(tuples[0].proto, "tcp");
assert_eq!(tuples[0].timestamps.len(), 3);
assert_eq!(tuples[0].timestamps[0], 1793461200.0);
assert_eq!(tuples[0].timestamps[1], 1793461205.0);
@@ -643,7 +892,6 @@ mod tests {
let temp_dir = tempfile::tempdir().unwrap();
let store = Storage::open(temp_dir.path()).unwrap();
// 2026-10-31 02:00:00 UTC = 1793412000
let log = "#separator \\x09\n#fields\tts\tuid\tid.orig_h\tid.orig_p\tid.resp_h\tid.resp_p\tproto\n1793412000.000000\tu1\t10.0.0.1\t1000\t10.0.0.2\t80\ttcp\n";
let log_file = temp_dir.path().join("conn.log");
fs::write(&log_file, log).unwrap();
@@ -676,7 +924,6 @@ mod tests {
let store = Storage::open(temp_dir.path()).unwrap();
let raw_conn = temp_dir.path().join("raw").join("conn");
// Day 1 (10 days ago) and Day 10 (recent)
let old_part = raw_conn.join("date=2026-10-01");
let new_part = raw_conn.join("date=2026-10-11");
fs::create_dir_all(&old_part).unwrap();
@@ -687,4 +934,154 @@ mod tests {
assert!(!old_part.exists());
assert!(new_part.exists());
}
#[test]
fn test_union_by_name_v11_and_v12_compatibility() {
let temp_dir = tempfile::tempdir().unwrap();
let store = Storage::open(temp_dir.path()).unwrap();
let conn = store.open_connection().unwrap();
let part_dir = store
.root()
.join("raw")
.join("conn")
.join("date=2026-10-31");
fs::create_dir_all(&part_dir).unwrap();
let part_str = part_dir.to_string_lossy().replace('\'', "''");
// Write v1.1 format (no history, no orig_bytes etc.)
conn.execute_batch(&format!(
"CREATE TEMP TABLE v11 (ts DOUBLE, uid VARCHAR, orig_h VARCHAR, orig_p USMALLINT, resp_h VARCHAR, resp_p USMALLINT, proto VARCHAR, date DATE);
INSERT INTO v11 VALUES (1793461200.0, 'u1', '10.0.0.1', 1000, '10.0.0.2', 80, 'tcp', '2026-10-31');
COPY v11 TO '{part_str}/v11.parquet' (FORMAT parquet);
DROP TABLE v11;"
)).unwrap();
// Write v1.2 format (with history, orig_bytes)
conn.execute_batch(&format!(
"CREATE TEMP TABLE v12 (ts DOUBLE, uid VARCHAR, orig_h VARCHAR, orig_p USMALLINT, resp_h VARCHAR, resp_p USMALLINT, proto VARCHAR, history VARCHAR, orig_bytes UBIGINT, date DATE);
INSERT INTO v12 VALUES (1793461210.0, 'u2', '10.0.0.1', 1001, '10.0.0.2', 80, 'tcp', 'ShAD', 500, '2026-10-31');
COPY v12 TO '{part_str}/v12.parquet' (FORMAT parquet);
DROP TABLE v12;"
)).unwrap();
let parquet_glob = store
.root()
.join("raw")
.join("conn")
.join("*")
.join("*.parquet")
.to_string_lossy()
.replace('\'', "''");
let read_sql = format!(
"SELECT count(*)::BIGINT, count(history)::BIGINT
FROM read_parquet('{parquet_glob}', hive_partitioning = true, union_by_name = true);"
);
let (total, with_history): (i64, i64) = conn
.query_row(&read_sql, [], |r| Ok((r.get(0)?, r.get(1)?)))
.unwrap();
assert_eq!(total, 2);
assert_eq!(with_history, 1);
}
#[test]
fn test_zeek_split_real_fixture_chaining() {
let temp_dir = tempfile::tempdir().unwrap();
let store = Storage::open(temp_dir.path()).unwrap();
let fixture_path = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests")
.join("fixtures")
.join("zeek_split")
.join("conn.log");
store.ingest_file(&fixture_path).unwrap();
let sessions = store.query_7day_sessions().unwrap();
assert_eq!(sessions.len(), 1);
assert_eq!(sessions[0].orig_h, "10.0.0.5");
assert_eq!(sessions[0].resp_h, "203.0.113.9");
assert_eq!(sessions[0].resp_p, 443);
assert_eq!(sessions[0].proto, "tcp");
assert_eq!(sessions[0].sessions.len(), 1);
let s = &sessions[0].sessions[0];
assert_eq!(s.parts, 2);
assert!(
(s.duration - 4201.05).abs() < 0.01,
"duration: expected 4201.05, got {}",
s.duration
);
assert_eq!(s.orig_bytes, 1200);
assert_eq!(s.resp_bytes, 2400);
}
#[test]
fn test_chaining_negative_cases() {
let temp_dir = tempfile::tempdir().unwrap();
let store = Storage::open(temp_dir.path()).unwrap();
// 1. Second line has 'S' in history -> 2 sessions
let log_syn = "#separator \\x09\n#fields\tts\tuid\tid.orig_h\tid.orig_p\tid.resp_h\tid.resp_p\tproto\tduration\thistory\n\
1793400000.0\tu1\t10.0.0.1\t40000\t10.0.0.2\t80\ttcp\t100.0\tShAD\n\
1793400200.0\tu2\t10.0.0.1\t40000\t10.0.0.2\t80\ttcp\t100.0\tShAD\n";
let f_syn = temp_dir.path().join("conn.syn.log");
fs::write(&f_syn, log_syn).unwrap();
store.ingest_file(&f_syn).unwrap();
let sess_syn = store.query_7day_sessions().unwrap();
assert_eq!(
sess_syn[0].sessions.len(),
2,
"history with 'S' must not chain"
);
// 2. Gap of 3601s -> 2 sessions
let temp_dir2 = tempfile::tempdir().unwrap();
let store2 = Storage::open(temp_dir2.path()).unwrap();
let log_gap = "#separator \\x09\n#fields\tts\tuid\tid.orig_h\tid.orig_p\tid.resp_h\tid.resp_p\tproto\tduration\thistory\n\
1793400000.0\tu1\t10.0.0.1\t40000\t10.0.0.2\t80\ttcp\t100.0\tShAD\n\
1793403702.0\tu2\t10.0.0.1\t40000\t10.0.0.2\t80\ttcp\t100.0\tAD\n";
let f_gap = temp_dir2.path().join("conn.gap.log");
fs::write(&f_gap, log_gap).unwrap();
store2.ingest_file(&f_gap).unwrap();
let sess_gap = store2.query_7day_sessions().unwrap();
assert_eq!(sess_gap[0].sessions.len(), 2, "gap > 3600s must not chain");
// 3. history is NULL -> does not chain
let temp_dir3 = tempfile::tempdir().unwrap();
let store3 = Storage::open(temp_dir3.path()).unwrap();
let log_null = "#separator \\x09\n#fields\tts\tuid\tid.orig_h\tid.orig_p\tid.resp_h\tid.resp_p\tproto\tduration\thistory\n\
1793400000.0\tu1\t10.0.0.1\t40000\t10.0.0.2\t80\ttcp\t100.0\tShAD\n\
1793400200.0\tu2\t10.0.0.1\t40000\t10.0.0.2\t80\ttcp\t100.0\t-\n";
let f_null = temp_dir3.path().join("conn.null.log");
fs::write(&f_null, log_null).unwrap();
store3.ingest_file(&f_null).unwrap();
let sess_null = store3.query_7day_sessions().unwrap();
assert_eq!(
sess_null[0].sessions.len(),
2,
"history NULL must not chain"
);
}
#[test]
fn test_partitions_affected_and_files_failed() {
let temp_dir = tempfile::tempdir().unwrap();
let store = Storage::open(temp_dir.path()).unwrap();
// 2 lines across 2 days (2026-10-30 and 2026-10-31)
let log = "#separator \\x09\n#fields\tts\tuid\tid.orig_h\tid.orig_p\tid.resp_h\tid.resp_p\tproto\n\
1793325600.0\tu1\t10.0.0.1\t1000\t10.0.0.2\t80\ttcp\n\
1793412000.0\tu2\t10.0.0.1\t1000\t10.0.0.2\t80\ttcp\n";
let f = temp_dir.path().join("conn.log");
fs::write(&f, log).unwrap();
let stats = store.ingest_dir(temp_dir.path()).unwrap();
assert_eq!(stats.partitions_affected, 2);
assert_eq!(stats.files_failed, 0);
}
}