driver / lint (pull_request) Successful in 15s
driver / standard (pull_request) Successful in 15s
driver / types (pull_request) Successful in 1m4s
driver / test (3.13) (pull_request) Successful in 1m5s
driver / test (3.12) (pull_request) Successful in 1m11s
driver / lowest (pull_request) Successful in 50s
driver / build (pull_request) Successful in 39s
driver / security (pull_request) Successful in 1m35s
CI / driver (pull_request) Successful in 2m55s
driver / publish (pull_request) Skipped
perf, python3-perf and bpftool are built from the kernel's source rpm, and
Red Hat's VEX lists them in every kernel CVE: 18 532 findings on an Oracle
Linux 9 host's three kernel tools alone. The rpm query now reads
%{SOURCERPM}, and each package carries its name as `source_rpm` (`perf` ->
`kernel`), absent where rpm names none (`gpg-pubkey`).
Not dpkg's `source_package`: netOrk reads that as the name a distribution
files its verdicts under, which holds for Debian and not for Oracle or Red
Hat, whose records name the binary (NetOrk/netork#2394).
2701 lines
101 KiB
Python
2701 lines
101 KiB
Python
"""Unit tests for LinuxDriver – parsing helpers (no real SSH connection needed)."""
|
||
|
||
import re
|
||
from unittest.mock import MagicMock, patch
|
||
|
||
import pytest
|
||
from napalm_device_types import DNF_INSTALLED_CVES_COMMAND
|
||
|
||
from napalm_linux._routes import IpRoute, parse_ip_route
|
||
from napalm_linux._rpm import source_rpm_name
|
||
from napalm_linux.linux import (
|
||
_YUM_SECURITY_COMMAND,
|
||
LinuxDriver,
|
||
_arm_vendor_from_model,
|
||
_split_status,
|
||
)
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Fixture – driver without a real connection
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
@pytest.fixture()
|
||
def driver():
|
||
"""Return a LinuxDriver instance with netmiko mocked out."""
|
||
d = LinuxDriver.__new__(LinuxDriver)
|
||
d.hostname = "testhost"
|
||
d.username = "user"
|
||
d.password = "pass" # noqa: S106
|
||
d.timeout = 60
|
||
d.port = 22
|
||
d._secret = "pass" # noqa: S105
|
||
d._forced_pkg_manager = None
|
||
d._pkg_manager = "apt"
|
||
# Set by __init__, which this fixture bypasses via __new__. Without it every
|
||
# call through _sudo() raises AttributeError, which the callers' broad
|
||
# `except Exception` turns into a plain {"success": False} -- so the tests
|
||
# failed for a reason that had nothing to do with what they were testing.
|
||
d._sudo_password = None
|
||
d.netmiko_optional_args = {}
|
||
d._device = MagicMock()
|
||
d._device.remote_conn_pre.get_transport.return_value = _ShellAnswers(d)
|
||
return d
|
||
|
||
|
||
_SCRIPTED_RC = re.compile(r"\n?^__NETORK_RC=(-?\d+)\s*$", re.MULTILINE)
|
||
|
||
|
||
class _ShellAnswers:
|
||
"""The SSH transport of the fixture: an exec channel answers what ``_send``
|
||
answers for the same command line, so a test that scripts the shell's
|
||
output scripts ``_sudo``'s too (it runs on an exec channel since
|
||
NetOrk/netork#1039). It refuses a line holding the sudo password.
|
||
|
||
The exit status is 0, or what a scripted ``__NETORK_RC=<n>`` line says when
|
||
the command did not echo that marker itself (``_with_rc``); that line is
|
||
then no output. ``test_sudo_off_the_command_line`` covers the channel itself."""
|
||
|
||
def __init__(self, driver):
|
||
self._driver = driver
|
||
|
||
def open_session(self):
|
||
return _AnsweringChannel(self._driver)
|
||
|
||
|
||
class _AnsweringChannel:
|
||
def __init__(self, driver):
|
||
self._driver = driver
|
||
self._out = b""
|
||
self._status = 0
|
||
|
||
def exec_command(self, command):
|
||
password = self._driver._sudo_password
|
||
assert not password or password not in command, f"sudo password in {command!r}"
|
||
output = self._driver._send(command)
|
||
marker = _SCRIPTED_RC.search(output)
|
||
if marker and "echo __NETORK_RC" not in command:
|
||
self._status = int(marker.group(1))
|
||
output = _SCRIPTED_RC.sub("", output)
|
||
self._out = output.encode()
|
||
|
||
def settimeout(self, timeout):
|
||
pass
|
||
|
||
def sendall(self, data):
|
||
pass
|
||
|
||
def shutdown_write(self):
|
||
pass
|
||
|
||
def close(self):
|
||
pass
|
||
|
||
def recv_ready(self):
|
||
return bool(self._out)
|
||
|
||
def recv(self, size):
|
||
chunk, self._out = self._out[:size], self._out[size:]
|
||
return chunk
|
||
|
||
def recv_stderr_ready(self):
|
||
return False
|
||
|
||
def recv_stderr(self, size):
|
||
return b""
|
||
|
||
def exit_status_ready(self):
|
||
return not self._out
|
||
|
||
def recv_exit_status(self):
|
||
return self._status
|
||
|
||
|
||
def _mock_send(driver_fixture, output: str):
|
||
"""Patch _send to return *output* for any command."""
|
||
driver_fixture._device.send_command.return_value = output
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# get_interfaces (parsing)
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
IP_LINK_OUTPUT = """\
|
||
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN mode DEFAULT group default qlen 1000\\ link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
|
||
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP mode DEFAULT group default qlen 1000\\ link/ether aa:bb:cc:dd:ee:ff brd ff:ff:ff:ff:ff:ff
|
||
3: eth1: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN mode DEFAULT group default qlen 1000\\ link/ether 11:22:33:44:55:66 brd ff:ff:ff:ff:ff:ff
|
||
"""
|
||
|
||
|
||
def test_get_interfaces_parses_state(driver):
|
||
with patch.object(driver, "_send", return_value=IP_LINK_OUTPUT):
|
||
result = driver.get_interfaces()
|
||
assert "eth0" in result
|
||
assert result["eth0"]["is_up"] is True
|
||
assert result["eth0"]["mtu"] == 1500
|
||
assert result["eth0"]["mac_address"] == "aa:bb:cc:dd:ee:ff"
|
||
assert "eth1" in result
|
||
assert result["eth1"]["is_up"] is False
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# get_arp_table
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
IP_NEIGH_OUTPUT = """\
|
||
192.168.1.1 dev eth0 lladdr aa:bb:cc:dd:ee:01 REACHABLE
|
||
192.168.1.20 dev eth0 lladdr aa:bb:cc:dd:ee:02 STALE
|
||
"""
|
||
|
||
|
||
def test_get_arp_table_reports_no_age(driver):
|
||
"""`ip neigh show` says nothing about when a neighbour was last confirmed --
|
||
a STALE entry may be hours old. 0.0 would read as "just now" to a caller
|
||
that ranks sightings by freshness (NetOrk/netork#1327)."""
|
||
with patch.object(driver, "_send", return_value=IP_NEIGH_OUTPUT):
|
||
result = driver.get_arp_table()
|
||
assert [(e["ip"], e["age"]) for e in result] == [
|
||
("192.168.1.1", -1.0),
|
||
("192.168.1.20", -1.0),
|
||
]
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# get_config
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
IP_ADDR_ROUTE_WITH_VETH = """\
|
||
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
|
||
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
|
||
inet 127.0.0.1/8 scope host lo
|
||
valid_lft forever preferred_lft forever
|
||
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
|
||
link/ether aa:bb:cc:dd:ee:ff brd ff:ff:ff:ff:ff:ff
|
||
inet 192.168.1.10/24 brd 192.168.1.255 scope global dynamic eth0
|
||
valid_lft 3542sec preferred_lft 3542sec
|
||
3512: veth5d7e34d@if2: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master br-ebb930396f3b state UP group default
|
||
link/ether 02:42:ac:11:00:02 brd ff:ff:ff:ff:ff:ff link-netnsid 0
|
||
default via 192.168.1.1 dev eth0
|
||
192.168.1.0/24 dev eth0 proto kernel scope link src 192.168.1.10
|
||
"""
|
||
|
||
|
||
def test_get_config_strips_dhcp_lease_timers(driver):
|
||
with patch.object(driver, "_send", return_value=IP_ADDR_ROUTE_WITH_VETH):
|
||
result = driver.get_config()
|
||
assert "valid_lft" not in result["running"]
|
||
assert "preferred_lft" not in result["running"]
|
||
|
||
|
||
def test_get_config_strips_veth_interfaces(driver):
|
||
"""Docker creates/destroys veth pairs on every container restart — including
|
||
them would make get_config() report a false-positive change on every poll."""
|
||
with patch.object(driver, "_send", return_value=IP_ADDR_ROUTE_WITH_VETH):
|
||
result = driver.get_config()
|
||
assert "veth5d7e34d" not in result["running"]
|
||
assert "3512:" not in result["running"]
|
||
# Real interfaces and routes must survive the filter
|
||
assert "eth0" in result["running"]
|
||
assert "default via 192.168.1.1" in result["running"]
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# _parse_uptime
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def test_parse_uptime(driver):
|
||
with patch.object(driver, "_send", return_value="86400.12 1234.56"):
|
||
assert driver._parse_uptime() == 86400
|
||
|
||
|
||
def test_parse_uptime_invalid(driver):
|
||
with patch.object(driver, "_send", return_value=""):
|
||
assert driver._parse_uptime() == 0
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# get_packages (apt)
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
#: What `dpkg-query` actually returns for the format this driver asks for.
|
||
#:
|
||
#: The previous fixture carried four fields against a format string asking for
|
||
#: five, so `source_package` was silently receiving the description and no
|
||
#: assertion noticed. A fixture simpler than the data cannot fail the way the
|
||
#: data does.
|
||
APT_PKG_OUTPUT = (
|
||
"ii \topenssh-server\t1:9.2p1-2+deb12u2\t512\topenssh\t1:9.2p1-2+deb12u2"
|
||
"\tsecure shell server\n"
|
||
"ii \tcurl\t7.88.1-10+deb12u5\t1024\tcurl\t7.88.1-10+deb12u5"
|
||
"\tcommand line tool for transferring data\n"
|
||
# The shape that matters: a binary package whose own upstream version has
|
||
# nothing to do with its source package's. ldb 2.11.0 is built from samba
|
||
# 4.22.11, and OSV states Debian ranges in source versions.
|
||
"ii \tlibldb2\t2:2.11.0+samba4.22.11+dfsg-0+deb13u1\t2048\tsamba"
|
||
"\t2:4.22.11+dfsg-0+deb13u1\tLDB shared library\n"
|
||
)
|
||
|
||
#: Removed packages whose configuration dpkg still keeps (state ``rc``), next to
|
||
#: a held one and one whose postinst failed -- both still on disk (#17).
|
||
APT_PKG_STATES = (
|
||
"rc \twazuh-agent\t4.14.7-1\t\twazuh-agent\t4.14.7-1\tWazuh agent\n"
|
||
"rc \tlinux-image-6.8.0-117-generic\t6.8.0-117.117\t\tlinux-signed\t6.8.0-117.117\tSigned kernel image generic\n"
|
||
"hi \tdocker-ce\t5:28.5.1-1~debian.13~trixie\t104858\tdocker-ce\t5:28.5.1-1~debian.13~trixie\tDocker: the open-source application container engine\n"
|
||
"iU \tzabbix-agent\t1:7.0.10-1\t1550\tzabbix\t1:7.0.10-1\tZabbix network monitoring solution - agent\n"
|
||
"ii \tcurl\t8.14.1-2\t512\tcurl\t8.14.1-2\tcommand line tool for transferring data with URL syntax\n"
|
||
)
|
||
|
||
|
||
def test_get_packages_apt_reads_the_package_state(driver):
|
||
driver._pkg_manager = "apt"
|
||
with patch.object(driver, "_send", return_value=APT_PKG_STATES) as send:
|
||
driver.get_packages()
|
||
assert send.call_args[0][0].startswith("dpkg-query -W -f='${db:Status-Abbrev}\\t${Package}")
|
||
|
||
|
||
def test_get_packages_apt_leaves_out_what_only_left_its_configuration(driver):
|
||
driver._pkg_manager = "apt"
|
||
with patch.object(driver, "_send", return_value=APT_PKG_STATES):
|
||
names = [p["name"] for p in driver.get_packages()]
|
||
assert names == ["docker-ce", "zabbix-agent", "curl"]
|
||
|
||
|
||
def test_get_packages_apt(driver):
|
||
driver._pkg_manager = "apt"
|
||
with patch.object(driver, "_send", return_value=APT_PKG_OUTPUT):
|
||
pkgs = driver.get_packages()
|
||
assert len(pkgs) == 3
|
||
assert pkgs[0]["name"] == "openssh-server"
|
||
assert pkgs[0]["version"] == "1:9.2p1-2+deb12u2"
|
||
assert pkgs[0]["installed"] is True
|
||
assert pkgs[0]["source"] == "apt"
|
||
assert pkgs[0]["description"] == "secure shell server"
|
||
|
||
|
||
def test_get_packages_apt_keeps_the_source_package_and_its_version(driver):
|
||
"""OSV states Debian ranges in *source* package versions.
|
||
|
||
A consumer that matches on the source package and then compares the binary
|
||
package's version is comparing two unrelated numbers. On a Debian 13 host
|
||
that reported four Samba libraries as vulnerable to CVE-2022-44640 while
|
||
running samba 4.22.11 — five releases past the fix — because dpkg reads
|
||
ldb's own `2.11.0` as older than samba's `2:4.17.4+dfsg-1`.
|
||
|
||
The driver cannot fix the comparison, but it is the only place that can
|
||
supply the number to compare.
|
||
"""
|
||
driver._pkg_manager = "apt"
|
||
with patch.object(driver, "_send", return_value=APT_PKG_OUTPUT):
|
||
pkgs = {p["name"]: p for p in driver.get_packages()}
|
||
|
||
assert pkgs["libldb2"]["source_package"] == "samba"
|
||
assert pkgs["libldb2"]["source_version"] == "2:4.22.11+dfsg-0+deb13u1"
|
||
assert pkgs["libldb2"]["version"] == "2:2.11.0+samba4.22.11+dfsg-0+deb13u1"
|
||
assert pkgs["libldb2"]["description"] == "LDB shared library"
|
||
|
||
|
||
def test_get_packages_apt_falls_back_when_dpkg_gives_no_source(driver):
|
||
"""`source:Package` is empty for a package whose source name equals its own.
|
||
Older dpkg builds leave `source:Version` empty in that case too."""
|
||
driver._pkg_manager = "apt"
|
||
with patch.object(driver, "_send", return_value="ii \tcurl\t7.88.1-10\t1024\t\t\ttool\n"):
|
||
(pkg,) = driver.get_packages()
|
||
|
||
assert pkg["source_package"] == "curl"
|
||
assert pkg["source_version"] == "7.88.1-10"
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# get_available_updates (apt)
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
APT_UPGRADABLE = (
|
||
"Listing... Done\n"
|
||
"openssh-server/stable 1:9.2p1-2+deb12u2 amd64 [upgradable from: 1:9.2p1-2+deb12u1]\n"
|
||
"curl/stable 7.88.1-10+deb12u6 amd64 [upgradable from: 7.88.1-10+deb12u5]\n"
|
||
"__APT_RC=0\n"
|
||
)
|
||
|
||
|
||
def test_get_available_updates_apt(driver):
|
||
driver._pkg_manager = "apt"
|
||
with patch.object(driver, "_send", return_value=APT_UPGRADABLE):
|
||
updates = driver.get_available_updates()
|
||
assert len(updates) == 2
|
||
assert updates[0]["name"] == "openssh-server"
|
||
assert updates[0]["current_version"] == "1:9.2p1-2+deb12u1"
|
||
assert updates[0]["new_version"] == "1:9.2p1-2+deb12u2"
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# get_os_users
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
PASSWD_OUT = (
|
||
"root:x:0:0:root:/root:/bin/bash\n"
|
||
"admin:x:1000:1000:Admin User:/home/admin:/bin/bash\n"
|
||
"daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin\n"
|
||
)
|
||
|
||
GROUP_OUT = "sudo:x:27:admin\ndocker:x:999:admin\nadm:x:4:admin\n"
|
||
|
||
|
||
def test_get_os_users(driver):
|
||
with patch.object(driver, "_send", side_effect=[PASSWD_OUT, GROUP_OUT]):
|
||
users = driver.get_os_users()
|
||
|
||
admin = next(u for u in users if u["username"] == "admin")
|
||
assert admin["uid"] == 1000
|
||
assert admin["gid"] == 1000
|
||
assert admin["home"] == "/home/admin"
|
||
assert admin["shell"] == "/bin/bash"
|
||
assert set(admin["groups"]) == {"sudo", "docker", "adm"}
|
||
|
||
|
||
def test_get_users_is_left_to_napalm(driver):
|
||
"""napalm-device-types 4.7 renamed OSDriver.get_users to get_os_users:
|
||
NAPALM's own get_users has another shape, and this driver does not implement it."""
|
||
assert LinuxDriver.get_users is not LinuxDriver.get_os_users
|
||
with pytest.raises(NotImplementedError):
|
||
driver.get_users()
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# ping parsing
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
PING_OUTPUT = """\
|
||
PING 8.8.8.8 (8.8.8.8) 100(128) bytes of data.
|
||
108 bytes from 8.8.8.8: icmp_seq=1 ttl=118 time=12.3 ms
|
||
108 bytes from 8.8.8.8: icmp_seq=2 ttl=118 time=11.9 ms
|
||
108 bytes from 8.8.8.8: icmp_seq=3 ttl=118 time=12.1 ms
|
||
|
||
--- 8.8.8.8 ping statistics ---
|
||
3 packets transmitted, 3 received, 0% packet loss, time 2003ms
|
||
rtt min/avg/max/mdev = 11.900/12.100/12.300/0.163 ms
|
||
"""
|
||
|
||
|
||
def test_ping_parses_output(driver):
|
||
with patch.object(driver, "_send", return_value=PING_OUTPUT):
|
||
result = driver.ping("8.8.8.8", count=3)
|
||
assert "success" in result
|
||
assert result["success"]["probes_sent"] == 3
|
||
assert result["success"]["packet_loss"] == 0
|
||
assert result["success"]["rtt_avg"] == pytest.approx(12.1)
|
||
|
||
|
||
#: BusyBox ping (Alpine 3.22), IPv4: "packets received", "seq=", no mdev (#15).
|
||
PING_BUSYBOX = """\
|
||
PING 192.0.2.1 (192.0.2.1): 100 data bytes
|
||
108 bytes from 192.0.2.1: seq=0 ttl=64 time=0.412 ms
|
||
108 bytes from 192.0.2.1: seq=1 ttl=64 time=0.388 ms
|
||
|
||
--- 192.0.2.1 ping statistics ---
|
||
2 packets transmitted, 2 packets received, 0% packet loss
|
||
round-trip min/avg/max = 0.388/0.400/0.412 ms
|
||
"""
|
||
|
||
#: BusyBox ping, IPv6 link-local.
|
||
PING_BUSYBOX_V6 = """\
|
||
PING fe80::1%eth0 (fe80::1%eth0): 100 data bytes
|
||
108 bytes from fe80::1%eth0: seq=0 ttl=64 time=0.511 ms
|
||
|
||
--- fe80::1%eth0 ping statistics ---
|
||
2 packets transmitted, 1 packets received, 50% packet loss
|
||
round-trip min/avg/max = 0.511/0.511/0.511 ms
|
||
"""
|
||
|
||
#: iputils ping (Debian 13), IPv6.
|
||
PING_IPUTILS_V6 = """\
|
||
PING 2001:db8::53 (2001:db8::53) 100 data bytes
|
||
108 bytes from 2001:db8::53: icmp_seq=1 ttl=58 time=10.5 ms
|
||
108 bytes from 2001:db8::53: icmp_seq=2 ttl=58 time=10.9 ms
|
||
|
||
--- 2001:db8::53 ping statistics ---
|
||
2 packets transmitted, 2 received, 0% packet loss, time 1002ms
|
||
rtt min/avg/max/mdev = 10.500/10.700/10.900/0.200 ms
|
||
"""
|
||
|
||
#: iputils ping to a name: the reply names the host, the address in brackets;
|
||
#: unreachable probes add an "errors" field to the summary.
|
||
PING_IPUTILS_NAME = """\
|
||
PING gw.example.net (192.0.2.1) 100(128) bytes of data.
|
||
108 bytes from gw.example.net (192.0.2.1): icmp_seq=1 ttl=64 time=0.301 ms
|
||
From 192.0.2.254 icmp_seq=2 Destination Host Unreachable
|
||
|
||
--- gw.example.net ping statistics ---
|
||
2 packets transmitted, 1 received, +1 errors, 50% packet loss, time 1001ms
|
||
rtt min/avg/max/mdev = 0.301/0.301/0.301/0.000 ms
|
||
"""
|
||
|
||
|
||
class TestPingFormats:
|
||
"""``ping`` reads BusyBox's and iputils' output, IPv4 and IPv6 (#15)."""
|
||
|
||
def _ping(self, driver, output):
|
||
with patch.object(driver, "_send", return_value=output):
|
||
return driver.ping("192.0.2.1", count=2)["success"]
|
||
|
||
def test_busybox_summary_and_rtt(self, driver):
|
||
reply = self._ping(driver, PING_BUSYBOX)
|
||
|
||
assert (reply["probes_sent"], reply["packet_loss"]) == (2, 0)
|
||
assert (reply["rtt_min"], reply["rtt_avg"], reply["rtt_max"]) == (0.388, 0.4, 0.412)
|
||
assert reply["rtt_stddev"] == 0.0
|
||
|
||
def test_busybox_probes(self, driver):
|
||
reply = self._ping(driver, PING_BUSYBOX)
|
||
|
||
assert reply["results"] == [
|
||
{"ip_address": "192.0.2.1", "rtt": 0.412},
|
||
{"ip_address": "192.0.2.1", "rtt": 0.388},
|
||
]
|
||
|
||
def test_busybox_ipv6(self, driver):
|
||
reply = self._ping(driver, PING_BUSYBOX_V6)
|
||
|
||
assert (reply["probes_sent"], reply["packet_loss"]) == (2, 1)
|
||
assert reply["results"] == [{"ip_address": "fe80::1%eth0", "rtt": 0.511}]
|
||
|
||
def test_iputils_ipv6(self, driver):
|
||
reply = self._ping(driver, PING_IPUTILS_V6)
|
||
|
||
assert reply["results"] == [
|
||
{"ip_address": "2001:db8::53", "rtt": 10.5},
|
||
{"ip_address": "2001:db8::53", "rtt": 10.9},
|
||
]
|
||
assert (reply["rtt_avg"], reply["rtt_stddev"]) == (10.7, 0.2)
|
||
|
||
def test_iputils_to_a_name_with_errors(self, driver):
|
||
reply = self._ping(driver, PING_IPUTILS_NAME)
|
||
|
||
assert (reply["probes_sent"], reply["packet_loss"]) == (2, 1)
|
||
assert reply["results"] == [{"ip_address": "192.0.2.1", "rtt": 0.301}]
|
||
|
||
def test_no_summary_is_an_error(self, driver):
|
||
with patch.object(driver, "_send", return_value="ping: unknown host nosuch"):
|
||
assert driver.ping("nosuch") == {"error": "ping: unknown host nosuch"}
|
||
|
||
|
||
class TestPingArguments:
|
||
"""``ping`` types its arguments into a shell: each one stays one word (#55)."""
|
||
|
||
def _sent(self, driver, *args, **kwargs):
|
||
with patch.object(driver, "_send", return_value=PING_OUTPUT) as send:
|
||
driver.ping(*args, **kwargs)
|
||
return send.call_args[0][0]
|
||
|
||
def test_the_destination_is_one_quoted_word(self, driver):
|
||
sent = self._sent(driver, "1.2.3.4; id")
|
||
|
||
assert sent == "ping -c 5 -W 2 -s 100 -t 255 '1.2.3.4; id' 2>&1"
|
||
|
||
def test_the_source_is_one_quoted_word(self, driver):
|
||
sent = self._sent(driver, "192.0.2.1", source="$(id)")
|
||
|
||
assert sent == "ping -c 5 -W 2 -s 100 -t 255 -I '$(id)' 192.0.2.1 2>&1"
|
||
|
||
def test_the_numbers_are_numbers(self, driver):
|
||
sent = self._sent(driver, "192.0.2.1", count="3", timeout=1.0, size="56", ttl=64)
|
||
|
||
assert sent == "ping -c 3 -W 1 -s 56 -t 64 192.0.2.1 2>&1"
|
||
|
||
@pytest.mark.parametrize(
|
||
("destination", "source"), [("-f", ""), ("192.0.2.1", "-f"), ("-p ff", "")]
|
||
)
|
||
def test_an_option_in_place_of_a_name_is_refused_before_anything_is_sent(
|
||
self, driver, destination, source
|
||
):
|
||
"""Quoting keeps a word one word, and ping still reads ``-f`` as its option (#63)."""
|
||
with patch.object(driver, "_send") as send, pytest.raises(ValueError, match="option"):
|
||
driver.ping(destination, source=source)
|
||
|
||
send.assert_not_called()
|
||
|
||
def test_a_number_that_is_not_one_is_refused_before_anything_is_sent(self, driver):
|
||
with patch.object(driver, "_send") as send, pytest.raises(ValueError):
|
||
driver.ping("192.0.2.1", count="5; id")
|
||
|
||
send.assert_not_called()
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# apply_updates – input validation
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
class TestApplyUpdatesValidation:
|
||
def test_valid_package_names_accepted(self, driver):
|
||
driver._pkg_manager = "apt"
|
||
apt_output = "Reading package lists... Done\nThe following packages will be upgraded:\n openssh-server\n1 upgraded."
|
||
with patch.object(driver, "_send", return_value=apt_output):
|
||
result = driver.apply_updates(["openssh-server", "curl", "lib32-foo+bar.so"])
|
||
assert result["success"] is True
|
||
|
||
def test_invalid_package_name_raises(self, driver):
|
||
with pytest.raises(ValueError, match="Invalid package name"):
|
||
driver.apply_updates(["open;ssh"])
|
||
|
||
def test_shell_injection_blocked(self, driver):
|
||
with pytest.raises(ValueError, match="Invalid package name"):
|
||
driver.apply_updates(["pkg && rm -rf /"])
|
||
|
||
def test_space_in_name_blocked(self, driver):
|
||
with pytest.raises(ValueError, match="Invalid package name"):
|
||
driver.apply_updates(["my package"])
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# apply_updates – apt
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
APT_UPGRADE_SUCCESS = (
|
||
"Reading package lists... Done\n"
|
||
"Building dependency tree... Done\n"
|
||
"The following packages will be upgraded:\n"
|
||
" openssh-server\n"
|
||
"1 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.\n"
|
||
)
|
||
|
||
APT_UPGRADE_ERROR = (
|
||
"Reading package lists... Done\n"
|
||
"E: Unable to lock the administration directory (/var/lib/dpkg/), "
|
||
"is another process using it?\n"
|
||
)
|
||
|
||
|
||
def test_apply_updates_apt_success(driver):
|
||
driver._pkg_manager = "apt"
|
||
with patch.object(driver, "_send", return_value=APT_UPGRADE_SUCCESS):
|
||
result = driver.apply_updates(["openssh-server"])
|
||
assert result["success"] is True
|
||
assert "openssh-server" in result["output"]
|
||
assert "error" not in result
|
||
|
||
|
||
def test_apply_updates_apt_error(driver):
|
||
driver._pkg_manager = "apt"
|
||
with patch.object(driver, "_send", return_value=APT_UPGRADE_ERROR):
|
||
result = driver.apply_updates(["openssh-server"])
|
||
assert result["success"] is False
|
||
assert "error" in result
|
||
assert result["error"].startswith("E:")
|
||
|
||
|
||
def test_apply_updates_apt_all_packages(driver):
|
||
"""Empty list should upgrade everything (no package name args)."""
|
||
driver._pkg_manager = "apt"
|
||
sent_commands = []
|
||
|
||
def capture_send(cmd, **kwargs):
|
||
# _sudo() passes read_timeout as a keyword; without **kwargs this raises
|
||
# TypeError, which the caller's `except Exception` reports as a failed
|
||
# upgrade rather than a broken test double.
|
||
sent_commands.append(cmd)
|
||
return APT_UPGRADE_SUCCESS
|
||
|
||
with patch.object(driver, "_send", side_effect=capture_send):
|
||
result = driver.apply_updates([])
|
||
|
||
assert result["success"] is True
|
||
# Should use 'apt-get upgrade' without specific package args
|
||
assert any("upgrade" in cmd and "install" not in cmd for cmd in sent_commands)
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# apply_updates – dnf
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
DNF_UPGRADE_SUCCESS = (
|
||
"Last metadata expiration check: 0:01:23 ago.\n"
|
||
"Dependencies resolved.\n"
|
||
"Upgraded:\n openssh-server-9.4p1-1.el9.x86_64\n"
|
||
"Complete!\n"
|
||
)
|
||
|
||
DNF_UPGRADE_ERROR = (
|
||
"Last metadata expiration check: 0:01:23 ago.\nError: No match for argument: nonexistent-pkg\n"
|
||
)
|
||
|
||
|
||
def test_apply_updates_dnf_success(driver):
|
||
driver._pkg_manager = "dnf"
|
||
with patch.object(driver, "_send", return_value=DNF_UPGRADE_SUCCESS):
|
||
result = driver.apply_updates(["openssh-server"])
|
||
assert result["success"] is True
|
||
|
||
|
||
def test_apply_updates_dnf_error(driver):
|
||
driver._pkg_manager = "dnf"
|
||
with patch.object(driver, "_send", return_value=DNF_UPGRADE_ERROR):
|
||
result = driver.apply_updates(["nonexistent-pkg"])
|
||
assert result["success"] is False
|
||
assert "error" in result
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# apply_updates – exception path
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def test_apply_updates_ssh_exception_returns_failure(driver):
|
||
driver._pkg_manager = "apt"
|
||
with patch.object(driver, "_send", side_effect=RuntimeError("SSH timeout")):
|
||
result = driver.apply_updates(["curl"])
|
||
assert result["success"] is False
|
||
assert "SSH timeout" in result.get("error", "")
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# apply_updates – unsupported package manager
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def test_apply_updates_unsupported_pm_raises(driver):
|
||
driver._pkg_manager = "zypper"
|
||
with pytest.raises(NotImplementedError):
|
||
driver.apply_updates(["curl"])
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# TYPE_LABEL
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def test_type_label_is_linux():
|
||
assert LinuxDriver.TYPE_LABEL == "Linux"
|
||
|
||
|
||
def test_type_label_overrides_os_driver():
|
||
from napalm_device_types import OSDriver
|
||
|
||
assert OSDriver.TYPE_LABEL == "OS"
|
||
assert LinuxDriver.TYPE_LABEL != OSDriver.TYPE_LABEL
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# _collect_platform_info
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def _dmi_output(
|
||
sys_vendor: str,
|
||
product_name: str,
|
||
product_version: str,
|
||
product_serial: str,
|
||
product_uuid: str,
|
||
detect_virt: str,
|
||
dt_model: str = "",
|
||
cpuinfo_serial: str = "",
|
||
cpuinfo_model: str = "",
|
||
) -> str:
|
||
# Mirrors the real shell output: DMIBEGIN sentinel followed by 9 fields.
|
||
# The sentinel prevents _send()'s .strip() from eating leading blank lines
|
||
# (which occur on ARM where all DMI files are absent).
|
||
return "\n".join(
|
||
[
|
||
"DMIBEGIN",
|
||
sys_vendor,
|
||
product_name,
|
||
product_version,
|
||
product_serial,
|
||
product_uuid,
|
||
detect_virt,
|
||
dt_model,
|
||
cpuinfo_serial,
|
||
cpuinfo_model,
|
||
]
|
||
)
|
||
|
||
|
||
class TestCollectPlatformInfo:
|
||
def test_baremetal_dell(self, driver):
|
||
raw = _dmi_output(
|
||
"Dell Inc.",
|
||
"PowerEdge R720",
|
||
"Not Specified",
|
||
"ABC123",
|
||
"8a2e3f00-dead-beef-0000-123456789abc",
|
||
"none",
|
||
)
|
||
with patch.object(driver, "_send", return_value=raw):
|
||
info = driver._collect_platform_info()
|
||
assert info["vendor"] == "Dell Inc."
|
||
assert info["model"] == "PowerEdge R720"
|
||
assert info["serial"] == "ABC123"
|
||
assert info["is_vm"] is False
|
||
|
||
def test_baremetal_lenovo_product_version_preferred(self, driver):
|
||
raw = _dmi_output(
|
||
"LENOVO",
|
||
"10M8000VUS",
|
||
"ThinkCentre M910x",
|
||
"MP1234",
|
||
"8a2e3f00-dead-beef-0000-123456789abc",
|
||
"none",
|
||
)
|
||
with patch.object(driver, "_send", return_value=raw):
|
||
info = driver._collect_platform_info()
|
||
assert info["vendor"] == "LENOVO"
|
||
assert info["model"] == "ThinkCentre M910x"
|
||
assert info["serial"] == "MP1234"
|
||
assert info["is_vm"] is False
|
||
|
||
def test_vm_kvm(self, driver):
|
||
raw = _dmi_output(
|
||
"QEMU",
|
||
"Standard PC (i440FX + PIIX, 1996)",
|
||
"pc-i440fx-9.1",
|
||
"",
|
||
"4c4c4544-0000-2010-8020-b4c04f534a31",
|
||
"kvm",
|
||
)
|
||
with patch.object(driver, "_send", return_value=raw):
|
||
info = driver._collect_platform_info()
|
||
assert info["vendor"] == "KVM"
|
||
assert info["model"] == "Virtual Machine"
|
||
assert info["serial"] == "4c4c4544-0000-2010-8020-b4c04f534a31"
|
||
assert info["is_vm"] is True
|
||
|
||
def test_vm_vmware(self, driver):
|
||
raw = _dmi_output(
|
||
"VMware, Inc.",
|
||
"VMware Virtual Platform",
|
||
"None",
|
||
"VMware-42 12 34 56",
|
||
"4244560c-dead-beef-0000-abcdef123456",
|
||
"vmware",
|
||
)
|
||
with patch.object(driver, "_send", return_value=raw):
|
||
info = driver._collect_platform_info()
|
||
assert info["vendor"] == "VMware ESXi"
|
||
assert info["model"] == "Virtual Machine"
|
||
assert info["serial"] == "VMware-42 12 34 56"
|
||
assert info["is_vm"] is True
|
||
|
||
def test_vm_hyperv(self, driver):
|
||
raw = _dmi_output(
|
||
"Microsoft Corporation",
|
||
"Virtual Machine",
|
||
"Hyper-V UEFI Release v4.1",
|
||
"",
|
||
"7C5B4B1F-1234-5678-ABCD-000000000001",
|
||
"microsoft",
|
||
)
|
||
with patch.object(driver, "_send", return_value=raw):
|
||
info = driver._collect_platform_info()
|
||
assert info["vendor"] == "Microsoft Hyper-V"
|
||
assert info["model"] == "Virtual Machine"
|
||
assert info["serial"] == "7C5B4B1F-1234-5678-ABCD-000000000001"
|
||
assert info["is_vm"] is True
|
||
|
||
def test_junk_dmi_values_filtered(self, driver):
|
||
raw = _dmi_output(
|
||
"To Be Filled By O.E.M.",
|
||
"To Be Filled By O.E.M.",
|
||
"Not Specified",
|
||
"To Be Filled By O.E.M.",
|
||
"",
|
||
"none",
|
||
)
|
||
with patch.object(driver, "_send", return_value=raw):
|
||
info = driver._collect_platform_info()
|
||
assert info["vendor"] == ""
|
||
assert info["model"] == ""
|
||
assert info["is_vm"] is False
|
||
|
||
def test_vm_kvm_fallback_via_dmi_when_detect_virt_unavailable(self, driver):
|
||
# systemd-detect-virt returns "none" (not installed), sys_vendor reveals QEMU
|
||
raw = _dmi_output(
|
||
"QEMU",
|
||
"Standard PC (i440FX + PIIX, 1996)",
|
||
"",
|
||
"",
|
||
"4c4c4544-0000-2010-8020-b4c04f534a31",
|
||
"none",
|
||
)
|
||
with patch.object(driver, "_send", return_value=raw):
|
||
info = driver._collect_platform_info()
|
||
assert info["is_vm"] is True
|
||
assert info["vendor"] == "KVM"
|
||
assert info["model"] == "Virtual Machine"
|
||
|
||
def test_container_docker(self, driver):
|
||
raw = _dmi_output(
|
||
"QEMU",
|
||
"Standard PC (i440FX + PIIX, 1996)",
|
||
"",
|
||
"",
|
||
"4c4c4544-0000-2010-8020-b4c04f534a31",
|
||
"docker",
|
||
)
|
||
with patch.object(driver, "_send", return_value=raw):
|
||
info = driver._collect_platform_info()
|
||
assert info["vendor"] == "Docker"
|
||
assert info["model"] == "Container"
|
||
assert info["is_vm"] is True
|
||
|
||
def test_container_lxc(self, driver):
|
||
raw = _dmi_output("", "", "", "", "", "lxc")
|
||
with patch.object(driver, "_send", return_value=raw):
|
||
info = driver._collect_platform_info()
|
||
assert info["vendor"] == "LXC"
|
||
assert info["model"] == "Container"
|
||
assert info["is_vm"] is True
|
||
|
||
def test_ssh_failure_returns_safe_defaults(self, driver):
|
||
with patch.object(driver, "_send", side_effect=Exception("SSH error")):
|
||
info = driver._collect_platform_info()
|
||
assert info["vendor"] == ""
|
||
assert info["model"] == ""
|
||
assert info["is_vm"] is False
|
||
|
||
def test_arm_device_tree_fallback(self, driver):
|
||
raw = _dmi_output(
|
||
"",
|
||
"",
|
||
"",
|
||
"",
|
||
"",
|
||
"none",
|
||
dt_model="Raspberry Pi 4 Model B Rev 1.4",
|
||
cpuinfo_serial="100000002a6d96dc",
|
||
cpuinfo_model="Raspberry Pi 4 Model B Rev 1.4",
|
||
)
|
||
with patch.object(driver, "_send", return_value=raw):
|
||
info = driver._collect_platform_info()
|
||
assert info["vendor"] == "Raspberry Pi Foundation"
|
||
assert info["model"] == "Raspberry Pi 4 Model B Rev 1.4"
|
||
assert info["serial"] == "100000002a6d96dc"
|
||
assert info["is_vm"] is False
|
||
|
||
def test_arm_cpuinfo_model_when_no_dt(self, driver):
|
||
raw = _dmi_output(
|
||
"",
|
||
"",
|
||
"",
|
||
"",
|
||
"",
|
||
"none",
|
||
dt_model="",
|
||
cpuinfo_serial="0000000012345678",
|
||
cpuinfo_model="Raspberry Pi 3 Model B Plus Rev 1.3",
|
||
)
|
||
with patch.object(driver, "_send", return_value=raw):
|
||
info = driver._collect_platform_info()
|
||
assert info["vendor"] == "Raspberry Pi Foundation"
|
||
assert info["model"] == "Raspberry Pi 3 Model B Plus Rev 1.3"
|
||
assert info["serial"] == "0000000012345678"
|
||
assert info["is_vm"] is False
|
||
|
||
def test_arm_no_fallback_data_returns_empty(self, driver):
|
||
raw = _dmi_output("", "", "", "", "", "none")
|
||
with patch.object(driver, "_send", return_value=raw):
|
||
info = driver._collect_platform_info()
|
||
assert info["vendor"] == ""
|
||
assert info["model"] == ""
|
||
assert info["is_vm"] is False
|
||
|
||
def test_bare_metal_detect_virt_exit1_does_not_shift_arm_fields(self, driver):
|
||
# systemd-detect-virt exits 1 on bare metal, old "|| echo none" caused
|
||
# d="none\nnone" which shifted subsequent lines off by one.
|
||
# With the ${d:-none} fix this no longer happens.
|
||
raw = _dmi_output(
|
||
"",
|
||
"",
|
||
"",
|
||
"",
|
||
"",
|
||
"none",
|
||
dt_model="",
|
||
cpuinfo_serial="0000000012345678",
|
||
cpuinfo_model="Raspberry Pi 3 Model B Rev 1.2",
|
||
)
|
||
with patch.object(driver, "_send", return_value=raw):
|
||
info = driver._collect_platform_info()
|
||
assert info["vendor"] == "Raspberry Pi Foundation"
|
||
assert info["model"] == "Raspberry Pi 3 Model B Rev 1.2"
|
||
assert info["serial"] == "0000000012345678"
|
||
|
||
def test_arm_fallback_ignored_when_dmi_present(self, driver):
|
||
raw = _dmi_output(
|
||
"Dell Inc.",
|
||
"PowerEdge R720",
|
||
"Not Specified",
|
||
"XYZ999",
|
||
"8a2e3f00-dead-beef-0000-123456789abc",
|
||
"none",
|
||
dt_model="some-dt-model",
|
||
cpuinfo_serial="deadbeef",
|
||
cpuinfo_model="some cpuinfo model",
|
||
)
|
||
with patch.object(driver, "_send", return_value=raw):
|
||
info = driver._collect_platform_info()
|
||
assert info["vendor"] == "Dell Inc."
|
||
assert info["model"] == "PowerEdge R720"
|
||
assert info["serial"] == "XYZ999"
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# _arm_vendor_from_model
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
"model,expected",
|
||
[
|
||
("Raspberry Pi 4 Model B Rev 1.4", "Raspberry Pi Foundation"),
|
||
("Raspberry Pi 3 Model B Rev 1.2", "Raspberry Pi Foundation"),
|
||
("ODROID-N2L", "Hardkernel"),
|
||
("NVIDIA Jetson Nano Developer Kit", "NVIDIA"),
|
||
("Rock Pi 4C", "Radxa"),
|
||
("Orange Pi 5 Plus", "Xunlong Software"),
|
||
("Banana Pi BPI-R3", "SinoVoip"),
|
||
("NanoPi R4S", "FriendlyElec"),
|
||
("PINE64 RockPro64", "Pine64"),
|
||
("BeagleBone Black", "BeagleBoard.org"),
|
||
("Unknown Board 1.0", "Unknown Board"),
|
||
("SomeSingleWordBoard", "SomeSingleWordBoard"),
|
||
],
|
||
)
|
||
def test_arm_vendor_from_model(model, expected):
|
||
assert _arm_vendor_from_model(model) == expected
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# get_facts uses _collect_platform_info
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def test_get_facts_baremetal_vendor_model_serial(driver):
|
||
platform = {
|
||
"vendor": "Dell Inc.",
|
||
"model": "PowerEdge R720",
|
||
"serial": "ABC123",
|
||
"is_vm": False,
|
||
}
|
||
with (
|
||
patch.object(driver, "_collect_platform_info", return_value=platform),
|
||
patch.object(driver, "_parse_uptime", return_value=86400),
|
||
patch.object(
|
||
driver,
|
||
"_send",
|
||
side_effect=[
|
||
"myhost",
|
||
"myhost.example.com",
|
||
"Debian GNU/Linux 12",
|
||
"eth0\neth1",
|
||
"6.1.0-18-amd64",
|
||
],
|
||
),
|
||
):
|
||
facts = driver.get_facts()
|
||
assert facts["vendor"] == "Dell Inc."
|
||
assert facts["model"] == "PowerEdge R720"
|
||
assert facts["serial_number"] == "ABC123"
|
||
assert facts["hostname"] == "myhost"
|
||
assert facts["uptime"] == 86400
|
||
# Booted kernel, not the newest installed one — kernel CVE relevance needs it.
|
||
assert facts["running_kernel"] == "6.1.0-18-amd64"
|
||
|
||
|
||
def test_get_facts_vm_kvm(driver):
|
||
platform = {
|
||
"vendor": "KVM",
|
||
"model": "Virtual Machine",
|
||
"serial": "4c4c4544-0000-2010-8020-b4c04f534a31",
|
||
"is_vm": True,
|
||
}
|
||
with (
|
||
patch.object(driver, "_collect_platform_info", return_value=platform),
|
||
patch.object(driver, "_parse_uptime", return_value=3600),
|
||
patch.object(
|
||
driver,
|
||
"_send",
|
||
side_effect=["vmhost", "vmhost.local", "Ubuntu 22.04 LTS", "eth0", "5.15.0-91-generic"],
|
||
),
|
||
):
|
||
facts = driver.get_facts()
|
||
assert facts["vendor"] == "KVM"
|
||
assert facts["model"] == "Virtual Machine"
|
||
assert facts["serial_number"] == "4c4c4544-0000-2010-8020-b4c04f534a31"
|
||
|
||
|
||
def test_get_facts_fallback_vendor_when_dmi_empty(driver):
|
||
platform = {"vendor": "", "model": "", "serial": "", "is_vm": False}
|
||
with (
|
||
patch.object(driver, "_collect_platform_info", return_value=platform),
|
||
patch.object(driver, "_parse_uptime", return_value=0),
|
||
patch.object(
|
||
driver,
|
||
"_send",
|
||
side_effect=["host", "host.local", "Alpine Linux 3.19", "eth0", "6.6.7-0-lts"],
|
||
),
|
||
):
|
||
facts = driver.get_facts()
|
||
assert facts["vendor"] == "Linux" # fallback to VENDOR class attribute
|
||
|
||
|
||
class TestNoDockerOfItsOwn:
|
||
"""Containers are read and handled by netOrk over the Engine API, through
|
||
``open_container_engine`` (NetOrk/netork#765). The old CLI methods are gone;
|
||
only the fix that lets the login user use Docker stays."""
|
||
|
||
def test_the_cli_methods_are_gone(self):
|
||
for name in (
|
||
"get_docker_info",
|
||
"get_docker_outdated",
|
||
"reconstruct_docker_run",
|
||
"_docker_bin",
|
||
):
|
||
assert not hasattr(LinuxDriver, name), name
|
||
|
||
def test_the_engine_access_and_the_permission_fix_stay(self):
|
||
assert hasattr(LinuxDriver, "open_container_engine")
|
||
assert callable(LinuxDriver.grant_container_engine_access)
|
||
|
||
|
||
class TestUninstallPackage:
|
||
"""Removing a package that does not want to go.
|
||
|
||
Both cases here were found during a fleet-wide Wazuh rollback. Of thirteen
|
||
hosts carrying the agent, seven sat at `install ok unpacked` with the unit
|
||
failed — an upgrade whose postinst could not reach a manager that no longer
|
||
existed. `apt-get remove` cannot help there: apt configures a package before
|
||
removing it, and configuring is exactly what was broken.
|
||
|
||
And `remove` leaves the configuration behind by design, which for the Wazuh
|
||
agent means its apt source keeps being fetched on every update, long after
|
||
the package is gone.
|
||
"""
|
||
|
||
def test_remove_is_still_the_default(self, driver):
|
||
"""Callers that did not ask for a purge must not get one: configuration
|
||
somebody may want back is not this function's to delete."""
|
||
_mock_send(driver, "Removing wazuh-agent ...")
|
||
|
||
driver.uninstall_package("wazuh-agent")
|
||
|
||
sent = driver._device.send_command.call_args[0][0]
|
||
assert "apt-get remove" in sent
|
||
assert "purge" not in sent
|
||
|
||
def test_purge_is_asked_for_explicitly(self, driver):
|
||
_mock_send(driver, "Purging configuration files for wazuh-agent ...")
|
||
|
||
driver.uninstall_package("wazuh-agent", purge=True)
|
||
|
||
assert "apt-get purge" in driver._device.send_command.call_args[0][0]
|
||
|
||
def test_a_half_configured_package_falls_back_to_dpkg(self, driver):
|
||
"""`install ok unpacked` is the state apt cannot get out of. On one host
|
||
only `dpkg --purge --force-all` removed it."""
|
||
driver._root = False
|
||
driver._device.send_command.side_effect = [
|
||
_with_rc("E: Sub-process /usr/bin/dpkg returned an error code (1)", 100),
|
||
_with_rc("Removing wazuh-agent (4.14.7-1) ...", 0),
|
||
]
|
||
|
||
result = driver.uninstall_package("wazuh-agent", purge=True)
|
||
|
||
assert result["success"] is True
|
||
second = driver._device.send_command.call_args_list[1][0][0]
|
||
assert "dpkg --purge --force-all" in second
|
||
|
||
def test_the_fallback_is_not_tried_when_the_first_pass_worked(self, driver):
|
||
"""A forced dpkg purge is a bigger hammer than apt and must stay a last
|
||
resort, not a routine second step."""
|
||
driver._root = False
|
||
_mock_send(driver, "Removing wazuh-agent ...")
|
||
|
||
driver.uninstall_package("wazuh-agent", purge=True)
|
||
|
||
assert driver._device.send_command.call_count == 1
|
||
|
||
def test_a_package_manager_without_purge_still_removes(self, driver):
|
||
"""apk and pacman have no separate purge; asking for one must not turn
|
||
into a failure or a command they do not understand."""
|
||
driver._pkg_manager = "apk"
|
||
_mock_send(driver, "(1/1) Purging wazuh-agent")
|
||
|
||
result = driver.uninstall_package("wazuh-agent", purge=True)
|
||
|
||
assert result["success"] is True
|
||
assert "apk del" in driver._device.send_command.call_args[0][0]
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# uninstall_package – success from the exit status, not from prose (netork#267)
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def _with_rc(output: str, rc: int) -> str:
|
||
"""What the shell prints for a command run through ``_sudo_status``."""
|
||
return f"{output}\n__NETORK_RC={rc}"
|
||
|
||
|
||
class TestSudoStatus:
|
||
"""``_sudo_status`` keeps the exit status that ``|| true`` throws away."""
|
||
|
||
def test_returns_output_and_exit_status(self, driver):
|
||
_mock_send(driver, _with_rc("Removing wazuh-agent ...", 0))
|
||
|
||
assert driver._sudo_status("apt-get remove -y wazuh-agent") == (
|
||
"Removing wazuh-agent ...",
|
||
0,
|
||
)
|
||
|
||
def test_a_non_zero_exit_status_is_reported(self, driver):
|
||
_mock_send(driver, _with_rc("E: Unable to locate package nope", 100))
|
||
|
||
assert driver._sudo_status("apt-get remove -y nope")[1] == 100
|
||
|
||
def test_the_command_keeps_its_own_exit_status(self, driver):
|
||
"""The exec channel reports the status (#1039): no ``|| true`` and no
|
||
marker in between, and no password in the line."""
|
||
driver._root = False
|
||
driver._sudo_password = "s3cret" # noqa: S105
|
||
_mock_send(driver, _with_rc("", 0))
|
||
|
||
driver._sudo_status("apt-get remove -y x 2>&1")
|
||
|
||
sent = driver._device.send_command.call_args[0][0]
|
||
assert sent.startswith("sudo -S -p '' sh -c ")
|
||
assert "apt-get remove -y x 2>&1" in sent
|
||
assert "|| true" not in sent
|
||
assert "__NETORK_RC" not in sent
|
||
|
||
def test_a_channel_closed_without_a_status_means_unknown_not_success(self, driver):
|
||
"""paramiko's -1 says nothing about the exit status; ``None`` says so
|
||
instead of guessing 0."""
|
||
_mock_send(driver, _with_rc("Removing wazuh-agent ...", -1))
|
||
|
||
assert driver._sudo_status("apt-get remove -y wazuh-agent") == (
|
||
"Removing wazuh-agent ...",
|
||
None,
|
||
)
|
||
|
||
def test_the_command_echo_is_not_mistaken_for_the_marker(self, driver):
|
||
"""A terminal may echo the command line back; its literal ``$?`` is not
|
||
a number, and only the marker on a line of its own counts."""
|
||
_mock_send(
|
||
driver,
|
||
"sudo apt-get remove -y x; echo __NETORK_RC=$?\nRemoving x ...\n__NETORK_RC=1",
|
||
)
|
||
|
||
output, rc = driver._sudo_status("apt-get remove -y x")
|
||
|
||
assert rc == 1
|
||
assert "__NETORK_RC=1" not in output
|
||
|
||
|
||
class _Channel:
|
||
"""A netmiko connection that hands out its output in chunks and stops where
|
||
netmiko does: at the first chunk after which ``expect_string`` matches all
|
||
that was read so far."""
|
||
|
||
def __init__(self, chunks):
|
||
self.chunks = list(chunks)
|
||
self.patterns: list = []
|
||
|
||
def send_command(self, command, *, expect_string, **_kwargs):
|
||
self.patterns.append(expect_string)
|
||
output = ""
|
||
while self.chunks:
|
||
output += self.chunks.pop(0)
|
||
if re.search(expect_string, output):
|
||
return output
|
||
raise TimeoutError(f"pattern not detected: {expect_string!r}")
|
||
|
||
|
||
#: What vault-01 sent on 2026-10-06 while its apt proxy served a corrupted
|
||
#: InRelease: the signature line ends in ">", which looks like a prompt (#615).
|
||
_BADSIG_CHUNKS = [
|
||
"sudo -n apt-get update -q 2>&1; echo __NETORK_RC=$?\n",
|
||
"Fehl:2 http://archive.ubuntu.com/ubuntu noble-updates InRelease\n"
|
||
" Die folgenden Signaturen waren ungültig: BADSIG 871920D1991BC93C "
|
||
"Ubuntu Archive Automatic Signing Key (2018) <ftpmaster@ubuntu.com>\n",
|
||
"W: Fehler beim Holen von http://archive.ubuntu.com/ubuntu/dists/noble-updates/InRelease\n"
|
||
"E: Das Depot ist nicht signiert.\n__NETORK_RC=100\n",
|
||
"chris@vault-01:~$ ",
|
||
]
|
||
|
||
|
||
_TRUE_WITH_STATUS = "true; echo __NETORK_RC=$?"
|
||
|
||
|
||
class TestReadToTheEnd:
|
||
"""A line the command prints can end in ``>``, ``#`` or ``$`` -- apt's
|
||
``<ftpmaster@ubuntu.com>`` after a bad signature. Taken for the prompt, it
|
||
ended the read while the command still ran, and the rest arrived as the next
|
||
command's output (#615). A command that echoes its exit status is read until
|
||
that marker and the prompt after it."""
|
||
|
||
def test_a_signature_line_does_not_end_the_refresh(self, driver):
|
||
driver._root = False
|
||
driver._device = _Channel(_BADSIG_CHUNKS)
|
||
|
||
result = driver.refresh_available_updates()
|
||
|
||
assert result["success"] is False
|
||
assert "E: Das Depot ist nicht signiert." in result["output"]
|
||
|
||
def test_the_session_stays_in_step(self, driver):
|
||
"""Everything up to the prompt is consumed, so the next command reads its own output."""
|
||
driver._root = False
|
||
driver._device = _Channel(_BADSIG_CHUNKS + ["true\n", "__NETORK_RC=0\nchris@vault-01:~$ "])
|
||
|
||
driver.refresh_available_updates()
|
||
output, status = _split_status(driver._send(_TRUE_WITH_STATUS))
|
||
|
||
assert status == 0
|
||
assert "BADSIG" not in output
|
||
|
||
def test_the_echoed_command_does_not_count_as_the_marker(self, driver):
|
||
"""Its literal ``$?`` is no number."""
|
||
channel = _Channel(
|
||
["sudo true; echo __NETORK_RC=$?\n", "__NETORK_RC=0\nchris@vault-01:~$ "]
|
||
)
|
||
driver._device = channel
|
||
|
||
assert _split_status(driver._send(_TRUE_WITH_STATUS))[1] == 0
|
||
assert channel.chunks == []
|
||
|
||
def test_the_marker_alone_is_not_the_end(self, driver):
|
||
"""The prompt after it has to be read too, or it would start the next output."""
|
||
channel = _Channel(["out\n__NETORK_RC=0\n", "chris@vault-01:~$ "])
|
||
driver._device = channel
|
||
|
||
driver._send(_TRUE_WITH_STATUS)
|
||
|
||
assert channel.chunks == []
|
||
|
||
@pytest.mark.parametrize(
|
||
"command",
|
||
[
|
||
"{ LC_ALL=C apt list --upgradable 2>/dev/null; echo __APT_RC=$?; } | cat",
|
||
"timeout 45 systemctl restart -- cron.service; echo __SVC_RC=$?",
|
||
],
|
||
)
|
||
def test_every_status_marker_is_waited_for(self, driver, command):
|
||
marker = re.search(r"echo (__[A-Z_]+=)", command).group(1)
|
||
channel = _Channel(["x <a@b>\n", f"{marker}0\nchris@host:~$ "])
|
||
driver._device = channel
|
||
|
||
output = driver._send(command)
|
||
|
||
assert f"{marker}0" in output
|
||
|
||
def test_a_command_without_a_marker_still_ends_at_the_prompt(self, driver):
|
||
channel = _Channel(["6.8.0-142-generic\nchris@host:~$ "])
|
||
driver._device = channel
|
||
|
||
assert driver._send("uname -r").startswith("6.8.0-142-generic")
|
||
assert channel.patterns == [r"[#$\>]\s*$"]
|
||
|
||
|
||
class TestUninstallExitStatus:
|
||
"""Whether a removal worked is what the package manager's exit status says.
|
||
|
||
Reading it out of human-readable output was guesswork in both directions:
|
||
apt's commonest failure (``E: Sub-process /usr/bin/dpkg returned an error
|
||
code (1)``) read as success until #240, and a successful removal whose
|
||
prerm merely *mentions* a failure read as a failure.
|
||
"""
|
||
|
||
def test_a_non_zero_exit_is_a_failure_whatever_the_output_says(self, driver):
|
||
"""Nothing in this output matches a failure keyword; only the exit
|
||
status knows."""
|
||
driver._pkg_manager = "dnf"
|
||
_mock_send(driver, _with_rc("Removing: wazuh-agent", 1))
|
||
|
||
result = driver.uninstall_package("wazuh-agent")
|
||
|
||
assert result["success"] is False
|
||
|
||
def test_a_zero_exit_is_a_success_even_if_the_output_mentions_failure(self, driver):
|
||
"""A prerm that cannot stop an already-dead unit prints "Failed" and
|
||
still lets the removal complete."""
|
||
_mock_send(
|
||
driver,
|
||
_with_rc(
|
||
"Removing wazuh-agent (4.14.7-1) ...\n"
|
||
"Failed to stop wazuh-agent.service: Unit wazuh-agent.service not loaded.",
|
||
0,
|
||
),
|
||
)
|
||
|
||
result = driver.uninstall_package("wazuh-agent")
|
||
|
||
assert result["success"] is True
|
||
|
||
def test_the_marker_does_not_reach_the_caller(self, driver):
|
||
_mock_send(driver, _with_rc("Removing wazuh-agent ...", 0))
|
||
|
||
result = driver.uninstall_package("wazuh-agent")
|
||
|
||
assert result["output"] == "Removing wazuh-agent ..."
|
||
|
||
def test_the_uninstall_command_keeps_its_exit_status(self, driver):
|
||
_mock_send(driver, _with_rc("Removing wazuh-agent ...", 0))
|
||
|
||
driver.uninstall_package("wazuh-agent")
|
||
|
||
sent = driver._device.send_command.call_args[0][0]
|
||
assert "|| true" not in sent # the exec channel reports the status (#1039)
|
||
|
||
def test_apt_failing_by_exit_status_falls_back_to_dpkg(self, driver):
|
||
driver._root = False
|
||
driver._device.send_command.side_effect = [
|
||
_with_rc("E: Sub-process /usr/bin/dpkg returned an error code (1)", 100),
|
||
_with_rc("Removing wazuh-agent (4.14.7-1) ...", 0),
|
||
]
|
||
|
||
result = driver.uninstall_package("wazuh-agent", purge=True)
|
||
|
||
assert result["success"] is True
|
||
second = driver._device.send_command.call_args_list[1][0][0]
|
||
assert "dpkg --purge --force-all" in second
|
||
assert "|| true" not in second
|
||
assert "__NETORK_RC" not in result["output"]
|
||
|
||
def test_the_dpkg_fallback_failing_is_a_failure(self, driver):
|
||
driver._root = False
|
||
driver._device.send_command.side_effect = [
|
||
_with_rc("E: Sub-process /usr/bin/dpkg returned an error code (1)", 100),
|
||
_with_rc("dpkg: error processing package wazuh-agent (--purge):", 1),
|
||
]
|
||
|
||
result = driver.uninstall_package("wazuh-agent", purge=True)
|
||
|
||
assert result["success"] is False
|
||
assert "dpkg --purge --force-all" in result["output"]
|
||
|
||
def test_a_zero_exit_does_not_trigger_the_fallback(self, driver):
|
||
"""Even when the output contains words that used to mean failure: apt
|
||
exits 0 for a package that is already gone, which is the state the
|
||
caller asked for."""
|
||
driver._root = False
|
||
_mock_send(driver, _with_rc("Package 'x' is not installed, so not removed", 0))
|
||
|
||
result = driver.uninstall_package("x", purge=True)
|
||
|
||
assert result["success"] is True
|
||
assert driver._device.send_command.call_count == 1
|
||
|
||
def test_without_an_exit_status_the_output_is_read_as_before(self, driver):
|
||
"""If the channel closed without a status, the keyword check is still the
|
||
best answer available — and it errs towards failure on apt's ``E:``."""
|
||
driver._pkg_manager = "dnf"
|
||
_mock_send(driver, _with_rc("E: Sub-process /usr/bin/dpkg returned an error code (1)", -1))
|
||
|
||
result = driver.uninstall_package("wazuh-agent")
|
||
|
||
assert result["success"] is False
|
||
|
||
|
||
class TestInstallExitStatus:
|
||
"""``install_package`` decides by the exit status too (#4), as removal does
|
||
since netork#267: keywords in the output were guesswork in both directions."""
|
||
|
||
def test_a_non_zero_exit_is_a_failure_whatever_the_output_says(self, driver):
|
||
driver._pkg_manager = "dnf"
|
||
_mock_send(driver, _with_rc("Last metadata expiration check: 0:01:02 ago.", 1))
|
||
|
||
result = driver.install_package("curl")
|
||
|
||
assert result["success"] is False
|
||
|
||
def test_a_zero_exit_is_a_success_even_if_the_output_mentions_failure(self, driver):
|
||
"""A postinst that cannot start a unit in a container says "Failed" and
|
||
apt still installs the package."""
|
||
_mock_send(
|
||
driver,
|
||
_with_rc(
|
||
"Setting up nginx (1.26.3-3) ...\n"
|
||
"Failed to start nginx.service: System has not been booted with systemd.",
|
||
0,
|
||
),
|
||
)
|
||
|
||
result = driver.install_package("nginx")
|
||
|
||
assert result["success"] is True
|
||
|
||
def test_the_install_command_keeps_its_exit_status(self, driver):
|
||
_mock_send(driver, _with_rc("Setting up curl ...", 0))
|
||
|
||
result = driver.install_package("curl")
|
||
|
||
sent = driver._device.send_command.call_args[0][0]
|
||
assert "|| true" not in sent
|
||
assert result["output"] == "Setting up curl ..."
|
||
|
||
def test_without_an_exit_status_the_output_is_read(self, driver):
|
||
_mock_send(driver, _with_rc("E: Unable to locate package nosuchpkg", -1))
|
||
|
||
result = driver.install_package("nosuchpkg")
|
||
|
||
assert result["success"] is False
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# get_kernel_facts -- the command and its parse live in napalm-device-types
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def _kernel_wire(report: str) -> str:
|
||
import base64
|
||
import gzip
|
||
|
||
return (
|
||
"KFACTS_BEGIN\n"
|
||
+ base64.encodebytes(gzip.compress(report.encode())).decode()
|
||
+ "KFACTS_END"
|
||
)
|
||
|
||
|
||
def test_get_kernel_facts_carries_the_shared_command_across(driver):
|
||
from napalm_device_types import KernelFactsMixin
|
||
from napalm_device_types.kernel import KERNEL_FACTS_COMMAND
|
||
|
||
assert isinstance(driver, KernelFactsMixin)
|
||
|
||
report = "[release]\n6.1.0-25-amd64\n[loaded]\ntipc\n[available]\nkernel/net/tipc/tipc.ko.xz\n"
|
||
with patch.object(driver, "_send", return_value=_kernel_wire(report)) as send:
|
||
facts = driver.get_kernel_facts()
|
||
|
||
assert send.call_args.args[0] == KERNEL_FACTS_COMMAND
|
||
assert facts["release"] == "6.1.0-25-amd64"
|
||
assert facts["loaded"] == ["tipc"]
|
||
assert facts["available"] == ["tipc"]
|
||
assert facts["builtin"] is None
|
||
|
||
|
||
def test_get_kernel_facts_raises_on_output_without_a_report(driver):
|
||
with patch.object(driver, "_send", return_value="sh: base64: not found"):
|
||
with pytest.raises(ValueError):
|
||
driver.get_kernel_facts()
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# get_service_packages -- the command and its parse live in napalm-device-types
|
||
# ---------------------------------------------------------------------------
|
||
|
||
_SVCPKG = (
|
||
"SVCPKG_BEGIN\n[units]\nId=nginx.service\n"
|
||
"FragmentPath=/lib/systemd/system/nginx.service\n"
|
||
"ExecStart={ path=/usr/sbin/nginx ; argv[]=/usr/sbin/nginx }\n\n"
|
||
"[dpkg]\nnginx-common: /lib/systemd/system/nginx.service\n"
|
||
"nginx-core: /usr/sbin/nginx\nSVCPKG_END\n"
|
||
)
|
||
|
||
|
||
def test_get_service_packages_runs_the_shared_command_under_sh_on_an_exec_channel(driver):
|
||
"""Read-only, so never through sudo; ``sh`` because the login shell may be another."""
|
||
from shlex import quote
|
||
|
||
from napalm_device_types import CommandResult, ServicePackagesMixin
|
||
from napalm_device_types.service_packages import SERVICE_PACKAGES_COMMAND
|
||
|
||
assert isinstance(driver, ServicePackagesMixin)
|
||
calls = []
|
||
|
||
def run_command(command, *, privileged=False, timeout=60, stdin=None):
|
||
calls.append((command, privileged))
|
||
return CommandResult(_SVCPKG, "", 0)
|
||
|
||
driver.run_command = run_command
|
||
|
||
assert driver.get_service_packages() == {"nginx": ["nginx-common", "nginx-core"]}
|
||
assert calls == [(f"sh -c {quote(SERVICE_PACKAGES_COMMAND)}", False)]
|
||
driver._device.send_command.assert_not_called()
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Services: listed in one round trip, controlled through systemctl (#7)
|
||
# ---------------------------------------------------------------------------
|
||
|
||
_REPORT = (
|
||
"SVC_BEGIN\n[files]\ncron.service enabled enabled\n[units]\n"
|
||
"MainPID=640\nId=cron.service\nNames=cron.service\nLoadState=loaded\n"
|
||
"ActiveState=active\nSubState=running\nUnitFileState=enabled\n"
|
||
"[generated]\nSVC_END\n"
|
||
)
|
||
|
||
|
||
class TestGetServices:
|
||
def test_one_command_lists_every_service(self, driver):
|
||
driver._device.send_command.return_value = _REPORT
|
||
|
||
services = driver.get_services()
|
||
|
||
assert services == [{"name": "cron", "running": True, "enabled": True, "pid": 640}]
|
||
assert driver._device.send_command.call_count == 1
|
||
assert "systemctl show" in driver._device.send_command.call_args[0][0]
|
||
|
||
def test_a_host_without_systemd_falls_back_to_service(self, driver):
|
||
driver._device.send_command.side_effect = [
|
||
"SVC_BEGIN\n[no-systemd]\n[files]\n[units]\n[generated]\nSVC_END\n",
|
||
" [ + ] cron\n [ - ] rsync\n",
|
||
]
|
||
|
||
services = driver.get_services()
|
||
|
||
assert {s["name"]: s["running"] for s in services} == {"cron": True, "rsync": False}
|
||
assert "service --status-all" in driver._device.send_command.call_args[0][0]
|
||
|
||
|
||
class TestManageService:
|
||
def _sent(self, driver) -> list[str]:
|
||
return [c[0][0] for c in driver._device.send_command.call_args_list]
|
||
|
||
def test_as_root_the_command_runs_as_it_is(self, driver):
|
||
driver._device.send_command.side_effect = ["0", "__SVC_RC=0"]
|
||
|
||
assert driver.manage_service("cron", "restart") == {"success": True, "output": ""}
|
||
uid, action = self._sent(driver)
|
||
assert uid == "id -u"
|
||
assert action.startswith("timeout 45 systemctl --no-ask-password restart -- cron.service")
|
||
|
||
def test_with_a_sudo_password_it_goes_through_sudo(self, driver):
|
||
driver._sudo_password = "pw" # noqa: S105
|
||
driver._device.send_command.side_effect = ["1000", "__SVC_RC=0"]
|
||
|
||
assert driver.manage_service("cron", "stop")["success"] is True
|
||
action = self._sent(driver)[1]
|
||
assert action.startswith("sudo -S -p '' sh -c ") # the password on stdin (#1039)
|
||
assert "timeout 45 systemctl --no-ask-password stop -- cron.service" in action
|
||
|
||
def test_without_one_sudo_never_waits_for_a_password(self, driver):
|
||
driver._device.send_command.side_effect = ["1000", "__SVC_RC=0"]
|
||
|
||
driver.manage_service("cron", "enable")
|
||
|
||
assert self._sent(driver)[1].startswith("sudo -n sh -c 'timeout 45 systemctl")
|
||
|
||
def test_a_missing_sudo_password_is_explained(self, driver):
|
||
driver._device.send_command.side_effect = [
|
||
"1000",
|
||
"sudo: a password is required\n__SVC_RC=1",
|
||
]
|
||
|
||
result = driver.manage_service("cron", "restart")
|
||
|
||
assert result["success"] is False
|
||
assert "sudo password" in result["output"]
|
||
assert "NOPASSWD" in result["output"]
|
||
|
||
def test_a_failure_keeps_systemctls_message(self, driver):
|
||
driver._device.send_command.side_effect = [
|
||
"0",
|
||
"Failed to start nope.service: Unit nope.service not found.\n__SVC_RC=5",
|
||
]
|
||
|
||
result = driver.manage_service("nope", "start")
|
||
|
||
assert result == {
|
||
"success": False,
|
||
"output": "Failed to start nope.service: Unit nope.service not found.",
|
||
}
|
||
|
||
def test_who_the_user_is_is_asked_once(self, driver):
|
||
driver._device.send_command.side_effect = ["0", "__SVC_RC=0", "__SVC_RC=0"]
|
||
|
||
driver.manage_service("cron", "stop")
|
||
driver.manage_service("cron", "start")
|
||
|
||
assert self._sent(driver).count("id -u") == 1
|
||
|
||
def test_an_invalid_name_is_refused_before_anything_is_sent(self, driver):
|
||
with pytest.raises(ValueError):
|
||
driver.manage_service("cron; reboot", "stop")
|
||
|
||
assert driver._device.send_command.call_count == 0
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Updates: origin and security, refresh, host status (netOrk MVP 5)
|
||
# ---------------------------------------------------------------------------
|
||
|
||
APT_WITH_SECURITY = (
|
||
"openssl/noble-updates,noble-security 3.0.13-0ubuntu3.6 amd64 [upgradable from: 3.0.13-0ubuntu3.5]\n"
|
||
"docker-compose-plugin/noble 5.6.0-1~ubuntu.24.04~noble amd64 [upgradable from: 5.5.1-1~ubuntu.24.04~noble]\n"
|
||
"__APT_RC=0\n"
|
||
)
|
||
|
||
|
||
class TestAvailableUpdates:
|
||
def test_apt_reports_origin_and_security(self, driver):
|
||
driver._pkg_manager = "apt"
|
||
_mock_send(driver, APT_WITH_SECURITY)
|
||
|
||
updates = {u["name"]: u for u in driver.get_available_updates()}
|
||
|
||
assert updates["openssl"]["security"] is True
|
||
assert updates["openssl"]["origin"] == "noble-updates,noble-security"
|
||
assert updates["docker-compose-plugin"]["security"] is False
|
||
|
||
def test_apt_that_could_not_read_raises_instead_of_reporting_nothing(self, driver):
|
||
driver._pkg_manager = "apt"
|
||
_mock_send(driver, "E: Could not open lock file\n__APT_RC=100\n")
|
||
|
||
with pytest.raises(ValueError):
|
||
driver.get_available_updates()
|
||
|
||
def test_apt_without_an_exit_status_raises(self, driver):
|
||
driver._pkg_manager = "apt"
|
||
_mock_send(driver, "openssl/noble-security 3.0.13-0ubuntu3.6 amd64 [upgradable fro")
|
||
|
||
with pytest.raises(ValueError):
|
||
driver.get_available_updates()
|
||
|
||
def test_dnf_marks_what_a_security_advisory_covers(self, driver):
|
||
driver._pkg_manager = "dnf"
|
||
driver._device.send_command.side_effect = [
|
||
"0", # id -u
|
||
(
|
||
"openssl-libs.x86_64 1:3.1.4-2.fc40 updates\n"
|
||
"vim-enhanced.x86_64 2:9.1.083-1.fc40 updates\n__NETORK_RC=100"
|
||
),
|
||
# DNF_SECURITY_COMMAND pipes through cat: the outer status is cat's, dnf's own
|
||
# is in the __DNF_RC marker.
|
||
(
|
||
"FEDORA-2024-1a2b3c4d5e Important/Sec. openssl-libs-1:3.1.4-2.fc40.x86_64\n"
|
||
"__DNF_RC=0\n__NETORK_RC=0"
|
||
),
|
||
]
|
||
|
||
updates = {u["name"]: u for u in driver.get_available_updates()}
|
||
|
||
assert updates["openssl-libs"]["security"] is True
|
||
assert updates["vim-enhanced"]["security"] is False
|
||
|
||
def test_dnf_without_advisories_leaves_security_unknown(self, driver):
|
||
driver._pkg_manager = "dnf"
|
||
driver._device.send_command.side_effect = [
|
||
"0",
|
||
"vim-enhanced.x86_64 2:9.1.083-1.fc40 updates\n__NETORK_RC=100",
|
||
"Error: updateinfo metadata missing\n__DNF_RC=1\n__NETORK_RC=0",
|
||
]
|
||
|
||
assert driver.get_available_updates()[0]["security"] is None
|
||
|
||
def test_yum_security_command_reports_its_own_exit_status(self):
|
||
# parse_dnf_security (napalm-device-types 4.7) needs the __DNF_RC marker, and
|
||
# behind "| cat" the outer status no longer says whether yum failed.
|
||
assert "echo __DNF_RC=$?" in _YUM_SECURITY_COMMAND
|
||
assert "yum --cacheonly updateinfo list security" in _YUM_SECURITY_COMMAND
|
||
|
||
def test_yum_marks_what_a_security_advisory_covers(self, driver):
|
||
driver._pkg_manager = "yum"
|
||
driver._device.send_command.side_effect = [
|
||
"0", # id -u
|
||
(
|
||
"openssl-libs.x86_64 1:1.0.2k-26.el7_9 updates\n"
|
||
"vim-enhanced.x86_64 2:7.4.629-8.el7_9 updates\n__NETORK_RC=100"
|
||
),
|
||
(
|
||
"RHSA-2023:3556 Important/Sec. openssl-libs-1:1.0.2k-26.el7_9.x86_64\n"
|
||
"__DNF_RC=0\n__NETORK_RC=0"
|
||
),
|
||
]
|
||
|
||
updates = {u["name"]: u for u in driver.get_available_updates()}
|
||
|
||
assert driver._device.send_command.call_count == 3
|
||
assert "echo __DNF_RC=$?" in driver._device.send_command.call_args_list[2][0][0]
|
||
assert updates["openssl-libs"]["security"] is True
|
||
assert updates["vim-enhanced"]["security"] is False
|
||
|
||
def test_yum_with_no_advisories_marks_nothing_as_security(self, driver):
|
||
driver._pkg_manager = "yum"
|
||
driver._device.send_command.side_effect = [
|
||
"0",
|
||
"vim-enhanced.x86_64 2:7.4.629-8.el7_9 updates\n__NETORK_RC=100",
|
||
"__DNF_RC=0\n__NETORK_RC=0",
|
||
]
|
||
|
||
assert driver.get_available_updates()[0]["security"] is False
|
||
|
||
def test_yum_that_failed_leaves_security_unknown(self, driver):
|
||
# A failed yum prints nothing on stdout (2>/dev/null): read as "no advisories",
|
||
# every update would be marked as not a security fix.
|
||
driver._pkg_manager = "yum"
|
||
driver._device.send_command.side_effect = [
|
||
"0",
|
||
"vim-enhanced.x86_64 2:7.4.629-8.el7_9 updates\n__NETORK_RC=100",
|
||
"__DNF_RC=1\n__NETORK_RC=0",
|
||
]
|
||
|
||
assert driver.get_available_updates()[0]["security"] is None
|
||
|
||
def test_yum_without_its_exit_status_leaves_security_unknown(self, driver):
|
||
driver._pkg_manager = "yum"
|
||
driver._device.send_command.side_effect = [
|
||
"0",
|
||
"vim-enhanced.x86_64 2:7.4.629-8.el7_9 updates\n__NETORK_RC=100",
|
||
"RHSA-2023:3556 Important/Sec. vim-enhanced-2:7.4.629-8.el7_9.x86_64\n__NETORK_RC=0",
|
||
]
|
||
|
||
assert driver.get_available_updates()[0]["security"] is None
|
||
|
||
def test_dnf_that_failed_raises(self, driver):
|
||
driver._pkg_manager = "dnf"
|
||
driver._device.send_command.side_effect = [
|
||
"0",
|
||
"Error: Failed to download metadata\n__NETORK_RC=1",
|
||
]
|
||
|
||
with pytest.raises(RuntimeError):
|
||
driver.get_available_updates()
|
||
|
||
@pytest.mark.parametrize("manager", ["dnf", "yum"])
|
||
def test_rpm_reads_only_the_cached_metadata(self, driver, manager):
|
||
"""An expired cache made check-update download the repositories' metadata
|
||
inside the poll, which outlasted its whole budget (#59)."""
|
||
driver._pkg_manager = manager
|
||
driver._device.send_command.side_effect = [
|
||
"0",
|
||
"__NETORK_RC=0",
|
||
"__DNF_RC=0\n__NETORK_RC=0",
|
||
]
|
||
|
||
driver.get_available_updates()
|
||
|
||
sent = [c[0][0] for c in driver._device.send_command.call_args_list]
|
||
assert f"{manager} --cacheonly check-update" in sent[1]
|
||
assert f"{manager} --cacheonly updateinfo" in sent[2]
|
||
|
||
def test_rpm_without_a_cache_says_to_refresh_it(self, driver):
|
||
# dnf --cacheonly fails at once without cached metadata; its stderr is
|
||
# discarded, so the reason has to come from here.
|
||
driver._pkg_manager = "dnf"
|
||
driver._device.send_command.side_effect = ["0", "__NETORK_RC=1"]
|
||
|
||
with pytest.raises(RuntimeError, match="refresh the package index"):
|
||
driver.get_available_updates()
|
||
|
||
|
||
class TestRefreshAvailableUpdates:
|
||
def _sent(self, driver) -> list:
|
||
return [c[0][0] for c in driver._device.send_command.call_args_list]
|
||
|
||
def test_apt_refreshes_its_index_as_root(self, driver):
|
||
driver._pkg_manager = "apt"
|
||
driver._device.send_command.side_effect = [
|
||
"0",
|
||
"Hit:1 http://archive.ubuntu.com noble InRelease\n__NETORK_RC=0",
|
||
]
|
||
|
||
result = driver.refresh_available_updates()
|
||
|
||
assert result["success"] is True
|
||
assert "apt-get update" in self._sent(driver)[1]
|
||
|
||
def test_without_a_sudo_password_it_never_waits_for_one(self, driver):
|
||
driver._pkg_manager = "apt"
|
||
driver._device.send_command.side_effect = [
|
||
"1000",
|
||
"sudo: a password is required\n__NETORK_RC=1",
|
||
]
|
||
|
||
result = driver.refresh_available_updates()
|
||
|
||
assert result["success"] is False
|
||
assert self._sent(driver)[1].startswith("sudo -n sh -c 'apt-get update")
|
||
|
||
def test_dnf_refreshes_its_metadata(self, driver):
|
||
driver._pkg_manager = "dnf"
|
||
driver._device.send_command.side_effect = ["0", "Metadata cache created.\n__NETORK_RC=0"]
|
||
|
||
assert driver.refresh_available_updates()["success"] is True
|
||
assert "dnf makecache" in self._sent(driver)[1]
|
||
|
||
def test_pacman_is_not_refreshed_on_its_own(self, driver):
|
||
"""pacman -Sy without -u invites a partial upgrade on the next install."""
|
||
driver._pkg_manager = "pacman"
|
||
|
||
result = driver.refresh_available_updates()
|
||
|
||
assert result["success"] is False
|
||
driver._device.send_command.assert_not_called()
|
||
|
||
|
||
class TestHostStatus:
|
||
def test_the_driver_carries_the_shared_command(self, driver):
|
||
from napalm_device_types.host_status import HOST_STATUS_COMMAND
|
||
|
||
_mock_send(
|
||
driver,
|
||
"HSTAT_BEGIN\n[reboot-required]\n[kernel]\n6.8.0-142-generic\n[modules]\n"
|
||
"6.8.0-142-generic\n[timers]\napt-daily-upgrade.timer enabled\nHSTAT_END\n",
|
||
)
|
||
|
||
status = driver.get_host_status()
|
||
|
||
assert driver._device.send_command.call_args[0][0] == HOST_STATUS_COMMAND
|
||
assert status["reboot_required"] is True
|
||
|
||
|
||
class TestTerminalCodes:
|
||
def test_a_status_marker_behind_a_terminal_code_is_still_read(self, driver):
|
||
"""apt-get on a pseudo-terminal leaves keypad codes in front of the marker."""
|
||
driver._pkg_manager = "apt"
|
||
driver._device.send_command.side_effect = ["0", "Hit:1 noble InRelease\n\x1b>__NETORK_RC=0"]
|
||
|
||
assert driver.refresh_available_updates()["success"] is True
|
||
|
||
|
||
class TestRebootHost:
|
||
"""``reboot_host`` (napalm-device-types' ``HostRebootMixin``) restarts the host.
|
||
|
||
Without it netOrk could not restart a Linux host at all: its capability check
|
||
looks for ``reboot_host`` and found nothing (netOrk #637). The restart is
|
||
detached and a moment late, so the launcher's exit status comes back before
|
||
the host goes down, and closing the session cannot take it along.
|
||
"""
|
||
|
||
def test_the_driver_can_restart_its_host(self):
|
||
assert callable(getattr(LinuxDriver, "reboot_host", None))
|
||
|
||
def test_the_restart_is_detached_and_privileged(self, driver):
|
||
driver._root = False
|
||
driver._device.send_command.return_value = "\n__NETORK_RC=0"
|
||
|
||
driver.reboot_host()
|
||
|
||
sent = driver._device.send_command.call_args[0][0]
|
||
assert sent.startswith("sudo -n sh -c ")
|
||
assert "/sbin/reboot" in sent and "trap" in sent and "&" in sent
|
||
assert sent.endswith("echo __NETORK_RC=$?")
|
||
|
||
def test_a_refusal_is_raised_with_what_the_host_said(self, driver):
|
||
driver._root = False
|
||
driver._device.send_command.return_value = "sudo: a password is required\n__NETORK_RC=1"
|
||
|
||
with pytest.raises(RuntimeError, match="password is required"):
|
||
driver.reboot_host()
|
||
|
||
def test_no_exit_status_is_no_success(self, driver):
|
||
driver._root = True
|
||
driver._device.send_command.return_value = "something else"
|
||
|
||
with pytest.raises(RuntimeError):
|
||
driver.reboot_host()
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Listening sockets: ss and the processes' cgroups, as root when it can
|
||
# ---------------------------------------------------------------------------
|
||
|
||
_SOCKETS = (
|
||
"SOCK_BEGIN\n[ss]\n"
|
||
'tcp LISTEN 0 128 0.0.0.0:5432 0.0.0.0:* users:(("postgres",pid=812,fd=6))\n'
|
||
"__SS_RC=0\n[cgroups]\n"
|
||
"812 0::/system.slice/system-postgresql.slice/postgresql@16-main.service\n"
|
||
"SOCK_END\n"
|
||
)
|
||
|
||
|
||
class TestGetListeningSockets:
|
||
def _sent(self, driver) -> list[str]:
|
||
return [c[0][0] for c in driver._device.send_command.call_args_list]
|
||
|
||
def test_it_reads_with_the_shared_command(self, driver):
|
||
from napalm_device_types import ListeningSocketsMixin
|
||
|
||
assert isinstance(driver, ListeningSocketsMixin)
|
||
driver._root = True
|
||
driver._device.send_command.return_value = _SOCKETS
|
||
|
||
reading = driver.get_listening_sockets()
|
||
|
||
assert reading["attributed"] is True
|
||
[socket] = reading["sockets"]
|
||
assert (socket["port"], socket["unit"]) == (5432, "postgresql@16-main")
|
||
assert self._sent(driver)[0].startswith("sh -c '")
|
||
|
||
def test_without_a_sudo_password_the_whole_script_runs_under_sudo_n(self, driver):
|
||
driver._root = False
|
||
driver._device.send_command.return_value = _SOCKETS
|
||
|
||
driver.get_listening_sockets()
|
||
|
||
assert self._sent(driver)[0].startswith("sudo -n sh -c '")
|
||
|
||
def test_with_a_sudo_password_it_goes_through_sudo(self, driver):
|
||
driver._root = False
|
||
driver._sudo_password = "pw" # noqa: S105
|
||
driver._device.send_command.return_value = _SOCKETS
|
||
|
||
driver.get_listening_sockets()
|
||
|
||
sent = self._sent(driver)[0]
|
||
assert sent.startswith("sudo -S -p '' sh -c ") # the password on stdin (#1039)
|
||
|
||
def test_when_sudo_refuses_it_reads_what_the_user_may_see(self, driver):
|
||
driver._root = False
|
||
driver._device.send_command.side_effect = ["sudo: a password is required", _SOCKETS]
|
||
|
||
reading = driver.get_listening_sockets()
|
||
|
||
assert reading["attributed"] is False
|
||
refused, plain = self._sent(driver)
|
||
assert refused.startswith("sudo -n sh -c '")
|
||
assert plain.startswith("sh -c '")
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Log sources: journald units and the log files processes hold open (#2049)
|
||
# ---------------------------------------------------------------------------
|
||
|
||
_LOGS = (
|
||
"LOGS_BEGIN\n[journald]\nnginx.service\n"
|
||
"[open]\n/proc/900/fd/5 /var/log/nginx/access.log\n"
|
||
"[stat]\n/proc/900/fd/5 2048 1762250200\n"
|
||
"[cgroups]\n900 0::/system.slice/nginx.service\n"
|
||
"[comm]\n900 nginx\n"
|
||
"LOGS_END\n"
|
||
)
|
||
|
||
|
||
class TestGetLogSources:
|
||
def _sent(self, driver) -> list[str]:
|
||
return [c[0][0] for c in driver._device.send_command.call_args_list]
|
||
|
||
def test_it_reads_with_the_shared_command_as_root(self, driver):
|
||
from napalm_device_types import LogSourcesMixin
|
||
|
||
assert isinstance(driver, LogSourcesMixin)
|
||
driver._root = True
|
||
driver._device.send_command.return_value = _LOGS
|
||
|
||
reading = driver.get_log_sources()
|
||
|
||
assert (reading["attributed"], reading["journald"]) == (True, True)
|
||
access = [s for s in reading["sources"] if s["kind"] == "file"]
|
||
assert [(s["path"], s["unit"]) for s in access] == [("/var/log/nginx/access.log", "nginx")]
|
||
assert self._sent(driver)[0].startswith("sh -c '")
|
||
|
||
def test_without_a_sudo_password_the_whole_script_runs_under_sudo_n(self, driver):
|
||
driver._root = False
|
||
driver._device.send_command.return_value = _LOGS
|
||
|
||
driver.get_log_sources()
|
||
|
||
assert self._sent(driver)[0].startswith("sudo -n sh -c '")
|
||
|
||
def test_when_sudo_refuses_it_reads_what_the_user_may_see(self, driver):
|
||
driver._root = False
|
||
driver._device.send_command.side_effect = ["sudo: a password is required", _LOGS]
|
||
|
||
reading = driver.get_log_sources()
|
||
|
||
assert reading["attributed"] is False
|
||
refused, plain = self._sent(driver)
|
||
assert refused.startswith("sudo -n sh -c '")
|
||
assert plain.startswith("sh -c '")
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# get_system_identity (napalm-device-types SystemIdentityMixin)
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
class TestGetSystemIdentity:
|
||
"""What ties a host to its BMC: SMBIOS UUID and serials, read as root on an exec
|
||
channel (product_uuid and product_serial are root's)."""
|
||
|
||
def test_it_reads_the_shared_command_as_root_on_an_exec_channel(self, driver):
|
||
from napalm_device_types import SYSTEM_IDENTITY_COMMAND, CommandResult, SystemIdentityMixin
|
||
|
||
assert isinstance(driver, SystemIdentityMixin)
|
||
calls = []
|
||
|
||
def run_command(command, *, privileged=False, timeout=60, stdin=None):
|
||
calls.append((command, privileged))
|
||
out = "IDBEGIN\n31303043-534D-C40C-7A72-6F1300000000\n0123456789\nZM155S026022\nIDEND\n"
|
||
return CommandResult(out, "", 0)
|
||
|
||
driver.run_command = run_command
|
||
|
||
identity = driver.get_system_identity()
|
||
|
||
assert identity == {
|
||
"system_uuid": "31303043-534d-c40c-7a72-6f1300000000",
|
||
"product_serial": "", # Supermicro's placeholder
|
||
"board_serial": "ZM155S026022",
|
||
}
|
||
assert calls == [(SYSTEM_IDENTITY_COMMAND, True)]
|
||
driver._device.send_command.assert_not_called()
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# get_host_firewall (napalm-device-types HostFirewallMixin, NetOrk/netork#1344)
|
||
# ---------------------------------------------------------------------------
|
||
|
||
_FIREWALL = (
|
||
"FW_BEGIN\n[iptables-save]\n"
|
||
"# Generated by iptables-save v1.8.10 (nf_tables) on Wed Oct 21 14:52:11 2026\n"
|
||
"*filter\n:INPUT ACCEPT [0:0]\n-A INPUT -i ens6 -j DROP\nCOMMIT\n__FW_RC=0\nFW_END\n"
|
||
)
|
||
|
||
|
||
class TestGetHostFirewall:
|
||
"""nft and iptables-save need root; the nft JSON is one long line, so the
|
||
command goes on an exec channel, never typed into the PTY netmiko holds."""
|
||
|
||
def test_it_reads_the_shared_command_as_root_on_an_exec_channel(self, driver):
|
||
from napalm_device_types import CommandResult, HostFirewallMixin
|
||
|
||
assert isinstance(driver, HostFirewallMixin)
|
||
calls = []
|
||
|
||
def run_command(command, *, privileged=False, timeout=60, stdin=None):
|
||
calls.append((command, privileged))
|
||
return CommandResult(_FIREWALL, "", 0)
|
||
|
||
driver.run_command = run_command
|
||
|
||
reading = driver.get_host_firewall()
|
||
|
||
assert reading["sources"] == ["iptables-nft"]
|
||
assert reading["chains"][0]["rules"][0]["verdict"] == "drop"
|
||
[(command, privileged)] = calls
|
||
assert privileged is True
|
||
assert command.startswith("sh -c '")
|
||
driver._device.send_command.assert_not_called()
|
||
|
||
def test_without_root_there_is_no_reading(self, driver):
|
||
from napalm_device_types import CommandResult, HostFirewallUnavailable
|
||
|
||
driver.run_command = lambda *a, **k: CommandResult("", "sudo: a password is required\n", 1)
|
||
|
||
with pytest.raises((HostFirewallUnavailable, ValueError)):
|
||
driver.get_host_firewall()
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# get_virtual_ips (napalm-device-types VirtualIpsMixin)
|
||
# ---------------------------------------------------------------------------
|
||
|
||
_VIPS = (
|
||
"VIPS_BEGIN\n[systemd]\n[vip-manager vip-manager.service]\nactive active\n"
|
||
"cfg ip 10.7.224.10\ncfg netmask 24\ncfg interface ens7\nVIPS_END\n"
|
||
)
|
||
|
||
|
||
class TestGetVirtualIps:
|
||
"""The command is about 4 kB -- past the line a terminal takes -- so it goes
|
||
on an exec channel, never typed into the PTY netmiko holds."""
|
||
|
||
@staticmethod
|
||
def _exec(driver, *answers):
|
||
from napalm_device_types import CommandResult
|
||
|
||
calls = []
|
||
replies = iter(answers)
|
||
|
||
def run_command(command, *, privileged=False, timeout=60, stdin=None):
|
||
calls.append((command, privileged))
|
||
return CommandResult(*next(replies))
|
||
|
||
driver.run_command = run_command
|
||
return calls
|
||
|
||
def test_it_reads_with_the_shared_command_on_an_exec_channel(self, driver):
|
||
from napalm_device_types import VirtualIpsMixin
|
||
|
||
assert isinstance(driver, VirtualIpsMixin)
|
||
calls = self._exec(driver, (_VIPS, "", 0))
|
||
|
||
reading = driver.get_virtual_ips()
|
||
|
||
assert reading["vip_manager"][0]["address"] == "10.7.224.10"
|
||
[(command, privileged)] = calls
|
||
assert privileged is True
|
||
assert command.startswith("sh -c '")
|
||
driver._device.send_command.assert_not_called()
|
||
|
||
def test_when_sudo_refuses_it_reads_what_the_user_may_see(self, driver):
|
||
calls = self._exec(driver, ("", "sudo: a password is required\n", 1), (_VIPS, "", 0))
|
||
|
||
reading = driver.get_virtual_ips()
|
||
|
||
assert reading["vip_manager"][0]["interface"] == "ens7"
|
||
assert [privileged for _, privileged in calls] == [True, False]
|
||
|
||
def test_without_a_sudo_password_the_whole_script_runs_under_sudo_n(self):
|
||
from types import SimpleNamespace
|
||
|
||
channels = []
|
||
|
||
class Channel:
|
||
def __init__(self):
|
||
channels.append(self)
|
||
|
||
def exec_command(self, command):
|
||
self.command = command
|
||
|
||
def settimeout(self, timeout):
|
||
pass
|
||
|
||
def shutdown_write(self):
|
||
pass
|
||
|
||
def close(self):
|
||
pass
|
||
|
||
def recv_ready(self):
|
||
return False
|
||
|
||
def recv(self, size):
|
||
return b""
|
||
|
||
def recv_stderr_ready(self):
|
||
return False
|
||
|
||
def recv_stderr(self, size):
|
||
return b""
|
||
|
||
def exit_status_ready(self):
|
||
return True
|
||
|
||
def recv_exit_status(self):
|
||
return 1
|
||
|
||
transport = SimpleNamespace(open_session=Channel)
|
||
driver = LinuxDriver("h", "u", "p", optional_args={})
|
||
driver._device = SimpleNamespace(
|
||
remote_conn_pre=SimpleNamespace(get_transport=lambda: transport)
|
||
)
|
||
driver._root = False
|
||
|
||
with pytest.raises(ValueError):
|
||
driver.get_virtual_ips()
|
||
|
||
privileged, plain = (c.command for c in channels)
|
||
assert privileged.startswith("sudo -n sh -c 'sh -c '")
|
||
assert plain.startswith("sh -c '")
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# get_service_clusters (napalm-device-types ServiceClustersMixin)
|
||
# ---------------------------------------------------------------------------
|
||
|
||
_CLUSTERS = (
|
||
"SVCC_BEGIN\n[systemd]\n[patroni patroni.service]\nactive active\nscope netork-db\n"
|
||
"name db-01\nrestapi 10.7.234.12:8008\nrest-unreachable\n[no-docker]\nSVCC_END\n"
|
||
)
|
||
|
||
|
||
class TestGetServiceClusters:
|
||
"""The same template as get_virtual_ips: an exec channel, root first."""
|
||
|
||
_exec = staticmethod(TestGetVirtualIps._exec)
|
||
|
||
def test_it_reads_with_the_shared_command_on_an_exec_channel(self, driver):
|
||
from napalm_device_types import ServiceClustersMixin
|
||
|
||
assert isinstance(driver, ServiceClustersMixin)
|
||
calls = self._exec(driver, (_CLUSTERS, "", 0))
|
||
|
||
reading = driver.get_service_clusters()
|
||
|
||
assert reading["patroni"][0]["cluster"] == "netork-db"
|
||
[(command, privileged)] = calls
|
||
assert privileged is True
|
||
assert command.startswith("sh -c '")
|
||
driver._device.send_command.assert_not_called()
|
||
|
||
def test_when_sudo_refuses_it_reads_what_the_user_may_see(self, driver):
|
||
calls = self._exec(driver, ("", "sudo: a password is required\n", 1), (_CLUSTERS, "", 0))
|
||
|
||
reading = driver.get_service_clusters()
|
||
|
||
assert reading["bunkerweb"] == []
|
||
assert [privileged for _, privileged in calls] == [True, False]
|
||
|
||
|
||
class TestHardensItsSshServer:
|
||
"""A stock Linux host runs a stock OpenSSH: the hardening netOrk offers for
|
||
ssh-audit findings comes from napalm-device-types, carried over run_command
|
||
(NetOrk/netork#1027)."""
|
||
|
||
def test_mixes_in_the_openssh_hardening(self):
|
||
from napalm_device_types import OpenSshServerMixin
|
||
|
||
assert issubclass(LinuxDriver, OpenSshServerMixin)
|
||
assert callable(getattr(LinuxDriver, "harden_ssh_server", None))
|
||
|
||
def test_reads_the_algorithms_as_root_over_the_command_channel(self, driver):
|
||
from napalm_device_types import CommandResult
|
||
|
||
out = "kexalgorithms a\nhostkeyalgorithms b\nciphers c\nmacs d\n"
|
||
with patch.object(driver, "run_command", return_value=CommandResult(out, "", 0)) as run:
|
||
assert driver.get_ssh_server_algorithms()["mac"] == ["d"]
|
||
assert run.call_args.kwargs["privileged"] is True
|
||
|
||
|
||
class TestWireGuardTunnelKeys:
|
||
"""A tunnel's key is a URL path segment for its consumer (#43): the public
|
||
key's base64 prefix is made URL-safe, as napalm-opnsense does."""
|
||
|
||
_DUMP = (
|
||
"wg0\tPRIVKEY\tSERVERPUBKEY=\t51820\toff\n"
|
||
"wg0\tab/c+d9EfGhIjKlMnOpQrStUvWxYz0123456789AB=\t(none)\t"
|
||
"198.51.100.7:51820\t10.8.0.2/32\t0\t1024\t2048\toff\n"
|
||
)
|
||
|
||
def test_a_slash_or_plus_in_the_key_prefix_is_url_safe(self, driver):
|
||
_mock_send(driver, self._DUMP)
|
||
|
||
tunnels = driver.get_vpn_tunnels()
|
||
|
||
assert list(tunnels) == ["wireguard-wg0-ab_c-d9E"]
|
||
|
||
def test_the_public_key_itself_is_reported_unchanged(self, driver):
|
||
_mock_send(driver, self._DUMP)
|
||
|
||
(tunnel,) = driver.get_vpn_tunnels().values()
|
||
|
||
assert tunnel["public_key"] == "ab/c+d9EfGhIjKlMnOpQrStUvWxYz0123456789AB="
|
||
|
||
|
||
class TestGetProcesses:
|
||
"""``lstart`` is five words; the split has to leave them together (#21)."""
|
||
|
||
_PS = (
|
||
" 1 0 root 0.0 0.1 23456 12345 ? Ss Tue Oct 6 08:47:15 2026 /sbin/init splash\n"
|
||
" 1234 1 chris 1.5 2.3 456789 98765 pts/0 S+ Tue Oct 6 09:01:02 2026 bash -c echo two spaces\n"
|
||
)
|
||
|
||
def test_started_is_the_whole_start_time(self, driver):
|
||
_mock_send(driver, self._PS)
|
||
|
||
init, shell = driver.get_processes()
|
||
|
||
assert init["started"] == "Tue Oct 6 08:47:15 2026"
|
||
assert shell["started"] == "Tue Oct 6 09:01:02 2026"
|
||
|
||
def test_command_is_the_command_line_alone(self, driver):
|
||
_mock_send(driver, self._PS)
|
||
|
||
init, shell = driver.get_processes()
|
||
|
||
assert init["command"] == "/sbin/init splash"
|
||
assert shell["command"] == "bash -c echo two spaces"
|
||
|
||
def test_the_other_columns(self, driver):
|
||
_mock_send(driver, self._PS)
|
||
|
||
shell = driver.get_processes()[1]
|
||
|
||
assert (shell["pid"], shell["ppid"], shell["user"], shell["tty"]) == (
|
||
1234,
|
||
1,
|
||
"chris",
|
||
"pts/0",
|
||
)
|
||
assert (shell["cpu"], shell["memory"], shell["vsz"], shell["rss"]) == (
|
||
1.5,
|
||
2.3,
|
||
456789,
|
||
98765,
|
||
)
|
||
assert shell["state"] == "S"
|
||
assert driver.get_processes()[0]["tty"] == ""
|
||
|
||
def test_the_start_time_is_in_c_locale_words(self, driver):
|
||
"""A German host says "Di Okt" -- one word each too, but only C promises that."""
|
||
_mock_send(driver, self._PS)
|
||
|
||
driver.get_processes()
|
||
|
||
assert driver._device.send_command.call_args[0][0].startswith("LC_ALL=C ps ")
|
||
|
||
def test_a_line_cut_short_is_skipped(self, driver):
|
||
_mock_send(driver, " 1 0 root 0.0 0.1 23456 12345 ? Ss Tue Oct 6\n")
|
||
|
||
assert driver.get_processes() == []
|
||
|
||
|
||
class TestRouteFamilies:
|
||
"""``ip -6 route show`` calls its default route ``default`` too (#6)."""
|
||
|
||
_V4 = (
|
||
"default via 192.0.2.1 dev eth0 proto dhcp src 192.0.2.10 metric 100\n"
|
||
"192.0.2.0/24 dev eth0 proto kernel scope link src 192.0.2.10 metric 100\n"
|
||
)
|
||
_V6 = (
|
||
"2001:db8:1::/64 dev eth0 proto ra metric 100 expires 86391sec pref medium\n"
|
||
"fe80::/64 dev eth0 proto kernel metric 256 pref medium\n"
|
||
"default via fe80::1 dev eth0 proto ra metric 100 expires 1791sec pref medium\n"
|
||
)
|
||
|
||
def _routes(self, driver, v6=_V6):
|
||
def send(command, **_kw):
|
||
out = ""
|
||
if "ip -4 route" in command:
|
||
out += self._V4
|
||
if "ip -6 route" in command:
|
||
out += v6
|
||
return out
|
||
|
||
with patch.object(driver, "_send", side_effect=send):
|
||
return driver.get_route_to()
|
||
|
||
def test_the_ipv6_default_route_is_its_own(self, driver):
|
||
routes = self._routes(driver)
|
||
|
||
assert [r["family"] for r in routes["::/0"]] == ["ipv6"]
|
||
assert routes["::/0"][0]["next_hop"] == "fe80::1"
|
||
|
||
def test_the_ipv4_default_route_stays_ipv4(self, driver):
|
||
routes = self._routes(driver)
|
||
|
||
assert [r["family"] for r in routes["0.0.0.0/0"]] == ["ipv4"]
|
||
assert routes["0.0.0.0/0"][0]["next_hop"] == "192.0.2.1"
|
||
|
||
def test_an_ipv6_host_route_is_a_128(self, driver):
|
||
routes = self._routes(
|
||
driver, v6="2001:db8:2::7 via fe80::1 dev eth0 proto static metric 1024\n"
|
||
)
|
||
|
||
assert "2001:db8:2::7/128" in routes
|
||
|
||
|
||
#: ``ip -4 route show`` / ``ip -6 route show``, iproute2 6.1.0 on Linux 7.0 (Linux Mint
|
||
#: 22.3), recorded in a network namespace set up for it: a multipath default per
|
||
#: family, and unreachable, prohibit, throw and blackhole routes (#57). Documentation
|
||
#: addresses only. The trailing blanks and the tabs are ip's.
|
||
_IP4_ROUTE_TYPES = (
|
||
"default proto static metric 100 \n"
|
||
"\tnexthop via 192.0.2.1 dev eth0 weight 1 \n"
|
||
"\tnexthop via 198.51.100.1 dev eth1 weight 1 \n"
|
||
"unreachable 10.0.0.0/8 metric 1024 \n"
|
||
"prohibit 172.16.0.0/12 \n"
|
||
"192.0.2.0/24 dev eth0 proto kernel scope link src 192.0.2.10 \n"
|
||
"throw 192.168.0.0/16 \n"
|
||
"198.51.100.0/24 dev eth1 proto kernel scope link src 198.51.100.10 \n"
|
||
"blackhole 203.0.113.0/24 proto static \n"
|
||
"203.0.113.7 via 192.0.2.1 dev eth0 \n"
|
||
)
|
||
_IP6_ROUTE_TYPES = (
|
||
"2001:db8:1::/64 dev eth0 proto kernel metric 256 pref medium\n"
|
||
"2001:db8:2::/64 dev eth1 proto kernel metric 256 pref medium\n"
|
||
"blackhole 2001:db8:beef::/48 dev lo metric 1024 pref medium\n"
|
||
"unreachable 2001:db8:dead::/48 dev lo metric 1024 pref medium\n"
|
||
"fe80::/64 dev eth0 proto kernel metric 256 pref medium\n"
|
||
"fe80::/64 dev eth1 proto kernel metric 256 pref medium\n"
|
||
"default proto static metric 1024 pref medium\n"
|
||
"\tnexthop via 2001:db8:1::1 dev eth0 weight 1 \n"
|
||
"\tnexthop via 2001:db8:2::1 dev eth1 weight 1 \n"
|
||
)
|
||
|
||
|
||
class TestRouteTypesAndMultipath:
|
||
"""A route type in front of the destination is the type, and a multipath
|
||
route's ``nexthop`` lines are its next hops (#57)."""
|
||
|
||
@pytest.fixture()
|
||
def routes(self, driver):
|
||
def send(command, **_kw):
|
||
if "ip -4 route" in command:
|
||
return _IP4_ROUTE_TYPES
|
||
if "ip -6 route" in command:
|
||
return _IP6_ROUTE_TYPES
|
||
return ""
|
||
|
||
with patch.object(driver, "_send", side_effect=send):
|
||
return driver.get_route_to()
|
||
|
||
def test_every_destination_is_an_address(self, routes):
|
||
assert sorted(routes) == sorted(
|
||
[
|
||
"0.0.0.0/0",
|
||
"10.0.0.0/8",
|
||
"172.16.0.0/12",
|
||
"192.0.2.0/24",
|
||
"192.168.0.0/16",
|
||
"198.51.100.0/24",
|
||
"203.0.113.0/24",
|
||
"203.0.113.7/32",
|
||
"2001:db8:1::/64",
|
||
"2001:db8:2::/64",
|
||
"2001:db8:beef::/48",
|
||
"2001:db8:dead::/48",
|
||
"fe80::/64",
|
||
"::/0",
|
||
]
|
||
)
|
||
|
||
@pytest.mark.parametrize(
|
||
("network", "route_type", "metric"),
|
||
[
|
||
("10.0.0.0/8", "unreachable", 1024),
|
||
("172.16.0.0/12", "prohibit", 0),
|
||
("192.168.0.0/16", "throw", 0),
|
||
("203.0.113.0/24", "blackhole", 0),
|
||
("2001:db8:beef::/48", "blackhole", 1024),
|
||
("2001:db8:dead::/48", "unreachable", 1024),
|
||
],
|
||
)
|
||
def test_a_route_that_forwards_nothing_says_its_type(self, routes, network, route_type, metric):
|
||
(entry,) = routes[network]
|
||
|
||
assert entry["protocol_attributes"] == {"type": route_type}
|
||
assert entry["preference"] == metric
|
||
# Nothing leaves through an interface; IPv6 names lo for it.
|
||
assert (entry["next_hop"], entry["outgoing_interface"]) == ("", "")
|
||
|
||
def test_the_rest_of_a_typed_line_is_read_as_before(self, routes):
|
||
assert routes["203.0.113.0/24"][0]["protocol"] == "static"
|
||
|
||
def test_a_unicast_route_has_no_type(self, routes):
|
||
assert routes["192.0.2.0/24"][0]["protocol_attributes"] == {}
|
||
|
||
@pytest.mark.parametrize(
|
||
("network", "hops"),
|
||
[
|
||
("0.0.0.0/0", [("192.0.2.1", "eth0"), ("198.51.100.1", "eth1")]),
|
||
("::/0", [("2001:db8:1::1", "eth0"), ("2001:db8:2::1", "eth1")]),
|
||
],
|
||
)
|
||
def test_a_multipath_route_has_one_entry_per_next_hop(self, routes, network, hops):
|
||
entries = routes[network]
|
||
|
||
assert [(e["next_hop"], e["outgoing_interface"]) for e in entries] == hops
|
||
assert {(e["protocol"], e["preference"]) for e in entries} == {
|
||
("static", 100 if network == "0.0.0.0/0" else 1024)
|
||
}
|
||
|
||
def test_no_next_hop_line_is_a_route_of_its_own(self, routes):
|
||
assert not any(network.startswith("nexthop") for network in routes)
|
||
|
||
|
||
class TestParseIpRoute:
|
||
"""``parse_ip_route`` line by line (#57)."""
|
||
|
||
def test_a_typed_route_that_forwards_keeps_its_interface(self):
|
||
# ``ip route show table local``: a local route names the interface it is on.
|
||
line = "local 192.0.2.10 dev eth0 proto kernel scope host src 192.0.2.10\n"
|
||
|
||
assert list(parse_ip_route(line, "ipv4")) == [
|
||
IpRoute("192.0.2.10/32", "kernel", "", "eth0", 0, "local")
|
||
]
|
||
|
||
def test_a_next_hop_line_without_a_route_is_dropped(self):
|
||
out = "\tnexthop via 192.0.2.1 dev eth0 weight 1\n192.0.2.0/24 dev eth0 proto kernel\n"
|
||
|
||
assert [r.network for r in parse_ip_route(out, "ipv4")] == ["192.0.2.0/24"]
|
||
|
||
def test_a_route_without_next_hop_lines_is_one_route(self):
|
||
out = "default via 192.0.2.1 dev eth0 proto dhcp metric 100\n"
|
||
|
||
assert list(parse_ip_route(out, "ipv4")) == [
|
||
IpRoute("0.0.0.0/0", "dhcp", "192.0.2.1", "eth0", 100)
|
||
]
|
||
|
||
|
||
class TestFrrHostRoutes:
|
||
"""The FRR enrichment completes a prefix without a length by its family (#64)."""
|
||
|
||
# FRR installs its routes as "proto zebra"; vtysh names the real source.
|
||
_IP6 = "2001:db8:2::7 via fe80::1 dev eth0 proto zebra metric 20 pref medium\n"
|
||
_VTYSH = (
|
||
"O>* 2001:db8:2::7 [110/20] via fe80::1, eth0, weight 1, 00:01:02\n"
|
||
"O>* 2001:db8:3::9 [110/30] via fe80::1, eth0, weight 1, 00:01:02\n"
|
||
"O>* 10.10.0.7 [110/20] via 10.255.255.2, wg0, weight 1, 00:01:02\n"
|
||
"O>* 10.10.1.0/24 [110/20] via 10.255.255.2, wg0, weight 1, 00:01:02\n"
|
||
)
|
||
|
||
@pytest.fixture()
|
||
def routes(self, driver):
|
||
def send(command, **_kw):
|
||
if command.startswith("command -v vtysh"):
|
||
return "/usr/bin/vtysh"
|
||
if command.startswith("vtysh"):
|
||
return self._VTYSH
|
||
if "ip -6 route" in command:
|
||
return self._IP6
|
||
return ""
|
||
|
||
with patch.object(driver, "_send", side_effect=send):
|
||
return driver.get_route_to()
|
||
|
||
def test_an_ipv6_host_route_is_a_128(self, routes):
|
||
assert "2001:db8:3::9/128" in routes
|
||
assert not any(
|
||
network.endswith("::7/32") or network.endswith("::9/32") for network in routes
|
||
)
|
||
|
||
def test_it_meets_the_kernel_route_of_the_same_host(self, routes):
|
||
assert [e["protocol"] for e in routes["2001:db8:2::7/128"]] == ["ospf"]
|
||
|
||
def test_an_ipv4_host_route_stays_a_32(self, routes):
|
||
assert "10.10.0.7/32" in routes
|
||
|
||
def test_a_prefix_with_a_length_keeps_it(self, routes):
|
||
assert "10.10.1.0/24" in routes
|
||
|
||
|
||
#: ``ip -4 route show``, iproute2 6.1.0 on Linux 7.0 (Linux Mint 22.3), recorded in a
|
||
#: network namespace set up for it: IPv4 routes with IPv6 next hops (RFC 8950), single
|
||
#: and multipath, as BGP unnumbered installs them (#65). Documentation addresses only.
|
||
_IP4_VIA_INET6 = (
|
||
"default via inet6 2001:db8:1::1 dev eth0 \n"
|
||
"10.20.0.0/16 proto bgp metric 20 \n"
|
||
"\tnexthop via inet6 2001:db8:1::1 dev eth0 weight 1 \n"
|
||
"\tnexthop via inet6 2001:db8:2::1 dev eth1 weight 1 \n"
|
||
"10.40.0.0/16 via inet6 2001:db8:1::1 dev eth0 proto bgp metric 20 \n"
|
||
"192.0.2.0/24 dev eth0 proto kernel scope link src 192.0.2.10 \n"
|
||
)
|
||
|
||
|
||
class TestIpv6NextHops:
|
||
"""``via inet6 <address>``: the next hop is the address (#65)."""
|
||
|
||
@pytest.fixture()
|
||
def routes(self, driver):
|
||
def send(command, **_kw):
|
||
return _IP4_VIA_INET6 if "ip -4 route" in command else ""
|
||
|
||
with patch.object(driver, "_send", side_effect=send):
|
||
return driver.get_route_to()
|
||
|
||
@pytest.mark.parametrize("network", ["0.0.0.0/0", "10.40.0.0/16"])
|
||
def test_the_next_hop_is_the_address(self, routes, network):
|
||
assert [e["next_hop"] for e in routes[network]] == ["2001:db8:1::1"]
|
||
|
||
def test_a_multipath_route_has_each_address(self, routes):
|
||
hops = [(e["next_hop"], e["outgoing_interface"]) for e in routes["10.20.0.0/16"]]
|
||
|
||
assert hops == [("2001:db8:1::1", "eth0"), ("2001:db8:2::1", "eth1")]
|
||
|
||
def test_the_route_stays_ipv4(self, routes):
|
||
"""The family is the destination's; an IPv6 next hop does not change it."""
|
||
assert {e["family"] for entries in routes.values() for e in entries} == {"ipv4"}
|
||
|
||
def test_a_family_word_for_ipv4_is_skipped_too(self):
|
||
out = "10.50.0.0/16 via inet 192.0.2.1 dev eth0\n"
|
||
|
||
assert [r.nexthop for r in parse_ip_route(out, "ipv4")] == ["192.0.2.1"]
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# get_packages (rpm) and the installed advisories (NetOrk/netork#2394)
|
||
# ---------------------------------------------------------------------------
|
||
|
||
# rpm -qa on Oracle Linux 9.8 (aarch64): gmp and openssl carry epoch 1; perf is
|
||
# built from the kernel's source rpm; gpg-pubkey has none.
|
||
RPM_QA = (
|
||
"glibc-common\t2.34-284.0.1.el9_8.4\t1210460\tglibc-2.34-284.0.1.el9_8.4.src.rpm"
|
||
"\tCommon binaries and locale data for glibc\n"
|
||
"gmp\t1:6.2.0-13.el9\t805146\tgmp-6.2.0-13.el9.src.rpm\tA GNU arbitrary precision library\n"
|
||
"openssl\t1:3.5.8-2.0.1.el9_8\t2106925\topenssl-3.5.8-2.0.1.el9_8.src.rpm"
|
||
"\tUtilities from the general purpose cryptography library\n"
|
||
"perf\t5.14.0-687.66.1.el9_8\t5401292\tkernel-5.14.0-687.66.1.el9_8.src.rpm"
|
||
"\tPerformance monitoring for the Linux kernel\n"
|
||
"gpg-pubkey\t8d8b756f-629e59ec\t0\t(none)\tOracle OSS group (Open Source Software group)\n"
|
||
)
|
||
|
||
|
||
class TestRpmPackages:
|
||
def test_the_version_carries_the_epoch_where_the_package_has_one(self, driver):
|
||
"""Oracle's and Red Hat's fixes name it (`1:6.2.0-13.el9`); without it an
|
||
epoch-1 fix reads as newer than every installed build."""
|
||
driver._pkg_manager = "dnf"
|
||
with patch.object(driver, "_send", return_value=RPM_QA) as send:
|
||
pkgs = {p["name"]: p for p in driver.get_packages()}
|
||
|
||
assert "%|EPOCH?{%{EPOCH}:}:{}|%{VERSION}-%{RELEASE}" in send.call_args.args[0]
|
||
assert pkgs["gmp"]["version"] == "1:6.2.0-13.el9"
|
||
assert pkgs["openssl"]["version"] == "1:3.5.8-2.0.1.el9_8"
|
||
assert pkgs["glibc-common"]["version"] == "2.34-284.0.1.el9_8.4"
|
||
assert pkgs["glibc-common"]["source"] == "dnf"
|
||
assert pkgs["glibc-common"]["size"] == 1210460
|
||
assert pkgs["openssl"]["description"] == (
|
||
"Utilities from the general purpose cryptography library"
|
||
)
|
||
|
||
def test_each_package_names_the_source_rpm_it_was_built_from(self, driver):
|
||
"""perf, python3-perf and bpftool are built from the kernel's source rpm,
|
||
and Red Hat lists them in every kernel CVE: netOrk tells them apart from
|
||
user space by that name (NetOrk/netork#2394)."""
|
||
driver._pkg_manager = "dnf"
|
||
with patch.object(driver, "_send", return_value=RPM_QA) as send:
|
||
pkgs = {p["name"]: p for p in driver.get_packages()}
|
||
|
||
assert "%{SOURCERPM}" in send.call_args.args[0]
|
||
assert pkgs["perf"]["source_rpm"] == "kernel"
|
||
assert pkgs["glibc-common"]["source_rpm"] == "glibc"
|
||
assert pkgs["openssl"]["source_rpm"] == "openssl"
|
||
assert "source_rpm" not in pkgs["gpg-pubkey"]
|
||
# Not `source_package`: netOrk reads that as the name a distribution
|
||
# files its verdicts under, and Oracle's and Red Hat's name the binary.
|
||
assert all("source_package" not in p for p in pkgs.values())
|
||
|
||
|
||
class TestInstalledAdvisoryCves:
|
||
def test_dnf_reads_the_installed_advisories_as_root(self, driver):
|
||
driver._pkg_manager = "dnf"
|
||
driver._device.send_command.side_effect = [
|
||
"0", # id -u
|
||
(
|
||
"CVE-2023-4911 Important/Sec. glibc-common-2.34-60.0.3.el9_2.7.aarch64\n"
|
||
"CVE-2023-38545 Important/Sec. curl-7.76.1-26.el9_3.2.aarch64\n"
|
||
"__DNF_RC=0\n__NETORK_RC=0"
|
||
),
|
||
]
|
||
|
||
assert driver.get_installed_advisory_cves() == {
|
||
"glibc-common": ["CVE-2023-4911"],
|
||
"curl": ["CVE-2023-38545"],
|
||
}
|
||
sent = driver._device.send_command.call_args.args[0]
|
||
assert DNF_INSTALLED_CVES_COMMAND in sent
|
||
|
||
def test_a_failed_dnf_raises_instead_of_reading_as_nothing_installed(self, driver):
|
||
driver._pkg_manager = "dnf"
|
||
driver._device.send_command.side_effect = ["0", "__DNF_RC=1\n__NETORK_RC=0"]
|
||
|
||
with pytest.raises(ValueError, match="exit status 1"):
|
||
driver.get_installed_advisory_cves()
|
||
|
||
@pytest.mark.parametrize("manager", ["yum", "apt", "apk", "pacman"])
|
||
def test_other_package_managers_keep_no_such_advisories(self, driver, manager):
|
||
driver._pkg_manager = manager
|
||
|
||
with pytest.raises(NotImplementedError):
|
||
driver.get_installed_advisory_cves()
|
||
|
||
|
||
class TestSourceRpmName:
|
||
@pytest.mark.parametrize(
|
||
("sourcerpm", "name"),
|
||
[
|
||
("kernel-5.14.0-687.66.1.el9_8.src.rpm", "kernel"),
|
||
("kernel-uek-6.12.0-104.43.4.3.el9uek.src.rpm", "kernel-uek"),
|
||
("python-dateutil-2.8.1-7.el9.src.rpm", "python-dateutil"),
|
||
("dummy-1.0-1.nosrc.rpm", "dummy"),
|
||
("(none)", None),
|
||
("", None),
|
||
("broken.src.rpm", None),
|
||
],
|
||
)
|
||
def test_the_name_is_what_precedes_version_and_release(self, sourcerpm, name):
|
||
assert source_rpm_name(sourcerpm) == name
|