import importlib.util import json from pathlib import Path import tempfile import unittest from unittest.mock import patch ROOT = Path(__file__).resolve().parents[2] spec = importlib.util.spec_from_file_location('exporter_access', ROOT / 'scripts/monitoring-exporter-access.py') ACCESS = importlib.util.module_from_spec(spec) spec.loader.exec_module(ACCESS) class ExporterAccessTests(unittest.TestCase): def test_cleanup_preserves_http_https_and_non_cni_rules(self): rules = '\n'.join([ '-A CNI-DN-old -p tcp --dport 9100 -j DNAT --to-destination 10.244.1.3:9100', '-A CNI-DN-old -p tcp --dport 80 -j DNAT --to-destination 10.244.1.3:80', '-A CNI-DN-old -p tcp --dport 443 -j DNAT --to-destination 10.244.1.3:443', '-A USER -p tcp --dport 9100 -j DROP', '-A CNI-HOSTPORT-DNAT -m comment --comment k8s-pod-network -p tcp -m multiport --dports 9100,80,443 -j CNI-DN-old', '-A CNI-DN-unrelated -p tcp --dport 9100 -j DNAT --to-destination 10.1.1.1:9100']) self.assertEqual(len(ACCESS.retired_rules(rules)), 1) self.assertEqual(ACCESS.retired_rules(rules)[0][1], 'CNI-DN-old') def test_sbin_tools_are_found_with_unprivileged_ssh_path(self): from types import SimpleNamespace inactive = SimpleNamespace(returncode=3) empty = SimpleNamespace(returncode=0, stdout='') with patch.object(ACCESS.shutil, 'which', return_value=None), \ patch.object(ACCESS.Path, 'exists', return_value=True), \ patch.object(ACCESS, 'run', return_value=''), \ patch.object(ACCESS.subprocess, 'run', side_effect=[inactive]*3 + [empty]*2) as execute: ACCESS.host() self.assertEqual(execute.call_args_list[3].args[0][2], '/usr/sbin/iptables') def test_active_kubernetes_runtime_blocks_cleanup(self): with patch.object(ACCESS.subprocess, 'run') as call, patch.object(ACCESS, 'run') as execute: call.return_value.returncode = 0 ACCESS.host() execute.assert_not_called() def test_runtime_process_blocks_cleanup_even_with_inactive_service(self): with patch.object(ACCESS.subprocess, 'run') as call, patch.object(ACCESS, 'run', return_value='k3s\n'): call.return_value.returncode = 3 with self.assertRaises(RuntimeError): ACCESS.host() @staticmethod def state(): return {'resources': [{'type': 'oci_core_network_security_group_security_rule', 'name': name, 'instances': [{'attributes': {'id': name, 'network_security_group_id': 'email-nsg'}}]} for name in ('email_ssh', 'email_monitoring')]} def test_email_requires_both_managed_rules_in_same_nsg(self): state = self.state() self.assertEqual(len(ACCESS.email_rules(state)), 2) state['resources'][1]['instances'][0]['attributes']['network_security_group_id'] = 'other' with self.assertRaises(ValueError): ACCESS.email_rules(state) with self.assertRaises(ValueError): ACCESS.email_rules({'resources': []}) def test_email_never_opens_broad_or_private_sources(self): for cidr in ('0.0.0.0/0', '192.168.100.73/32', '8.8.8.0/24'): with self.subTest(cidr=cidr), patch.object(ACCESS, 'run') as execute: with self.assertRaises(ValueError): ACCESS.email('/not/read', cidr, 'oci') execute.assert_not_called() def test_email_firewall_allowance_precedes_image_reject(self): listing = '-P INPUT DROP\n-A INPUT -j REJECT --reject-with icmp-host-prohibited\n-A INPUT -j ufw-before-input\n' with patch.object(ACCESS, 'run', side_effect=[listing, '']) as execute: ACCESS.email_firewall('8.8.8.8/32') args = execute.call_args.args[0] self.assertEqual(args[3:6], ['-I', 'INPUT', '1']) self.assertIn('8.8.8.8/32', args) self.assertEqual(args[args.index('--dport') + 1], '9100') def test_email_firewall_preserves_unrelated_input_rules(self): listing = ('-P INPUT DROP\n-A INPUT -p tcp --dport 22 -j ACCEPT\n' '-A INPUT -s 9.9.9.9/32 -p tcp --dport 9100 -m comment --comment jeannie-email-exporter -j ACCEPT\n') with patch.object(ACCESS, 'run', side_effect=[listing, '', '']) as execute: ACCESS.email_firewall('8.8.8.8/32') removed = execute.call_args_list[1].args[0] self.assertIn('9.9.9.9/32', removed) self.assertNotIn('22', removed) def test_email_updates_only_exact_managed_ports(self): state = self.state() rules = [{'id': name, 'direction': 'INGRESS', 'protocol': '6', 'source-type': 'CIDR_BLOCK', 'source': '9.9.9.9/32', 'tcp-options': {'destination-port-range': {'min': port, 'max': port}}} for name, port in [('email_ssh', 22), ('email_monitoring', 9100)]] with tempfile.TemporaryDirectory() as directory: path = Path(directory) / 'state.json'; path.write_text(json.dumps(state)) with patch.object(ACCESS.Path, 'home', return_value=Path(directory)), patch.object(ACCESS, 'run') as execute: execute.side_effect = [json.dumps({'data': rules}), '{"data": {}}'] ACCESS.email(path, '8.8.8.8/32', 'oci') arguments = execute.call_args.args[0] changes = json.loads(arguments[arguments.index('--security-rules') + 1]) self.assertEqual({c['id'] for c in changes}, {'email_ssh', 'email_monitoring'}) self.assertTrue(all(c['source'] == '8.8.8.8/32' for c in changes)) self.assertTrue(all('description' not in c for c in changes)) class ScheduledExporterTests(unittest.TestCase): def exercise(self, *, enabled=True, address_changed=False, down=False, timeout=False): import io import shutil import urllib.request with tempfile.TemporaryDirectory() as directory: root = Path(directory) shutil.copyfile(ROOT / 'scripts/oci-foundation-resolve.py', root / 'oci-foundation-resolve.py') state = root / 'state.json' state.write_text(json.dumps({'version': 4, 'resources': []})) source = '9.9.9.9/32' if address_changed else '8.8.8.8/32' values = {'LAB_OCI_EMAIL_ENABLED': str(enabled).lower(), 'LAB_EMAIL_PUBLIC_IP': '1.1.1.1', 'LAB_OCI_FOUNDATION_STATE_FILE': str(state), 'LAB_OCI_EMAIL_ADMIN_CIDR': source, 'LAB_OCI_EMAIL_MONITORING_CIDR': source, 'LAB_TEST_PRESERVED': 'test-value'} config = root / 'foundation.env' config.write_text(''.join('export ' + k + '=' + v + '\n' for k, v in values.items())) original = config.read_text() (root / 'exporter-settings.json').write_text(json.dumps({ 'config': str(config), 'names': list(values), 'cli': 'oci', 'ssh_key': '/test/key', 'ssh_user': 'ubuntu'})) up = {'debian-host': {'health': 'up'}, 'oci-email-node': {'health': 'up'}} unhealthy = {**up, 'oci-email-node': {'health': 'down'}} samples = [unhealthy if down else up, unhealthy if timeout else up] if enabled else [up] with patch.object(ACCESS, 'run', return_value='') as local, \ patch.object(ACCESS, 'email') as repair, \ patch.object(ACCESS.subprocess, 'run') as ssh, \ patch.object(ACCESS, 'healthy_targets', side_effect=samples), \ patch.object(urllib.request, 'urlopen', return_value=io.BytesIO(b'8.8.8.8')) as public_ip, \ patch('time.monotonic', side_effect=[0, 100]): if timeout: with self.assertRaisesRegex(RuntimeError, 'expected exporter targets UP'): ACCESS.reconcile(root) else: ACCESS.reconcile(root) local.assert_called_once() needs_repair = enabled and (down or address_changed) self.assertEqual(repair.call_count, int(needs_repair)) self.assertEqual(ssh.call_count, int(needs_repair)) self.assertEqual(public_ip.call_count, int(enabled)) if needs_repair: self.assertIn('export LAB_TEST_PRESERVED=test-value', config.read_text()) self.assertIn('export LAB_OCI_EMAIL_MONITORING_CIDR=8.8.8.8/32', config.read_text()) else: self.assertEqual(config.read_text(), original) def test_healthy_unchanged_exporters_avoid_cloud_and_ssh_mutations(self): self.exercise() def test_down_email_exporter_triggers_repair(self): self.exercise(down=True) def test_public_ip_change_triggers_repair_even_before_scrape_fails(self): self.exercise(address_changed=True) def test_disabled_email_has_no_external_dependencies(self): self.exercise(enabled=False) def test_unrecovered_exporter_fails_scheduled_run(self): self.exercise(down=True, timeout=True) if __name__ == '__main__': unittest.main()