From e76e9572824f4b470700a61a04aaec76f253109c Mon Sep 17 00:00:00 2001 From: patrick Date: Fri, 23 Oct 2026 09:43:46 -0400 Subject: [PATCH] fix(auditor): report range decisions the kernel can't enforce instead of healing A LAPI range decision (e.g. 195.178.110.0/24) inserted into an nft set without the interval flag is stored as its bare network address. The string diff saw that as one missing and one extra entry, and every heal re-added the same address, so nodes stuck in DESYNC_DETECTED with the flap guard suppressing repeat heals. Pair such ranges with their network address, report them as unenforceable_ranges with a dedicated warning, and keep them out of the drift counts and fingerprint. The reporter records unenforceable_range_count and shows DEGRADED for a node that is otherwise in sync. Desync log lines now name the missing and extra values. Co-Authored-By: Claude Opus 5.5 --- auditor.py | 56 +++++++++++++++++++++++++-- healing.py | 1 + main.py | 1 + reporter.py | 16 +++++++- tests/test_auditor.py | 87 ++++++++++++++++++++++++++++++++++++++++++ tests/test_reporter.py | 18 +++++++++ 6 files changed, 175 insertions(+), 4 deletions(-) diff --git a/auditor.py b/auditor.py index 5526a6d..a0138bf 100644 --- a/auditor.py +++ b/auditor.py @@ -5,6 +5,7 @@ import json import logging import hashlib import datetime +import ipaddress try: from dotenv import load_dotenv except ImportError: @@ -389,8 +390,18 @@ class FirewallAuditor: truth_set = set(truth_map.keys()) reality_set = set(reality_map.keys()) - missing = sorted(truth_set - reality_set) - extra = sorted(reality_set - truth_set) + missing, extra, unenforceable_ranges = self._match_collapsed_ranges( + sorted(truth_set - reality_set), + reality_set, + reality_set - truth_set, + ) + if unenforceable_ranges: + logging.warning( + "Range decisions not enforced: the nft set holds only their network " + "address (it lacks the interval flag), so a bouncer restart cannot " + f"fix them (count={len(unenforceable_ranges)}) " + f"ranges={self._preview_values(unenforceable_ranges)}" + ) if missing or extra: drift = { @@ -399,10 +410,13 @@ class FirewallAuditor: "extra_count": len(extra), "metadata_drift_count": 0, "fingerprint": self._fingerprint_drift(missing, extra, []), + "unenforceable_ranges": unenforceable_ranges, } logging.warning( "Desync: IP membership mismatch " - f"(missing={drift['missing_count']}, extra={drift['extra_count']})." + f"(missing={drift['missing_count']}, extra={drift['extra_count']}) " + f"missing_values={self._preview_values(missing)} " + f"extra_values={self._preview_values(extra)}" ) return False, len(reality_set), drift @@ -440,6 +454,7 @@ class FirewallAuditor: "extra_count": 0, "metadata_drift_count": len(metadata_drift), "fingerprint": self._fingerprint_drift([], [], metadata_drift), + "unenforceable_ranges": unenforceable_ranges, } logging.warning( "Metadata Drift detected " @@ -453,9 +468,44 @@ class FirewallAuditor: "extra_count": 0, "metadata_drift_count": 0, "fingerprint": "", + "unenforceable_ranges": unenforceable_ranges, } return True, len(reality_map), drift + def _match_collapsed_ranges(self, missing, kernel_values, extra): + """ + Pairs LAPI range decisions with the bare network address that a set without + the interval flag stores in their place. A restart re-adds that same address, + so these ranges are reported apart from drift rather than healed. + + Returns (missing, extra, unenforceable_ranges) with the paired values removed. + A full-length prefix (/32, /128) stored as its address is fully enforced, so + it is dropped from missing without being reported. + """ + remaining_missing = [] + remaining_extra = set(extra) + unenforceable_ranges = [] + for value in missing: + try: + network = ipaddress.ip_network(value, strict=False) + except ValueError: + remaining_missing.append(value) + continue + address = str(network.network_address) + if address not in kernel_values: + remaining_missing.append(value) + continue + remaining_extra.discard(address) + if network.prefixlen < network.max_prefixlen: + unenforceable_ranges.append(value) + return remaining_missing, sorted(remaining_extra), unenforceable_ranges + + def _preview_values(self, values, limit=10): + shown = ",".join(str(v) for v in values[:limit]) + if len(values) > limit: + shown += f",+{len(values) - limit} more" + return f"[{shown}]" + def _fingerprint_drift(self, missing, extra, metadata_drift): payload = { "missing": sorted(missing), diff --git a/healing.py b/healing.py index 65815a3..0d4f23e 100644 --- a/healing.py +++ b/healing.py @@ -150,6 +150,7 @@ def execute_heal_and_verify(auditor, reporter, count, drift, heal_verify_delay): metadata_drift_count=post_drift.get("metadata_drift_count", 0), last_drift_fingerprint=post_drift.get("fingerprint", ""), heal_result=heal_result, + unenforceable_range_count=len(post_drift.get("unenforceable_ranges", [])), ) logging.warning( diff --git a/main.py b/main.py index 255325e..0e35c86 100644 --- a/main.py +++ b/main.py @@ -114,6 +114,7 @@ def main(): checks_increment=1, drift_events_increment=0 if is_synced else 1, heal_suppressed=not heal_approved, + unenforceable_range_count=len(drift.get("unenforceable_ranges", [])), ) if is_synced: diff --git a/reporter.py b/reporter.py index f80b5d3..c486c66 100644 --- a/reporter.py +++ b/reporter.py @@ -128,12 +128,17 @@ class LocalStateReporter: drift_events_increment=0, heal_result=None, heal_suppressed=False, + unenforceable_range_count=0, ): """ Writes the current health snapshot to a JSON file. heal_suppressed marks a drift the heal gate skipped because the same drift was healed moments ago, so every drift event is either a heal attempt or a suppressed heal. + + unenforceable_range_count is the number of LAPI range decisions the kernel holds + only as a single address. They are not drift a heal can fix, so a node that is + otherwise in sync reports DEGRADED rather than HEALTHY. """ previous = self._load_previous_state() effective_heal_result = ( @@ -193,13 +198,14 @@ class LocalStateReporter: status_data = { "node_name": self.node_name, "last_check": datetime.now(timezone.utc).isoformat(), - "status": "HEALTHY" if is_synced else "DESYNC_DETECTED", + "status": self._status_label(is_synced, unenforceable_range_count), "is_synced": is_synced, "kernel_ban_count": ban_count, "last_error": last_error, "missing_count": missing_count, "extra_count": extra_count, "metadata_drift_count": metadata_drift_count, + "unenforceable_range_count": unenforceable_range_count, "last_drift_fingerprint": last_drift_fingerprint, "last_heal_result": effective_heal_result, "last_heal_timestamp": effective_last_heal_timestamp, @@ -227,6 +233,14 @@ class LocalStateReporter: except Exception as e: logging.error(f"Reporter: Failed to write state file: {e}") + @staticmethod + def _status_label(is_synced, unenforceable_range_count): + if not is_synced: + return "DESYNC_DETECTED" + if unenforceable_range_count: + return "DEGRADED" + return "HEALTHY" + def get_history_file(self): base, _ = os.path.splitext(self.state_file) return f"{base}.history" diff --git a/tests/test_auditor.py b/tests/test_auditor.py index 24b46c6..7935200 100644 --- a/tests/test_auditor.py +++ b/tests/test_auditor.py @@ -67,6 +67,93 @@ class AuditorDecisionExtractionTests(unittest.TestCase): 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")) diff --git a/tests/test_reporter.py b/tests/test_reporter.py index 2fccbe4..5c1a8e8 100644 --- a/tests/test_reporter.py +++ b/tests/test_reporter.py @@ -37,6 +37,24 @@ class ReporterStateTests(unittest.TestCase): self.assertEqual("abc123", payload["last_drift_fingerprint"]) self.assertEqual("failed", payload["last_heal_result"]) + def test_update_status_reports_degraded_when_synced_with_unenforceable_ranges(self): + with tempfile.TemporaryDirectory() as tmp_dir: + state_file = os.path.join(tmp_dir, "state.json") + reporter = LocalStateReporter(state_file=state_file, node_name="n1") + + reporter.update_status(True, 10, unenforceable_range_count=1) + with open(state_file, "r") as f: + degraded = json.load(f) + reporter.update_status(True, 10) + with open(state_file, "r") as f: + healthy = json.load(f) + + self.assertEqual("DEGRADED", degraded["status"]) + self.assertTrue(degraded["is_synced"]) + self.assertEqual(1, degraded["unenforceable_range_count"]) + self.assertEqual("HEALTHY", healthy["status"]) + self.assertEqual(0, healthy["unenforceable_range_count"]) + def test_update_status_preserves_last_heal_result_when_omitted(self): with tempfile.TemporaryDirectory() as tmp_dir: state_file = os.path.join(tmp_dir, "state.json") -- 2.54.1