import unittest import datetime import json import subprocess from unittest.mock import patch, call from auditor import FirewallAuditor, LapiUnavailableError class AuditorDecisionExtractionTests(unittest.TestCase): def test_extract_decisions_handles_flat_and_nested_payloads(self): auditor = FirewallAuditor() payload = [ {"value": "1.1.1.1", "duration": "4h", "origin": "lists"}, { "decisions": [ {"value": "2.2.2.2", "duration": "8h", "origin": "crowdsec"}, {"value": "2.2.2.2", "duration": "8h", "origin": "crowdsec"}, ] }, { "source": { "decisions": [ {"value": "3.3.3.3", "duration": "12h", "origin": "manual"} ] } }, ] decisions = list(auditor._extract_decisions(payload)) decision_keys = { (d.get("value"), d.get("duration"), d.get("origin")) for d in decisions } self.assertIn(("1.1.1.1", "4h", "lists"), decision_keys) self.assertIn(("2.2.2.2", "8h", "crowdsec"), decision_keys) self.assertIn(("3.3.3.3", "12h", "manual"), decision_keys) self.assertEqual(3, len(decision_keys)) def test_reconcile_detects_metadata_drift_for_extended_duration(self): auditor = FirewallAuditor() auditor.get_remote_lapi_truth = lambda: { "1.1.1.1": {"duration": "24h", "until_epoch": None} } auditor.get_kernel_state = lambda: {"1.1.1.1": 3 * 3600 * 1000} is_synced, count, drift = auditor.reconcile() self.assertFalse(is_synced) self.assertEqual(1, count) self.assertEqual("metadata_drift", drift["reason"]) self.assertEqual(1, drift["metadata_drift_count"]) def test_reconcile_uses_until_for_expected_remaining(self): now_epoch = datetime.datetime.now(datetime.timezone.utc).timestamp() auditor = FirewallAuditor() auditor.get_remote_lapi_truth = lambda: { "2.2.2.2": { "duration": "4h", "until_epoch": now_epoch + (24 * 3600), } } auditor.get_kernel_state = lambda: {"2.2.2.2": 2 * 3600 * 1000} is_synced, _, drift = auditor.reconcile() self.assertFalse(is_synced) self.assertEqual("metadata_drift", drift["reason"]) def test_reconcile_reports_range_collapsed_to_network_address_without_drift(self): auditor = FirewallAuditor() auditor.get_remote_lapi_truth = lambda: { "195.178.110.0/24": {"duration": "11h", "until_epoch": None}, "1.1.1.1": {"duration": "4h", "until_epoch": None}, } auditor.get_kernel_state = lambda: {"195.178.110.0": 40000, "1.1.1.1": 14000} is_synced, count, drift = auditor.reconcile() self.assertTrue(is_synced) self.assertEqual(2, count) self.assertEqual("in_sync", drift["reason"]) self.assertEqual(["195.178.110.0/24"], drift["unenforceable_ranges"]) def test_reconcile_keeps_real_drift_alongside_collapsed_range(self): auditor = FirewallAuditor() auditor.get_remote_lapi_truth = lambda: { "195.178.110.0/24": {"duration": "11h", "until_epoch": None}, "2.2.2.2": {"duration": "4h", "until_epoch": None}, } auditor.get_kernel_state = lambda: {"195.178.110.0": 40000, "9.9.9.9": 14000} is_synced, _, drift = auditor.reconcile() self.assertFalse(is_synced) self.assertEqual("membership_mismatch", drift["reason"]) self.assertEqual(1, drift["missing_count"]) self.assertEqual(1, drift["extra_count"]) self.assertEqual( auditor._fingerprint_drift(["2.2.2.2"], ["9.9.9.9"], []), drift["fingerprint"], ) self.assertEqual(["195.178.110.0/24"], drift["unenforceable_ranges"]) def test_reconcile_matches_range_whose_network_address_is_also_banned(self): auditor = FirewallAuditor() auditor.get_remote_lapi_truth = lambda: { "10.0.0.0/24": {"duration": "4h", "until_epoch": None}, "10.0.0.0": {"duration": "4h", "until_epoch": None}, } auditor.get_kernel_state = lambda: {"10.0.0.0": 14000} is_synced, _, drift = auditor.reconcile() self.assertTrue(is_synced) self.assertEqual(["10.0.0.0/24"], drift["unenforceable_ranges"]) def test_reconcile_treats_full_length_prefix_stored_as_address_as_in_sync(self): auditor = FirewallAuditor() auditor.get_remote_lapi_truth = lambda: { "1.2.3.4/32": {"duration": "4h", "until_epoch": None}, "2001:db8::1/128": {"duration": "4h", "until_epoch": None}, } auditor.get_kernel_state = lambda: {"1.2.3.4": 14000, "2001:db8::1": 14000} is_synced, _, drift = auditor.reconcile() self.assertTrue(is_synced) self.assertEqual([], drift["unenforceable_ranges"]) def test_reconcile_logs_missing_and_extra_values(self): auditor = FirewallAuditor() auditor.get_remote_lapi_truth = lambda: { "2.2.2.2": {"duration": "4h", "until_epoch": None} } auditor.get_kernel_state = lambda: {"9.9.9.9": 14000} with self.assertLogs(level="WARNING") as logs: auditor.reconcile() self.assertTrue( any( "missing_values=[2.2.2.2]" in line and "extra_values=[9.9.9.9]" in line for line in logs.output ) ) def test_preview_values_truncates_long_lists(self): auditor = FirewallAuditor() values = [f"10.0.0.{i}" for i in range(12)] self.assertEqual( "[" + ",".join(values[:10]) + ",+2 more]", auditor._preview_values(values), ) def test_parse_duration_supports_compound_values(self): auditor = FirewallAuditor() self.assertEqual(5400, auditor.parse_duration("1h30m")) self.assertEqual(1209600, auditor.parse_duration("14d")) def test_reconcile_skips_metadata_check_when_kernel_expiry_unavailable(self): auditor = FirewallAuditor() auditor.get_remote_lapi_truth = lambda: { "4.4.4.4": {"duration": "14d", "until_epoch": None} } auditor.get_kernel_state = lambda: {"4.4.4.4": None} is_synced, count, drift = auditor.reconcile() self.assertTrue(is_synced) self.assertEqual(1, count) self.assertEqual("in_sync", drift["reason"]) def test_reconcile_supports_kernel_ttl_reported_in_seconds(self): auditor = FirewallAuditor() auditor.get_remote_lapi_truth = lambda: { "5.5.5.5": {"duration": "14d", "until_epoch": None} } # Some nft stacks report expires directly in seconds. auditor.get_kernel_state = lambda: {"5.5.5.5": 13 * 24 * 3600} is_synced, count, drift = auditor.reconcile() self.assertTrue(is_synced) self.assertEqual(1, count) self.assertEqual("in_sync", drift["reason"]) @patch("auditor.subprocess.run") def test_lapi_query_failure_raises_instead_of_returning_empty_truth(self, run_mock): auditor = FirewallAuditor() run_mock.side_effect = subprocess.CalledProcessError( 1, ["/usr/bin/cscli"], stderr="dial tcp 100.64.0.1:8080: connection refused\n" ) with self.assertRaisesRegex(LapiUnavailableError, "connection refused"): auditor.get_remote_lapi_truth() def test_reconcile_does_not_report_drift_when_lapi_unreachable(self): auditor = FirewallAuditor() def unreachable(): raise LapiUnavailableError("LAPI unreachable: connection refused") auditor.get_remote_lapi_truth = unreachable auditor.get_kernel_state = lambda: {"1.1.1.1": 3600} with self.assertRaises(LapiUnavailableError): auditor.reconcile() @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", "handle": 7}}]}), ), None, # flush ip set subprocess.CompletedProcess( args=[], returncode=0, stdout=json.dumps({"nftables": [{"set": {"name": "::/0-cscli", "handle": 8}}]}), ), 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, ) @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", "handle": 9}}]}), ), 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 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], ) @patch("auditor.subprocess.run") def test_heal_metadata_drift_falls_back_to_handle_on_name_syntax_error(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", "handle": 21}}]}), ), subprocess.CalledProcessError( 1, ["/usr/sbin/nft", "flush", "set", "ip", "crowdsec", "0.0.0.0/0-cscli"], stderr="Error: syntax error, unexpected /", ), None, # fallback flush by handle succeeds subprocess.CalledProcessError(1, ["/usr/sbin/nft"]), # ip6 crowdsec6 absent None, # restart ] ok = auditor.heal_with_drift({"reason": "metadata_drift"}) self.assertTrue(ok) self.assertIn( call( ["/usr/sbin/nft", "flush", "set", "ip", "crowdsec", "handle", "21"], check=True, capture_output=True, text=True, ), run_mock.call_args_list, ) @patch("auditor.subprocess.run") def test_get_kernel_state_filters_to_configured_managed_sets(self, run_mock): auditor = FirewallAuditor( targets=[("ip", "crowdsec")], managed_sets=["0.0.0.0/0-cscli"], ) run_mock.return_value = subprocess.CompletedProcess( args=[], returncode=0, stdout=json.dumps( { "nftables": [ { "set": { "name": "0.0.0.0/0-cscli", "elem": [{"elem": {"val": "1.1.1.1", "expires": 1000}}], } }, { "set": { "name": "crowdsec-blacklists", "elem": [{"elem": {"val": "9.9.9.9", "expires": 2000}}], } }, ] } ), ) kernel_state = auditor.get_kernel_state() self.assertEqual({"1.1.1.1": 1000.0}, kernel_state) @patch("auditor.subprocess.run") def test_get_kernel_state_keeps_longest_expiry_for_ip_in_multiple_sets(self, run_mock): auditor = FirewallAuditor(targets=[("ip", "crowdsec")]) run_mock.return_value = subprocess.CompletedProcess( args=[], returncode=0, stdout=json.dumps( { "nftables": [ { "set": { "name": "crowdsec-blacklists-cscli", "elem": [{"elem": {"val": "1.1.1.1", "expires": 600000}}], } }, { "set": { "name": "crowdsec-blacklists-crowdsec", "elem": [{"elem": {"val": "1.1.1.1", "expires": 13000}}], } }, ] } ), ) kernel_state = auditor.get_kernel_state() self.assertEqual({"1.1.1.1": 600000.0}, kernel_state) @patch("auditor.subprocess.run") def test_get_kernel_state_falls_back_when_configured_sets_do_not_match(self, run_mock): auditor = FirewallAuditor( targets=[("ip", "crowdsec")], managed_sets=["missing-set-name"], ) run_mock.return_value = subprocess.CompletedProcess( args=[], returncode=0, stdout=json.dumps( { "nftables": [ { "set": { "name": "0.0.0.0/0-cscli", "elem": [{"elem": {"val": "1.1.1.1", "expires": 1000}}], } } ] } ), ) kernel_state = auditor.get_kernel_state() self.assertEqual({"1.1.1.1": 1000.0}, kernel_state) @patch("auditor.subprocess.run") def test_startup_check_warns_when_configured_sets_have_no_overlap(self, run_mock): auditor = FirewallAuditor( targets=[("ip", "crowdsec")], managed_sets=["missing-set-name"], ) run_mock.return_value = subprocess.CompletedProcess( args=[], returncode=0, stdout=json.dumps( {"nftables": [{"set": {"name": "crowdsec-blacklists-cscli"}}]} ), ) with self.assertLogs(level="WARNING") as logs: auditor.log_enforcement_startup_state() self.assertTrue( any("Configured enforcement sets not found" in msg for msg in logs.output) ) @patch("auditor.subprocess.run") @patch("auditor.logging.warning") def test_startup_check_no_warning_when_overlap_exists(self, warning_mock, run_mock): auditor = FirewallAuditor( targets=[("ip", "crowdsec")], managed_sets=["crowdsec-blacklists-cscli"], ) run_mock.return_value = subprocess.CompletedProcess( args=[], returncode=0, stdout=json.dumps( {"nftables": [{"set": {"name": "crowdsec-blacklists-cscli"}}]} ), ) auditor.log_enforcement_startup_state() warning_mock.assert_not_called() if __name__ == "__main__": unittest.main()