The seed line now names the held count ('N current-state finding(s) held
for the next tick') so a silent seed tick is explainable without --verbose
log archaeology, and tests/test_seed.py::TestSeedHoldsCurrentStateTripwires
pins the whole contract: seed tick silent with a drop-spike firing, the
fingerprint stored with last_alert='' (due, not cooled), the first warm
tick reports it once, the second is quiet.
186 lines
7.5 KiB
Python
186 lines
7.5 KiB
Python
"""A seed is history, not news: it is absorbed, never announced.
|
|
|
|
Pins the acceptance of t_cf3e563a: a cold start and *every* resume tick of a
|
|
budget-limited seed keep stdout empty (so the cron's delivery outcome is
|
|
`suppressed`), `--dry-run` included — a dry run against an unseeded state must
|
|
not look like the alert storm it used to print. Silence has to be explained,
|
|
so each seeding tick writes one `seed: N tuple(s) absorbed, 0 reported` line
|
|
with the window it actually covered.
|
|
|
|
The opposite failure is a permanently silent sensor, so the seeded-state
|
|
single-fire test lives right next to these (test_archives.py pins it too).
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import contextlib
|
|
import gzip
|
|
import io
|
|
import json
|
|
import tempfile
|
|
import unittest
|
|
from pathlib import Path
|
|
from unittest import mock
|
|
|
|
from helpers import fixture_lines
|
|
|
|
from netsec_scan import __main__ as cli
|
|
from netsec_scan import config, state as state_mod
|
|
|
|
LIVE = "flows-20261127T070000Z-1.jsonl"
|
|
ARCHIVES = ("flows-20261127T060000Z-1.jsonl.gz",
|
|
"flows-20261127T050000Z-1.jsonl.gz",
|
|
"flows-20261127T040000Z-1.jsonl.gz")
|
|
SEED_RE = r"seed: \d+ tuple\(s\) absorbed, 0 reported; window \S+ from 2026-11-27T04:00:00\+00:00"
|
|
|
|
|
|
def _store(root: Path) -> None:
|
|
lines = fixture_lines("egress-sample.jsonl")
|
|
for name in ARCHIVES:
|
|
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")
|
|
|
|
|
|
class TestSeedIsSilent(unittest.TestCase):
|
|
def setUp(self):
|
|
self.tmp = tempfile.TemporaryDirectory()
|
|
self.root = Path(self.tmp.name)
|
|
self.flows = self.root / "flows"
|
|
self.flows.mkdir()
|
|
_store(self.flows)
|
|
self.state = self.root / "state.json"
|
|
self.reports = self.root / "reports"
|
|
|
|
def tearDown(self):
|
|
self.tmp.cleanup()
|
|
|
|
def tick(self, *extra: str):
|
|
"""Returns (stdout, stderr) from one real main() run."""
|
|
out, err = io.StringIO(), io.StringIO()
|
|
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
|
|
code = cli.main(["--flows-dir", str(self.flows), "--no-prom",
|
|
"--state", str(self.state), "--reports", str(self.reports),
|
|
*extra])
|
|
self.assertEqual(code, 0)
|
|
return out.getvalue(), err.getvalue()
|
|
|
|
def test_cold_start_is_silent_and_names_the_absorbed_window(self):
|
|
out, err = self.tick()
|
|
self.assertEqual(out, "", "a cold start must not announce the retained window")
|
|
self.assertRegex(err, SEED_RE)
|
|
st = state_mod.load(self.state)
|
|
self.assertTrue(st["seeded"])
|
|
self.assertEqual(st["seed"]["absorbed"], len(st["seen"]))
|
|
self.assertEqual(len(st["seen"]), len(st["egress_counts"]))
|
|
self.assertGreater(len(st["seen"]), 0)
|
|
self.assertEqual(st["observed_since"], "2026-11-27T04:00:00+00:00")
|
|
|
|
def test_dry_run_cold_start_is_silent_and_persists_nothing(self):
|
|
out, err = self.tick("--dry-run")
|
|
self.assertEqual(out, "", "a dry run over an unseeded state reads history, not news")
|
|
self.assertIn("0 reported", err)
|
|
self.assertIn("dry run: nothing persisted", err)
|
|
self.assertFalse(self.state.exists())
|
|
|
|
def test_resume_tick_is_silent_while_still_unseeded(self):
|
|
original = config.ARCHIVE_MAX_FILES
|
|
config.ARCHIVE_MAX_FILES = 1 # 1 archive per tick, 3 archives
|
|
try:
|
|
out1, err1 = self.tick()
|
|
st = state_mod.load(self.state)
|
|
self.assertEqual(out1, "")
|
|
self.assertFalse(st["seeded"], "a partial baseline is not a baseline")
|
|
self.assertIn("still pending", err1)
|
|
|
|
out2, err2 = self.tick() # the tick t_cf3e563a was filed about
|
|
st = state_mod.load(self.state)
|
|
self.assertEqual(out2, "", "a resume tick must stay silent too")
|
|
self.assertFalse(st["seeded"])
|
|
self.assertIn("still pending", err2)
|
|
|
|
out3, _err3 = self.tick()
|
|
self.assertEqual(out3, "")
|
|
self.assertTrue(state_mod.load(self.state)["seeded"])
|
|
finally:
|
|
config.ARCHIVE_MAX_FILES = original
|
|
|
|
def test_seeded_state_still_fires_exactly_once(self):
|
|
self.tick()
|
|
obj = json.loads(fixture_lines("egress-sample.jsonl")[0])
|
|
obj["flow"]["IP"]["destination"] = "203.0.113.77"
|
|
proto = next(iter(obj["flow"]["l4"]))
|
|
obj["flow"]["l4"][proto]["destination_port"] = 5000
|
|
line = json.dumps(obj) + "\n"
|
|
with open(self.flows / LIVE, "a", encoding="utf-8") as handle:
|
|
handle.write(line)
|
|
first, _err = self.tick()
|
|
self.assertEqual(len(first.strip().splitlines()), 1, first)
|
|
self.assertIn("203.0.113.77:5000/tcp", first)
|
|
second, _err = self.tick()
|
|
self.assertEqual(second, "", "a reported tuple does not repeat")
|
|
|
|
|
|
class TestSeedHoldsCurrentStateTripwires(unittest.TestCase):
|
|
"""A seed tick stays silent even when a PromQL tripwire is firing.
|
|
|
|
The tripwire is current state, not history, so it must not be swallowed: it
|
|
is recorded with no cooldown clock and reported by the first warm tick. The
|
|
silence costs one interval; a 24 h STATE_COOLDOWN would be a real miss.
|
|
"""
|
|
|
|
def setUp(self):
|
|
self.tmp = tempfile.TemporaryDirectory()
|
|
self.root = Path(self.tmp.name)
|
|
self.flows = self.root / "flows"
|
|
self.flows.mkdir()
|
|
lines = fixture_lines("egress-sample.jsonl")
|
|
with gzip.open(self.flows / ARCHIVES[-1], "wt", encoding="utf-8") as handle:
|
|
handle.write("\n".join(lines) + "\n")
|
|
(self.flows / LIVE).write_text("\n".join(lines) + "\n")
|
|
self.state = self.root / "state.json"
|
|
self.reports = self.root / "reports"
|
|
|
|
def tearDown(self):
|
|
self.tmp.cleanup()
|
|
|
|
@staticmethod
|
|
def _scalar(expr: str) -> float:
|
|
"""drop-spike shape: 0.9/s now against a 0.01/s baseline."""
|
|
if "hubble_drop_total" in expr and "offset 5m" in expr:
|
|
return 0.01
|
|
if "hubble_drop_total" in expr:
|
|
return 0.9
|
|
return 0.0
|
|
|
|
def tick(self):
|
|
from netsec_scan import prom as prom_mod
|
|
out, err = io.StringIO(), io.StringIO()
|
|
with mock.patch.object(prom_mod, "query", return_value=[]), \
|
|
mock.patch.object(prom_mod, "scalar", side_effect=self._scalar):
|
|
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
|
|
code = cli.main(["--flows-dir", str(self.flows),
|
|
"--state", str(self.state), "--reports", str(self.reports)])
|
|
self.assertEqual(code, 0)
|
|
return out.getvalue(), err.getvalue()
|
|
|
|
def test_seed_tick_is_silent_and_the_next_tick_reports_the_tripwire(self):
|
|
out, err = self.tick()
|
|
self.assertEqual(out, "", "a firing tripwire must not break the seed's silence")
|
|
self.assertIn("held for the next tick", err)
|
|
st = state_mod.load(self.state)
|
|
self.assertTrue(st["seeded"])
|
|
drop = [v for v in st["seen"].values() if v["rule"] == "drop-spike"]
|
|
self.assertEqual(len(drop), 1)
|
|
self.assertEqual(drop[0]["last_alert"], "", "a held tripwire is due, not cooled down")
|
|
|
|
warm, _err = self.tick()
|
|
self.assertEqual(len(warm.strip().splitlines()), 1, warm)
|
|
self.assertIn("drop-spike", warm)
|
|
|
|
after, _err = self.tick()
|
|
self.assertEqual(after, "", "the state cooldown applies once it has been reported")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|