Merge pull request 'fix(healing): judge post-heal verification against the pre-heal decisions' (#7) from fix/verify-ignores-new-decisions into main
CI / Unit tests (push) Successful in 6s
CI / Unit tests (push) Successful in 6s
Reviewed-on: #7
This commit was merged in pull request #7.
This commit is contained in:
commit
05f437e673
5 files changed
+160
-3
No files matched your search
@@ -355,6 +355,7 @@ See [Range decisions](#range-decisions).
|
||||
- This agent is best suited for hosts where CrowdSec enforcement correctness matters enough to justify active reconciliation.
|
||||
- It is intentionally conservative about repeated heals and uses drift fingerprints to suppress flap loops.
|
||||
- Post-heal verification is part of the design, not an optional extra: a restart is not treated as success unless state actually converges.
|
||||
- Verification is judged against the decisions the heal started from. A decision issued or removed during the verification window (which the bouncer applies on its next poll) is logged as `lapi_changed` and left to the next audit, so it is not counted as a failed heal. Drift on decisions that existed when the heal started still fails verification.
|
||||
- `doctor.py` should be run before first deployment or after major environment changes.
|
||||
|
||||
---
|
||||
|
||||
+30
-1
@@ -31,6 +31,9 @@ class FirewallAuditor:
|
||||
# Per-IP evidence from the latest scan, used only for drift diagnostics.
|
||||
self._last_decisions = {}
|
||||
self._last_kernel_sources = {}
|
||||
# Decision values the latest reconcile saw in the LAPI. A heal records them as
|
||||
# the baseline its post-heal verification is judged against.
|
||||
self.last_truth_values = None
|
||||
|
||||
def log_enforcement_startup_state(self):
|
||||
target_desc = ", ".join(f"{family}:{table}" for family, table in self.targets)
|
||||
@@ -393,12 +396,23 @@ class FirewallAuditor:
|
||||
f"({family} {table} {set_name}): {stderr or e}"
|
||||
)
|
||||
|
||||
def reconcile(self):
|
||||
def reconcile(self, baseline_truth=None):
|
||||
"""
|
||||
Compares LAPI decisions (the truth) with the kernel's nft sets.
|
||||
|
||||
baseline_truth: decision values from an earlier reconcile. Values whose LAPI
|
||||
membership changed since then (added or removed) are left out of the drift:
|
||||
the bouncer applies such changes on its next poll, so a post-heal check would
|
||||
otherwise blame the heal for a decision issued after it started. They are
|
||||
returned in drift["lapi_changed_values"] and checked again by the next audit.
|
||||
"""
|
||||
truth_map = self.get_remote_lapi_truth()
|
||||
reality_map = self.get_kernel_state()
|
||||
|
||||
truth_set = set(truth_map.keys())
|
||||
reality_set = set(reality_map.keys())
|
||||
self.last_truth_values = frozenset(truth_set)
|
||||
changed = set() if baseline_truth is None else truth_set ^ set(baseline_truth)
|
||||
missing, extra, unenforceable_ranges = self._match_collapsed_ranges(
|
||||
sorted(truth_set - reality_set),
|
||||
reality_set,
|
||||
@@ -422,9 +436,20 @@ class FirewallAuditor:
|
||||
f"ranges={self._preview_values(unenforceable_ranges)}"
|
||||
)
|
||||
|
||||
lapi_changed = sorted(value for value in [*missing, *extra] if value in changed)
|
||||
if lapi_changed:
|
||||
missing = [value for value in missing if value not in changed]
|
||||
extra = [value for value in extra if value not in changed]
|
||||
logging.info(
|
||||
"Not counted as drift: LAPI decisions changed since the baseline "
|
||||
f"(count={len(lapi_changed)}); the bouncer applies them on its next poll "
|
||||
f"and the next audit checks them. values={self._preview_values(lapi_changed)}"
|
||||
)
|
||||
|
||||
if missing or extra:
|
||||
drift = {
|
||||
"reason": "membership_mismatch",
|
||||
"lapi_changed_values": lapi_changed,
|
||||
"missing_count": len(missing),
|
||||
"extra_count": len(extra),
|
||||
"metadata_drift_count": 0,
|
||||
@@ -443,6 +468,8 @@ class FirewallAuditor:
|
||||
now_epoch = datetime.datetime.now(datetime.timezone.utc).timestamp()
|
||||
|
||||
for ip, decision_meta in truth_map.items():
|
||||
if ip in changed:
|
||||
continue
|
||||
siem_seconds = self._expected_remaining_seconds(decision_meta, now_epoch)
|
||||
if siem_seconds <= 0:
|
||||
continue
|
||||
@@ -469,6 +496,7 @@ class FirewallAuditor:
|
||||
if metadata_drift:
|
||||
drift = {
|
||||
"reason": "metadata_drift",
|
||||
"lapi_changed_values": lapi_changed,
|
||||
"missing_count": 0,
|
||||
"extra_count": 0,
|
||||
"metadata_drift_count": len(metadata_drift),
|
||||
@@ -483,6 +511,7 @@ class FirewallAuditor:
|
||||
|
||||
drift = {
|
||||
"reason": "in_sync",
|
||||
"lapi_changed_values": lapi_changed,
|
||||
"missing_count": 0,
|
||||
"extra_count": 0,
|
||||
"metadata_drift_count": 0,
|
||||
|
||||
+9
-1
@@ -118,6 +118,10 @@ def execute_heal_and_verify(auditor, reporter, count, drift, heal_verify_delay):
|
||||
Executes heal + post-heal verification and persists reporter state.
|
||||
"""
|
||||
drift = drift or {}
|
||||
# The decisions the drift was found against. Verification is judged against
|
||||
# them, so a decision issued after the heal started (which the bouncer only
|
||||
# applies on its next poll) is not counted as a failed heal.
|
||||
baseline_truth = getattr(auditor, "last_truth_values", None)
|
||||
if hasattr(auditor, "heal_with_drift"):
|
||||
heal_ok = auditor.heal_with_drift(drift)
|
||||
else:
|
||||
@@ -138,7 +142,10 @@ def execute_heal_and_verify(auditor, reporter, count, drift, heal_verify_delay):
|
||||
)
|
||||
time.sleep(heal_verify_delay)
|
||||
try:
|
||||
if baseline_truth is None:
|
||||
post_is_synced, post_count, post_drift = auditor.reconcile()
|
||||
else:
|
||||
post_is_synced, post_count, post_drift = auditor.reconcile(baseline_truth=baseline_truth)
|
||||
heal_result = "success" if post_is_synced else "failed"
|
||||
verify_error = None if post_is_synced else "Post-heal verification failed"
|
||||
reporter.update_status(
|
||||
@@ -159,7 +166,8 @@ def execute_heal_and_verify(auditor, reporter, count, drift, heal_verify_delay):
|
||||
f"post={post_drift.get('fingerprint', '')} "
|
||||
f"missing={post_drift.get('missing_count', 0)} "
|
||||
f"extra={post_drift.get('extra_count', 0)} "
|
||||
f"metadata={post_drift.get('metadata_drift_count', 0)}"
|
||||
f"metadata={post_drift.get('metadata_drift_count', 0)} "
|
||||
f"lapi_changed={len(post_drift.get('lapi_changed_values', []))}"
|
||||
)
|
||||
except Exception as e:
|
||||
heal_result = "verify_error"
|
||||
|
||||
+51
-1
@@ -35,7 +35,8 @@ class FakeAuditor:
|
||||
self.last_heal_drift = drift
|
||||
return self.heal_ok
|
||||
|
||||
def reconcile(self):
|
||||
def reconcile(self, **kwargs):
|
||||
self.reconcile_kwargs = kwargs
|
||||
if self.reconcile_exception:
|
||||
raise self.reconcile_exception
|
||||
return self.reconcile_result
|
||||
@@ -158,6 +159,55 @@ class PostHealVerificationTests(unittest.TestCase):
|
||||
self.assertEqual("verify_error", reporter.update_calls[0]["heal_result"])
|
||||
|
||||
|
||||
class PostHealBaselineTests(unittest.TestCase):
|
||||
@patch("healing.time.sleep", return_value=None)
|
||||
def test_verification_is_judged_against_the_pre_heal_truth(self, _sleep):
|
||||
auditor = FakeAuditor(heal_ok=True, reconcile_result=(True, 3, {"reason": "in_sync"}))
|
||||
auditor.last_truth_values = frozenset({"192.0.2.1"})
|
||||
|
||||
execute_heal_and_verify(auditor, FakeReporter(), count=3, drift={}, heal_verify_delay=0)
|
||||
|
||||
self.assertEqual({"baseline_truth": frozenset({"192.0.2.1"})}, auditor.reconcile_kwargs)
|
||||
|
||||
@patch("healing.time.sleep", return_value=None)
|
||||
def test_auditor_without_baseline_support_is_verified_as_before(self, _sleep):
|
||||
auditor = FakeAuditor(heal_ok=True, reconcile_result=(True, 3, {"reason": "in_sync"}))
|
||||
|
||||
execute_heal_and_verify(auditor, FakeReporter(), count=3, drift={}, heal_verify_delay=0)
|
||||
|
||||
self.assertEqual({}, auditor.reconcile_kwargs)
|
||||
|
||||
@patch("healing.time.sleep", return_value=None)
|
||||
def test_decision_issued_during_verification_window_does_not_fail_the_heal(self, _sleep):
|
||||
# Replays a logged metadata heal: the heal fixed the stale TTL, but a new
|
||||
# decision arrived in the 5 s before verification, before the bouncer's next
|
||||
# poll. That used to be recorded as heal_result=failed.
|
||||
from auditor import FirewallAuditor
|
||||
|
||||
long_ban = {"duration": "335h", "until_epoch": None}
|
||||
truth = {"192.0.2.10": long_ban, "192.0.2.11": long_ban}
|
||||
kernel = {"192.0.2.10": 13780, "192.0.2.11": 335 * 3600}
|
||||
auditor = FirewallAuditor()
|
||||
auditor.get_remote_lapi_truth = lambda: dict(truth)
|
||||
auditor.get_kernel_state = lambda: dict(kernel)
|
||||
|
||||
def heal(_drift):
|
||||
kernel["192.0.2.10"] = 335 * 3600 # the restarted bouncer re-adds with the full TTL
|
||||
truth["203.0.113.70"] = dict(long_ban) # new decision, not yet applied
|
||||
return True
|
||||
|
||||
auditor.heal_with_drift = heal
|
||||
is_synced, count, drift = auditor.reconcile()
|
||||
self.assertEqual("metadata_drift", drift["reason"])
|
||||
|
||||
reporter = FakeReporter()
|
||||
heal_result, post_drift = execute_heal_and_verify(auditor, reporter, count, drift, heal_verify_delay=0)
|
||||
|
||||
self.assertEqual("success", heal_result)
|
||||
self.assertEqual(["203.0.113.70"], post_drift["lapi_changed_values"])
|
||||
self.assertTrue(reporter.update_calls[-1]["is_synced"])
|
||||
|
||||
|
||||
class MembershipRecheckTests(unittest.TestCase):
|
||||
MISMATCH = (False, 10, {"reason": "membership_mismatch", "missing_count": 1})
|
||||
IN_SYNC = (True, 11, {"reason": "in_sync"})
|
||||
|
||||
@@ -543,5 +543,74 @@ class AuditorDecisionExtractionTests(unittest.TestCase):
|
||||
warning_mock.assert_not_called()
|
||||
|
||||
|
||||
class ReconcileBaselineTests(unittest.TestCase):
|
||||
"""Post-heal verification is judged against the decisions the heal started from."""
|
||||
|
||||
LONG = {"duration": "4h", "until_epoch": None}
|
||||
|
||||
def _auditor(self, truth, kernel):
|
||||
auditor = FirewallAuditor()
|
||||
auditor.get_remote_lapi_truth = lambda: {value: dict(self.LONG) for value in truth}
|
||||
auditor.get_kernel_state = lambda: {value: 14000 for value in kernel}
|
||||
return auditor
|
||||
|
||||
def test_reconcile_records_the_truth_values_it_saw(self):
|
||||
auditor = self._auditor(["192.0.2.1", "192.0.2.2"], ["192.0.2.1", "192.0.2.2"])
|
||||
|
||||
auditor.reconcile()
|
||||
|
||||
self.assertEqual(frozenset({"192.0.2.1", "192.0.2.2"}), auditor.last_truth_values)
|
||||
|
||||
def test_without_baseline_a_new_decision_not_yet_applied_is_drift(self):
|
||||
auditor = self._auditor(["192.0.2.1", "198.51.100.7"], ["192.0.2.1"])
|
||||
|
||||
is_synced, _, drift = auditor.reconcile()
|
||||
|
||||
self.assertFalse(is_synced)
|
||||
self.assertEqual("membership_mismatch", drift["reason"])
|
||||
self.assertEqual(1, drift["missing_count"])
|
||||
self.assertEqual([], drift["lapi_changed_values"])
|
||||
|
||||
def test_decision_added_since_baseline_is_not_drift(self):
|
||||
auditor = self._auditor(["192.0.2.1", "198.51.100.7"], ["192.0.2.1"])
|
||||
|
||||
is_synced, _, drift = auditor.reconcile(baseline_truth={"192.0.2.1"})
|
||||
|
||||
self.assertTrue(is_synced)
|
||||
self.assertEqual("in_sync", drift["reason"])
|
||||
self.assertEqual(0, drift["missing_count"])
|
||||
self.assertEqual(["198.51.100.7"], drift["lapi_changed_values"])
|
||||
|
||||
def test_decision_removed_since_baseline_is_not_drift(self):
|
||||
auditor = self._auditor(["192.0.2.1"], ["192.0.2.1", "198.51.100.8"])
|
||||
|
||||
is_synced, _, drift = auditor.reconcile(baseline_truth={"192.0.2.1", "198.51.100.8"})
|
||||
|
||||
self.assertTrue(is_synced)
|
||||
self.assertEqual(0, drift["extra_count"])
|
||||
self.assertEqual(["198.51.100.8"], drift["lapi_changed_values"])
|
||||
|
||||
def test_drift_on_decisions_present_at_baseline_still_counts(self):
|
||||
auditor = self._auditor(["192.0.2.1", "192.0.2.2", "198.51.100.7"], ["192.0.2.1"])
|
||||
|
||||
is_synced, _, drift = auditor.reconcile(baseline_truth={"192.0.2.1", "192.0.2.2"})
|
||||
|
||||
self.assertFalse(is_synced)
|
||||
self.assertEqual("membership_mismatch", drift["reason"])
|
||||
self.assertEqual(1, drift["missing_count"])
|
||||
self.assertEqual(["198.51.100.7"], drift["lapi_changed_values"])
|
||||
self.assertEqual(auditor._fingerprint_drift(["192.0.2.2"], [], []), drift["fingerprint"])
|
||||
|
||||
def test_metadata_check_skips_decisions_changed_since_baseline(self):
|
||||
auditor = FirewallAuditor()
|
||||
auditor.get_remote_lapi_truth = lambda: {"198.51.100.7": {"duration": "24h", "until_epoch": None}}
|
||||
auditor.get_kernel_state = lambda: {"198.51.100.7": 3 * 3600 * 1000}
|
||||
|
||||
is_synced, _, drift = auditor.reconcile(baseline_truth=set())
|
||||
|
||||
self.assertTrue(is_synced)
|
||||
self.assertEqual(0, drift["metadata_drift_count"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user