diff --git a/agent.py b/agent.py index b368e42..0135e96 100644 --- a/agent.py +++ b/agent.py @@ -165,6 +165,49 @@ def should_heal(history_file, drift_fingerprint, min_interval=900): return True +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() + heal_result = "restart_failed" + post_drift = { + "reason": "not_verified", + "missing_count": 0, + "extra_count": 0, + "metadata_drift_count": 0, + "fingerprint": "", + } + + if heal_ok: + logging.info( + f"Post-heal verification in {heal_verify_delay}s " + f"(pre_fingerprint={drift.get('fingerprint', '')})." + ) + time.sleep(heal_verify_delay) + post_is_synced, post_count, post_drift = auditor.reconcile() + heal_result = "success" if post_is_synced else "failed" + verify_error = None if post_is_synced else "Post-heal verification failed" + reporter.update_status(post_is_synced, post_count, last_error=verify_error) + + logging.warning( + "Post-heal verification result " + f"result={heal_result} pre={drift.get('fingerprint', '')} " + f"post={post_drift.get('fingerprint', '')} " + f"missing={post_drift.get('missing_count', 0)} " + f"extra={post_drift.get('extra_count', 0)} " + f"metadata={post_drift.get('metadata_drift_count', 0)}" + ) + else: + reporter.update_status(False, count, last_error="Bouncer restart failed") + logging.error( + f"Heal restart failed; skipping verification " + f"(pre_fingerprint={drift.get('fingerprint', '')})." + ) + + return heal_result, post_drift + + ################ ##### Main ##### ################ @@ -249,41 +292,13 @@ def main(): min_interval=heal_min_interval, ): logging.warning("Healing approved.") - heal_ok = auditor.heal() - heal_result = "restart_failed" - post_drift = { - "reason": "not_verified", - "missing_count": 0, - "extra_count": 0, - "metadata_drift_count": 0, - "fingerprint": "", - } - - if heal_ok: - logging.info( - f"Post-heal verification in {heal_verify_delay}s " - f"(pre_fingerprint={drift.get('fingerprint', '')})." - ) - time.sleep(heal_verify_delay) - post_is_synced, post_count, post_drift = auditor.reconcile() - heal_result = "success" if post_is_synced else "failed" - verify_error = None if post_is_synced else "Post-heal verification failed" - reporter.update_status(post_is_synced, post_count, last_error=verify_error) - - logging.warning( - "Post-heal verification result " - f"result={heal_result} pre={drift.get('fingerprint', '')} " - f"post={post_drift.get('fingerprint', '')} " - f"missing={post_drift.get('missing_count', 0)} " - f"extra={post_drift.get('extra_count', 0)} " - f"metadata={post_drift.get('metadata_drift_count', 0)}" - ) - else: - reporter.update_status(False, count, last_error="Bouncer restart failed") - logging.error( - f"Heal restart failed; skipping verification " - f"(pre_fingerprint={drift.get('fingerprint', '')})." - ) + heal_result, post_drift = execute_heal_and_verify( + auditor, + reporter, + count, + drift, + heal_verify_delay, + ) reporter.log_heal_event( count, @@ -311,8 +326,8 @@ def main(): # Ensure the reporter notes the error state try: reporter.update_status(False, 0, last_error=str(e)) - except: - pass + except Exception as reporter_error: + logging.error(f"Reporter update failed during exception handling: {reporter_error}") time.sleep(60) if __name__ == "__main__": diff --git a/tests/test_agent.py b/tests/test_agent.py new file mode 100644 index 0000000..ac6497a --- /dev/null +++ b/tests/test_agent.py @@ -0,0 +1,95 @@ +import tempfile +import unittest +from datetime import datetime +from unittest.mock import patch + +from agent import should_heal, execute_heal_and_verify + + +class FakeReporter: + def __init__(self): + self.update_calls = [] + + def update_status(self, is_synced, ban_count, last_error=None): + self.update_calls.append((is_synced, ban_count, last_error)) + + +class FakeAuditor: + def __init__(self, heal_ok=True, reconcile_result=None): + self.heal_ok = heal_ok + self.reconcile_result = reconcile_result + + def heal(self): + return self.heal_ok + + def reconcile(self): + return self.reconcile_result + + +class HealGateTests(unittest.TestCase): + def test_should_heal_suppresses_identical_recent_fingerprint(self): + now = datetime.now().isoformat() + with tempfile.NamedTemporaryFile(mode="w", delete=False) as tmp: + tmp.write( + f"{now} - HEAL: drift_fingerprint=abc123 heal_result=success post_drift_fingerprint=\n" + ) + path = tmp.name + + self.assertFalse(should_heal(path, "abc123", min_interval=900)) + + def test_should_heal_allows_different_fingerprint(self): + now = datetime.now().isoformat() + with tempfile.NamedTemporaryFile(mode="w", delete=False) as tmp: + tmp.write( + f"{now} - HEAL: drift_fingerprint=abc123 heal_result=success post_drift_fingerprint=\n" + ) + path = tmp.name + + self.assertTrue(should_heal(path, "xyz999", min_interval=900)) + + +class PostHealVerificationTests(unittest.TestCase): + @patch("agent.time.sleep", return_value=None) + def test_execute_heal_and_verify_success(self, _sleep): + reporter = FakeReporter() + post_drift = { + "reason": "in_sync", + "missing_count": 0, + "extra_count": 0, + "metadata_drift_count": 0, + "fingerprint": "", + } + auditor = FakeAuditor(heal_ok=True, reconcile_result=(True, 12, post_drift)) + + heal_result, returned_post_drift = execute_heal_and_verify( + auditor, + reporter, + count=12, + drift={"fingerprint": "pre123"}, + heal_verify_delay=0, + ) + + self.assertEqual("success", heal_result) + self.assertEqual(post_drift, returned_post_drift) + self.assertEqual([(True, 12, None)], reporter.update_calls) + + @patch("agent.time.sleep", return_value=None) + def test_execute_heal_and_verify_restart_failed(self, _sleep): + reporter = FakeReporter() + auditor = FakeAuditor(heal_ok=False, reconcile_result=(True, 0, {})) + + heal_result, returned_post_drift = execute_heal_and_verify( + auditor, + reporter, + count=7, + drift={"fingerprint": "pre123"}, + heal_verify_delay=0, + ) + + self.assertEqual("restart_failed", heal_result) + self.assertEqual("not_verified", returned_post_drift["reason"]) + self.assertEqual([(False, 7, "Bouncer restart failed")], reporter.update_calls) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_auditor.py b/tests/test_auditor.py new file mode 100644 index 0000000..52488b1 --- /dev/null +++ b/tests/test_auditor.py @@ -0,0 +1,38 @@ +import unittest + +from auditor import FirewallAuditor + + +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)) + + +if __name__ == "__main__": + unittest.main()