Files
napalm-linux/tests/test_zabbix_agent.py
T
Christian Manivong a3b9e4a02d feat(zabbix): an active-only agent closes the port netOrk opened for it (NetOrk/netork#2693)
Every rule the firewall step adds in firewalld, ufw or iptables is recorded in
napalm-device-types' opened_ports record, only when the firewall did not have
it before. For an active-only agent, _revoke_zabbix_agent_sources removes
exactly the agent's recorded rules and reports what is left for the port.
2026-11-26 08:19:19 +01:00

355 lines
12 KiB
Python

"""configure_zabbix_agent on a Linux host without a container engine (NetOrk/netork#2571).
The template (napalm-device-types ``ZabbixAgentMixin``) installs ``zabbix-agent`` from
the host's packages, and from Zabbix's repository where those have none; this driver
adds that repository, writes ``/etc/zabbix/zabbix_agentd.conf`` and opens the port.
"""
from __future__ import annotations
from unittest.mock import MagicMock
import pytest
from napalm_device_types import (
OPENED_PORTS_RECORD,
CommandResult,
read_opened_ports_command,
)
from napalm_linux import LinuxDriver
CONFIG = "/etc/zabbix/zabbix_agentd.conf"
STOCK = "PidFile=/run/zabbix/zabbix_agentd.pid\nServer=127.0.0.1\nServerActive=127.0.0.1\nHostname=Zabbix server\n"
SETTINGS = {
"server": "zabbix.example.com",
"server_active": "zabbix.example.com",
"listen_port": 10050,
"allowed_sources": ["10.0.0.5"],
"hostname": "web-01",
"release": "7.4",
}
UBUNTU = 'ID=ubuntu\nVERSION_ID="24.04"\nID_LIKE=debian\n'
class _Host:
"""A Linux host: what runs as root, the files it reads, its packages and services."""
def __init__(self, *, config=STOCK, os_release=UBUNTU, firewall="ufw", firewalld=False):
self.config = config
self.os_release = os_release
self.firewall = firewall
self.firewalld = firewalld
self.root: list[str] = []
self.written: list[tuple[str, str]] = []
self.services: list[tuple[str, str]] = []
self.packages: list[str] = []
self.distribution_has_it = True
self.refuse = ""
#: What reading the record of opened rules prints (NetOrk/netork#2693).
self.record = ""
#: What counting the rules left for the port prints.
self.left = "0"
def sudo_status(self, command, read_timeout=100):
self.root.append(command)
if self.refuse and self.refuse in command:
return ("E: refused", 1)
if command == read_opened_ports_command():
return (self.record.strip(), 0)
if "grep -c" in command:
return (self.left, 0)
if "repo.zabbix.com" in command:
self.distribution_has_it = True
return ("", 0)
def send(self, command, read_timeout=100):
if command == "systemctl is-active firewalld 2>/dev/null":
return "active" if self.firewalld else "inactive"
if command == f"command -v {self.firewall} 2>/dev/null":
return f"/usr/sbin/{self.firewall}"
return ""
def run_command(self, command, *, privileged=False, timeout=60, stdin=None):
if self.refuse and self.refuse in command:
return CommandResult("", "Permission denied", 1)
if command == "cat /etc/os-release":
return CommandResult(self.os_release, "", 0)
if command == f"cat {CONFIG}" and privileged:
return CommandResult(self.config, "", 0)
return CommandResult("", "", 0)
def install_file(self, path, content):
self.written.append((path, content))
self.config = content
return CommandResult("", "", 0)
def ensure_package(self, name):
self.packages.append(name)
ok = self.distribution_has_it
return {"success": ok, "steps": [], "output": "installed" if ok else "E: Unable to locate"}
def manage_service(self, name, action):
self.services.append((action, name))
return {"success": True, "output": ""}
@pytest.fixture
def host():
return _Host()
@pytest.fixture
def driver(host):
d = LinuxDriver("h", "admin", "p")
d._device = MagicMock()
d._pkg_manager = "apt"
d._root = True
d._sudo_status = host.sudo_status
d._send = host.send
d.run_command = host.run_command
d._install_file_as_root = host.install_file
d.ensure_package = host.ensure_package
d.manage_service = host.manage_service
d.refresh_available_updates = lambda: {"success": True, "output": ""}
return d
def test_installs_writes_opens_and_starts(driver, host):
result = driver.configure_zabbix_agent(SETTINGS)
assert result["success"] is True, result["output"]
assert [s["step"] for s in result["steps"]] == ["install", "configure", "firewall", "start"]
assert host.packages == ["zabbix-agent"]
assert host.services == [("enable", "zabbix-agent"), ("restart", "zabbix-agent")]
def test_the_config_gets_the_caller_s_values_and_keeps_the_rest(driver, host):
driver.configure_zabbix_agent(SETTINGS)
path, content = host.written[0]
assert path == CONFIG
assert "Server=zabbix.example.com\n" in content
assert "Hostname=web-01\n" in content
assert content.startswith("PidFile=/run/zabbix/zabbix_agentd.pid\n")
assert f"cp -p {CONFIG} {CONFIG}.bak" in host.root
def test_a_config_that_already_says_it_is_not_written(driver, host):
driver.configure_zabbix_agent(SETTINGS)
host.written.clear()
result = driver.configure_zabbix_agent(SETTINGS)
assert result["success"] is True
assert host.written == []
def test_a_config_that_cannot_be_read_stops_the_fix(driver, host):
host.refuse = f"cat {CONFIG}"
result = driver.configure_zabbix_agent(SETTINGS)
assert result["success"] is False
assert result["steps"][-1]["step"] == "configure"
assert host.services == []
def test_without_the_distribution_s_package_zabbix_s_repository_is_added(driver, host):
host.distribution_has_it = False
result = driver.configure_zabbix_agent(SETTINGS)
assert result["success"] is True, result["output"]
repository = next(c for c in host.root if "repo.zabbix.com" in c)
assert (
"https://repo.zabbix.com/zabbix/7.4/release/ubuntu/pool/main/z/zabbix-release/"
"zabbix-release_latest_7.4+ubuntu24.04_all.deb"
) in repository
assert "dpkg -i" in repository
assert host.packages == ["zabbix-agent", "zabbix-agent"]
def test_a_distribution_zabbix_publishes_nothing_for_fails_the_install(driver, host):
host.distribution_has_it = False
host.os_release = 'ID=arch\nVERSION_ID="rolling"\n'
result = driver.configure_zabbix_agent(SETTINGS)
assert result["success"] is False
assert "Zabbix publishes no repository for arch" in result["output"]
assert not any("repo.zabbix.com" in c for c in host.root)
def test_ufw_opens_the_listen_port_for_the_sources(driver, host):
driver.configure_zabbix_agent(SETTINGS)
assert any("ufw allow from 10.0.0.5/32 to any port 10050 proto tcp" in c for c in host.root)
def test_iptables_opens_the_listen_port_for_the_sources(driver, host):
host.firewall = "iptables"
driver.configure_zabbix_agent(SETTINGS)
assert any(
"iptables -I INPUT -s 10.0.0.5/32 -p tcp --dport 10050 -j ACCEPT" in c for c in host.root
)
def test_a_running_firewalld_gets_a_rich_rule_for_tcp(driver, host):
host.firewalld = True
driver.configure_zabbix_agent(SETTINGS)
rule = next(c for c in host.root if "firewall-cmd" in c)
assert (
'rule family="ipv4" source address="10.0.0.5/32" port port="10050" protocol="tcp" accept'
in rule
)
def test_no_sources_change_no_firewall(driver, host):
result = driver.configure_zabbix_agent({**SETTINGS, "allowed_sources": []})
assert result["success"] is True
assert not any("ufw" in c or "iptables" in c or "firewall-cmd" in c for c in host.root)
def test_the_snmp_rule_is_still_udp_161(driver, host):
driver.configure_snmp_agent({"community": "c0mm", "allowed_sources": ["10.0.0.5"]})
assert any("ufw allow from 10.0.0.5/32 to any port 161 proto udp" in c for c in host.root)
# --- The record of the rules netOrk opened (NetOrk/netork#2693) ---------------------
ACTIVE_ONLY = {**SETTINGS, "active_only": True, "allowed_sources": []}
ROOT = "0 755 directory\n0 644 regular file\n"
ZABBIX_UFW = "v1 zabbix-agent ufw tcp 10050 10.0.0.5/32"
SNMP_UFW = "v1 snmp ufw udp 161 10.0.0.5/32"
def _opened(host) -> str:
return next(c for c in host.root if "allow" in c or "-I INPUT" in c or "--add-rich" in c)
def test_ufw_records_the_rule_it_added_under_the_agent(driver, host):
driver.configure_zabbix_agent(SETTINGS)
opened = _opened(host)
assert "*Skipping*) ;;" in opened
assert f'"{ZABBIX_UFW}" >> {OPENED_PORTS_RECORD}' in opened
def test_iptables_records_the_rule_only_where_the_check_found_none(driver, host):
host.firewall = "iptables"
driver.configure_zabbix_agent(SETTINGS)
opened = _opened(host)
check = "iptables -C INPUT -s 10.0.0.5/32 -p tcp --dport 10050 -j ACCEPT 2>/dev/null ||"
assert check in opened
assert '"v1 zabbix-agent iptables tcp 10050 10.0.0.5/32" >>' in opened.split(check)[1]
def test_firewalld_records_each_zone_and_configuration_it_added_to(driver, host):
host.firewalld = True
driver.configure_zabbix_agent(SETTINGS)
opened = _opened(host)
assert '"v1 zabbix-agent firewalld tcp 10050 10.0.0.5/32 $z runtime"' in opened
assert '"v1 zabbix-agent firewalld tcp 10050 10.0.0.5/32 $z permanent"' in opened
def test_the_snmp_rule_is_recorded_under_snmp(driver, host):
driver.configure_snmp_agent({"community": "c0mm", "allowed_sources": ["10.0.0.5"]})
assert f'"{SNMP_UFW}" >>' in _opened(host)
def test_active_only_removes_the_agent_s_recorded_rules_and_keeps_the_rest(driver, host):
host.record = ROOT + f"{ZABBIX_UFW}\n{SNMP_UFW}\nv9 something else\n"
result = driver.configure_zabbix_agent(ACTIVE_ONLY)
assert result["success"] is True, result["output"]
deletes = [c for c in host.root if "ufw delete" in c]
assert len(deletes) == 1
assert "ufw delete allow from 10.0.0.5/32 to any port 10050 proto tcp" in deletes[0]
assert host.written[-1] == (OPENED_PORTS_RECORD, f"{SNMP_UFW}\nv9 something else\n")
firewall = result["steps"][2]["output"]
assert "removed" in firewall and "10.0.0.5/32" in firewall
assert "v9 something else" in firewall
assert not any("ufw allow" in c for c in host.root)
def test_active_only_removes_firewalld_rules_from_the_zone_and_configuration_recorded(driver, host):
host.firewalld = True
host.record = ROOT + (
"v1 zabbix-agent firewalld tcp 10050 10.0.0.5/32 public permanent\n"
"v1 zabbix-agent firewalld tcp 10050 10.0.0.5/32 public runtime\n"
)
result = driver.configure_zabbix_agent(ACTIVE_ONLY)
assert result["success"] is True, result["output"]
removes = [c for c in host.root if "--remove-rich-rule" in c]
rule = 'rule family="ipv4" source address="10.0.0.5/32" port port="10050" protocol="tcp" accept'
assert any("--permanent --zone=public --remove-rich-rule=" in c and rule in c for c in removes)
assert any("firewall-cmd --zone=public --remove-rich-rule=" in c and rule in c for c in removes)
assert host.written[-1] == (OPENED_PORTS_RECORD, "")
def test_active_only_removes_a_recorded_iptables_rule(driver, host):
host.firewall = "iptables"
host.record = ROOT + "v1 zabbix-agent iptables tcp 10050 10.0.0.5/32\n"
driver.configure_zabbix_agent(ACTIVE_ONLY)
assert any(
"iptables -D INPUT -s 10.0.0.5/32 -p tcp --dport 10050 -j ACCEPT" in c for c in host.root
)
def test_a_rule_recorded_under_an_earlier_port_is_removed_too(driver, host):
host.record = ROOT + "v1 zabbix-agent ufw tcp 10051 10.0.0.5/32\n"
driver.configure_zabbix_agent(ACTIVE_ONLY)
assert any("ufw delete allow from 10.0.0.5/32 to any port 10051" in c for c in host.root)
def test_without_a_record_nothing_is_removed_and_what_is_left_is_reported(driver, host):
host.left = "1"
result = driver.configure_zabbix_agent(ACTIVE_ONLY)
assert result["success"] is True
assert not any("ufw delete" in c for c in host.root)
assert host.written[-1][0] == CONFIG
firewall = result["steps"][2]["output"]
assert "netOrk recorded no rule" in firewall
assert "1 rule(s) for tcp/10050" in firewall
def test_a_record_someone_else_could_write_is_not_acted_on(driver, host):
host.record = f"1000 755 directory\n0 644 regular file\n{ZABBIX_UFW}\n"
result = driver.configure_zabbix_agent(ACTIVE_ONLY)
assert result["success"] is False
assert "not root's" in result["output"]
assert not any("ufw delete" in c for c in host.root)
def test_a_rule_that_will_not_go_stays_in_the_record(driver, host):
host.record = ROOT + f"{ZABBIX_UFW}\n"
host.refuse = "ufw delete"
result = driver.configure_zabbix_agent(ACTIVE_ONLY)
assert result["success"] is False
assert not any(path == OPENED_PORTS_RECORD for path, _ in host.written)
assert host.services == []