fix(auditor): report range decisions the kernel can't enforce instead of healing
CI / Unit tests (push) Successful in 3s
CI / Unit tests (pull_request) Successful in 7s

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 <noreply@anthropic.com>
This commit is contained in:
patrickandClaude Opus 5.5 committed 2026-10-23 09:43:46 -04:00
1 parent 57ed6cfc1c
commit e76e957282
6 files changed
+175 -4

No files matched your search

+53 -3
View File
@@ -5,6 +5,7 @@ import json
import logging import logging
import hashlib import hashlib
import datetime import datetime
import ipaddress
try: try:
from dotenv import load_dotenv from dotenv import load_dotenv
except ImportError: except ImportError:
@@ -389,8 +390,18 @@ class FirewallAuditor:
truth_set = set(truth_map.keys()) truth_set = set(truth_map.keys())
reality_set = set(reality_map.keys()) reality_set = set(reality_map.keys())
missing = sorted(truth_set - reality_set) missing, extra, unenforceable_ranges = self._match_collapsed_ranges(
extra = sorted(reality_set - truth_set) 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: if missing or extra:
drift = { drift = {
@@ -399,10 +410,13 @@ class FirewallAuditor:
"extra_count": len(extra), "extra_count": len(extra),
"metadata_drift_count": 0, "metadata_drift_count": 0,
"fingerprint": self._fingerprint_drift(missing, extra, []), "fingerprint": self._fingerprint_drift(missing, extra, []),
"unenforceable_ranges": unenforceable_ranges,
} }
logging.warning( logging.warning(
"Desync: IP membership mismatch " "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 return False, len(reality_set), drift
@@ -440,6 +454,7 @@ class FirewallAuditor:
"extra_count": 0, "extra_count": 0,
"metadata_drift_count": len(metadata_drift), "metadata_drift_count": len(metadata_drift),
"fingerprint": self._fingerprint_drift([], [], metadata_drift), "fingerprint": self._fingerprint_drift([], [], metadata_drift),
"unenforceable_ranges": unenforceable_ranges,
} }
logging.warning( logging.warning(
"Metadata Drift detected " "Metadata Drift detected "
@@ -453,9 +468,44 @@ class FirewallAuditor:
"extra_count": 0, "extra_count": 0,
"metadata_drift_count": 0, "metadata_drift_count": 0,
"fingerprint": "", "fingerprint": "",
"unenforceable_ranges": unenforceable_ranges,
} }
return True, len(reality_map), drift 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): def _fingerprint_drift(self, missing, extra, metadata_drift):
payload = { payload = {
"missing": sorted(missing), "missing": sorted(missing),
+1
View File
@@ -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), metadata_drift_count=post_drift.get("metadata_drift_count", 0),
last_drift_fingerprint=post_drift.get("fingerprint", ""), last_drift_fingerprint=post_drift.get("fingerprint", ""),
heal_result=heal_result, heal_result=heal_result,
unenforceable_range_count=len(post_drift.get("unenforceable_ranges", [])),
) )
logging.warning( logging.warning(
+1
View File
@@ -114,6 +114,7 @@ def main():
checks_increment=1, checks_increment=1,
drift_events_increment=0 if is_synced else 1, drift_events_increment=0 if is_synced else 1,
heal_suppressed=not heal_approved, heal_suppressed=not heal_approved,
unenforceable_range_count=len(drift.get("unenforceable_ranges", [])),
) )
if is_synced: if is_synced:
+15 -1
View File
@@ -128,12 +128,17 @@ class LocalStateReporter:
drift_events_increment=0, drift_events_increment=0,
heal_result=None, heal_result=None,
heal_suppressed=False, heal_suppressed=False,
unenforceable_range_count=0,
): ):
""" """
Writes the current health snapshot to a JSON file. Writes the current health snapshot to a JSON file.
heal_suppressed marks a drift the heal gate skipped because the same drift was 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. 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() previous = self._load_previous_state()
effective_heal_result = ( effective_heal_result = (
@@ -193,13 +198,14 @@ class LocalStateReporter:
status_data = { status_data = {
"node_name": self.node_name, "node_name": self.node_name,
"last_check": datetime.now(timezone.utc).isoformat(), "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, "is_synced": is_synced,
"kernel_ban_count": ban_count, "kernel_ban_count": ban_count,
"last_error": last_error, "last_error": last_error,
"missing_count": missing_count, "missing_count": missing_count,
"extra_count": extra_count, "extra_count": extra_count,
"metadata_drift_count": metadata_drift_count, "metadata_drift_count": metadata_drift_count,
"unenforceable_range_count": unenforceable_range_count,
"last_drift_fingerprint": last_drift_fingerprint, "last_drift_fingerprint": last_drift_fingerprint,
"last_heal_result": effective_heal_result, "last_heal_result": effective_heal_result,
"last_heal_timestamp": effective_last_heal_timestamp, "last_heal_timestamp": effective_last_heal_timestamp,
@@ -227,6 +233,14 @@ class LocalStateReporter:
except Exception as e: except Exception as e:
logging.error(f"Reporter: Failed to write state file: {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): def get_history_file(self):
base, _ = os.path.splitext(self.state_file) base, _ = os.path.splitext(self.state_file)
return f"{base}.history" return f"{base}.history"
+87
View File
@@ -67,6 +67,93 @@ class AuditorDecisionExtractionTests(unittest.TestCase):
self.assertFalse(is_synced) self.assertFalse(is_synced)
self.assertEqual("metadata_drift", drift["reason"]) 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): def test_parse_duration_supports_compound_values(self):
auditor = FirewallAuditor() auditor = FirewallAuditor()
self.assertEqual(5400, auditor.parse_duration("1h30m")) self.assertEqual(5400, auditor.parse_duration("1h30m"))
+18
View File
@@ -37,6 +37,24 @@ class ReporterStateTests(unittest.TestCase):
self.assertEqual("abc123", payload["last_drift_fingerprint"]) self.assertEqual("abc123", payload["last_drift_fingerprint"])
self.assertEqual("failed", payload["last_heal_result"]) 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): def test_update_status_preserves_last_heal_result_when_omitted(self):
with tempfile.TemporaryDirectory() as tmp_dir: with tempfile.TemporaryDirectory() as tmp_dir:
state_file = os.path.join(tmp_dir, "state.json") state_file = os.path.join(tmp_dir, "state.json")