75 lines
2.6 KiB
Python
75 lines
2.6 KiB
Python
import unittest
|
|
import datetime
|
|
|
|
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))
|
|
|
|
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_parse_duration_supports_compound_values(self):
|
|
auditor = FirewallAuditor()
|
|
self.assertEqual(5400, auditor.parse_duration("1h30m"))
|
|
self.assertEqual(1209600, auditor.parse_duration("14d"))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|