"""Regression tests for ingestion, replay, persistence and credential handling.""" import copy import importlib.util import json import os from pathlib import Path import socket import sys import tempfile import threading import time import unittest from unittest.mock import patch, Mock sys.path.insert(0, str(Path(__file__).resolve().parents[1]/'controller')) from leaf_controller.alertsock import AlertSocket, MAX_RECORD from leaf_controller.config import Config, DEFAULTS, load_config, read_key_env from leaf_controller.eve import EveTailer from leaf_controller.main import Audit, Controller from leaf_controller.vyos_client import VyosClient from test_controller import Router ROOT=Path(__file__).resolve().parents[1] def module(name, path): spec=importlib.util.spec_from_file_location(name, ROOT/path) m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m);return m rotation=module('key_rotation', 'scripts/rotate-vyos-key.py') retention=module('eve_rotation', 'scripts/rotate-eve.py') injector=module('injector','tests/drill_synsensor.py') class Repairs(unittest.TestCase): def setUp(self): self.tmp=tempfile.TemporaryDirectory();self.root=Path(self.tmp.name) def tearDown(self): self.tmp.cleanup() def controller(self): raw=copy.deepcopy(DEFAULTS) raw.update(state_db=str(self.root/'state'),audit_log=str(self.root/'audit')) raw['alert_socket']['path']=str(self.root/'alerts.sock') raw['policy'].update(mode='immediate',block_src=True) with patch.object(Config,'vyos_key',return_value='fake'): c=Controller(Config(raw)) c.client=Router();self.addCleanup(c.close);return c def event(self): return dict(event_type='alert',src_ip='203.0.113.12',dest_ip='192.0.2.202', alert=dict(signature_id=1000001,metadata=dict(leaf_action=['block']))) def test_dry_run_preserves_live_socket_and_audit(self): c=self.controller();c._sock.bind() before=os.stat(c._sock.path).st_ino dry=Controller(c.cfg,dry_run=True) try: dry.handle_event(self.event()) self.assertIsNone(dry._sock) finally: dry.close() self.assertEqual(os.stat(c._sock.path).st_ino,before) self.assertEqual((self.root/'audit').read_text(),'') def test_distinct_state_cannot_steal_socket(self): a=AlertSocket(str(self.root/'sock'));a.bind();self.addCleanup(a.close) b=AlertSocket(a.path) with self.assertRaises(OSError):b.bind() self.assertTrue(Path(a.path).exists()) def test_unmanaged_active_listener_preserved(self): path=str(self.root/'sock') with socket.socket(socket.AF_UNIX) as s: s.bind(path);s.listen() with self.assertRaises(OSError):AlertSocket(path).bind() self.assertTrue(Path(path).exists()) def test_non_socket_path_preserved(self): p=self.root/'sock';p.write_text('preserve') with self.assertRaises(OSError):AlertSocket(str(p)).bind() self.assertEqual(p.read_text(),'preserve') def test_shutdown_persists_accepted_queue(self): c=self.controller();c._sock._enqueue(json.dumps(self.event()).encode()) c.close() from leaf_controller.state import State state=State(str(self.root/'state')) try:self.assertIsNotNone(state.get('192.0.2.202')) finally:state.close() def test_oversized_and_recursive_frames_do_not_kill_reader(self): a=AlertSocket(str(self.root/'sock'));a.bind();a.start();self.addCleanup(a.close) with socket.socket(socket.AF_UNIX) as s: s.connect(a.path) s.sendall(b'x'*(MAX_RECORD+65536)+b'\n'+b'['*2000+b']'*2000+b'\n'+ json.dumps(self.event()).encode()+b'\n') self.assertTrue(a.available.wait(3)) self.assertGreaterEqual(a.counts['parse_errors'],1) self.assertEqual(a.counts['parse_errors']+a.counts['other'],2) self.assertEqual(len(a.drain()),1) self.assertTrue(a._thread.is_alive()) def test_partial_eof_counted(self): a=AlertSocket(str(self.root/'sock'));a.bind();a.start();self.addCleanup(a.close) with socket.socket(socket.AF_UNIX) as s:s.connect(a.path);s.sendall(b'{') end=time.monotonic()+2 while a.counts['parse_errors']==0 and time.monotonic()