Compare commits

...
Author SHA1 Message Date
Sirius DevOps
beb54afb89 netsec-scan: say how many tripwires a seed tick held, and test the path
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.
2026-11-27 02:21:34 -05:00
Sirius DevOps
5e45aa0713 netsec-scan: hold current-state tripwires on a seed tick instead of printing them
A seed tick's contract is 'stdout empty + one summary line'. PromQL rules
run before the seed block and their findings were still printed, so a cold
start on a cluster with an active drop-spike (or four new-port lines) was
NOT silent and its cron delivery outcome was 'delivered', not 'suppressed'
— i.e. the seed tick still looked like the alert storm it exists to
prevent. Observed live at 07:17Z: drop-spike + 4x new-port were firing.

They are now absorbed with no cooldown clock (last_alert='') so the first
warm tick reports them: the silence costs one interval, never a 24 h
STATE_COOLDOWN.
2026-11-27 02:18:26 -05:00
3 changed files with 94 additions and 6 deletions

View file

@ -81,7 +81,11 @@ count: the same finding keeps the same id across ticks, restarts and days.
`seed: N tuple(s) absorbed, 0 reported; window Xh from <stamp>, N file(s)`. The
baseline holds **every distinct egress tuple** in the window, not only the ones
that became findings (a web-port tuple never becomes one on its first tick).
PromQL findings still speak on the first tick — they are current state.
**Current-state tripwires are held, not dropped**: a PromQL rule that fires
during a seeding tick goes into `seen` with no cooldown clock
(`last_alert: ""`), so the first warm tick reports it — the silence costs one
interval, never a 24 h `STATE_COOLDOWN`. The seed line says how many were
held.
* A **warm** state that has never read the gzip archives (i.e. one upgraded to a
gzipped store) absorbs its first archive pass the same way: announcing it would
print `first-seen … (no prior in ~Xh of observed flows)` for a tuple that is

View file

@ -616,6 +616,23 @@ def main(argv: Optional[List[str]] = None) -> int:
st, (http_end - http_window, http_end), args, args.verbose)
findings.extend(http_findings)
held = 0
if seeding and findings:
# A current-state tripwire is real, but a seed tick's contract is
# "stdout empty, one summary line" — printing here is what made a
# cold start indistinguishable from an alert storm. Record the
# fingerprints (nothing is forgotten) but leave a state rule *due*:
# no cooldown clock, so the first warm tick reports it instead of a
# 24 h STATE_COOLDOWN eating it. A seed spanning several ticks
# defers them by at most that many intervals.
for finding in findings:
fresh = absorb(st, finding.kind, finding.entity, finding.rule,
finding.severity)
if fresh and finding.kind == "state":
st["seen"][finding.fingerprint]["last_alert"] = ""
held = len(findings)
findings = []
if baseline["archive"]:
# Not a fault, and not news either: these tuples are inside the
# window the next alert would quote. Say so once, loudly enough to
@ -625,8 +642,9 @@ def main(argv: Optional[List[str]] = None) -> int:
if seeding:
# Baseline run: every flow-store result was already absorbed in
# on_batch, so nothing from the retained window reaches stdout.
# PromQL findings still speak (they are current state, not history).
# on_batch and every current-state tripwire is held (above), so
# nothing reaches stdout and the tick's delivery outcome is
# `suppressed` by construction.
#
# Belt and braces: absorb *every* egress tuple the window carried,
# not only the ones this pass turned into findings. A web-port tuple
@ -634,6 +652,8 @@ def main(argv: Optional[List[str]] = None) -> int:
# finding on the tick it first appears and would otherwise alert on
# tick 3 for traffic that was inside the retained window all along.
# On a resume tick this is a no-op (already absorbed).
held_txt = ("%d current-state finding(s) held for the next tick"
% held) if held else ""
for key in list(st["egress_counts"]):
if absorb(st, "novelty", key, "egress-new-dst", "MEDIUM"):
baseline["seed"] += 1
@ -660,17 +680,19 @@ def main(argv: Optional[List[str]] = None) -> int:
# next tick continues the baseline — and stays silent — instead
# of alerting from a window that is still being filled.
note("seed: %d tuple(s) absorbed, 0 reported; window %s so far, "
"%d archive(s) still pending, next tick continues silently"
"%d archive(s) still pending, next tick continues silently%s"
% (baseline["seed"], window_text(st, window_h),
len(stats["pending"])))
len(stats["pending"]),
"; " + held_txt if held_txt else ""))
else:
if not args.dry_run:
st["seeded"] = True
st["seeded_at"] = datetime.now(timezone.utc).isoformat(timespec="seconds")
note("seed: %d tuple(s) absorbed, 0 reported; window %s, "
"%d file(s) (%d archive(s)) in %.2fs%s"
"%d file(s) (%d archive(s)) in %.2fs%s%s"
% (baseline["seed"], window_text(st, window_h),
stats["files_read"], stats["archives"], stats["seconds"],
"; " + held_txt if held_txt else "",
" (dry run: nothing persisted)" if args.dry_run else ""))
flow_findings = []

View file

@ -20,6 +20,7 @@ import json
import tempfile
import unittest
from pathlib import Path
from unittest import mock
from helpers import fixture_lines
@ -120,5 +121,66 @@ class TestSeedIsSilent(unittest.TestCase):
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()