my-homelab-configs/tests/jeannie/test_monitoring_exporter_ac...

108 lines
5.7 KiB
Python

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))
if __name__ == '__main__':
unittest.main()