Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
59839b4efa | ||
|
|
c0453655b7 |
No files matched your search
+10
-20
@@ -7,28 +7,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||||||
|
|
||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
|
|
||||||
## [0.17.0] - 2026-11-26
|
## [0.18.0] - 2026-11-28
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
- `get_update_history(since)` before PVE 9.3: apt's history log over the node's SSH
|
- `get_pve_firewall()` on the PVE driver (NetOrk/netork#2654): the PVE firewall as the operator
|
||||||
session, through napalm-device-types' `AptHistoryMixin` (NetOrk/netork#2728). A
|
wrote it, read only -- the datacenter's options, rules, security groups, IP sets and aliases,
|
||||||
transaction gets the id 9.3's `GET /nodes/{node}/apt/history` gives it (start time and
|
this node's options and rules, and every guest's on this node with which of its NICs carry
|
||||||
the index among those that started in the same second of the same log file), so a node
|
`firewall=1`. Each rule keeps PVE's own fields and says where it came from. A part PVE refuses
|
||||||
keeps its ids when it moves to 9.3; 9.3 and later still read the API. A node without an
|
is None, not empty: an unread level is no claim. Nothing is written; pve-firewall rules stay
|
||||||
SSH login raises `NotImplementedError`, a failed read `RuntimeError`.
|
the operator's.
|
||||||
|
- `get_host_firewall()` on the PVE driver (napalm-device-types' `HostFirewallMixin`): what the
|
||||||
### Changed
|
node has loaded -- proxmox-firewall's nftables tables on PVE 9, pve-firewall's iptables chains
|
||||||
- Needs napalm-device-types 4.47.0 or later (`AptHistoryMixin`).
|
before -- read as root over SSH, as for any Linux host.
|
||||||
|
|
||||||
### Fixed
|
|
||||||
- `get_credential_expiry()` reads an API token's expiry from `GET /access/users/{userid}`
|
|
||||||
(`tokens[tokenid].expire`), in the same one call as the account's (NetOrk/netork#2728).
|
|
||||||
`GET /access/users/{userid}/token/{tokenid}` refused practically every token: a token's
|
|
||||||
request runs as `user@realm!tokenid`, which that endpoint's `userid-param self` check
|
|
||||||
never matches, and its alternative is `User.Modify`. `read_user` needs `Sys.Audit` on
|
|
||||||
`/access/groups` or a group of the user, which PVEAuditor on `/` gives; a 403 raises a
|
|
||||||
`PermissionError` that names it. A token without an expiry of its own expires with its
|
|
||||||
user, and one with its own stops working with its user too: the earlier counts.
|
|
||||||
|
|
||||||
## [0.16.0] - 2026-11-26
|
## [0.16.0] - 2026-11-26
|
||||||
|
|
||||||
|
|||||||
@@ -133,6 +133,8 @@ device = driver(
|
|||||||
| `configure_time_sync(ntp_servers=, timezone=)` | servers to `/etc/chrony/sources.d/netork.sources`, every other configured source commented out (DHCP's `sourcedir` stays), then a reload or a restart of chrony; the zone through `PUT /nodes/{node}/time` (the token needs `Sys.Modify` on `/nodes/{node}`), so `/etc/timezone` and the web UI follow. Only this node: in a cluster each node keeps its own clock |
|
| `configure_time_sync(ntp_servers=, timezone=)` | servers to `/etc/chrony/sources.d/netork.sources`, every other configured source commented out (DHCP's `sourcedir` stays), then a reload or a restart of chrony; the zone through `PUT /nodes/{node}/time` (the token needs `Sys.Modify` on `/nodes/{node}`), so `/etc/timezone` and the web UI follow. Only this node: in a cluster each node keeps its own clock |
|
||||||
| `get_certificates` | `GET /nodes/{node}/certificates/info`, in netOrk's contract shape: `{name, issuer, valid_from, valid_to, in_use_by}` (Unix timestamps; the file name, the issuer's CN; `in_use_by` 1 for the one pveproxy serves, `pveproxy-ssl.pem` before `pve-ssl.pem`), plus `subject`, `fingerprint` and `acme`: true for `pveproxy-ssl.pem` when the node's config names an ACME domain (one more call, `GET /nodes/{node}/config`). Never the PEM. `[]` when unreadable |
|
| `get_certificates` | `GET /nodes/{node}/certificates/info`, in netOrk's contract shape: `{name, issuer, valid_from, valid_to, in_use_by}` (Unix timestamps; the file name, the issuer's CN; `in_use_by` 1 for the one pveproxy serves, `pveproxy-ssl.pem` before `pve-ssl.pem`), plus `subject`, `fingerprint` and `acme`: true for `pveproxy-ssl.pem` when the node's config names an ACME domain (one more call, `GET /nodes/{node}/config`). Never the PEM. `[]` when unreadable |
|
||||||
| `get_services_need_restart` | the services that still run code an update replaced on disk, as root over SSH (napalm-device-types' `ServicesRestartMixin`): `needrestart` in list-only mode where it is installed, else the processes whose `/proc/<pid>/maps` maps deleted code. A running VM's QEMU is a process (`processes`), an LXC container's processes are left out (the container updates itself). Only as root: another SSH login gets no reading, rather than a clean one |
|
| `get_services_need_restart` | the services that still run code an update replaced on disk, as root over SSH (napalm-device-types' `ServicesRestartMixin`): `needrestart` in list-only mode where it is installed, else the processes whose `/proc/<pid>/maps` maps deleted code. A running VM's QEMU is a process (`processes`), an LXC container's processes are left out (the container updates itself). Only as root: another SSH login gets no reading, rather than a clean one |
|
||||||
|
| `get_pve_firewall` | the PVE firewall as the operator wrote it, read only (NetOrk/netork#2654): the datacenter's `options`, `rules`, security `groups` (name → rules), `ipsets` (name → `[{cidr, nomatch, comment}]`) and `aliases` (name → cidr), this node's `options` and `rules`, and every guest's on this node (`vmid`, `type`, `name`, `options`, `rules`, and `nics`: `[{name, firewall}]` from `netN … firewall=1`). Each rule keeps PVE's fields and its `origin` (`cluster`, `group`, `node`, `guest`). A part PVE refuses is `null`, never empty |
|
||||||
|
| `get_host_firewall` | what the node has loaded, as for any Linux host (napalm-device-types' `HostFirewallMixin`): `nft list ruleset` (PVE 9's proxmox-firewall) or `iptables-save` (pve-firewall), as root over SSH |
|
||||||
|
|
||||||
**Not implemented** (raise `NotImplementedError`):
|
**Not implemented** (raise `NotImplementedError`):
|
||||||
`get_bgp_config`, `get_bgp_neighbors`, `get_bgp_neighbors_detail`,
|
`get_bgp_config`, `get_bgp_neighbors`, `get_bgp_neighbors_detail`,
|
||||||
@@ -239,6 +241,7 @@ napalm_proxmox/
|
|||||||
├── pbs_backups.py # The backup-server role: datastores, groups, jobs, remotes, actions
|
├── pbs_backups.py # The backup-server role: datastores, groups, jobs, remotes, actions
|
||||||
├── pbs_host.py # The backup server as a host: facts, interfaces, disks, ZFS pools
|
├── pbs_host.py # The backup server as a host: facts, interfaces, disks, ZFS pools
|
||||||
├── certificates.py # get_certificates on both: the node's TLS certificates, and ACME
|
├── certificates.py # get_certificates on both: the node's TLS certificates, and ACME
|
||||||
|
├── firewall_mixin.py # get_pve_firewall: the PVE firewall at every level, read only
|
||||||
└── utils.py # MAC normalisation, CIDR parsing, ARP/OVS parsers
|
└── utils.py # MAC normalisation, CIDR parsing, ARP/OVS parsers
|
||||||
tests/
|
tests/
|
||||||
├── conftest.py # Shared fixtures and mock API payloads
|
├── conftest.py # Shared fixtures and mock API payloads
|
||||||
@@ -251,6 +254,7 @@ tests/
|
|||||||
├── test_misc.py # NTP statistics, SNMP, users, config, ping, traceroute, CLI, LLDP
|
├── test_misc.py # NTP statistics, SNMP, users, config, ping, traceroute, CLI, LLDP
|
||||||
├── test_time_sync.py # get_time_sync / configure_time_sync on both drivers
|
├── test_time_sync.py # get_time_sync / configure_time_sync on both drivers
|
||||||
├── test_certificates.py # get_certificates on both drivers
|
├── test_certificates.py # get_certificates on both drivers
|
||||||
|
├── test_firewall.py # get_pve_firewall and get_host_firewall
|
||||||
├── test_utils.py # Unit tests for napalm_proxmox.utils
|
├── test_utils.py # Unit tests for napalm_proxmox.utils
|
||||||
├── fixtures/pbs_api.json # What a Proxmox Backup Server 4.2 answered (sanitised)
|
├── fixtures/pbs_api.json # What a Proxmox Backup Server 4.2 answered (sanitised)
|
||||||
├── pbs_fake.py # A proxmoxer stand-in answering from that recording
|
├── pbs_fake.py # A proxmoxer stand-in answering from that recording
|
||||||
|
|||||||
@@ -251,10 +251,6 @@ class ProxmoxBase:
|
|||||||
f"Cannot run a command on {self.hostname} over SSH: {exc}"
|
f"Cannot run a command on {self.hostname} over SSH: {exc}"
|
||||||
) from exc
|
) from exc
|
||||||
|
|
||||||
def _has_ssh_login(self) -> bool:
|
|
||||||
"""Whether the driver has something to log in to the node's SSH with."""
|
|
||||||
return bool(self._ssh_password or self.password or self._ssh_key)
|
|
||||||
|
|
||||||
def _node_ssh(self) -> Any: # paramiko.SSHClient; paramiko is imported lazily
|
def _node_ssh(self) -> Any: # paramiko.SSHClient; paramiko is imported lazily
|
||||||
"""The SSH session to the node on port 22, opened once.
|
"""The SSH session to the node on port 22, opened once.
|
||||||
|
|
||||||
|
|||||||
@@ -1,28 +1,23 @@
|
|||||||
"""When the credential the Proxmox VE driver logs in with expires (NetOrk/netork#2728).
|
"""When the credential the Proxmox VE driver logs in with expires (NetOrk/netork#2728).
|
||||||
|
|
||||||
``CredentialExpiryMixin`` of napalm-device-types. The driver logs in either with
|
``CredentialExpiryMixin`` of napalm-device-types. The driver logs in either with
|
||||||
an API token (``user@realm!tokenid``) or with a user's password; both are read
|
an API token (``user@realm!tokenid``) or with a user's password:
|
||||||
with one ``GET /access/users/{userid}`` (``read_user``), which returns the
|
|
||||||
account's ``expire`` and ``tokens: {tokenid: {expire, privsep, comment}}``:
|
|
||||||
|
|
||||||
- a password: the account's ``expire``;
|
- a token: ``GET /access/users/{userid}/token/{tokenid}``, its ``expire``. A token
|
||||||
- a token: ``tokens[tokenid].expire``. A token without one of its own (``0`` or
|
without one of its own expires with its user (the schema's default, "same as
|
||||||
none, "same as user") expires with its user; one with its own still stops
|
user"), read as for a password;
|
||||||
working when its user expires first, so the earlier of the two counts.
|
- a password: ``GET /access/users/{userid}``, the account's ``expire``.
|
||||||
|
|
||||||
``0`` or no value is never. PVE 9.3's datacenter ``token-policy`` can require an
|
``0`` or no value is never. PVE 9.3's datacenter ``token-policy`` can require an
|
||||||
expiry on every token; the fields themselves are older, so every release is read.
|
expiry on every token; the fields themselves are older, so every release is read.
|
||||||
|
PVE lets a user read itself and its tokens; a privilege-separated token may be
|
||||||
``read_user`` needs ``Sys.Audit`` (or ``User.Modify``) on ``/access/groups`` or on
|
refused its user (``User.Modify`` or ``Sys.Audit`` on the user's group), and a
|
||||||
a group of the user; PVEAuditor on ``/`` gives it. Not even a user may read
|
403 is a ``PermissionError``, as the contract says.
|
||||||
itself without it, and a 403 is a ``PermissionError`` that names the privilege,
|
|
||||||
as the contract says. ``GET /access/users/{userid}/token/{tokenid}`` is no way
|
|
||||||
round: a token's request runs as ``user@realm!tokenid``, which that endpoint's
|
|
||||||
``userid-param self`` check never matches, and its alternative is ``User.Modify``.
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from collections.abc import Callable
|
||||||
from typing import TYPE_CHECKING, Any
|
from typing import TYPE_CHECKING, Any
|
||||||
|
|
||||||
from napalm_device_types import CredentialExpiryDict, CredentialExpiryMixin
|
from napalm_device_types import CredentialExpiryDict, CredentialExpiryMixin
|
||||||
@@ -30,19 +25,24 @@ from proxmoxer.core import ResourceException
|
|||||||
|
|
||||||
_JsonDict = dict[str, Any]
|
_JsonDict = dict[str, Any]
|
||||||
|
|
||||||
#: What ``GET /access/users/{userid}`` asks of the login, for a 403's message.
|
|
||||||
_PRIVILEGE = "Sys.Audit on /access/groups (PVEAuditor on / gives it)"
|
|
||||||
|
|
||||||
|
|
||||||
def _expires(value: Any) -> int | None:
|
def _expires(value: Any) -> int | None:
|
||||||
"""PVE's ``expire``: unix seconds, ``0`` or none for never."""
|
"""PVE's ``expire``: unix seconds, ``0`` or none for never."""
|
||||||
return int(value or 0) or None
|
return int(value or 0) or None
|
||||||
|
|
||||||
|
|
||||||
def _earliest(*values: int | None) -> int | None:
|
def _read(get: Callable[[], Any], what: str) -> _JsonDict:
|
||||||
"""The earliest of *values* that is a time; None where none is."""
|
"""``get()``'s answer; a refusal as ``PermissionError``, another failure as
|
||||||
times = [v for v in values if v is not None]
|
``RuntimeError``."""
|
||||||
return min(times) if times else None
|
try:
|
||||||
|
answer = get()
|
||||||
|
except ResourceException as exc:
|
||||||
|
if exc.status_code == 403:
|
||||||
|
raise PermissionError(f"Proxmox VE will not tell {what}'s expiry: {exc}") from exc
|
||||||
|
raise RuntimeError(f"Cannot read the expiry of {what}: {exc}") from exc
|
||||||
|
except Exception as exc:
|
||||||
|
raise RuntimeError(f"Cannot read the expiry of {what}: {exc}") from exc
|
||||||
|
return dict(answer or {})
|
||||||
|
|
||||||
|
|
||||||
class ProxmoxCredentialExpiryMixin(CredentialExpiryMixin):
|
class ProxmoxCredentialExpiryMixin(CredentialExpiryMixin):
|
||||||
@@ -58,29 +58,16 @@ class ProxmoxCredentialExpiryMixin(CredentialExpiryMixin):
|
|||||||
"""The API token or the account this connection logged in with, and its expiry."""
|
"""The API token or the account this connection logged in with, and its expiry."""
|
||||||
login = self._api_kwargs()
|
login = self._api_kwargs()
|
||||||
userid = str(login["user"])
|
userid = str(login["user"])
|
||||||
user = self._read_user(userid)
|
|
||||||
account = _expires(user.get("expire"))
|
|
||||||
if "token_value" not in login:
|
if "token_value" not in login:
|
||||||
return {"kind": "account", "name": userid, "expires": account}
|
return {"kind": "account", "name": userid, "expires": self._user_expiry(userid)}
|
||||||
token_id = str(login["token_name"])
|
name = f"{userid}!{login['token_name']}"
|
||||||
token = dict((user.get("tokens") or {}).get(token_id) or {})
|
token = _read(lambda: self._api.access.users(userid).token(login["token_name"]).get(), name)
|
||||||
|
expire = token.get("expire")
|
||||||
return {
|
return {
|
||||||
"kind": "api-token",
|
"kind": "api-token",
|
||||||
"name": f"{userid}!{token_id}",
|
"name": name,
|
||||||
"expires": _earliest(_expires(token.get("expire")), account),
|
"expires": self._user_expiry(userid) if expire is None else _expires(expire),
|
||||||
}
|
}
|
||||||
|
|
||||||
def _read_user(self, userid: str) -> _JsonDict:
|
def _user_expiry(self, userid: str) -> int | None:
|
||||||
"""``GET /access/users/{userid}``; a refusal as ``PermissionError``, another
|
return _expires(_read(lambda: self._api.access.users(userid).get(), userid).get("expire"))
|
||||||
failure as ``RuntimeError``."""
|
|
||||||
try:
|
|
||||||
answer = self._api.access.users(userid).get()
|
|
||||||
except ResourceException as exc:
|
|
||||||
if exc.status_code == 403:
|
|
||||||
raise PermissionError(
|
|
||||||
f"Proxmox VE will not tell {userid}'s expiry without {_PRIVILEGE}: {exc}"
|
|
||||||
) from exc
|
|
||||||
raise RuntimeError(f"Cannot read the expiry of {userid}: {exc}") from exc
|
|
||||||
except Exception as exc:
|
|
||||||
raise RuntimeError(f"Cannot read the expiry of {userid}: {exc}") from exc
|
|
||||||
return dict(answer or {})
|
|
||||||
@@ -29,6 +29,7 @@ from napalm_device_types import (
|
|||||||
AptProxyMixin,
|
AptProxyMixin,
|
||||||
EnsurePackageMixin,
|
EnsurePackageMixin,
|
||||||
FingerprintRule,
|
FingerprintRule,
|
||||||
|
HostFirewallMixin,
|
||||||
HostStatusMixin,
|
HostStatusMixin,
|
||||||
HypervisorDriver,
|
HypervisorDriver,
|
||||||
KernelFactsMixin,
|
KernelFactsMixin,
|
||||||
@@ -54,6 +55,7 @@ from napalm_proxmox.certificates import ProxmoxCertificatesMixin
|
|||||||
from napalm_proxmox.cluster_mixin import ProxmoxClusterMixin
|
from napalm_proxmox.cluster_mixin import ProxmoxClusterMixin
|
||||||
from napalm_proxmox.config_mixin import ProxmoxConfigMixin
|
from napalm_proxmox.config_mixin import ProxmoxConfigMixin
|
||||||
from napalm_proxmox.credential_expiry import ProxmoxCredentialExpiryMixin
|
from napalm_proxmox.credential_expiry import ProxmoxCredentialExpiryMixin
|
||||||
|
from napalm_proxmox.firewall_mixin import ProxmoxFirewallMixin
|
||||||
from napalm_proxmox.host_mixin import ProxmoxHostMixin
|
from napalm_proxmox.host_mixin import ProxmoxHostMixin
|
||||||
from napalm_proxmox.interfaces_mixin import ProxmoxInterfaceMixin
|
from napalm_proxmox.interfaces_mixin import ProxmoxInterfaceMixin
|
||||||
from napalm_proxmox.lldp_mixin import ProxmoxLLDPMixin
|
from napalm_proxmox.lldp_mixin import ProxmoxLLDPMixin
|
||||||
@@ -98,7 +100,9 @@ class ProxmoxDriver(
|
|||||||
ProxmoxRoutingMixin,
|
ProxmoxRoutingMixin,
|
||||||
ProxmoxSystemMixin,
|
ProxmoxSystemMixin,
|
||||||
ProxmoxHostMixin,
|
ProxmoxHostMixin,
|
||||||
|
ProxmoxFirewallMixin,
|
||||||
KernelFactsMixin,
|
KernelFactsMixin,
|
||||||
|
HostFirewallMixin,
|
||||||
ServicePackagesMixin,
|
ServicePackagesMixin,
|
||||||
ListeningSocketsMixin,
|
ListeningSocketsMixin,
|
||||||
LogSourcesMixin,
|
LogSourcesMixin,
|
||||||
|
|||||||
@@ -0,0 +1,190 @@
|
|||||||
|
"""The PVE firewall of the cluster, read-only (NetOrk/netork#2654).
|
||||||
|
|
||||||
|
``get_pve_firewall()`` reads what the operator wrote, at every level PVE has one:
|
||||||
|
the datacenter's options, rules, security groups, IP sets and aliases, the node's
|
||||||
|
options and rules, and each guest's on this node -- options, rules, and which NICs
|
||||||
|
carry ``firewall=1``. The datacenter level is the cluster's (pmxcfs keeps it once
|
||||||
|
for every node), so every node reads the same; a node reads its own guests, the
|
||||||
|
ones it runs. Nothing is written: pve-firewall rules are the operator's (see
|
||||||
|
``host_mixin``), and netOrk only reads them.
|
||||||
|
|
||||||
|
Each rule keeps PVE's own fields -- ``pos``, ``type`` (``in``, ``out``, ``group``,
|
||||||
|
``forward``), ``action`` (``ACCEPT``, ``DROP``, ``REJECT``, or a group's name),
|
||||||
|
``macro``, ``source``, ``dest``, ``proto``, ``dport``, ``sport``, ``iface``,
|
||||||
|
``enable``, ``comment`` -- and says where it came from (``origin``: ``cluster``,
|
||||||
|
``node``, ``guest`` or ``group``). A level whose call is refused (no
|
||||||
|
``Sys.Audit``/``VM.Audit``) is None, not empty: an unread level is no claim.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import re
|
||||||
|
from typing import TYPE_CHECKING, Any
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
_JsonDict = dict[str, Any]
|
||||||
|
|
||||||
|
#: The rule fields kept as PVE returns them.
|
||||||
|
_RULE_FIELDS = (
|
||||||
|
"pos",
|
||||||
|
"type",
|
||||||
|
"action",
|
||||||
|
"macro",
|
||||||
|
"source",
|
||||||
|
"dest",
|
||||||
|
"proto",
|
||||||
|
"dport",
|
||||||
|
"sport",
|
||||||
|
"iface",
|
||||||
|
"comment",
|
||||||
|
"log",
|
||||||
|
"icmp-type",
|
||||||
|
)
|
||||||
|
#: A guest's NIC keys: ``net0`` … for both QEMU and LXC.
|
||||||
|
_NIC = re.compile(r"^net\d+$")
|
||||||
|
|
||||||
|
|
||||||
|
def _rule(raw: _JsonDict, origin: str) -> _JsonDict:
|
||||||
|
found = {k.replace("-", "_"): raw[k] for k in _RULE_FIELDS if raw.get(k) not in (None, "")}
|
||||||
|
found["enable"] = str(raw.get("enable", 1)) not in ("0", "")
|
||||||
|
found["origin"] = origin
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
def _rules(rows: Any, origin: str) -> list[_JsonDict]:
|
||||||
|
return [_rule(r, origin) for r in rows or [] if isinstance(r, dict)]
|
||||||
|
|
||||||
|
|
||||||
|
def nic_firewalls(config: _JsonDict) -> list[_JsonDict]:
|
||||||
|
"""Each NIC of a guest config with whether ``firewall=1`` is set on it."""
|
||||||
|
found = []
|
||||||
|
for key in sorted(k for k in config if _NIC.match(k)):
|
||||||
|
options = dict(part.split("=", 1) for part in str(config[key]).split(",") if "=" in part)
|
||||||
|
found.append({"name": key, "firewall": options.get("firewall") == "1"})
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
def _read(call: Any, what: str) -> Any:
|
||||||
|
"""One GET; None when PVE refuses or fails it -- an unread level, not an empty one."""
|
||||||
|
try:
|
||||||
|
return call.get()
|
||||||
|
except Exception as exc: # noqa: BLE001 - proxmoxer raises its own and requests' errors
|
||||||
|
logger.warning("get_pve_firewall: %s not read: %s", what, exc)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _rules_or_none(rows: Any, origin: str) -> list[_JsonDict] | None:
|
||||||
|
return None if rows is None else _rules(rows, origin)
|
||||||
|
|
||||||
|
|
||||||
|
def _named(rows: Any, key: str) -> list[str]:
|
||||||
|
return [str(r[key]) for r in rows or [] if isinstance(r, dict) and r.get(key)]
|
||||||
|
|
||||||
|
|
||||||
|
def _groups(fw: Any) -> dict[str, list[_JsonDict]] | None:
|
||||||
|
"""Each security group's rules; a group whose rules are refused has none listed."""
|
||||||
|
listed = _read(fw.groups, "security groups")
|
||||||
|
if listed is None:
|
||||||
|
return None
|
||||||
|
return {
|
||||||
|
name: _rules(_read(fw.groups(name), f"group {name}"), "group")
|
||||||
|
for name in _named(listed, "group")
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _entry(raw: _JsonDict) -> _JsonDict:
|
||||||
|
return {
|
||||||
|
"cidr": raw.get("cidr"),
|
||||||
|
"nomatch": bool(raw.get("nomatch")),
|
||||||
|
"comment": raw.get("comment"),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _ipsets(fw: Any) -> dict[str, list[_JsonDict]] | None:
|
||||||
|
listed = _read(fw.ipset, "IP sets")
|
||||||
|
if listed is None:
|
||||||
|
return None
|
||||||
|
return {
|
||||||
|
name: [
|
||||||
|
_entry(e) for e in _read(fw.ipset(name), f"IP set {name}") or [] if isinstance(e, dict)
|
||||||
|
]
|
||||||
|
for name in _named(listed, "name")
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _aliases(rows: Any) -> dict[str, Any] | None:
|
||||||
|
if rows is None:
|
||||||
|
return None
|
||||||
|
return {str(a["name"]): a.get("cidr") for a in rows if isinstance(a, dict) and a.get("name")}
|
||||||
|
|
||||||
|
|
||||||
|
class ProxmoxFirewallMixin:
|
||||||
|
"""``get_pve_firewall`` for the PVE driver: the cluster's firewall as written, read only."""
|
||||||
|
|
||||||
|
_node_name: str
|
||||||
|
|
||||||
|
if TYPE_CHECKING: # pragma: no cover - the driver's (napalm_proxmox._base)
|
||||||
|
_api: Any
|
||||||
|
|
||||||
|
def _node_api(self) -> Any: ...
|
||||||
|
|
||||||
|
def _cluster_firewall(self) -> _JsonDict:
|
||||||
|
fw = self._api.cluster.firewall
|
||||||
|
return {
|
||||||
|
"options": _read(fw.options, "datacenter options"),
|
||||||
|
"rules": _rules_or_none(_read(fw.rules, "datacenter rules"), "cluster"),
|
||||||
|
"groups": _groups(fw),
|
||||||
|
"ipsets": _ipsets(fw),
|
||||||
|
"aliases": _aliases(_read(fw.aliases, "aliases")),
|
||||||
|
}
|
||||||
|
|
||||||
|
def _guest_firewall(self, kind: str, guest: _JsonDict) -> _JsonDict:
|
||||||
|
vmid = int(guest.get("vmid", 0))
|
||||||
|
api = getattr(self._node_api(), kind)(vmid)
|
||||||
|
rules = _read(api.firewall.rules, f"{kind} {vmid} rules")
|
||||||
|
config = _read(api.config, f"{kind} {vmid} config")
|
||||||
|
return {
|
||||||
|
"vmid": str(vmid),
|
||||||
|
"type": "vm" if kind == "qemu" else "container",
|
||||||
|
"name": guest.get("name") or "",
|
||||||
|
"node": self._node_name,
|
||||||
|
"options": _read(api.firewall.options, f"{kind} {vmid} options"),
|
||||||
|
"rules": _rules_or_none(rules, "guest"),
|
||||||
|
"nics": None if config is None else nic_firewalls(config),
|
||||||
|
}
|
||||||
|
|
||||||
|
def _guests(self) -> list[_JsonDict]:
|
||||||
|
found: list[_JsonDict] = []
|
||||||
|
for kind in ("qemu", "lxc"):
|
||||||
|
for guest in _read(getattr(self._node_api(), kind), f"{kind} guests") or []:
|
||||||
|
if isinstance(guest, dict) and guest.get("vmid") is not None:
|
||||||
|
found.append(self._guest_firewall(kind, guest))
|
||||||
|
return found
|
||||||
|
|
||||||
|
def get_pve_firewall(self) -> _JsonDict:
|
||||||
|
"""
|
||||||
|
Return the PVE firewall as the operator wrote it: the datacenter level, this
|
||||||
|
node's, and every guest's on this node. Read only.
|
||||||
|
|
||||||
|
* cluster (dict) - ``options``, ``rules``, ``groups`` (name -> rules),
|
||||||
|
``ipsets`` (name -> ``[{cidr, nomatch, comment}]``), ``aliases`` (name -> cidr)
|
||||||
|
* node (dict) - ``name``, ``options``, ``rules``
|
||||||
|
* guests (list) - ``vmid``, ``type`` (``vm``/``container``), ``name``, ``node``,
|
||||||
|
``options``, ``rules``, ``nics`` (``[{name, firewall}]``)
|
||||||
|
|
||||||
|
Any part PVE refuses is None, never empty. Each rule carries PVE's fields and
|
||||||
|
its ``origin`` (``cluster``, ``group``, ``node``, ``guest``).
|
||||||
|
"""
|
||||||
|
node = self._node_api().firewall
|
||||||
|
rules = _read(node.rules, "node rules")
|
||||||
|
return {
|
||||||
|
"cluster": self._cluster_firewall(),
|
||||||
|
"node": {
|
||||||
|
"name": self._node_name,
|
||||||
|
"options": _read(node.options, "node options"),
|
||||||
|
"rules": _rules_or_none(rules, "node"),
|
||||||
|
},
|
||||||
|
"guests": self._guests(),
|
||||||
|
}
|
||||||
@@ -72,6 +72,12 @@ class ProxmoxHostMixin:
|
|||||||
"""The transport for ``KernelFactsMixin.get_kernel_facts``: the exec path."""
|
"""The transport for ``KernelFactsMixin.get_kernel_facts``: the exec path."""
|
||||||
return self._exec_ssh_command(command)
|
return self._exec_ssh_command(command)
|
||||||
|
|
||||||
|
def _run_host_firewall_command(self, command: str, *, privileged: bool) -> str:
|
||||||
|
"""The transport for ``HostFirewallMixin.get_host_firewall``: the exec path, which
|
||||||
|
runs as root either way. What the node has loaded -- proxmox-firewall's nftables
|
||||||
|
tables on PVE 9, pve-firewall's iptables chains before (NetOrk/netork#2654)."""
|
||||||
|
return str(self._exec_ssh_command(command))
|
||||||
|
|
||||||
def _run_service_packages_command(self, command: str) -> str:
|
def _run_service_packages_command(self, command: str) -> str:
|
||||||
"""The transport for ``ServicePackagesMixin.get_service_packages``: the exec path."""
|
"""The transport for ``ServicePackagesMixin.get_service_packages``: the exec path."""
|
||||||
return str(self._exec_ssh_command(command))
|
return str(self._exec_ssh_command(command))
|
||||||
|
|||||||
@@ -4,23 +4,15 @@ PVE 9.3 reads apt's history log for ``GET /nodes/{node}/apt/history``, newest
|
|||||||
first, also the transactions netOrk did not start (an operator's ``apt``,
|
first, also the transactions netOrk did not start (an operator's ``apt``,
|
||||||
unattended-upgrades). A transaction is named by its ``start-time`` and its
|
unattended-upgrades). A transaction is named by its ``start-time`` and its
|
||||||
``start-index`` among those that started in the same second of the same log
|
``start-index`` among those that started in the same second of the same log
|
||||||
file. An older node has no such endpoint: the driver reads the same log over
|
file. An older node has no such endpoint: the driver raises
|
||||||
its SSH session with napalm-device-types' ``AptHistoryMixin``, which names a
|
``NotImplementedError`` and parses no log over SSH.
|
||||||
transaction the same way, so the ids stay when the node moves to 9.3. A node
|
|
||||||
without an SSH login raises ``NotImplementedError`` there.
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from typing import TYPE_CHECKING, Any, cast
|
from typing import TYPE_CHECKING, Any, cast
|
||||||
|
|
||||||
from napalm.base.exceptions import ConnectionException
|
from napalm_device_types import UpdateHistoryAction, UpdateHistoryDict, UpdateHistoryPackageDict
|
||||||
from napalm_device_types import (
|
|
||||||
AptHistoryMixin,
|
|
||||||
UpdateHistoryAction,
|
|
||||||
UpdateHistoryDict,
|
|
||||||
UpdateHistoryPackageDict,
|
|
||||||
)
|
|
||||||
|
|
||||||
from napalm_proxmox.pve_values import PVE_9_3
|
from napalm_proxmox.pve_values import PVE_9_3
|
||||||
|
|
||||||
@@ -54,9 +46,8 @@ def _transaction(row: _JsonDict) -> UpdateHistoryDict:
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
class ProxmoxUpdateHistoryMixin(AptHistoryMixin):
|
class ProxmoxUpdateHistoryMixin:
|
||||||
"""Relies on the driver's ``_node_api``, ``_version_at_least``, ``_has_ssh_login``
|
"""Relies on the driver's ``_node_api`` and ``_version_at_least``."""
|
||||||
and ``run_command``."""
|
|
||||||
|
|
||||||
_node_name: str
|
_node_name: str
|
||||||
|
|
||||||
@@ -64,31 +55,21 @@ class ProxmoxUpdateHistoryMixin(AptHistoryMixin):
|
|||||||
|
|
||||||
def _node_api(self) -> Any: ...
|
def _node_api(self) -> Any: ...
|
||||||
def _version_at_least(self, major: int, minor: int) -> bool: ...
|
def _version_at_least(self, major: int, minor: int) -> bool: ...
|
||||||
def _has_ssh_login(self) -> bool: ...
|
|
||||||
|
|
||||||
def get_update_history(self, since: int | None = None) -> list[UpdateHistoryDict]:
|
def get_update_history(self, since: int | None = None) -> list[UpdateHistoryDict]:
|
||||||
"""The node's APT transactions, newest first, from ``since`` (unix seconds) on.
|
"""The node's APT transactions, newest first, from ``since`` (unix seconds) on.
|
||||||
|
|
||||||
:raises NotImplementedError: before PVE 9.3 on a node without an SSH login.
|
:raises NotImplementedError: before PVE 9.3, which has no history endpoint.
|
||||||
:raises RuntimeError: the history could not be read; never an empty list.
|
:raises RuntimeError: the history could not be read; never an empty list.
|
||||||
"""
|
"""
|
||||||
if not self._version_at_least(*PVE_9_3):
|
if not self._version_at_least(*PVE_9_3):
|
||||||
return self._history_over_ssh(since)
|
raise NotImplementedError(
|
||||||
|
f"Proxmox VE on {self._node_name} keeps no APT history its API reports "
|
||||||
|
"(from 9.3 on)"
|
||||||
|
)
|
||||||
params = {} if since is None else {"since": since}
|
params = {} if since is None else {"since": since}
|
||||||
try:
|
try:
|
||||||
rows = self._node_api().apt.history.get(**params) or []
|
rows = self._node_api().apt.history.get(**params) or []
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
raise RuntimeError(f"Cannot read the APT history of {self._node_name}: {exc}") from exc
|
raise RuntimeError(f"Cannot read the APT history of {self._node_name}: {exc}") from exc
|
||||||
return [_transaction(row) for row in rows]
|
return [_transaction(row) for row in rows]
|
||||||
|
|
||||||
def _history_over_ssh(self, since: int | None) -> list[UpdateHistoryDict]:
|
|
||||||
"""Before 9.3: apt's log over the SSH session, root's login."""
|
|
||||||
if not self._has_ssh_login():
|
|
||||||
raise NotImplementedError(
|
|
||||||
f"Proxmox VE on {self._node_name} reports its APT history from 9.3 on; "
|
|
||||||
"before that it is read over SSH, and the node has no SSH login"
|
|
||||||
)
|
|
||||||
try:
|
|
||||||
return super().get_update_history(since)
|
|
||||||
except (ConnectionException, ValueError) as exc:
|
|
||||||
raise RuntimeError(f"Cannot read the APT history of {self._node_name}: {exc}") from exc
|
|
||||||
+2
-2
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|||||||
|
|
||||||
[project]
|
[project]
|
||||||
name = "napalm-proxmox"
|
name = "napalm-proxmox"
|
||||||
version = "0.17.0"
|
version = "0.18.0"
|
||||||
description = "NAPALM drivers for Proxmox VE (classic Linux networking, SDN, OVS) and Proxmox Backup Server"
|
description = "NAPALM drivers for Proxmox VE (classic Linux networking, SDN, OVS) and Proxmox Backup Server"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
license = "Apache-2.0"
|
license = "Apache-2.0"
|
||||||
@@ -21,7 +21,7 @@ classifiers = [
|
|||||||
requires-python = ">=3.12"
|
requires-python = ">=3.12"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"napalm>=5.0.0",
|
"napalm>=5.0.0",
|
||||||
"napalm_device_types>=4.47.0", # AptHistoryMixin; ServicesRestartMixin with LXC left out
|
"napalm_device_types>=4.46.0", # ServicesRestartMixin with LXC left out; CredentialExpiryMixin
|
||||||
"paramiko>=5.0.0", # CVE-2026-44405; imported directly for the node's SSH session (_base.py)
|
"paramiko>=5.0.0", # CVE-2026-44405; imported directly for the node's SSH session (_base.py)
|
||||||
"proxmoxer>=2.0.0",
|
"proxmoxer>=2.0.0",
|
||||||
"netaddr>=0.9.0",
|
"netaddr>=0.9.0",
|
||||||
|
|||||||
@@ -1,14 +1,11 @@
|
|||||||
"""When the credential the driver logs in with stops working (NetOrk/netork#2728).
|
"""When the credential the driver logs in with stops working (NetOrk/netork#2728).
|
||||||
|
|
||||||
PVE 9.3's datacenter ``token-policy`` can require an expiry on every API token;
|
PVE 9.3's datacenter ``token-policy`` can require an expiry on every API token;
|
||||||
the platform keeps one on every token and account anyway. Both are read with one
|
the platform keeps one on every token and account anyway. A token is read with
|
||||||
``GET /access/users/{userid}`` (``read_user``): the account's ``expire`` and
|
``GET /access/users/{userid}/token/{tokenid}``; a token without an ``expire``
|
||||||
``tokens: {tokenid: {expire, privsep, comment}}``. It needs ``Sys.Audit`` (or
|
of its own expires with its user (``default: same as user``), read with
|
||||||
``User.Modify``) on ``/access/groups`` or a group of the user, which PVEAuditor
|
``GET /access/users/{userid}``, which is also where a password's account says
|
||||||
on ``/`` gives. ``GET /access/users/{userid}/token/{tokenid}`` is not used: a
|
when it expires. ``0`` is never.
|
||||||
token's request runs as ``user@realm!tokenid``, which its ``userid-param self``
|
|
||||||
check never matches. ``0`` is never; a token without an expiry of its own
|
|
||||||
expires with its user, and one with its own stops working with its user too.
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -36,105 +33,83 @@ def _token_driver(token_name: str = "netork@pve!poll") -> tuple[ProxmoxDriver, M
|
|||||||
return _driver(token_name=token_name, token_value="s3cret", realm="pve")
|
return _driver(token_name=token_name, token_value="s3cret", realm="pve")
|
||||||
|
|
||||||
|
|
||||||
def _user(api: MagicMock, expire: int | None = None, **tokens: dict[str, Any]) -> MagicMock:
|
|
||||||
"""``GET /access/users/{userid}`` answers with *expire* and *tokens*."""
|
|
||||||
answer: dict[str, Any] = {"userid": "netork@pve", "enable": 1}
|
|
||||||
if expire is not None:
|
|
||||||
answer["expire"] = expire
|
|
||||||
if tokens:
|
|
||||||
answer["tokens"] = tokens
|
|
||||||
get = api.access.users.return_value.get
|
|
||||||
get.return_value = answer
|
|
||||||
return get
|
|
||||||
|
|
||||||
|
|
||||||
def _forbidden() -> ResourceException:
|
def _forbidden() -> ResourceException:
|
||||||
return ResourceException(
|
return ResourceException(403, "Forbidden", "Permission check failed (/access, User.Modify)")
|
||||||
403, "Forbidden", "Permission check failed (/access/groups, User.Modify|Sys.Audit)"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class TestApiToken:
|
class TestApiToken:
|
||||||
def test_the_tokens_own_expiry(self):
|
def test_the_tokens_own_expiry(self):
|
||||||
drv, api = _token_driver()
|
drv, api = _token_driver()
|
||||||
get = _user(api, 0, poll={"expire": 1767225600, "privsep": 1})
|
api.access.users.return_value.token.return_value.get.return_value = {
|
||||||
|
"expire": 1767225600,
|
||||||
|
"privsep": 1,
|
||||||
|
}
|
||||||
assert drv.get_credential_expiry() == {
|
assert drv.get_credential_expiry() == {
|
||||||
"kind": "api-token",
|
"kind": "api-token",
|
||||||
"name": "netork@pve!poll",
|
"name": "netork@pve!poll",
|
||||||
"expires": 1767225600,
|
"expires": 1767225600,
|
||||||
}
|
}
|
||||||
api.access.users.assert_called_once_with("netork@pve")
|
api.access.users.assert_called_with("netork@pve")
|
||||||
get.assert_called_once_with()
|
api.access.users.return_value.token.assert_called_once_with("poll")
|
||||||
|
|
||||||
def test_the_token_endpoint_is_not_asked(self):
|
def test_zero_never_expires(self):
|
||||||
drv, api = _token_driver()
|
drv, api = _token_driver()
|
||||||
_user(api, 0, poll={"expire": 1767225600})
|
api.access.users.return_value.token.return_value.get.return_value = {"expire": 0}
|
||||||
drv.get_credential_expiry()
|
assert drv.get_credential_expiry()["expires"] is None
|
||||||
api.access.users.return_value.token.assert_not_called()
|
api.access.users.return_value.get.assert_not_called()
|
||||||
|
|
||||||
def test_a_token_without_expiry_expires_with_its_user(self):
|
def test_a_token_without_expiry_expires_with_its_user(self):
|
||||||
drv, api = _token_driver()
|
drv, api = _token_driver()
|
||||||
_user(api, 1798761600, poll={"privsep": 1})
|
api.access.users.return_value.token.return_value.get.return_value = {"privsep": 1}
|
||||||
assert drv.get_credential_expiry()["expires"] == 1798761600
|
api.access.users.return_value.get.return_value = {
|
||||||
|
"userid": "netork@pve",
|
||||||
def test_a_token_whose_expiry_is_zero_expires_with_its_user(self):
|
"expire": 1798761600,
|
||||||
drv, api = _token_driver()
|
}
|
||||||
_user(api, 1798761600, poll={"expire": 0})
|
|
||||||
assert drv.get_credential_expiry()["expires"] == 1798761600
|
|
||||||
|
|
||||||
def test_a_token_stops_working_with_its_user(self):
|
|
||||||
drv, api = _token_driver()
|
|
||||||
_user(api, 1767225600, poll={"expire": 1798761600})
|
|
||||||
assert drv.get_credential_expiry()["expires"] == 1767225600
|
|
||||||
|
|
||||||
def test_zero_on_both_never_expires(self):
|
|
||||||
drv, api = _token_driver()
|
|
||||||
_user(api, 0, poll={"expire": 0})
|
|
||||||
assert drv.get_credential_expiry()["expires"] is None
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("tokens", [{}, {"other": {"expire": 1767225600}}])
|
|
||||||
def test_a_token_the_user_does_not_list_expires_with_its_user(self, tokens):
|
|
||||||
drv, api = _token_driver()
|
|
||||||
_user(api, 1798761600, **tokens)
|
|
||||||
assert drv.get_credential_expiry()["expires"] == 1798761600
|
assert drv.get_credential_expiry()["expires"] == 1798761600
|
||||||
|
|
||||||
def test_a_token_name_without_user_is_the_login_users(self):
|
def test_a_token_name_without_user_is_the_login_users(self):
|
||||||
drv, api = _token_driver(token_name="poll")
|
drv, api = _token_driver(token_name="poll")
|
||||||
_user(api, 0, poll={"expire": 1767225600})
|
api.access.users.return_value.token.return_value.get.return_value = {"expire": 0}
|
||||||
assert drv.get_credential_expiry() == {
|
assert drv.get_credential_expiry()["name"] == "netork@pve!poll"
|
||||||
"kind": "api-token",
|
api.access.users.assert_called_with("netork@pve")
|
||||||
"name": "netork@pve!poll",
|
|
||||||
"expires": 1767225600,
|
|
||||||
}
|
|
||||||
api.access.users.assert_called_once_with("netork@pve")
|
|
||||||
|
|
||||||
def test_a_refused_read_names_the_privilege(self):
|
def test_a_refused_read_is_a_permission_error(self):
|
||||||
drv, api = _token_driver()
|
drv, api = _token_driver()
|
||||||
|
api.access.users.return_value.token.return_value.get.side_effect = _forbidden()
|
||||||
|
with pytest.raises(PermissionError, match="User.Modify"):
|
||||||
|
drv.get_credential_expiry()
|
||||||
|
|
||||||
|
def test_a_refused_read_of_the_user_is_a_permission_error(self):
|
||||||
|
drv, api = _token_driver()
|
||||||
|
api.access.users.return_value.token.return_value.get.return_value = {}
|
||||||
api.access.users.return_value.get.side_effect = _forbidden()
|
api.access.users.return_value.get.side_effect = _forbidden()
|
||||||
with pytest.raises(PermissionError, match="Sys.Audit on /access/groups"):
|
with pytest.raises(PermissionError):
|
||||||
drv.get_credential_expiry()
|
drv.get_credential_expiry()
|
||||||
|
|
||||||
|
|
||||||
class TestAccount:
|
class TestAccount:
|
||||||
def test_a_password_login_reads_its_account(self):
|
def test_a_password_login_reads_its_account(self):
|
||||||
drv, api = _driver()
|
drv, api = _driver()
|
||||||
_user(api, 1767225600)
|
api.access.users.return_value.get.return_value = {
|
||||||
|
"userid": "netork@pam",
|
||||||
|
"expire": 1767225600,
|
||||||
|
}
|
||||||
assert drv.get_credential_expiry() == {
|
assert drv.get_credential_expiry() == {
|
||||||
"kind": "account",
|
"kind": "account",
|
||||||
"name": "netork@pam",
|
"name": "netork@pam",
|
||||||
"expires": 1767225600,
|
"expires": 1767225600,
|
||||||
}
|
}
|
||||||
api.access.users.assert_called_once_with("netork@pam")
|
api.access.users.assert_called_with("netork@pam")
|
||||||
|
|
||||||
def test_an_account_without_expiry_never_expires(self):
|
def test_an_account_without_expiry_never_expires(self):
|
||||||
drv, api = _driver()
|
drv, api = _driver()
|
||||||
_user(api)
|
api.access.users.return_value.get.return_value = {"userid": "netork@pam", "enable": 1}
|
||||||
assert drv.get_credential_expiry()["expires"] is None
|
assert drv.get_credential_expiry()["expires"] is None
|
||||||
|
|
||||||
def test_a_refused_read_names_the_privilege(self):
|
def test_a_refused_read_is_a_permission_error(self):
|
||||||
drv, api = _driver()
|
drv, api = _driver()
|
||||||
api.access.users.return_value.get.side_effect = _forbidden()
|
api.access.users.return_value.get.side_effect = _forbidden()
|
||||||
with pytest.raises(PermissionError, match="Sys.Audit on /access/groups"):
|
with pytest.raises(PermissionError):
|
||||||
drv.get_credential_expiry()
|
drv.get_credential_expiry()
|
||||||
|
|
||||||
@pytest.mark.parametrize(
|
@pytest.mark.parametrize(
|
||||||
|
|||||||
@@ -0,0 +1,197 @@
|
|||||||
|
"""The PVE firewall, read only (NetOrk/netork#2654).
|
||||||
|
|
||||||
|
``get_pve_firewall`` reads the datacenter level -- options, rules, security groups,
|
||||||
|
IP sets, aliases -- the node's options and rules, and every guest's on the node with
|
||||||
|
which of its NICs carry ``firewall=1``. Each rule says where it came from. A level
|
||||||
|
PVE refuses is None, not empty. ``get_host_firewall`` reads what the node has loaded
|
||||||
|
(``nft list ruleset`` / ``iptables-save``), as for any Linux host.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from unittest.mock import MagicMock
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from napalm_proxmox.firewall_mixin import nic_firewalls
|
||||||
|
|
||||||
|
DC_OPTIONS = {"enable": 1, "policy_in": "DROP", "policy_out": "ACCEPT"}
|
||||||
|
DC_RULES = [
|
||||||
|
{
|
||||||
|
"pos": 0,
|
||||||
|
"type": "in",
|
||||||
|
"action": "ACCEPT",
|
||||||
|
"macro": "SSH",
|
||||||
|
"source": "+dc/admins",
|
||||||
|
"enable": 1,
|
||||||
|
},
|
||||||
|
{"pos": 1, "type": "group", "action": "web", "enable": 1},
|
||||||
|
]
|
||||||
|
GROUP_RULES = [
|
||||||
|
{"pos": 0, "type": "in", "action": "ACCEPT", "proto": "tcp", "dport": "80,443", "enable": 1}
|
||||||
|
]
|
||||||
|
IPSET = [{"cidr": "198.51.100.0/24", "comment": "office"}, {"cidr": "198.51.100.7", "nomatch": 1}]
|
||||||
|
ALIASES = [{"name": "monitor", "cidr": "203.0.113.5/32", "comment": "zabbix"}]
|
||||||
|
NODE_RULES = [
|
||||||
|
{"pos": 0, "type": "in", "action": "ACCEPT", "dport": "8006", "proto": "tcp", "enable": 0}
|
||||||
|
]
|
||||||
|
GUEST_OPTIONS = {"enable": 1, "policy_in": "DROP"}
|
||||||
|
GUEST_RULES = [
|
||||||
|
{
|
||||||
|
"pos": 0,
|
||||||
|
"type": "in",
|
||||||
|
"action": "ACCEPT",
|
||||||
|
"proto": "tcp",
|
||||||
|
"dport": "22",
|
||||||
|
"source": "monitor",
|
||||||
|
"enable": 1,
|
||||||
|
"comment": "zabbix ssh",
|
||||||
|
},
|
||||||
|
{"pos": 1, "type": "group", "action": "web", "enable": 1},
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def _api() -> MagicMock:
|
||||||
|
api = MagicMock()
|
||||||
|
fw = api.cluster.firewall
|
||||||
|
fw.options.get.return_value = DC_OPTIONS
|
||||||
|
fw.rules.get.return_value = DC_RULES
|
||||||
|
fw.groups.get.return_value = [{"group": "web", "comment": "web servers"}]
|
||||||
|
fw.groups.return_value.get.return_value = GROUP_RULES
|
||||||
|
fw.ipset.get.return_value = [{"name": "admins"}]
|
||||||
|
fw.ipset.return_value.get.return_value = IPSET
|
||||||
|
fw.aliases.get.return_value = ALIASES
|
||||||
|
node = api.nodes.return_value
|
||||||
|
node.firewall.options.get.return_value = {"enable": 1}
|
||||||
|
node.firewall.rules.get.return_value = NODE_RULES
|
||||||
|
node.qemu.get.return_value = [{"vmid": 100, "name": "web-01"}]
|
||||||
|
vm = node.qemu.return_value
|
||||||
|
vm.firewall.options.get.return_value = GUEST_OPTIONS
|
||||||
|
vm.firewall.rules.get.return_value = GUEST_RULES
|
||||||
|
vm.config.get.return_value = {
|
||||||
|
"net0": "virtio=AA:BB:CC:DD:EE:01,bridge=vmbr0,firewall=1",
|
||||||
|
"net1": "virtio=AA:BB:CC:DD:EE:02,bridge=vmbr1",
|
||||||
|
"name": "web-01",
|
||||||
|
}
|
||||||
|
node.lxc.get.return_value = [{"vmid": 200, "name": "dns-01"}]
|
||||||
|
ct = node.lxc.return_value
|
||||||
|
ct.firewall.options.get.return_value = {}
|
||||||
|
ct.firewall.rules.get.return_value = []
|
||||||
|
ct.config.get.return_value = {"net0": "name=eth0,bridge=vmbr0,firewall=1,ip=dhcp"}
|
||||||
|
return api
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def fw_driver(driver):
|
||||||
|
driver._api = _api()
|
||||||
|
return driver
|
||||||
|
|
||||||
|
|
||||||
|
class TestTheDatacenter:
|
||||||
|
def test_options_rules_groups_ipsets_aliases(self, fw_driver):
|
||||||
|
cluster = fw_driver.get_pve_firewall()["cluster"]
|
||||||
|
|
||||||
|
assert cluster["options"] == DC_OPTIONS
|
||||||
|
assert [
|
||||||
|
(r["origin"], r["type"], r.get("macro"), r["enable"]) for r in cluster["rules"]
|
||||||
|
] == [
|
||||||
|
("cluster", "in", "SSH", True),
|
||||||
|
("cluster", "group", None, True),
|
||||||
|
]
|
||||||
|
assert cluster["groups"] == {
|
||||||
|
"web": [
|
||||||
|
{
|
||||||
|
"pos": 0,
|
||||||
|
"type": "in",
|
||||||
|
"action": "ACCEPT",
|
||||||
|
"proto": "tcp",
|
||||||
|
"dport": "80,443",
|
||||||
|
"enable": True,
|
||||||
|
"origin": "group",
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
assert cluster["ipsets"] == {
|
||||||
|
"admins": [
|
||||||
|
{"cidr": "198.51.100.0/24", "nomatch": False, "comment": "office"},
|
||||||
|
{"cidr": "198.51.100.7", "nomatch": True, "comment": None},
|
||||||
|
]
|
||||||
|
}
|
||||||
|
assert cluster["aliases"] == {"monitor": "203.0.113.5/32"}
|
||||||
|
|
||||||
|
def test_a_level_pve_refuses_is_none_not_empty(self, fw_driver):
|
||||||
|
fw_driver._api.cluster.firewall.ipset.get.side_effect = RuntimeError("403 Forbidden")
|
||||||
|
|
||||||
|
cluster = fw_driver.get_pve_firewall()["cluster"]
|
||||||
|
|
||||||
|
assert cluster["ipsets"] is None
|
||||||
|
assert cluster["aliases"] == {"monitor": "203.0.113.5/32"}
|
||||||
|
|
||||||
|
|
||||||
|
class TestTheNodeAndItsGuests:
|
||||||
|
def test_the_nodes_rules_keep_their_switch(self, fw_driver):
|
||||||
|
node = fw_driver.get_pve_firewall()["node"]
|
||||||
|
|
||||||
|
assert node["name"] == fw_driver._node_name
|
||||||
|
assert node["options"] == {"enable": 1}
|
||||||
|
assert node["rules"][0]["enable"] is False
|
||||||
|
assert node["rules"][0]["origin"] == "node"
|
||||||
|
|
||||||
|
def test_every_guest_with_its_rules_and_nics(self, fw_driver):
|
||||||
|
guests = fw_driver.get_pve_firewall()["guests"]
|
||||||
|
|
||||||
|
assert [(g["vmid"], g["type"], g["name"]) for g in guests] == [
|
||||||
|
("100", "vm", "web-01"),
|
||||||
|
("200", "container", "dns-01"),
|
||||||
|
]
|
||||||
|
vm = guests[0]
|
||||||
|
assert vm["options"] == GUEST_OPTIONS
|
||||||
|
assert vm["rules"][0] == {
|
||||||
|
"pos": 0,
|
||||||
|
"type": "in",
|
||||||
|
"action": "ACCEPT",
|
||||||
|
"proto": "tcp",
|
||||||
|
"dport": "22",
|
||||||
|
"source": "monitor",
|
||||||
|
"comment": "zabbix ssh",
|
||||||
|
"enable": True,
|
||||||
|
"origin": "guest",
|
||||||
|
}
|
||||||
|
assert vm["nics"] == [
|
||||||
|
{"name": "net0", "firewall": True},
|
||||||
|
{"name": "net1", "firewall": False},
|
||||||
|
]
|
||||||
|
|
||||||
|
def test_a_guest_whose_config_is_refused_has_no_nics_reading(self, fw_driver):
|
||||||
|
fw_driver._api.nodes.return_value.qemu.return_value.config.get.side_effect = RuntimeError(
|
||||||
|
"403"
|
||||||
|
)
|
||||||
|
|
||||||
|
vm = fw_driver.get_pve_firewall()["guests"][0]
|
||||||
|
|
||||||
|
assert vm["nics"] is None
|
||||||
|
assert vm["rules"] is not None
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_nic_without_the_flag_is_not_filtered():
|
||||||
|
assert nic_firewalls({"net0": "virtio=AA:BB:CC:DD:EE:01,bridge=vmbr0,firewall=0"}) == [
|
||||||
|
{"name": "net0", "firewall": False}
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
class TestTheLoadedRuleset:
|
||||||
|
def test_the_node_reads_its_netfilter_rules_like_a_linux_host(self, driver):
|
||||||
|
seen: list[str] = []
|
||||||
|
|
||||||
|
def run(command: str) -> str:
|
||||||
|
seen.append(command)
|
||||||
|
return ""
|
||||||
|
|
||||||
|
driver._exec_ssh_command = run # type: ignore[method-assign]
|
||||||
|
|
||||||
|
assert hasattr(driver, "get_host_firewall")
|
||||||
|
try:
|
||||||
|
driver.get_host_firewall()
|
||||||
|
except Exception:
|
||||||
|
pass # an empty answer is no report; the transport is what is tested here
|
||||||
|
assert seen and "nft" in seen[0] and "iptables-save" in seen[0]
|
||||||
@@ -4,21 +4,14 @@ PVE 9.3 reads apt's history log for ``GET /nodes/{node}/apt/history``, newest
|
|||||||
first. The payload below follows its schema: a transaction is identified by
|
first. The payload below follows its schema: a transaction is identified by
|
||||||
``start-time`` with ``start-index`` (default 0) among those that started in the
|
``start-time`` with ``start-index`` (default 0) among those that started in the
|
||||||
same second; ``end-time`` is missing while it runs or after it was interrupted.
|
same second; ``end-time`` is missing while it runs or after it was interrupted.
|
||||||
An older node has no such endpoint: the driver reads the same log over its SSH
|
An older node has no such endpoint, and the driver parses no log over SSH.
|
||||||
session with napalm-device-types' ``AptHistoryMixin``, which names a transaction
|
|
||||||
the same way, and a node without an SSH login has no history.
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from unittest.mock import MagicMock, patch
|
from unittest.mock import MagicMock
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
from napalm.base.exceptions import ConnectionException
|
|
||||||
from napalm_device_types import APT_HISTORY_COMMAND, CommandResult
|
|
||||||
|
|
||||||
from napalm_proxmox.driver import ProxmoxDriver
|
|
||||||
from tests.conftest import _build_mock_api
|
|
||||||
|
|
||||||
HISTORY = [
|
HISTORY = [
|
||||||
{
|
{
|
||||||
@@ -124,73 +117,8 @@ class TestUpdateHistory:
|
|||||||
with pytest.raises(RuntimeError, match="timed out"):
|
with pytest.raises(RuntimeError, match="timed out"):
|
||||||
driver.get_update_history()
|
driver.get_update_history()
|
||||||
|
|
||||||
|
def test_an_older_node_has_no_history(self, driver, history):
|
||||||
#: The node's log as AptHistoryMixin's command prints it: the transaction the API
|
driver._api.version.get.return_value = {"version": "9.2.4", "release": "9.2"}
|
||||||
#: names 1764158400-1 is the second to start in that second (12:00:00 UTC) of the file.
|
with pytest.raises(NotImplementedError):
|
||||||
LOG = """\
|
driver.get_update_history()
|
||||||
### apt-history zone /usr/share/zoneinfo/Etc/UTC
|
|
||||||
### apt-history offset +0000
|
|
||||||
### apt-history file /var/log/apt/history.log
|
|
||||||
|
|
||||||
Start-Date: 2025-11-26 12:00:00
|
|
||||||
Commandline: apt-get update-kernel
|
|
||||||
Install: proxmox-kernel-6.17.2-1-pve-signed:amd64 (6.17.2-1, automatic)
|
|
||||||
End-Date: 2025-11-26 12:00:00
|
|
||||||
|
|
||||||
Start-Date: 2025-11-26 12:00:00
|
|
||||||
Commandline: apt-get -y dist-upgrade
|
|
||||||
Requested-By: admin (1000)
|
|
||||||
Upgrade: openssh-server:amd64 (1:10.0p1-7, 1:10.0p1-7+deb13u1)
|
|
||||||
Purge: ifupdown:amd64 (0.8.44)
|
|
||||||
End-Date: 2025-11-26 12:01:00
|
|
||||||
|
|
||||||
### apt-history status 0
|
|
||||||
### apt-history end
|
|
||||||
"""
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
|
||||||
def older(driver, history) -> MagicMock:
|
|
||||||
"""A 9.2 node whose SSH session prints :data:`LOG`."""
|
|
||||||
driver._api.version.get.return_value = {"version": "9.2.4", "release": "9.2"}
|
|
||||||
run = MagicMock(return_value=CommandResult(LOG, "", 0))
|
|
||||||
driver.run_command = run
|
|
||||||
return run
|
|
||||||
|
|
||||||
|
|
||||||
class TestBeforeNineThree:
|
|
||||||
def test_the_log_is_read_over_ssh(self, driver, history, older):
|
|
||||||
newest, first = driver.get_update_history()
|
|
||||||
assert newest["id"] == "1764158400-1" # the API's id for the same transaction
|
|
||||||
assert newest["end"] == 1764158460
|
|
||||||
assert newest["requested_by"] == "admin"
|
|
||||||
assert [p["action"] for p in newest["packages"]] == ["upgrade", "purge"]
|
|
||||||
assert first["id"] == "1764158400-0"
|
|
||||||
older.assert_called_once()
|
|
||||||
assert older.call_args.args == (APT_HISTORY_COMMAND,)
|
|
||||||
history.assert_not_called()
|
history.assert_not_called()
|
||||||
|
|
||||||
def test_since_filters_the_log(self, driver, history, older):
|
|
||||||
assert driver.get_update_history(since=1764158401) == []
|
|
||||||
|
|
||||||
def test_a_failed_ssh_read_raises(self, driver, history, older):
|
|
||||||
older.side_effect = ConnectionException("Cannot run a command on pve1 over SSH: reset")
|
|
||||||
with pytest.raises(RuntimeError, match="reset"):
|
|
||||||
driver.get_update_history()
|
|
||||||
|
|
||||||
def test_a_log_cut_short_raises(self, driver, history, older):
|
|
||||||
older.return_value = CommandResult(LOG.replace("### apt-history end\n", ""), "", 0)
|
|
||||||
with pytest.raises(RuntimeError, match="cut short"):
|
|
||||||
driver.get_update_history()
|
|
||||||
|
|
||||||
def test_a_node_without_ssh_login_has_no_history(self):
|
|
||||||
drv = ProxmoxDriver(
|
|
||||||
"pve1", "netork", "", optional_args={"token_name": "poll", "token_value": "s3cret"}
|
|
||||||
)
|
|
||||||
api = _build_mock_api(version={"version": "9.2.4", "release": "9.2"})
|
|
||||||
with patch("napalm_proxmox.driver.ProxmoxAPI", return_value=api):
|
|
||||||
drv.open()
|
|
||||||
drv.run_command = MagicMock()
|
|
||||||
with pytest.raises(NotImplementedError, match="SSH"):
|
|
||||||
drv.get_update_history()
|
|
||||||
drv.run_command.assert_not_called()
|
|
||||||
Reference in new issue
Block a user