netsec-agent/tests/test_archives.py

226 lines
9.4 KiB
Python
Raw Permalink Normal View History

"""Archive handling: `.jsonl.gz` is read once, bounded, and never fatal.
The collector gzips a file when it rotates, so the retained window is archives
plus one live plain file. These tests pin the three properties that matter:
a cold start baselines from the archives, a torn archive costs a note and not
the tick, and the seed budget leaves the rest unread instead of pretending to a
window it never examined.
"""
from __future__ import annotations
import contextlib
import gzip
import io
import json
import shutil
import tempfile
import unittest
from pathlib import Path
from helpers import FIXTURES, fixture_lines
from netsec_scan import __main__ as cli
from netsec_scan import config, state as state_mod
from netsec_scan.flows import (
ArchiveTruncated,
LocalFlowStore,
flow_stamp,
is_usable,
iter_archive,
)
LIVE = "flows-20261127T060000Z-1.jsonl"
ARCH_NEW = "flows-20261127T050000Z-1.jsonl.gz"
ARCH_OLD = "flows-20261127T040000Z-2.jsonl.gz"
def _adopted_dir(root: Path) -> None:
"""Two archives and one live file, all built from the real egress fixture."""
lines = fixture_lines("egress-sample.jsonl")
for name in (ARCH_OLD, ARCH_NEW):
with gzip.open(root / name, "wt", encoding="utf-8") as handle:
handle.write("\n".join(lines) + "\n")
(root / LIVE).write_text("\n".join(lines) + "\n")
def _synthetic_flow(dst="203.0.113.77", port=5000) -> str:
"""One workload->world line on a non-web port (fires on the first tick)."""
obj = json.loads(fixture_lines("egress-sample.jsonl")[0])
obj["flow"]["IP"]["destination"] = dst
proto = next(iter(obj["flow"]["l4"]))
obj["flow"]["l4"][proto]["destination_port"] = port
return json.dumps(obj)
class TestArchiveNames(unittest.TestCase):
def test_stamp_is_the_coverage_start(self):
new = flow_stamp(ARCH_NEW)
live = flow_stamp("/var/log/netsec/" + LIVE)
self.assertIsNotNone(new)
self.assertIsNotNone(live)
assert new is not None and live is not None
self.assertEqual(new.isoformat(), "2026-11-27T05:00:00+00:00")
self.assertEqual(live.isoformat(), "2026-11-27T06:00:00+00:00")
self.assertIsNone(flow_stamp("flows-nonsense.jsonl"))
def test_inflight_gzip_and_foreign_names_are_not_usable(self):
self.assertTrue(is_usable(ARCH_NEW))
self.assertTrue(is_usable(LIVE))
self.assertFalse(is_usable("flows-20261127T050000Z-1.jsonl.gz.tmp.4242"))
self.assertFalse(is_usable("notes.jsonl"))
def test_listing_covers_archives_and_skips_inflight(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
_adopted_dir(root)
(root / "flows-20261127T070000Z-1.jsonl.gz.tmp.7").write_bytes(b"marker")
names = sorted(name for name, _size in LocalFlowStore(tmp).list_files())
self.assertEqual(names, sorted([ARCH_NEW, ARCH_OLD, LIVE]))
class TestArchiveReader(unittest.TestCase):
def test_reads_a_gzip_archive(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
_adopted_dir(root)
store = LocalFlowStore(tmp)
lines = list(iter_archive(store, ARCH_NEW))
self.assertEqual(len([ln for ln in lines if ln.strip()]),
len(fixture_lines("egress-sample.jsonl")))
def test_truncated_archive_yields_what_it_can_then_raises(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
_adopted_dir(root)
whole = (root / ARCH_NEW).read_bytes()
(root / ARCH_NEW).write_bytes(whole[: len(whole) // 2])
seen = 0
with self.assertRaises(ArchiveTruncated):
for _line in iter_archive(LocalFlowStore(tmp), ARCH_NEW):
seen += 1
self.assertGreaterEqual(seen, 0) # prefix is kept, tick survives
class TestColdStart(unittest.TestCase):
"""End-to-end through main(): the state file is the only thing that matters."""
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.root = Path(self.tmp.name)
self.flows = self.root / "flows"
self.flows.mkdir()
_adopted_dir(self.flows)
self.state = self.root / "state.json"
self.reports = self.root / "reports"
def tearDown(self):
self.tmp.cleanup()
def tick(self) -> str:
buffer = io.StringIO()
with contextlib.redirect_stdout(buffer), contextlib.redirect_stderr(io.StringIO()):
code = cli.main(["--flows-dir", str(self.flows), "--no-prom",
"--state", str(self.state), "--reports", str(self.reports)])
self.assertEqual(code, 0)
return buffer.getvalue()
def test_seed_reads_archives_silently_and_the_next_tick_is_quiet(self):
self.assertEqual(self.tick(), "") # no alert storm
st = state_mod.load(self.state)
self.assertTrue(st["seeded"])
self.assertEqual(set(st["archives"]), {ARCH_NEW, ARCH_OLD})
self.assertEqual(st["observed_since"], "2026-11-27T04:00:00+00:00")
self.assertGreater(len(st["egress_counts"]), 0)
# Every distinct tuple in the window is in the baseline, including the
# web-port ones the 3-tick gate never turns into a finding.
self.assertEqual(len(st["seen"]), len(st["egress_counts"]))
self.assertEqual(st["seed"]["archives"], 2)
self.assertEqual(self.tick(), "") # warm tick, still quiet
def test_warm_state_meeting_archives_for_the_first_time_absorbs_them(self):
"""The upgrade case: a seeded sensor whose baseline was the live file only.
The archives hold tuples that are *inside* the window the alert would
quote, so announcing them would state a falsehood ("no prior in ~Xh")
and produce a burst. They are absorbed instead; the live file still
alerts normally.
"""
st = state_mod.empty()
st["seeded"] = True # baseline built before archives existed
state_mod.save(self.state, st)
self.assertEqual(self.tick(), "") # archives absorbed, nothing announced
after = state_mod.load(self.state)
self.assertTrue(after["archive_baseline"])
self.assertGreaterEqual(len(after["seen"]), len(after["egress_counts"]))
# A genuinely new live destination still speaks.
with open(self.flows / LIVE, "a", encoding="utf-8") as handle:
handle.write(_synthetic_flow() + "\n")
out = self.tick()
self.assertEqual(len(out.strip().splitlines()), 1, out)
self.assertIn("203.0.113.77:5000/tcp", out)
def test_archive_is_not_reread_on_a_warm_tick(self):
self.tick()
before = state_mod.load(self.state)["archives"][ARCH_NEW]["read_at"]
self.tick()
after = state_mod.load(self.state)["archives"][ARCH_NEW]["read_at"]
self.assertEqual(before, after)
def test_synthetic_destination_fires_once_and_only_once(self):
self.tick()
with open(self.flows / LIVE, "a", encoding="utf-8") as handle:
handle.write(_synthetic_flow() + "\n")
first = self.tick()
self.assertEqual(len(first.strip().splitlines()), 1, first)
self.assertIn("203.0.113.77:5000/tcp", first)
self.assertIn("egress-new-dst", first)
self.assertEqual(self.tick(), "") # exactly once
def test_deleting_the_fingerprint_re_arms_one_line(self):
self.tick()
with open(self.flows / LIVE, "a", encoding="utf-8") as handle:
handle.write(_synthetic_flow() + "\n")
first = self.tick().strip()
st = state_mod.load(self.state)
fp = first.split()[1]
del st["seen"][fp]
state_mod.save(self.state, st)
with open(self.flows / LIVE, "a", encoding="utf-8") as handle:
handle.write(_synthetic_flow() + "\n")
again = self.tick()
self.assertEqual(len(again.strip().splitlines()), 1, again)
self.assertEqual(again.split()[1], fp)
self.assertEqual(self.tick(), "")
def test_truncated_archive_is_noted_not_fatal(self):
whole = (self.flows / ARCH_NEW).read_bytes()
(self.flows / ARCH_NEW).write_bytes(whole[: len(whole) // 2])
self.assertEqual(self.tick(), "") # tick survives
st = state_mod.load(self.state)
self.assertIn(ARCH_NEW, st["archives"])
self.assertIn("EOFError", st["archives"][ARCH_NEW]["error"])
self.assertIn(ARCH_NEW, st["seed"]["failed"])
self.assertEqual(self.tick(), "")
def test_budget_leaves_archives_pending_instead_of_narrowing_silently(self):
original = config.ARCHIVE_MAX_FILES
config.ARCHIVE_MAX_FILES = 1
try:
self.assertEqual(self.tick(), "")
st = state_mod.load(self.state)
self.assertFalse(st["seeded"], "a partial baseline is not a baseline")
self.assertEqual(len(st["archives"]), 1)
self.assertEqual(st["seed"]["pending"], 1)
# The next tick continues; once nothing is pending it seeds.
self.tick()
st = state_mod.load(self.state)
self.assertTrue(st["seeded"])
self.assertEqual(st["seed"]["pending"], 0)
self.assertEqual(len(st["archives"]), 2)
finally:
config.ARCHIVE_MAX_FILES = original
if __name__ == "__main__":
unittest.main()