Repair exporter access through the Jeannie monitoring pipeline

This commit is contained in:
juvenal.diaz 2026-12-03 08:12:35 -06:00
parent 20c59955e9
commit e51d13006a
13 changed files with 377 additions and 8 deletions

View File

@ -318,7 +318,7 @@ resource "oci_core_network_security_group_security_rule" "email_ssh" {
network_security_group_id = oci_core_network_security_group.email[0].id
direction = "INGRESS"
protocol = "6"
source = var.admin_cidr
source = trimspace(var.email_admin_cidr) != "" ? var.email_admin_cidr : var.admin_cidr
source_type = "CIDR_BLOCK"
tcp_options {
destination_port_range {
@ -438,7 +438,7 @@ resource "oci_core_network_security_group_security_rule" "email_monitoring" {
network_security_group_id = oci_core_network_security_group.email[0].id
direction = "INGRESS"
protocol = "6"
source = trimspace(var.monitoring_cidr) != "" ? var.monitoring_cidr : var.admin_cidr
source = trimspace(var.email_monitoring_cidr) != "" ? var.email_monitoring_cidr : (trimspace(var.monitoring_cidr) != "" ? var.monitoring_cidr : var.admin_cidr)
source_type = "CIDR_BLOCK"
tcp_options {
destination_port_range {

View File

@ -396,3 +396,15 @@ check "foundation_inputs" {
error_message = "The foundation is restricted to OCI Always Free VM.Standard.E2.1.Micro instances, at most 2 total OCPUs, 2 GB total memory, and 200 GB total boot volumes."
}
}
variable "email_admin_cidr" {
description = "Optional email SSH source override, refreshed by monitoring exporters."
type = string
default = ""
}
variable "email_monitoring_cidr" {
description = "Optional email exporter source override for the Debian scraper public IPv4."
type = string
default = ""
}

View File

@ -56,3 +56,21 @@ with the remaining Debian memory; moving monitoring does not reserve host RAM.
The migration does not repair the Orange Pi SSD or migrate Loki. A down Loki
target remains a real failure, rather than being hidden by this move. Original
PVCs and backups should be retained until recovery requirements are reviewed.
`./jeannie monitoring exporters` repairs and validates the Debian and OCI email
node-exporter targets. On Debian it removes only retired CNI TCP/9100 hostPort
rules when all Kubernetes services and runtime processes are absent; shared
HTTP/HTTPS rules and other firewall policy remain intact. Rule backups are
saved under `~/.local/share/homelab/exporter-backups`.
For email it learns Debian's current public IPv4 and updates only the two
state-identified email NSG rules (SSH and exporter) to that `/32`, then adds the
matching UFW exporter permission through SSH. A managed systemd oneshot keeps
a source-restricted TCP/9100 INPUT allowance before the Oracle image's default
REJECT rule, including after reboot. It saves email-specific CIDR
overrides in the canonical OCI configuration so subsequent foundation applies
retain the new source. Existing UFW permissions are not reset or removed, and
edge access rules remain unchanged. Re-run after a home public-IP change.
The command finishes only after both exporters return metrics and Prometheus
observes both jobs UP. It needs the existing managed email rules, OCI CLI
credentials, SSH key and passwordless sudo; it does not recreate either host.

View File

@ -80,7 +80,7 @@ Build And Bootstrap
deploy-api Deploy the Temporal-backed Jeannie API on Debian.
deploy-heimdall Deploy the Debian-hosted Heimdall dashboard.
deploy-dex Deploy the Debian-hosted Dex SSO stack.
monitoring {plan|migrate|apply|refresh|status|validate} Manage Debian monitoring; preserve cluster discovery and Dex.
monitoring {plan|migrate|apply|refresh|exporters|status|validate} Manage Debian monitoring; preserve cluster discovery and Dex.
deploy-office Deploy Nextcloud + ONLYOFFICE online office.
deploy-matrix Deploy the Matrix homeserver (Synapse + Element + Postgres).
deploy-ai-stack Deploy the Debian-hosted AI gateway stack.

View File

@ -4050,7 +4050,7 @@ oci_foundation_config_names=(
LAB_OCI_OPEN_MAIL_PORTS LAB_OCI_AUTO_CONFIGURE_EDGE LAB_EDGE_HOST LAB_EDGE_TAILSCALE_IP
LAB_OCI_AUTO_CONFIGURE_EMAIL LAB_OCI_AUTO_UPDATE_DUCKDNS LAB_DUCKDNS_DOMAINS
LAB_OCI_FOUNDATION_STATE_FILE
LAB_OCI_MONITORING_ENABLED LAB_OCI_MONITORING_CIDR LAB_OCI_MONITORING_ALARMS_ENABLED LAB_OCI_MONITORING_TOPIC_NAME LAB_OCI_MONITORING_TOPIC_ID LAB_OCI_MONITORING_NOTIFICATION_EMAIL LAB_OCI_EDGE_TAILNET_SSH_CIDR
LAB_OCI_EMAIL_ADMIN_CIDR LAB_OCI_EMAIL_MONITORING_CIDR LAB_OCI_MONITORING_ENABLED LAB_OCI_MONITORING_CIDR LAB_OCI_MONITORING_ALARMS_ENABLED LAB_OCI_MONITORING_TOPIC_NAME LAB_OCI_MONITORING_TOPIC_ID LAB_OCI_MONITORING_NOTIFICATION_EMAIL LAB_OCI_EDGE_TAILNET_SSH_CIDR
LAB_OCI_BACKUP_BUCKET_ENABLED LAB_OCI_BACKUP_BUCKET LAB_OCI_BACKUP_BUCKET_NAME LAB_OCI_BACKUP_BUCKET_NAMESPACE LAB_OCI_BACKUP_BUCKET_ID
LAB_OCI_BASTION_ENABLED LAB_OCI_BASTION_NAME LAB_OCI_BASTION_TARGET_SUBNET_ID LAB_OCI_BASTION_SSH_SOURCE_CIDR
LAB_OCI_BASTION_CLIENT_CIDRS_JSON LAB_OCI_BASTION_MAX_SESSION_TTL LAB_OCI_BASTION_ID LAB_OCI_EDGE_COMPARTMENT_ID LAB_OCI_EDGE_INSTANCE_ID LAB_OCI_EMAIL_INSTANCE_ID LAB_OCI_EDGE_INSTANCE_MANAGED

View File

@ -412,6 +412,8 @@ export_oci_foundation_tf_vars() {
export_if_unset TF_VAR_email_subnet_cidr "${LAB_OCI_EMAIL_SUBNET_CIDR:-}"
export_if_unset TF_VAR_admin_cidr "${LAB_OCI_ADMIN_CIDR:-}"
export_if_unset TF_VAR_monitoring_enabled "${LAB_OCI_MONITORING_ENABLED:-}"
export_if_unset TF_VAR_email_admin_cidr "${LAB_OCI_EMAIL_ADMIN_CIDR:-}"
export_if_unset TF_VAR_email_monitoring_cidr "${LAB_OCI_EMAIL_MONITORING_CIDR:-}"
export_if_unset TF_VAR_monitoring_cidr "${LAB_OCI_MONITORING_CIDR:-${LAB_OCI_ADMIN_CIDR:-}}"
export_if_unset TF_VAR_monitoring_alarms_enabled "${LAB_OCI_MONITORING_ALARMS_ENABLED:-}"
export_if_unset TF_VAR_monitoring_topic_name "${LAB_OCI_MONITORING_TOPIC_NAME:-}"

View File

@ -17,10 +17,54 @@ configure_platform_grafana_sso() {
fi
}
monitoring_exporters() {
require_debian_server "monitoring exporters"
local foundation_lock
exec {foundation_lock}>"${REPO_ROOT}/bootstrap/oci/.jeannie-foundation.lock"
if ! flock -n "${foundation_lock}"; then
echo "Another OCI foundation operation is active; retry exporter repair after it finishes." >&2
return 1
fi
record_change_journal monitoring-exporters
bash "${REPO_ROOT}/scripts/monitoring-host-exporter.sh" || return 1
local cidr cli email_ip
cidr="$(curl --noproxy '*' -4 -fsS --connect-timeout 5 --max-time 15 https://api.ipify.org)/32" || return 1
cli="${OCI_CLI_BIN:-${HOME}/.local/share/homelab/venvs/oci-cli/bin/oci}"
python3 "${REPO_ROOT}/scripts/monitoring-exporter-access.py" email \
--state "${LAB_OCI_FOUNDATION_STATE_FILE:?OCI foundation state required}" --cidr "${cidr}" --cli "${cli}" || return 1
export LAB_OCI_EMAIL_ADMIN_CIDR="${cidr}" LAB_OCI_EMAIL_MONITORING_CIDR="${cidr}"
oci_foundation_save_config || return 1
email_ip="${LAB_EMAIL_PUBLIC_IP:?Email VM address required}"
# Repair only monitoring access on the mail host; do not reinstall/reset mail or UFW.
ssh -T -o BatchMode=yes -o ConnectTimeout=10 -i "${LAB_EMAIL_SSH_PRIVATE_KEY:-${HOME}/.ssh/id_ed25519}" \
"${LAB_EMAIL_SSH_USER:-ubuntu}@${email_ip}" \
"temporary=\$(mktemp /tmp/jeannie-email-exporter.XXXXXX.py); trap 'rm -f \"\$temporary\"' EXIT; cat >\"\$temporary\"; sudo -n python3 \"\$temporary\" email-host --cidr '${cidr}'" \
<"${REPO_ROOT}/scripts/monitoring-exporter-access.py" || return 1
python3 - "${email_ip}" <<'PYEXPORT'
import json, sys, time, urllib.request
for host in ('127.0.0.1', sys.argv[1]):
with urllib.request.urlopen('http://' + host + ':9100/metrics', timeout=10) as response:
if b'node_exporter_build_info' not in response.read():
raise SystemExit('Node exporter metrics missing for ' + host)
print('Exporter metrics verified: ' + host)
deadline = time.monotonic() + 90
while True:
targets = json.load(urllib.request.urlopen('http://127.0.0.1:19090/api/v1/targets', timeout=15))['data']['activeTargets']
selected = {t['scrapePool']: t for t in targets if t['scrapePool'] in ('debian-host', 'oci-email-node')}
if len(selected) == 2 and all(t['health'] == 'up' for t in selected.values()):
for name, target in selected.items(): print(name + ': UP ' + target['scrapeUrl'])
break
if time.monotonic() >= deadline:
raise SystemExit('Exporter HTTP works but Prometheus has not confirmed both targets UP')
time.sleep(5)
PYEXPORT
}
monitoring_debian() {
local action="${1:-status}" root="${LAB_MONITORING_INSTALL_DIR:-/data/homelab-monitoring}"
require_debian_server "monitoring"
case "${action}" in
exporters) monitoring_exporters; return $? ;;
plan)
echo "Move Prometheus, Alertmanager and Grafana to ${root} on Debian; preserve PVCs, database, dashboards and Dex."
echo "Keep the Operator and exporters in K3s; refresh rules, discovery credentials and dashboards every five minutes."
@ -29,7 +73,7 @@ monitoring_debian() {
python3 "${REPO_ROOT}/scripts/monitoring-debian.py" "${action}" --root "${root}"
return $? ;;
migrate|apply|refresh) ;;
*) echo 'Usage: ./jeannie monitoring {plan|migrate|apply|refresh|status|validate}' >&2; return 2 ;;
*) echo 'Usage: ./jeannie monitoring {plan|migrate|apply|refresh|exporters|status|validate}' >&2; return 2 ;;
esac
cluster_context_require || return 1
record_change_journal "monitoring-${action}" "$@"

View File

@ -40,7 +40,7 @@ fi
domain="${LAB_EMAIL_DOMAIN:-}"
open_mail="${LAB_EMAIL_OPEN_MAIL_PORTS:-false}"
monitoring_cidr="${LAB_OCI_MONITORING_CIDR:-${LAB_OCI_ADMIN_CIDR:-}}"
monitoring_cidr="${LAB_OCI_EMAIL_MONITORING_CIDR:-${LAB_OCI_MONITORING_CIDR:-${LAB_OCI_ADMIN_CIDR:-}}}"
echo "Preparing Postfix and Dovecot on ${ssh_target} (domain=${domain:-pending}, mail_ports=${open_mail})."
ssh "${ssh_opts[@]}" "${ssh_target}" sudo bash -s -- "${domain}" "${open_mail}" "${monitoring_cidr}" <<'REMOTE'
set -euo pipefail

View File

@ -0,0 +1,179 @@
#!/usr/bin/env python3
"""Repair narrowly identified exporter access rules; never flush host firewalls."""
import argparse
import ipaddress
import json
from pathlib import Path
import shlex
import shutil
import subprocess
def run(args):
return subprocess.check_output(args, text=True, timeout=90)
def retired_rules(text):
"""Only stale CNI per-port rules, leaving shared HTTP/HTTPS rules intact."""
parsed = [shlex.split(line) for line in text.splitlines()]
owned = {t[t.index('-j') + 1] for t in parsed
if len(t) > 2 and t[:2] == ['-A', 'CNI-HOSTPORT-DNAT']
and '-j' in t and 'k8s-pod-network' in ' '.join(t)}
result = []
for tokens in parsed:
if (len(tokens) > 3 and tokens[0] == '-A' and tokens[1].startswith('CNI-DN-') and tokens[1] in owned
and '--dport' in tokens and tokens[tokens.index('--dport') + 1] == '9100'):
result.append(tokens)
return result
def host():
for service in ('k3s', 'k3s-agent', 'kubelet'):
active = subprocess.run(['systemctl', 'is-active', '--quiet', service]).returncode == 0
if active:
print('Active Kubernetes runtime; CNI rules left untouched.')
return
processes = run(['ps', '-eo', 'comm=']).splitlines()
if any(p.strip() in ('k3s', 'kubelet', 'k3s-server', 'k3s-agent') for p in processes):
raise RuntimeError('Kubernetes runtime process still present; refusing CNI cleanup')
# A retired node's saved hostPort DNAT can shadow an otherwise healthy listener.
for binary in ('iptables', 'iptables-legacy'):
executable = shutil.which(binary) or '/usr/sbin/' + binary
if not Path(executable).exists():
continue
listing = subprocess.run(['sudo', '-n', executable, '-t', 'nat', '-S'], capture_output=True, text=True)
if listing.returncode:
continue
candidates = retired_rules(listing.stdout)
if not candidates:
continue
directory = Path.home() / '.local/share/homelab/exporter-backups'
directory.mkdir(parents=True, exist_ok=True, mode=0o700)
from datetime import datetime, timezone
backup = directory / (datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S%f') + '-' + binary + '.rules')
backup.write_text(listing.stdout)
backup.chmod(0o600)
for tokens in candidates:
run(['sudo', '-n', executable, '-w', '5', '-t', 'nat', '-D', *tokens[1:]])
print(f'Removed {len(candidates)} retired TCP/9100 CNI rules ({binary}); HTTP/HTTPS rules preserved. Backup: {backup}')
def email_rules(state):
found = {}
for resource in state.get('resources', []):
if resource.get('mode', 'managed') != 'managed' or resource.get('type') != 'oci_core_network_security_group_security_rule':
continue
for instance in resource.get('instances', []):
if resource['name'] in ('email_ssh', 'email_monitoring') and not instance.get('deposed'):
if resource['name'] in found:
raise ValueError('Ambiguous managed email access rule')
found[resource['name']] = instance['attributes']
if set(found) != {'email_ssh', 'email_monitoring'}:
raise ValueError('Both managed email NSG rules must be present in foundation state')
if len({rule['network_security_group_id'] for rule in found.values()}) != 1:
raise ValueError('Email access rules belong to different NSGs')
return found
def public_source(cidr):
network = ipaddress.ip_network(cidr)
if network.version != 4 or network.prefixlen != 32 or not network.network_address.is_global:
raise ValueError('Email access requires the current public IPv4 /32')
return str(network)
def email_firewall(cidr):
cidr = public_source(cidr)
binary = '/usr/sbin/iptables'
listing = run([binary, '-t', 'filter', '-S', 'INPUT'])
owned = []
for line in listing.splitlines():
tokens = shlex.split(line)
if ('--comment' in tokens and tokens[tokens.index('--comment') + 1] == 'jeannie-email-exporter'
and '--dport' in tokens and tokens[tokens.index('--dport') + 1] == '9100'):
owned.append(tokens)
desired = ['-A', 'INPUT', '-s', cidr, '-p', 'tcp', '-m', 'tcp', '--dport', '9100',
'-m', 'comment', '--comment', 'jeannie-email-exporter', '-j', 'ACCEPT']
if owned == [desired] and listing.splitlines()[1:2] == [shlex.join(desired)]:
return
for tokens in owned:
run([binary, '-w', '5', '-D', *tokens[1:]])
run([binary, '-w', '5', '-I', 'INPUT', '1', *desired[2:]])
print('Email exporter INPUT allowance installed before the image default REJECT.')
def email_host(cidr):
cidr = public_source(cidr)
import os
if os.geteuid() != 0:
raise RuntimeError('Email host firewall setup requires sudo')
destination = Path('/usr/local/lib/jeannie/monitoring-exporter-access.py')
destination.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(__file__, destination)
destination.chmod(0o755)
unit = ('[Unit]\nDescription=Jeannie restricted email exporter access\n'
'After=ufw.service netfilter-persistent.service\nBefore=prometheus-node-exporter.service\n'
'[Service]\nType=oneshot\nRemainAfterExit=yes\n'
f'ExecStart=/usr/bin/python3 {destination} email-firewall --cidr {cidr}\n'
'[Install]\nWantedBy=multi-user.target\n')
Path('/etc/systemd/system/jeannie-email-exporter-access.service').write_text(unit)
run(['ufw', 'allow', 'from', cidr, 'to', 'any', 'port', '9100', 'proto', 'tcp'])
run(['systemctl', 'daemon-reload'])
run(['systemctl', 'enable', 'jeannie-email-exporter-access.service'])
run(['systemctl', 'restart', 'jeannie-email-exporter-access.service'])
run(['systemctl', 'enable', '--now', 'prometheus-node-exporter'])
print('Email exporter service and persistent restricted firewall access reconciled.')
def email(state_path, cidr, cli):
cidr = public_source(cidr)
rules = email_rules(json.loads(Path(state_path).read_text()))
nsg = next(iter(rules.values()))['network_security_group_id']
def oci(*args):
return json.loads(run([cli, 'network', 'nsg', 'rules', *args, '--nsg-id', nsg, '--output', 'json']))['data']
actual = {r['id']: r for r in oci('list', '--all')}
updates = []
previous = []
for name, recorded in rules.items():
rule = actual[recorded['id']]
port = 22 if name == 'email_ssh' else 9100
if (rule.get('direction') != 'INGRESS' or rule.get('protocol') != '6' or
rule.get('source-type') != 'CIDR_BLOCK' or
rule.get('tcp-options', {}).get('destination-port-range') != {'min': port, 'max': port}):
raise ValueError('Live email access rule no longer matches its managed role')
if rule['source'] == cidr:
continue
previous.append(rule)
updates.append({'id': rule['id'], 'direction': 'INGRESS', 'protocol': '6',
'source': cidr, 'sourceType': 'CIDR_BLOCK',
'isStateless': rule.get('is-stateless', False),
'tcpOptions': {'destinationPortRange': {'min': port, 'max': port}}})
if rule.get('description'):
updates[-1]['description'] = rule['description']
if rule.get('tcp-options', {}).get('source-port-range'):
updates[-1]['tcpOptions']['sourcePortRange'] = rule['tcp-options']['source-port-range']
if updates:
directory = Path.home() / '.local/share/homelab/exporter-backups'
directory.mkdir(parents=True, exist_ok=True, mode=0o700)
import time
backup = directory / f'email-nsg-{time.time_ns()}.json'
backup.write_text(json.dumps(previous, indent=2)); backup.chmod(0o600)
oci('update', '--security-rules', json.dumps(updates))
print(f'Updated only managed email SSH/exporter NSG rules to {cidr}; backup: {backup}')
else:
print('Managed email SSH/exporter NSG rules already match the Debian public IPv4.')
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('action', choices=['host', 'email', 'email-host', 'email-firewall'])
parser.add_argument('--state'); parser.add_argument('--cidr'); parser.add_argument('--cli')
args = parser.parse_args()
if args.action == 'host':
host()
elif args.action == 'email-host':
email_host(args.cidr)
elif args.action == 'email-firewall':
email_firewall(args.cidr)
else:
email(args.state, args.cidr, args.cli)

View File

@ -2,6 +2,12 @@
# Install the distribution node exporter on a monitored Debian-family host.
set -euo pipefail
# Retired CNI hostPort rules can intercept requests before the host listener.
script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
if [[ -f "${script_dir}/monitoring-exporter-access.py" ]]; then
python3 "${script_dir}/monitoring-exporter-access.py" host
fi
if curl --max-time 5 -fsS http://127.0.0.1:9100/metrics 2>/dev/null |
grep -F 'node_exporter_build_info' >/dev/null; then
echo "Node exporter is already responding on TCP/9100."

View File

@ -591,13 +591,13 @@ def reconcile(args):
continue
nsg_id = item["id"]
rules = oci.call("network", "nsg", "rules", "list", "--nsg-id", nsg_id, "--all")
desired = {"ssh": (22, values["LAB_OCI_ADMIN_CIDR"])}
desired = {"ssh": (22, (values.get("LAB_OCI_EMAIL_ADMIN_CIDR") if role == "email" else "") or values["LAB_OCI_ADMIN_CIDR"])}
if role == "edge":
desired.update(web=(80, "0.0.0.0/0"), https=(443, "0.0.0.0/0"))
if values.get("LAB_OCI_EDGE_TAILNET_SSH_CIDR"):
desired["tailnet_ssh"] = (22, values["LAB_OCI_EDGE_TAILNET_SSH_CIDR"])
if enabled(values, "LAB_OCI_MONITORING_ENABLED"):
desired["monitoring"] = (9100, values.get("LAB_OCI_MONITORING_CIDR") or values["LAB_OCI_ADMIN_CIDR"])
desired["monitoring"] = (9100, (values.get("LAB_OCI_EMAIL_MONITORING_CIDR") if role == "email" else "") or values.get("LAB_OCI_MONITORING_CIDR") or values["LAB_OCI_ADMIN_CIDR"])
if role == "edge":
desired["container_monitoring"] = (9101, desired["monitoring"][1])
if enabled(values, "LAB_OCI_BASTION_ENABLED"):

View File

@ -128,6 +128,7 @@ validate_unit_tests() {
python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_go_launchers.py'
python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_doctor_focus.py'
python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_stale_pod_candidate.py'
python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_monitoring_exporter_access.py'
python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_monitoring_debian.py'
python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_monitoring_readiness.py'
python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_doctor_k3s_storage.py'

View File

@ -0,0 +1,107 @@
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()