Compare commits

..
Author SHA1 Message Date
Christian Manivong 68a6087571 chore(release): 0.17.0
driver / standard (pull_request) Successful in 16s
driver / lint (pull_request) Successful in 13s
driver / test (3.12) (pull_request) Failing after 17s
driver / types (pull_request) Failing after 26s
driver / test (3.13) (pull_request) Failing after 16s
driver / lowest (pull_request) Failing after 16s
driver / security (pull_request) Failing after 34s
driver / build (pull_request) Successful in 28s
CI / driver (pull_request) Failing after 1m28s
driver / publish (pull_request) Skipped
2026-11-26 23:10:08 +01:00
Christian Manivong 87aca53ec2 fix(credentials): a token's expiry from the user it belongs to (NetOrk/netork#2728)
GET /access/users/{userid}/token/{tokenid} checks userid-param self, which a
token's request (user@realm!tokenid) never matches, so a token could not read
itself without User.Modify. GET /access/users/{userid} needs Sys.Audit on
/access/groups (PVEAuditor) and returns the user's expire and every token's.
One call now serves both logins; a 403 names the privilege.
2026-11-26 23:08:47 +01:00
Christian Manivong 707b24748b feat(updates): the update history before PVE 9.3 from apt's log over SSH (NetOrk/netork#2728)
Below 9.3 get_update_history reads apt's history log over the node's SSH session
with napalm-device-types' AptHistoryMixin, which names a transaction as
GET /nodes/{node}/apt/history does, so the ids stay when the node moves to 9.3.
A node without an SSH login still raises NotImplementedError. Requires
napalm-device-types 4.47.0.
2026-11-26 23:07:22 +01:00
christianmanivong dc0d6345a8 Merge pull request 'feat(services-restart): which services on the node still run replaced code, as root (NetOrk/netork#2750)' (#77) from feature/services-need-restart into main
driver / types (push) Successful in 55s
driver / standard (push) Successful in 16s
driver / lint (push) Successful in 15s
driver / test (3.12) (push) Successful in 1m10s
driver / lowest (push) Successful in 33s
driver / test (3.13) (push) Successful in 1m1s
driver / build (push) Successful in 32s
driver / security (push) Successful in 1m13s
driver / publish (push) Successful in 31s
CI / driver (push) Successful in 3m27s
2026-11-26 19:41:28 +00:00
Christian Manivong f9088bae3a Merge remote-tracking branch 'origin/main' into feature/services-need-restart
driver / standard (pull_request) Successful in 18s
driver / lint (pull_request) Successful in 16s
driver / types (pull_request) Successful in 1m5s
driver / test (3.13) (pull_request) Successful in 1m9s
driver / test (3.12) (pull_request) Successful in 1m17s
driver / lowest (pull_request) Successful in 34s
driver / build (pull_request) Successful in 34s
driver / security (pull_request) Successful in 1m5s
CI / driver (pull_request) Successful in 2m33s
driver / publish (pull_request) Skipped
# Conflicts:
#	CHANGELOG.md
#	README.md
#	pyproject.toml
2026-11-26 19:52:53 +01:00
christianmanivong ca44e4405d Merge pull request 'feat(certificates): get_certificates on both drivers, with ACME, 0.15.0 (NetOrk/netork#2656)' (#75) from feature/certificates-2656 into main
driver / types (push) Successful in 1m0s
driver / standard (push) Successful in 17s
driver / lint (push) Successful in 16s
driver / test (3.12) (push) Successful in 1m11s
driver / lowest (push) Successful in 33s
driver / test (3.13) (push) Successful in 1m6s
driver / build (push) Successful in 30s
driver / security (push) Successful in 1m6s
driver / publish (push) Successful in 29s
CI / driver (push) Successful in 3m20s
2026-11-26 18:46:01 +00:00
Christian Manivong b37672a269 Merge origin/main (0.14.0) into feature/services-need-restart
driver / standard (pull_request) Successful in 17s
driver / lint (pull_request) Successful in 14s
driver / types (pull_request) Failing after 25s
driver / test (3.12) (pull_request) Failing after 17s
driver / test (3.13) (pull_request) Failing after 17s
driver / lowest (pull_request) Failing after 18s
driver / security (pull_request) Failing after 37s
driver / build (pull_request) Successful in 32s
CI / driver (pull_request) Failing after 1m32s
driver / publish (pull_request) Skipped
Needs napalm-device-types 4.46.0: ServicesRestartMixin with an LXC
container's processes left out, and 0.14.0's CredentialExpiryMixin.
2026-11-26 19:26:58 +01:00
Christian Manivong bc5127b80f chore(release): 0.15.0
driver / standard (pull_request) Successful in 19s
driver / lint (pull_request) Successful in 16s
driver / types (pull_request) Successful in 57s
driver / test (3.12) (pull_request) Successful in 1m10s
driver / test (3.13) (pull_request) Successful in 1m5s
driver / lowest (pull_request) Successful in 34s
driver / build (pull_request) Successful in 30s
driver / security (pull_request) Successful in 1m4s
CI / driver (pull_request) Successful in 2m35s
driver / publish (pull_request) Skipped
2026-11-26 19:26:24 +01:00
Christian Manivong 24089412a7 Merge remote-tracking branch 'origin/main' into feature/certificates-2656
# Conflicts:
#	CHANGELOG.md
#	napalm_proxmox/driver.py
2026-11-26 19:26:13 +01:00
Christian Manivong 63ffc64050 chore(release): 0.16.0
driver / standard (pull_request) Successful in 19s
driver / lint (pull_request) Successful in 18s
driver / types (pull_request) Failing after 58s
driver / test (3.12) (pull_request) Failing after 57s
driver / test (3.13) (pull_request) Failing after 52s
driver / lowest (pull_request) Failing after 27s
driver / build (pull_request) Successful in 34s
driver / security (pull_request) Successful in 1m12s
CI / driver (pull_request) Failing after 2m45s
driver / publish (pull_request) Skipped
2026-11-26 19:01:33 +01:00
Christian Manivong b792f6d210 feat(services-restart): which services on the node still run replaced code, as root (NetOrk/netork#2750)
Both drivers mix in napalm-device-types' ServicesRestartMixin. The command
goes over the exec path, root's login as a rule, behind an id -u guard: a
login other than root would see only its own processes and read as
clean, so it prints nothing and the read raises. A running VM's QEMU is
listed as a process; an LXC container's processes are left out by the
parse, since a container updates itself. No stdin.
2026-11-26 18:55:13 +01:00
Christian Manivong 1db3fb329f chore(release): 0.14.0
driver / lint (pull_request) Successful in 14s
driver / standard (pull_request) Successful in 17s
driver / types (pull_request) Successful in 50s
driver / test (3.13) (pull_request) Successful in 1m2s
driver / test (3.12) (pull_request) Successful in 1m7s
driver / lowest (pull_request) Successful in 33s
driver / build (pull_request) Successful in 29s
driver / security (pull_request) Successful in 1m2s
CI / driver (pull_request) Successful in 2m21s
driver / publish (pull_request) Skipped
2026-11-26 17:59:41 +01:00
Christian Manivong ff4ccc4818 feat(certificates): get_certificates on both drivers, with ACME (NetOrk/netork#2656)
The node's TLS certificates from GET /nodes/{node}/certificates/info (PBS:
/nodes/localhost/certificates/info) in netOrk's certificate contract,
{name, issuer, valid_from, valid_to, in_use_by} with Unix timestamps, so
netOrk's expiry warnings cover a node's web UI and API certificate.

One more call, the node's config, says whether ACME renews the certificate
the proxy serves (acme). The PEM is not returned; unreadable certificates
are [] and an unreadable config reads as no ACME.
2026-11-26 17:59:35 +01:00
14 changed files with 746 additions and 93 deletions

No files matched your search

+54
View File
@@ -7,6 +7,60 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased] ## [Unreleased]
## [0.17.0] - 2026-11-26
### Added
- `get_update_history(since)` before PVE 9.3: apt's history log over the node's SSH
session, through napalm-device-types' `AptHistoryMixin` (NetOrk/netork#2728). A
transaction gets the id 9.3's `GET /nodes/{node}/apt/history` gives it (start time and
the index among those that started in the same second of the same log file), so a node
keeps its ids when it moves to 9.3; 9.3 and later still read the API. A node without an
SSH login raises `NotImplementedError`, a failed read `RuntimeError`.
### Changed
- Needs napalm-device-types 4.47.0 or later (`AptHistoryMixin`).
### 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
### Added
- `get_services_need_restart()` on both drivers (napalm-device-types' `ServicesRestartMixin`,
NetOrk/netork#2750): the services that still run code an update replaced on disk, so they
keep the old library until they restart. One fixed, read-only command over the exec path,
which is root's login: `needs-restarting -s`, else `needrestart` in list-only mode, else the
processes whose `/proc/<pid>/maps` maps deleted code, each named by its cgroup's service. A
running VM's QEMU (`qemu.slice`) is listed as a process; an LXC container's processes are
left out, since a container updates itself. It runs only when the login is root
(`id -u` is 0): another login gets no report and the read raises, rather than read as
clean what it cannot see. No stdin.
### Changed
- Needs napalm-device-types 4.46.0 or later (`ServicesRestartMixin`, with an LXC
container's processes left out).
## [0.15.0] - 2026-11-26
### Added
- `get_certificates()` on both drivers (NetOrk/netork#2656): the node's TLS certificates from
`GET /nodes/{node}/certificates/info` (PBS: `/nodes/localhost/certificates/info`) in
netOrk's certificate contract, `{name, issuer, valid_from, valid_to, in_use_by}` with Unix
timestamps, so netOrk's expiry warnings cover a node's web UI and API certificate.
`name` is the file name (`pve-root-ca.pem`, `pve-ssl.pem`, `pveproxy-ssl.pem`; `proxy.pem` on
PBS), `issuer` and `subject` the common names, `in_use_by` 1 for the certificate the proxy
serves. `acme` is true for the certificate ACME renews (`pveproxy-ssl.pem`, PBS `proxy.pem`)
when the node's config names a domain, read with one more call (`GET /nodes/{node}/config`);
an unreadable config reads as no ACME. The PEM is not returned. Unreadable certificates are
`[]`, as on OPNsense.
## [0.14.0] - 2026-11-26 ## [0.14.0] - 2026-11-26
### Added ### Added
+6 -1
View File
@@ -131,6 +131,8 @@ device = driver(
| `put_scheduled_job(spec)` / `delete_scheduled_job(key, digest=)` | an application's own job, as a systemd timer | | `put_scheduled_job(spec)` / `delete_scheduled_job(key, digest=)` | an application's own job, as a systemd timer |
| `get_time_sync` | chrony's sources, the ones DHCP gave apart (`dhcp_ntp_servers`), whether it is synchronised, the zone from `timedatectl`, in one round trip over SSH (napalm-device-types' `PosixTimeSyncMixin`); the zone from `GET /nodes/{node}/time` only where the host names none | | `get_time_sync` | chrony's sources, the ones DHCP gave apart (`dhcp_ntp_servers`), whether it is synchronised, the zone from `timedatectl`, in one round trip over SSH (napalm-device-types' `PosixTimeSyncMixin`); the zone from `GET /nodes/{node}/time` only where the host names none |
| `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_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 |
**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`,
@@ -188,9 +190,10 @@ the disks and ZFS pools the server manages itself.
| `get_facts`, `get_interfaces`, `get_interfaces_ip`, `get_environment` | the API; host name, DMI and MAC addresses over SSH | | `get_facts`, `get_interfaces`, `get_interfaces_ip`, `get_environment` | the API; host name, DMI and MAC addresses over SSH |
| `get_disks`, `get_disk_pools` | `/nodes/localhost/disks/{list,zfs}` | | `get_disks`, `get_disk_pools` | `/nodes/localhost/disks/{list,zfs}` |
| `get_licenses` | `pbs-subscription` | | `get_licenses` | `pbs-subscription` |
| packages, updates, services, kernel, listening sockets, sshd hardening, `reboot_host`, `shutdown_host` | as on Proxmox VE | | packages, updates, services, kernel, listening sockets, services still running replaced code, sshd hardening, `reboot_host`, `shutdown_host` | as on Proxmox VE |
| scheduled jobs | as on Proxmox VE; `proxmox-backup*` units are `platform`. Verify, prune, sync and GC jobs are `get_backup_jobs`, not scheduled jobs | | scheduled jobs | as on Proxmox VE; `proxmox-backup*` units are `platform`. Verify, prune, sync and GC jobs are `get_backup_jobs`, not scheduled jobs |
| `get_time_sync`, `configure_time_sync`, `get_ntp_servers` | as on Proxmox VE, the zone through `/nodes/localhost/time` (writing it needs `Sys.Modify` on `/system/time`) | | `get_time_sync`, `configure_time_sync`, `get_ntp_servers` | as on Proxmox VE, the zone through `/nodes/localhost/time` (writing it needs `Sys.Modify` on `/system/time`) |
| `get_certificates` | as on Proxmox VE, from `/nodes/localhost/certificates/info` and `/nodes/localhost/config`: one certificate, `proxy.pem`, which ACME renews where a domain is configured |
**API token rights.** Reading needs the role `Audit` on `/` (`Sys.Audit`, **API token rights.** Reading needs the role `Audit` on `/` (`Sys.Audit`,
`Datastore.Audit`); the remotes need `Remote.Audit` on `/remote` as well, which `Datastore.Audit`); the remotes need `Remote.Audit` on `/remote` as well, which
@@ -235,6 +238,7 @@ napalm_proxmox/
├── backup_driver.py # ProxmoxBackupDriver (proxmox_backup) ├── backup_driver.py # ProxmoxBackupDriver (proxmox_backup)
├── 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
└── 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
@@ -246,6 +250,7 @@ tests/
├── test_ovs_and_arp.py # get_arp_table, get_mac_address_table, ARP/OVS utils ├── test_ovs_and_arp.py # get_arp_table, get_mac_address_table, ARP/OVS utils
├── 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_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
+4
View File
@@ -251,6 +251,10 @@ 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.
+4
View File
@@ -27,6 +27,7 @@ from napalm_device_types import (
OpenSshServerMixin, OpenSshServerMixin,
PortSpec, PortSpec,
ServicePackagesMixin, ServicePackagesMixin,
ServicesRestartMixin,
StorageDriver, StorageDriver,
SystemdServicesMixin, SystemdServicesMixin,
SystemIdentityMixin, SystemIdentityMixin,
@@ -38,6 +39,7 @@ except ImportError as exc: # pragma: no cover - proxmoxer is a dependency
raise ImportError("proxmoxer is required: pip install proxmoxer") from exc raise ImportError("proxmoxer is required: pip install proxmoxer") from exc
from napalm_proxmox._base import ProxmoxBase from napalm_proxmox._base import ProxmoxBase
from napalm_proxmox.certificates import PbsCertificatesMixin
from napalm_proxmox.host_mixin import ProxmoxHostMixin from napalm_proxmox.host_mixin import ProxmoxHostMixin
from napalm_proxmox.pbs_backups import ProxmoxBackupServerMixin from napalm_proxmox.pbs_backups import ProxmoxBackupServerMixin
from napalm_proxmox.pbs_host import ProxmoxPbsHostMixin from napalm_proxmox.pbs_host import ProxmoxPbsHostMixin
@@ -59,12 +61,14 @@ class ProxmoxBackupDriver(
ProxmoxPbsHostMixin, ProxmoxPbsHostMixin,
ProxmoxHostMixin, ProxmoxHostMixin,
ProxmoxTimeSyncMixin, ProxmoxTimeSyncMixin,
PbsCertificatesMixin,
BackupServerDriver, BackupServerDriver,
StorageDriver, StorageDriver,
KernelFactsMixin, KernelFactsMixin,
ServicePackagesMixin, ServicePackagesMixin,
ListeningSocketsMixin, ListeningSocketsMixin,
LogSourcesMixin, LogSourcesMixin,
ServicesRestartMixin,
SystemIdentityMixin, SystemIdentityMixin,
SystemdServicesMixin, SystemdServicesMixin,
ProxmoxScheduledJobsMixin, ProxmoxScheduledJobsMixin,
+115
View File
@@ -0,0 +1,115 @@
"""The node's TLS certificates and whether ACME renews them (NetOrk/netork#2656).
``get_certificates`` answers netOrk's certificate contract, the one the OPNsense
driver set: one ``{name, issuer, valid_from, valid_to, in_use_by}`` per
certificate, the validity as Unix timestamps. netOrk's expiry warnings read it
from every driver that has it.
Both products list their certificates at ``GET /nodes/{node}/certificates/info``
(PBS: ``/nodes/localhost/certificates/info``). Proxmox VE has three: its
cluster's CA (``pve-root-ca.pem``), the node certificate the CA signed
(``pve-ssl.pem``) and, where one was uploaded or ACME ordered one,
``pveproxy-ssl.pem``, which ``pveproxy`` then serves instead. A backup server has
one, ``proxy.pem``. ``in_use_by`` is 1 for the certificate the web UI and API
serve, 0 for the others.
One call more, the node's ``config``, says whether ACME renews the served
certificate (``acme``): a domain is configured (``acmedomain0``…, or
``domains=`` in the older ``acme`` property). The daily update job of either
product renews it 30 days before it runs out, so an ACME certificate close to
its end means the renewal failed. A config that cannot be read means no ACME.
``name`` is the file name, as the products' own certificate lists show it;
``issuer`` and ``subject`` are the common names. The PEM never leaves the node
reading: netOrk keeps only what it shows.
"""
from __future__ import annotations
import logging
import re
from typing import TYPE_CHECKING, Any, ClassVar
logger = logging.getLogger(__name__)
_JsonDict = dict[str, Any]
#: ``CN=x`` in either form the products print a name in: ``/O=y/CN=x`` (PVE) or
#: ``CN = x, O = y`` (PBS).
_COMMON_NAME = re.compile(r"(?:^|[/,])\s*CN\s*=\s*([^/,]+)")
def common_name(name: str | None) -> str:
"""The CN of a distinguished name as Proxmox prints it, else the name itself."""
if not name:
return ""
found = _COMMON_NAME.search(name)
return found.group(1).strip() if found else name.strip()
def _seconds(value: Any) -> int:
try:
return int(value or 0)
except (TypeError, ValueError):
return 0
def acme_configured(config: _JsonDict) -> bool:
"""Whether the node's config names a domain for ACME to order a certificate for."""
if any(key.startswith("acmedomain") and value for key, value in config.items()):
return True
return "domains=" in str(config.get("acme") or "")
class ProxmoxCertificatesMixin:
"""``get_certificates`` for a Proxmox VE node; the backup server sets its file names."""
#: The files the proxy serves, the first one present wins.
served_certificates: ClassVar[tuple[str, ...]] = ("pveproxy-ssl.pem", "pve-ssl.pem")
#: The file an ACME order writes.
acme_certificate: ClassVar[str] = "pveproxy-ssl.pem"
_node_name: str
if TYPE_CHECKING: # pragma: no cover - the driver's (napalm_proxmox._base)
def _node_api(self) -> Any: ...
def get_certificates(self) -> list[_JsonDict]:
"""The node's certificates in netOrk's contract shape; ``[]`` when unreadable."""
try:
rows = self._node_api().certificates.info.get() or []
except Exception as exc:
logger.warning("get_certificates() failed on %s: %s", self._node_name, exc)
return []
files = [row.get("filename") for row in rows]
served = next((f for f in self.served_certificates if f in files), None)
acme = self.acme_certificate in files and self._acme_configured()
return [self._certificate(row, served, acme) for row in rows]
def _acme_configured(self) -> bool:
try:
return acme_configured(self._node_api().config.get() or {})
except Exception as exc:
logger.debug("node config unreadable on %s: %s", self._node_name, exc)
return False
def _certificate(self, row: _JsonDict, served: str | None, acme: bool) -> _JsonDict:
filename = str(row.get("filename") or "")
return {
"name": filename,
"issuer": common_name(row.get("issuer")),
"valid_from": _seconds(row.get("notbefore")),
"valid_to": _seconds(row.get("notafter")),
"in_use_by": 1 if filename == served else 0,
"subject": common_name(row.get("subject")),
"fingerprint": row.get("fingerprint") or "",
"acme": acme and filename == self.acme_certificate,
}
class PbsCertificatesMixin(ProxmoxCertificatesMixin):
"""A backup server has one certificate, ``proxy.pem``, which ACME renews too."""
served_certificates: ClassVar[tuple[str, ...]] = ("proxy.pem",)
acme_certificate: ClassVar[str] = "proxy.pem"
+42 -29
View File
@@ -1,23 +1,28 @@
"""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: an API token (``user@realm!tokenid``) or with a user's password; both are read
with one ``GET /access/users/{userid}`` (``read_user``), which returns the
account's ``expire`` and ``tokens: {tokenid: {expire, privsep, comment}}``:
- a token: ``GET /access/users/{userid}/token/{tokenid}``, its ``expire``. A token - a password: the account's ``expire``;
without one of its own expires with its user (the schema's default, "same as - a token: ``tokens[tokenid].expire``. A token without one of its own (``0`` or
user"), read as for a password; none, "same as user") expires with its user; one with its own still stops
- a password: ``GET /access/users/{userid}``, the account's ``expire``. working when its user expires first, so the earlier of the two counts.
``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
refused its user (``User.Modify`` or ``Sys.Audit`` on the user's group), and a ``read_user`` needs ``Sys.Audit`` (or ``User.Modify``) on ``/access/groups`` or on
403 is a ``PermissionError``, as the contract says. a group of the user; PVEAuditor on ``/`` gives it. Not even a user may read
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
@@ -25,24 +30,19 @@ 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 _read(get: Callable[[], Any], what: str) -> _JsonDict: def _earliest(*values: int | None) -> int | None:
"""``get()``'s answer; a refusal as ``PermissionError``, another failure as """The earliest of *values* that is a time; None where none is."""
``RuntimeError``.""" times = [v for v in values if v is not None]
try: return min(times) if times else None
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,16 +58,29 @@ 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": self._user_expiry(userid)} return {"kind": "account", "name": userid, "expires": account}
name = f"{userid}!{login['token_name']}" token_id = str(login["token_name"])
token = _read(lambda: self._api.access.users(userid).token(login["token_name"]).get(), name) token = dict((user.get("tokens") or {}).get(token_id) or {})
expire = token.get("expire")
return { return {
"kind": "api-token", "kind": "api-token",
"name": name, "name": f"{userid}!{token_id}",
"expires": self._user_expiry(userid) if expire is None else _expires(expire), "expires": _earliest(_expires(token.get("expire")), account),
} }
def _user_expiry(self, userid: str) -> int | None: def _read_user(self, userid: str) -> _JsonDict:
return _expires(_read(lambda: self._api.access.users(userid).get(), userid).get("expire")) """``GET /access/users/{userid}``; a refusal as ``PermissionError``, another
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 {})
+4
View File
@@ -38,6 +38,7 @@ from napalm_device_types import (
OpenSshServerMixin, OpenSshServerMixin,
PortSpec, PortSpec,
ServicePackagesMixin, ServicePackagesMixin,
ServicesRestartMixin,
SnmpAgentMixin, SnmpAgentMixin,
SystemdServicesMixin, SystemdServicesMixin,
SystemIdentityMixin, SystemIdentityMixin,
@@ -49,6 +50,7 @@ except ImportError as exc:
raise ImportError("proxmoxer is required: pip install proxmoxer") from exc raise ImportError("proxmoxer is required: pip install proxmoxer") from exc
from napalm_proxmox._base import ProxmoxBase from napalm_proxmox._base import ProxmoxBase
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
@@ -100,11 +102,13 @@ class ProxmoxDriver(
ServicePackagesMixin, ServicePackagesMixin,
ListeningSocketsMixin, ListeningSocketsMixin,
LogSourcesMixin, LogSourcesMixin,
ServicesRestartMixin,
SystemIdentityMixin, SystemIdentityMixin,
SystemdServicesMixin, SystemdServicesMixin,
ProxmoxScheduledJobsMixin, ProxmoxScheduledJobsMixin,
ProxmoxRunningBackupsMixin, ProxmoxRunningBackupsMixin,
ProxmoxTimeSyncMixin, ProxmoxTimeSyncMixin,
ProxmoxCertificatesMixin,
ProxmoxCredentialExpiryMixin, ProxmoxCredentialExpiryMixin,
ProxmoxUpdateHistoryMixin, ProxmoxUpdateHistoryMixin,
HostStatusMixin, HostStatusMixin,
+12 -5
View File
@@ -1,11 +1,11 @@
"""What a Proxmox VE node and a Proxmox Backup Server share as Debian hosts. """What a Proxmox VE node and a Proxmox Backup Server share as Debian hosts.
The transports for napalm-device-types' host readers (kernel facts, service The transports for napalm-device-types' host readers (kernel facts, service
packages, system identity, listening sockets, systemd services, host status, packages, system identity, listening sockets, the services that still run replaced
apt's proxy), packages and APT updates, the subscription, root file writes, code, systemd services, host status, apt's proxy), packages and APT updates, the
and restarting or shutting the host down. All of it is the same on both subscription, root file writes, and restarting or shutting the host down. All of it
products: the same ``/nodes/{node}/apt``, ``/subscription`` and ``/status`` is the same on both products: the same ``/nodes/{node}/apt``, ``/subscription`` and
endpoints, and root's shell over the driver's own SSH session. ``/status`` endpoints, and root's shell over the driver's own SSH session.
""" """
from __future__ import annotations from __future__ import annotations
@@ -91,6 +91,13 @@ class ProxmoxHostMixin:
which runs as root either way.""" which runs as root either way."""
return str(self._exec_ssh_command(command)) return str(self._exec_ssh_command(command))
def _run_services_restart_command(self, command: str) -> str:
"""The transport for ``ServicesRestartMixin.get_services_need_restart``: the exec
path, which is root's login as a rule. Run only as root: a reading of the login's
own processes would read as clean, so another login prints nothing and the parse
raises (NetOrk/netork#2750). No stdin."""
return str(self._exec_ssh_command(f'[ "$(id -u)" = 0 ] && {command}'))
def get_packages(self) -> list[PackageDict]: def get_packages(self) -> list[PackageDict]:
"""Return installed Debian packages with available-update info. """Return installed Debian packages with available-update info.
+29 -10
View File
@@ -4,15 +4,23 @@ 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 raises file. An older node has no such endpoint: the driver reads the same log over
``NotImplementedError`` and parses no log over SSH. its SSH session with napalm-device-types' ``AptHistoryMixin``, which names a
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_device_types import UpdateHistoryAction, UpdateHistoryDict, UpdateHistoryPackageDict from napalm.base.exceptions import ConnectionException
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
@@ -46,8 +54,9 @@ def _transaction(row: _JsonDict) -> UpdateHistoryDict:
} }
class ProxmoxUpdateHistoryMixin: class ProxmoxUpdateHistoryMixin(AptHistoryMixin):
"""Relies on the driver's ``_node_api`` and ``_version_at_least``.""" """Relies on the driver's ``_node_api``, ``_version_at_least``, ``_has_ssh_login``
and ``run_command``."""
_node_name: str _node_name: str
@@ -55,21 +64,31 @@ class ProxmoxUpdateHistoryMixin:
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, which has no history endpoint. :raises NotImplementedError: before PVE 9.3 on a node without an SSH login.
: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):
raise NotImplementedError( return self._history_over_ssh(since)
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
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project] [project]
name = "napalm-proxmox" name = "napalm-proxmox"
version = "0.14.0" version = "0.17.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.44.0", # CredentialExpiryMixin, UpdateHistoryDict, VMDict.uid "napalm_device_types>=4.47.0", # AptHistoryMixin; ServicesRestartMixin with LXC left out
"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",
+255
View File
@@ -0,0 +1,255 @@
"""The node's TLS certificates and whether ACME renews them (NetOrk/netork#2656).
``get_certificates`` answers netOrk's certificate contract, the one the OPNsense
driver set: ``{name, issuer, valid_from, valid_to, in_use_by}`` with Unix
timestamps, so netOrk's expiry warnings apply to a Proxmox node as to any device.
The source is ``GET /nodes/{node}/certificates/info`` (PBS:
``/nodes/localhost/certificates/info``), and one more call, the node's
``config``, tells whether ACME renews the certificate the proxy serves.
The responses are shaped as Proxmox VE 8 and PBS 3 answer (``pvenode cert info``,
``proxmox-backup-manager cert info``), the PEM left out.
"""
from __future__ import annotations
from typing import Any
from unittest.mock import patch
import pytest
from proxmoxer.core import ResourceException
from napalm_proxmox import ProxmoxBackupDriver, ProxmoxDriver
from tests.conftest import _build_mock_api
from tests.pbs_fake import FakePbsApi
ROOT_CA = {
"filename": "pve-root-ca.pem",
"fingerprint": "5E:41:...:0A",
"issuer": "/CN=Proxmox Virtual Environment/OU=2d4e8a1c-7b9f/O=PVE Cluster Manager CA",
"notafter": 2017526400,
"notbefore": 1702166400,
"public-key-bits": 2048,
"public-key-type": "rsaEncryption",
"san": [],
"subject": "/CN=Proxmox Virtual Environment/OU=2d4e8a1c-7b9f/O=PVE Cluster Manager CA",
}
PVE_SSL = {
"filename": "pve-ssl.pem",
"fingerprint": "A1:B2:...:C3",
"issuer": "/CN=Proxmox Virtual Environment/OU=2d4e8a1c-7b9f/O=PVE Cluster Manager CA",
"notafter": 1765238400,
"notbefore": 1702166400,
"public-key-bits": 2048,
"public-key-type": "rsaEncryption",
"san": [
"127.0.0.1",
"0000:0000:0000:0000:0000:0000:0000:0001",
"localhost",
"pve1",
"pve1.example.com",
],
"subject": "/OU=PVE Cluster Node/O=Proxmox Virtual Environment/CN=pve1.example.com",
}
PVEPROXY_SSL = {
"filename": "pveproxy-ssl.pem",
"fingerprint": "D4:E5:...:F6",
"issuer": "/C=US/O=Let's Encrypt/CN=R11",
"notafter": 1771977600,
"notbefore": 1764201600,
"public-key-bits": 2048,
"public-key-type": "rsaEncryption",
"san": ["pve1.example.com"],
"subject": "/CN=pve1.example.com",
}
ACME_CONFIG = {
"acme": "account=default",
"acmedomain0": "domain=pve1.example.com,plugin=cloudflare",
"digest": "4f0c...",
}
PROXY_PEM = {
"filename": "proxy.pem",
"fingerprint": "0A:1B:...:2C",
"issuer": "CN = pbs1.example.com, O = Proxmox Backup Server, OU = 4c6e1d2a",
"notafter": 2017526400,
"notbefore": 1702166400,
"public-key-bits": 4096,
"public-key-type": "rsaEncryption",
"san": ["IP Address:127.0.0.1", "DNS:localhost", "DNS:pbs1", "DNS:pbs1.example.com"],
"subject": "CN = pbs1.example.com, O = Proxmox Backup Server, OU = 4c6e1d2a",
}
def _pve(info: Any, config: Any = None) -> tuple[ProxmoxDriver, Any]:
driver = ProxmoxDriver(
"pve1.example.com", "root", "secret", optional_args={"verify_ssl": False}
)
api = _build_mock_api()
node = api.nodes.return_value
if isinstance(info, Exception):
node.certificates.info.get.side_effect = info
else:
node.certificates.info.get.return_value = info
if isinstance(config, Exception):
node.config.get.side_effect = config
else:
node.config.get.return_value = config or {}
with patch("napalm_proxmox.driver.ProxmoxAPI", return_value=api):
driver.open()
return driver, api
def _pbs(**responses: Any) -> tuple[ProxmoxBackupDriver, FakePbsApi]:
api = FakePbsApi(**responses)
driver = ProxmoxBackupDriver("pbs1.example.com", "root@pam", "secret")
with patch("napalm_proxmox.backup_driver.ProxmoxAPI", return_value=api):
driver.open()
return driver, api
# -- Proxmox VE -------------------------------------------------------------------------------
def test_every_certificate_of_the_node_in_the_contract_shape() -> None:
driver, api = _pve([ROOT_CA, PVE_SSL, PVEPROXY_SSL])
certs = driver.get_certificates()
api.nodes.assert_any_call("pve1")
assert certs == [
{
"name": "pve-root-ca.pem",
"issuer": "Proxmox Virtual Environment",
"valid_from": 1702166400,
"valid_to": 2017526400,
"in_use_by": 0,
"subject": "Proxmox Virtual Environment",
"fingerprint": "5E:41:...:0A",
"acme": False,
},
{
"name": "pve-ssl.pem",
"issuer": "Proxmox Virtual Environment",
"valid_from": 1702166400,
"valid_to": 1765238400,
"in_use_by": 0,
"subject": "pve1.example.com",
"fingerprint": "A1:B2:...:C3",
"acme": False,
},
{
"name": "pveproxy-ssl.pem",
"issuer": "R11",
"valid_from": 1764201600,
"valid_to": 1771977600,
"in_use_by": 1,
"subject": "pve1.example.com",
"fingerprint": "D4:E5:...:F6",
"acme": False,
},
]
def test_the_timestamps_are_integers() -> None:
driver, _ = _pve([{**PVE_SSL, "notafter": "1765238400", "notbefore": None}])
(cert,) = driver.get_certificates()
assert cert["valid_to"] == 1765238400
assert cert["valid_from"] == 0
def test_without_a_custom_certificate_pveproxy_serves_pve_ssl() -> None:
driver, _ = _pve([ROOT_CA, PVE_SSL])
in_use = {c["name"]: c["in_use_by"] for c in driver.get_certificates()}
assert in_use == {"pve-root-ca.pem": 0, "pve-ssl.pem": 1}
def test_acme_renews_the_certificate_pveproxy_serves() -> None:
driver, api = _pve([ROOT_CA, PVE_SSL, PVEPROXY_SSL], ACME_CONFIG)
acme = {c["name"]: c["acme"] for c in driver.get_certificates()}
assert acme == {"pve-root-ca.pem": False, "pve-ssl.pem": False, "pveproxy-ssl.pem": True}
# One call more than the certificates: the node's config.
api.nodes.return_value.config.get.assert_called_once_with()
def test_acme_in_its_older_form_names_the_domains_in_acme() -> None:
config = {"acme": "account=default,domains=pve1.example.com"}
driver, _ = _pve([PVE_SSL, PVEPROXY_SSL], config)
acme = {c["name"]: c["acme"] for c in driver.get_certificates()}
assert acme == {"pve-ssl.pem": False, "pveproxy-ssl.pem": True}
def test_an_acme_account_without_domains_renews_nothing() -> None:
driver, _ = _pve([PVE_SSL, PVEPROXY_SSL], {"acme": "account=default"})
assert not any(c["acme"] for c in driver.get_certificates())
def test_acme_never_renews_pve_ssl() -> None:
# Without pveproxy-ssl.pem there is no ACME certificate yet, even with domains set.
driver, _ = _pve([ROOT_CA, PVE_SSL], ACME_CONFIG)
assert not any(c["acme"] for c in driver.get_certificates())
def test_an_unreadable_config_reads_as_no_acme() -> None:
driver, _ = _pve([PVE_SSL, PVEPROXY_SSL], ResourceException(403, "Forbidden", "no Sys.Audit"))
certs = driver.get_certificates()
assert [c["name"] for c in certs] == ["pve-ssl.pem", "pveproxy-ssl.pem"]
assert not any(c["acme"] for c in certs)
def test_unreadable_certificates_are_none_rather_than_a_failed_poll() -> None:
driver, api = _pve(ResourceException(403, "Forbidden", "no Sys.Audit"))
assert driver.get_certificates() == []
api.nodes.return_value.config.get.assert_not_called()
# -- Proxmox Backup Server ---------------------------------------------------------------------
def test_the_backup_server_reads_localhost() -> None:
driver, api = _pbs(
**{"nodes/localhost/certificates/info": [PROXY_PEM], "nodes/localhost/config": {}}
)
assert driver.get_certificates() == [
{
"name": "proxy.pem",
"issuer": "pbs1.example.com",
"valid_from": 1702166400,
"valid_to": 2017526400,
"in_use_by": 1,
"subject": "pbs1.example.com",
"fingerprint": "0A:1B:...:2C",
"acme": False,
}
]
assert ("GET", "nodes/localhost/certificates/info", {}) in api.calls
def test_acme_renews_the_backup_servers_proxy_certificate() -> None:
config = {"acme": "account=default", "acmedomain0": "domain=pbs1.example.com"}
driver, _ = _pbs(
**{"nodes/localhost/certificates/info": [PROXY_PEM], "nodes/localhost/config": config}
)
(cert,) = driver.get_certificates()
assert cert["acme"] is True
@pytest.mark.parametrize("cls", [ProxmoxDriver, ProxmoxBackupDriver], ids=["pve", "pbs"])
def test_both_drivers_have_it(cls: type) -> None:
assert callable(getattr(cls, "get_certificates", None))
+66 -41
View File
@@ -1,11 +1,14 @@
"""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. A token is read with the platform keeps one on every token and account anyway. Both are read with one
``GET /access/users/{userid}/token/{tokenid}``; a token without an ``expire`` ``GET /access/users/{userid}`` (``read_user``): the account's ``expire`` and
of its own expires with its user (``default: same as user``), read with ``tokens: {tokenid: {expire, privsep, comment}}``. It needs ``Sys.Audit`` (or
``GET /access/users/{userid}``, which is also where a password's account says ``User.Modify``) on ``/access/groups`` or a group of the user, which PVEAuditor
when it expires. ``0`` is never. on ``/`` gives. ``GET /access/users/{userid}/token/{tokenid}`` is not used: a
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
@@ -33,83 +36,105 @@ 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(403, "Forbidden", "Permission check failed (/access, User.Modify)") return ResourceException(
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()
api.access.users.return_value.token.return_value.get.return_value = { get = _user(api, 0, poll={"expire": 1767225600, "privsep": 1})
"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_with("netork@pve") api.access.users.assert_called_once_with("netork@pve")
api.access.users.return_value.token.assert_called_once_with("poll") get.assert_called_once_with()
def test_zero_never_expires(self): def test_the_token_endpoint_is_not_asked(self):
drv, api = _token_driver() drv, api = _token_driver()
api.access.users.return_value.token.return_value.get.return_value = {"expire": 0} _user(api, 0, poll={"expire": 1767225600})
assert drv.get_credential_expiry()["expires"] is None drv.get_credential_expiry()
api.access.users.return_value.get.assert_not_called() api.access.users.return_value.token.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()
api.access.users.return_value.token.return_value.get.return_value = {"privsep": 1} _user(api, 1798761600, poll={"privsep": 1})
api.access.users.return_value.get.return_value = { assert drv.get_credential_expiry()["expires"] == 1798761600
"userid": "netork@pve",
"expire": 1798761600, def test_a_token_whose_expiry_is_zero_expires_with_its_user(self):
} 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")
api.access.users.return_value.token.return_value.get.return_value = {"expire": 0} _user(api, 0, poll={"expire": 1767225600})
assert drv.get_credential_expiry()["name"] == "netork@pve!poll" assert drv.get_credential_expiry() == {
api.access.users.assert_called_with("netork@pve") "kind": "api-token",
"name": "netork@pve!poll",
"expires": 1767225600,
}
api.access.users.assert_called_once_with("netork@pve")
def test_a_refused_read_is_a_permission_error(self): def test_a_refused_read_names_the_privilege(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): with pytest.raises(PermissionError, match="Sys.Audit on /access/groups"):
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()
api.access.users.return_value.get.return_value = { _user(api, 1767225600)
"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_with("netork@pam") api.access.users.assert_called_once_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()
api.access.users.return_value.get.return_value = {"userid": "netork@pam", "enable": 1} _user(api)
assert drv.get_credential_expiry()["expires"] is None assert drv.get_credential_expiry()["expires"] is None
def test_a_refused_read_is_a_permission_error(self): def test_a_refused_read_names_the_privilege(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): with pytest.raises(PermissionError, match="Sys.Audit on /access/groups"):
drv.get_credential_expiry() drv.get_credential_expiry()
@pytest.mark.parametrize( @pytest.mark.parametrize(
+76
View File
@@ -0,0 +1,76 @@
"""`get_services_need_restart`: the services on the node that still run replaced code.
An openssl or glibc update replaces the files on disk; every daemon that had them
loaded keeps the old code until it restarts (NetOrk/netork#2750). On a hypervisor that
is where a restart instead of a reboot matters most. The command and its parse are
napalm-device-types' (``ServicesRestartMixin``); the driver only carries the command
over its exec path, which runs as root. A login that is not root gets no reading: it
would see only its own processes and read as clean.
"""
from __future__ import annotations
import subprocess
from unittest.mock import patch
import pytest
from napalm_device_types import ServicesRestartMixin
from napalm_proxmox import ProxmoxBackupDriver
from napalm_proxmox.driver import ProxmoxDriver
#: A PVE node after an openssl update, read by the /proc scan (no needrestart):
#: pveproxy and a running VM's QEMU still map the old library, and so does a
#: container's own nginx, which the container updates itself.
WIRE = (
"RST_BEGIN\n[maps]\n"
"2101 pveproxy worker\n"
"3100 kvm\n"
"4100 nginx\n"
"[cgroups]\n"
"2101 0::/system.slice/pveproxy.service\n"
"3100 0::/qemu.slice/101.scope\n"
"4100 0::/lxc/200/ns/system.slice/nginx.service\n"
"RST_END\n"
)
@pytest.mark.parametrize("driver_class", [ProxmoxDriver, ProxmoxBackupDriver])
def test_both_drivers_declare_the_contract(driver_class):
assert issubclass(driver_class, ServicesRestartMixin)
def test_it_reads_as_root_over_the_exec_path(driver):
with patch.object(driver, "_exec_ssh_command", return_value=WIRE) as exec_:
reading = driver.get_services_need_restart()
[command] = [c.args[0] for c in exec_.call_args_list]
assert command.startswith('[ "$(id -u)" = 0 ] && sh -c \'')
assert reading == {
"source": "maps",
"units": ["pveproxy"],
"processes": [{"pid": 3100, "name": "kvm"}],
}
def test_the_backup_server_reads_it_the_same_way():
drv = ProxmoxBackupDriver("192.0.2.80", "root", "", optional_args={"token_name": "a!b"})
wire = "RST_BEGIN\n[needrestart]\nNEEDRESTART-SVC: proxmox-backup-proxy.service\nRST_END\n"
with patch.object(drv, "_exec_ssh_command", return_value=wire):
reading = drv.get_services_need_restart()
assert reading["units"] == ["proxmox-backup-proxy"]
def test_a_login_other_than_root_gets_no_reading(driver):
"""The guard runs nothing but as root, so no report comes back and the parse raises."""
def as_this_user(command: str) -> str:
return subprocess.run(["sh", "-c", command], capture_output=True, text=True).stdout
if subprocess.run(["id", "-u"], capture_output=True, text=True).stdout.strip() == "0":
pytest.skip("runs as root here")
with patch.object(driver, "_exec_ssh_command", side_effect=as_this_user):
with pytest.raises(ValueError):
driver.get_services_need_restart()
+77 -5
View File
@@ -4,14 +4,21 @@ 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, and the driver parses no log over SSH. An older node has no such endpoint: the driver reads the same log over its 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 from unittest.mock import MagicMock, patch
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 = [
{ {
@@ -117,8 +124,73 @@ 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
#: names 1764158400-1 is the second to start in that second (12:00:00 UTC) of the file.
LOG = """\
### 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"} driver._api.version.get.return_value = {"version": "9.2.4", "release": "9.2"}
with pytest.raises(NotImplementedError): run = MagicMock(return_value=CommandResult(LOG, "", 0))
driver.get_update_history() 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()