import unittest from fgai.anomaly import anomaly_summary, detect_source_anomalies from fgai.logs import parse_log_line class AnomalyTests(unittest.TestCase): def test_scores_repeated_utm_public_source_as_anomaly(self): events = [ parse_log_line(f'type=traffic srcip=10.0.0.{i} dstip=1.1.1.1 service=https action=accept sentbyte=100 rcvdbyte=100') for i in range(1, 8) ] events.extend( parse_log_line( 'type=utm subtype=ips srcip=8.8.8.8 dstip=10.0.0.10 service=https ' 'action=blocked severity=critical sentbyte=0 rcvdbyte=0' ) for _ in range(5) ) findings = detect_source_anomalies(events) self.assertEqual(findings[0].subject, "8.8.8.8") self.assertGreaterEqual(findings[0].score, 60) self.assertIn(findings[0].severity, {"high", "critical"}) def test_summary_counts_severities(self): events = [ parse_log_line( 'type=utm subtype=ips srcip=8.8.8.8 dstip=10.0.0.10 service=https ' 'action=blocked severity=critical' ) for _ in range(5) ] summary = anomaly_summary(detect_source_anomalies(events)) self.assertEqual(summary["total"], 1) def test_includes_rate_ports_and_hitcount_in_evidence(self): events = [ parse_log_line( f"eventtime={1_700_000_000_000_000_000 + index * 100_000_000} type=traffic " f"srcip=203.0.113.10 dstip=10.0.0.{index} srcport={40000 + index} dstport={1000 + index} " "service=tcp/unknown action=deny hitcount=200" ) for index in range(12) ] events.extend( parse_log_line( f"eventtime={1_700_000_000_000_000_000 + index * 60_000_000_000} type=traffic " f"srcip=10.0.0.{index} dstip=1.1.1.1 service=https action=accept hitcount=1" ) for index in range(1, 8) ) finding = next(item for item in detect_source_anomalies(events) if item.subject == "203.0.113.10") self.assertGreater(finding.evidence["events_per_minute"], 20) self.assertEqual(finding.evidence["distinct_dst_ports"], 12) self.assertEqual(finding.evidence["distinct_src_ports"], 12) self.assertEqual(finding.evidence["hitcount_total"], 2400) if __name__ == "__main__": unittest.main()