Harden metadata heal across nft table variants and non-fatal flush errors

This commit is contained in:
patrick committed 2026-02-26 13:37:48 -05:00
1 parent aae920fb73
commit 716468901c
2 files changed
+42 -1

No files matched your search

+8 -1
View File
@@ -217,7 +217,7 @@ class FirewallAuditor:
return False
def _flush_crowdsec_sets(self):
for family, table in (("ip", "crowdsec"), ("ip6", "crowdsec6")):
for family, table in (("ip", "crowdsec"), ("ip6", "crowdsec6"), ("inet", "crowdsec")):
try:
res = subprocess.run(
["/usr/sbin/nft", "-j", "list", "table", family, table],
@@ -240,12 +240,19 @@ class FirewallAuditor:
set_names.append(set_name)
for set_name in set_names:
try:
subprocess.run(
["/usr/sbin/nft", "flush", "set", family, table, set_name],
check=True,
capture_output=True,
text=True,
)
except subprocess.CalledProcessError as e:
stderr = (e.stderr or "").strip()
logging.warning(
"Heal: Failed to flush set "
f"({family} {table} {set_name}): {stderr or e}"
)
def reconcile(self):
truth_map = self.get_remote_lapi_truth()
+34
View File
@@ -116,6 +116,7 @@ class AuditorDecisionExtractionTests(unittest.TestCase):
stdout=json.dumps({"nftables": [{"set": {"name": "::/0-cscli"}}]}),
),
None, # flush ip6 set
subprocess.CalledProcessError(1, ["/usr/sbin/nft"]), # inet crowdsec absent
None, # systemctl restart
]
@@ -148,6 +149,12 @@ class AuditorDecisionExtractionTests(unittest.TestCase):
capture_output=True,
text=True,
),
call(
["/usr/sbin/nft", "-j", "list", "table", "inet", "crowdsec"],
check=True,
capture_output=True,
text=True,
),
call(["systemctl", "restart", "crowdsec-firewall-bouncer"], check=True),
],
run_mock.call_args_list,
@@ -166,6 +173,33 @@ class AuditorDecisionExtractionTests(unittest.TestCase):
run_mock.call_args_list,
)
@patch("auditor.subprocess.run")
def test_heal_metadata_drift_continues_when_one_flush_fails(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"}}]}),
),
subprocess.CalledProcessError(
1,
["/usr/sbin/nft", "flush", "set", "ip", "crowdsec", "0.0.0.0/0-cscli"],
stderr="No such file or directory",
),
subprocess.CalledProcessError(1, ["/usr/sbin/nft"]), # ip6 crowdsec6 absent
subprocess.CalledProcessError(1, ["/usr/sbin/nft"]), # inet crowdsec absent
None, # restart still executes
]
ok = auditor.heal_with_drift({"reason": "metadata_drift"})
self.assertTrue(ok)
self.assertEqual(
call(["systemctl", "restart", "crowdsec-firewall-bouncer"], check=True),
run_mock.call_args_list[-1],
)
if __name__ == "__main__":
unittest.main()