From 0f7f03f00540a8f2fa5d43b324275124ecf25155 Mon Sep 17 00:00:00 2001 From: patrickbeane Date: Wed, 25 Feb 2026 14:59:44 -0500 Subject: [PATCH] Fix metadata-drift healing by flushing CrowdSec nft sets before restart Add drift-aware heal path in FirewallAuditor to remediate metadata drift by discovering and flushing *-cscli sets in crowdsec/crowdsec6 tables, then restarting the bouncer. Update execute_heal_and_verify to pass drift context to heal_with_drift when supported, keeping backward compatibility via heal(). Add unit tests covering metadata-drift flush+restart behavior, non-metadata restart-only behavior, and drift context propagation. --- auditor.py | 43 +++++++++++++++++++++++++- healing.py | 5 +++- tests/test_agent.py | 6 ++++ tests/test_auditor.py | 70 +++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 122 insertions(+), 2 deletions(-) diff --git a/auditor.py b/auditor.py index 87c02f0..4d4f0c9 100644 --- a/auditor.py +++ b/auditor.py @@ -175,14 +175,55 @@ class FirewallAuditor: return kernel_seconds + allowed_shortfall < expected_seconds def heal(self): - """Directly restarts the bouncer service.""" + """Executes heal actions based on drift type, then restarts the bouncer.""" + return self.heal_with_drift({}) + + def heal_with_drift(self, drift): + """Performs targeted pre-heal remediation for metadata drift.""" try: + if drift.get("reason") == "metadata_drift": + self._flush_crowdsec_sets() + logging.info("Heal: Flushed CrowdSec nft sets to clear stale metadata.") subprocess.run(["systemctl", "restart", "crowdsec-firewall-bouncer"], check=True) logging.info("Heal: Bouncer restarted successfully.") return True except subprocess.CalledProcessError as e: logging.error(f"Heal Failed: Could not restart bouncer: {e}") return False + except Exception as e: + logging.error(f"Heal Failed: Unexpected error: {e}") + return False + + def _flush_crowdsec_sets(self): + for family, table in (("ip", "crowdsec"), ("ip6", "crowdsec6")): + try: + res = subprocess.run( + ["/usr/sbin/nft", "-j", "list", "table", family, table], + check=True, + capture_output=True, + text=True, + ) + except subprocess.CalledProcessError: + logging.debug(f"Heal: Table not present, skip flush ({family} {table}).") + continue + + data = json.loads(res.stdout or "{}") + set_names = [] + for item in data.get("nftables", []): + nft_set = item.get("set") + if not isinstance(nft_set, dict): + continue + set_name = nft_set.get("name") + if isinstance(set_name, str) and set_name.endswith("-cscli"): + set_names.append(set_name) + + for set_name in set_names: + subprocess.run( + ["/usr/sbin/nft", "flush", "set", family, table, set_name], + check=True, + capture_output=True, + text=True, + ) def reconcile(self): truth_map = self.get_remote_lapi_truth() diff --git a/healing.py b/healing.py index caa9e1b..81ae7a0 100644 --- a/healing.py +++ b/healing.py @@ -48,7 +48,10 @@ def execute_heal_and_verify(auditor, reporter, count, drift, heal_verify_delay): """ Executes heal + post-heal verification and persists reporter state. """ - heal_ok = auditor.heal() + if hasattr(auditor, "heal_with_drift"): + heal_ok = auditor.heal_with_drift(drift or {}) + else: + heal_ok = auditor.heal() heal_result = "restart_failed" post_drift = { "reason": "not_verified", diff --git a/tests/test_agent.py b/tests/test_agent.py index 6c8db2a..597c1dc 100644 --- a/tests/test_agent.py +++ b/tests/test_agent.py @@ -18,10 +18,15 @@ class FakeAuditor: def __init__(self, heal_ok=True, reconcile_result=None): self.heal_ok = heal_ok self.reconcile_result = reconcile_result + self.last_heal_drift = None def heal(self): return self.heal_ok + def heal_with_drift(self, drift): + self.last_heal_drift = drift + return self.heal_ok + def reconcile(self): return self.reconcile_result @@ -72,6 +77,7 @@ class PostHealVerificationTests(unittest.TestCase): self.assertEqual("success", heal_result) self.assertEqual(post_drift, returned_post_drift) self.assertEqual([(True, 12, None)], reporter.update_calls) + self.assertEqual({"fingerprint": "pre123"}, auditor.last_heal_drift) @patch("healing.time.sleep", return_value=None) def test_execute_heal_and_verify_restart_failed(self, _sleep): diff --git a/tests/test_auditor.py b/tests/test_auditor.py index 1f0676e..33fdc92 100644 --- a/tests/test_auditor.py +++ b/tests/test_auditor.py @@ -1,5 +1,8 @@ import unittest import datetime +import json +import subprocess +from unittest.mock import patch, call from auditor import FirewallAuditor @@ -69,6 +72,73 @@ class AuditorDecisionExtractionTests(unittest.TestCase): self.assertEqual(5400, auditor.parse_duration("1h30m")) self.assertEqual(1209600, auditor.parse_duration("14d")) + @patch("auditor.subprocess.run") + def test_heal_with_metadata_drift_flushes_sets_before_restart(self, run_mock): + auditor = FirewallAuditor() + + run_mock.side_effect = [ + subprocess.CompletedProcess( + args=[], + returncode=0, + stdout=json.dumps({"nftables": [{"set": {"name": "0.0.0.0/0-cscli"}}]}), + ), + None, # flush ip set + subprocess.CompletedProcess( + args=[], + returncode=0, + stdout=json.dumps({"nftables": [{"set": {"name": "::/0-cscli"}}]}), + ), + None, # flush ip6 set + None, # systemctl restart + ] + + ok = auditor.heal_with_drift({"reason": "metadata_drift"}) + + self.assertTrue(ok) + self.assertEqual( + [ + call( + ["/usr/sbin/nft", "-j", "list", "table", "ip", "crowdsec"], + check=True, + capture_output=True, + text=True, + ), + call( + ["/usr/sbin/nft", "flush", "set", "ip", "crowdsec", "0.0.0.0/0-cscli"], + check=True, + capture_output=True, + text=True, + ), + call( + ["/usr/sbin/nft", "-j", "list", "table", "ip6", "crowdsec6"], + check=True, + capture_output=True, + text=True, + ), + call( + ["/usr/sbin/nft", "flush", "set", "ip6", "crowdsec6", "::/0-cscli"], + check=True, + capture_output=True, + text=True, + ), + call(["systemctl", "restart", "crowdsec-firewall-bouncer"], check=True), + ], + run_mock.call_args_list, + ) + + @patch("auditor.subprocess.run") + def test_heal_without_metadata_drift_only_restarts_bouncer(self, run_mock): + auditor = FirewallAuditor() + run_mock.return_value = None + + ok = auditor.heal_with_drift({"reason": "membership_mismatch"}) + + self.assertTrue(ok) + self.assertEqual( + [call(["systemctl", "restart", "crowdsec-firewall-bouncer"], check=True)], + run_mock.call_args_list, + ) + if __name__ == "__main__": unittest.main()