Compare commits
11
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cd60286ac1 | ||
|
|
9acf93182f | ||
|
|
ab1cac3833 | ||
|
|
3d661e0b3f | ||
|
|
b7e36abcbd | ||
|
|
7d33e6d48d | ||
|
|
4455f71bd7 | ||
|
|
7e22142359 | ||
|
|
93ba43071b | ||
|
|
f554e2cc79 | ||
|
|
7e300c740e |
No files matched your search
@@ -7,6 +7,59 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.22.0] - 2026-12-06
|
||||
|
||||
### Added
|
||||
- The images on the cluster's storages (napalm-device-types 4.61.0, NetOrk/netork#3176).
|
||||
`get_clusters()` gives each storage with `iso` or `import` content its `images`: every
|
||||
such file with its volid, format, size, creation time and the nodes it is on. A shared
|
||||
storage is read once, a local one on each of its nodes. A storage that cannot be read
|
||||
whole is None.
|
||||
- `stage_storage_image()` downloads a cloud image into an import storage through
|
||||
`download-url`, verified, under the name a provisioning download gives it.
|
||||
`storage_image_checksum()` hashes a file on the node. `delete_storage_image()` deletes
|
||||
one. The static `staged_image_name()` and `staged_image_series()` tell two builds of one
|
||||
image apart.
|
||||
- `create_vm_from_cloud_init(image_volume=…)` imports a disk image already on a storage
|
||||
as the root disk. It refuses installation media, or a file the node does not have,
|
||||
before creating anything. The result names the volume the root disk came from:
|
||||
`image_volume`, None over the SSH path.
|
||||
|
||||
## [0.21.0] - 2026-12-01
|
||||
|
||||
### Added
|
||||
- `get_login_sessions()` on PVE and PBS (napalm-device-types' `LoginSessionsMixin`,
|
||||
4.55.0): the interactive logins the node recorded over the last seven days -- someone's
|
||||
own `ssh`, or the web interface's shell -- each with its account, terminal, address and
|
||||
times, and the address of the driver's own SSH session (NetOrk/netork#2881). Over the
|
||||
node's exec path; an API-token-only node, which has no SSH login, raises as the other
|
||||
readings over SSH do.
|
||||
|
||||
## [0.20.0] - 2026-11-29
|
||||
|
||||
### Added
|
||||
- `get_web_login_auth()` on both drivers (napalm-device-types' `WebLoginAuthDict`,
|
||||
NetOrk/netork#662): how the web interface lets people log in, one source per realm with
|
||||
someone who can log in. A realm asks for a password and a one-time code when its own `tfa`
|
||||
is set (PVE) or every enabled, unexpired user of it has an enabled second factor
|
||||
(`/access/tfa`); a password alone when one user has none; OpenID is `external`. Read only.
|
||||
The API login needs `Sys.Audit` or `User.Modify` on `/access/groups` on Proxmox VE and
|
||||
`Sys.Audit` on `/access/users` on PBS: without it both list only the caller, so the driver
|
||||
checks `/access/permissions` first and raises `PermissionError` rather than judge the
|
||||
server by one account.
|
||||
|
||||
## [0.19.0] - 2026-11-28
|
||||
|
||||
### Added
|
||||
- `install_cpu_microcode()` on both drivers (napalm-device-types' `CpuMicrocodeMixin`, 4.53.0,
|
||||
NetOrk/netork#2838): the CPU vendor's microcode on a node that runs on its own CPU. A Proxmox
|
||||
install enables no `non-free-firmware`, where Debian keeps `intel-microcode` and
|
||||
`amd64-microcode`: it is added to Debian's own sources (never to Proxmox's or another
|
||||
vendor's), the index is loaded with `apt-get update` over the exec path -- waited for, unlike
|
||||
the API's refresh task -- and the package installed. Refused on a node that runs virtualized
|
||||
(a PBS in a VM): its host loads the microcode. The microcode loads at the next boot.
|
||||
- The hardening reading carries `virtualization` and `cpu_vendor` (napalm-device-types 4.53.0).
|
||||
|
||||
## [0.18.0] - 2026-11-28
|
||||
|
||||
### Added
|
||||
|
||||
@@ -17,7 +17,7 @@ It supports all three networking domains of Proxmox VE:
|
||||
|
||||
- Python ≥ 3.12
|
||||
- NAPALM ≥ 5.0.0
|
||||
- napalm-device-types ≥ 4.22.0
|
||||
- napalm-device-types ≥ 4.50.0
|
||||
- proxmoxer ≥ 2.0.0
|
||||
- netaddr ≥ 0.9.0
|
||||
- requests ≥ 2.31.0
|
||||
@@ -135,7 +135,9 @@ device = driver(
|
||||
| `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 |
|
||||
| `get_hardening` | how the node is hardened (napalm-device-types' `HardeningMixin`, NetOrk/netork#2776): security modules, SELinux and AppArmor, crypto policy, FIPS mode, CPU vulnerabilities, kernel command line, as root over SSH. On the backup server too |
|
||||
| `get_hardening` | how the node is hardened (napalm-device-types' `HardeningMixin`, NetOrk/netork#2776): security modules, SELinux and AppArmor, crypto policy, FIPS mode, CPU vulnerabilities, kernel command line, whether the node runs virtualized and its CPU vendor, as root over SSH. On the backup server too |
|
||||
| `install_cpu_microcode` | the CPU vendor's microcode (`intel-microcode`, `amd64-microcode`; napalm-device-types' `CpuMicrocodeMixin`, NetOrk/netork#2838): Debian's `non-free-firmware` added to Debian's own sources where missing, `apt-get update` over SSH (waited for, unlike the API's refresh task), then the install. Refused on a node that runs virtualized. Loads at the next boot. On the backup server too |
|
||||
| `get_web_login_auth` | how the web interface lets people log in (napalm-device-types' `WebLoginAuthDict`, NetOrk/netork#662): one source per realm with someone who can log in, by realm name. `password_otp` when the realm's own `tfa` is set or every enabled, unexpired user of it has an enabled second factor (`GET /access/tfa`: TOTP, WebAuthn, U2F, Yubico or recovery keys), `password` when one has none (often `root@pam`, or an account that only holds API tokens: the API does not say whether a user has a password, and a second factor on it does not affect its tokens), `external` for OpenID, `unknown` for a realm type the driver does not know. Needs `Sys.Audit` or `User.Modify` on `/access/groups` (the `PVEAuditor` role on `/` has it): without it PVE lists only the caller, so the driver raises `PermissionError` instead of judging the datacenter by one account. API tokens skip the second factor by design and are not web logins. On the backup server too |
|
||||
|
||||
**Not implemented** (raise `NotImplementedError`):
|
||||
`get_bgp_config`, `get_bgp_neighbors`, `get_bgp_neighbors_detail`,
|
||||
@@ -197,6 +199,7 @@ the disks and ZFS pools the server manages itself.
|
||||
| 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_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 |
|
||||
| `get_web_login_auth` | as on Proxmox VE, from `/access/domains`, `/access/users` and `/access/tfa`; PBS has no realm-wide `tfa`, so each user's second factors decide. Needs `Sys.Audit` on `/access/users` (the `Audit` role on `/` has it), checked first: without it PBS lists only the caller |
|
||||
|
||||
**API token rights.** Reading needs the role `Audit` on `/` (`Sys.Audit`,
|
||||
`Datastore.Audit`); the remotes need `Remote.Audit` on `/remote` as well, which
|
||||
@@ -256,7 +259,8 @@ tests/
|
||||
├── test_time_sync.py # get_time_sync / configure_time_sync on both drivers
|
||||
├── test_certificates.py # get_certificates on both drivers
|
||||
├── test_firewall.py # get_pve_firewall and get_host_firewall
|
||||
├── test_hardening.py # get_hardening on both drivers
|
||||
├── test_hardening.py # get_hardening and install_cpu_microcode on both drivers
|
||||
├── test_web_login.py # get_web_login_auth on both drivers
|
||||
├── test_utils.py # Unit tests for napalm_proxmox.utils
|
||||
├── fixtures/pbs_api.json # What a Proxmox Backup Server 4.2 answered (sanitised)
|
||||
├── pbs_fake.py # A proxmoxer stand-in answering from that recording
|
||||
|
||||
@@ -17,6 +17,7 @@ from typing import Any
|
||||
from napalm_device_types import (
|
||||
AptProxyMixin,
|
||||
BackupServerDriver,
|
||||
CpuMicrocodeMixin,
|
||||
EnsurePackageMixin,
|
||||
FingerprintRule,
|
||||
HardeningMixin,
|
||||
@@ -24,6 +25,7 @@ from napalm_device_types import (
|
||||
KernelFactsMixin,
|
||||
LicenseMixin,
|
||||
ListeningSocketsMixin,
|
||||
LoginSessionsMixin,
|
||||
LogSourcesMixin,
|
||||
OpenSshServerMixin,
|
||||
PortSpec,
|
||||
@@ -47,6 +49,7 @@ from napalm_proxmox.pbs_host import ProxmoxPbsHostMixin
|
||||
from napalm_proxmox.running_backups import PbsRunningBackupsMixin
|
||||
from napalm_proxmox.scheduled_jobs import PBS_PLATFORM_SOURCES, ProxmoxScheduledJobsMixin
|
||||
from napalm_proxmox.time_sync import ProxmoxTimeSyncMixin
|
||||
from napalm_proxmox.web_login import ProxmoxWebLoginMixin
|
||||
from napalm_proxmox.zabbix_agent import ProxmoxZabbixAgentMixin
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -63,6 +66,7 @@ class ProxmoxBackupDriver(
|
||||
ProxmoxHostMixin,
|
||||
ProxmoxTimeSyncMixin,
|
||||
PbsCertificatesMixin,
|
||||
ProxmoxWebLoginMixin,
|
||||
BackupServerDriver,
|
||||
StorageDriver,
|
||||
KernelFactsMixin,
|
||||
@@ -70,6 +74,7 @@ class ProxmoxBackupDriver(
|
||||
ServicePackagesMixin,
|
||||
ListeningSocketsMixin,
|
||||
LogSourcesMixin,
|
||||
LoginSessionsMixin,
|
||||
ServicesRestartMixin,
|
||||
SystemIdentityMixin,
|
||||
SystemdServicesMixin,
|
||||
@@ -77,6 +82,7 @@ class ProxmoxBackupDriver(
|
||||
HostStatusMixin,
|
||||
LicenseMixin,
|
||||
ProxmoxZabbixAgentMixin,
|
||||
CpuMicrocodeMixin,
|
||||
EnsurePackageMixin,
|
||||
AptProxyMixin,
|
||||
OpenSshServerMixin,
|
||||
@@ -94,6 +100,8 @@ class ProxmoxBackupDriver(
|
||||
FULL_UPGRADE = True
|
||||
#: The backup server's own timer is ``platform``.
|
||||
PLATFORM_SOURCES = PBS_PLATFORM_SOURCES
|
||||
#: Shows every user and their second factors (``web_login``).
|
||||
WEB_LOGIN_PRIVILEGE = ("/access/users", ("Sys.Audit",))
|
||||
PORT_SPECS = [
|
||||
PortSpec("https", 8007, weight=8.0),
|
||||
]
|
||||
|
||||
@@ -15,7 +15,8 @@ cluster of one, without a name). Read from:
|
||||
of their zone;
|
||||
- ``GET /cluster/ha/status/manager_status``: which node is in maintenance;
|
||||
- quorum votes and HA resources: see ``cluster_ha``; backup jobs and backups:
|
||||
see ``cluster_backups``. Each of those is best-effort and None when it cannot
|
||||
see ``cluster_backups``; the files on iso and import storages: see
|
||||
``storage_images``. Each of those is best-effort and None when it cannot
|
||||
be read, without failing the rest of the report.
|
||||
"""
|
||||
|
||||
@@ -30,6 +31,7 @@ from napalm_proxmox.network_targets import bridge_targets, vnet_target
|
||||
from napalm_proxmox.pve_values import split_list as _list
|
||||
from napalm_proxmox.pve_values import to_flag as _flag
|
||||
from napalm_proxmox.pve_values import to_int as _int
|
||||
from napalm_proxmox.storage_images import read_images
|
||||
from napalm_proxmox.utils import cpu_flags
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -186,6 +188,7 @@ class ProxmoxClusterMixin:
|
||||
members = self._members(status if head else [])
|
||||
storages = _storages(resources)
|
||||
_name_backup_servers(storages, self._api)
|
||||
read_images(self._api, storages, self._node_name)
|
||||
return [
|
||||
{
|
||||
"id": _cluster_id(head, status),
|
||||
|
||||
@@ -27,6 +27,7 @@ from typing import Any
|
||||
from napalm.base.exceptions import ConnectionException
|
||||
from napalm_device_types import (
|
||||
AptProxyMixin,
|
||||
CpuMicrocodeMixin,
|
||||
EnsurePackageMixin,
|
||||
FingerprintRule,
|
||||
HardeningMixin,
|
||||
@@ -36,6 +37,7 @@ from napalm_device_types import (
|
||||
KernelFactsMixin,
|
||||
LicenseMixin,
|
||||
ListeningSocketsMixin,
|
||||
LoginSessionsMixin,
|
||||
LogSourcesMixin,
|
||||
OpenSshServerMixin,
|
||||
PortSpec,
|
||||
@@ -64,6 +66,7 @@ from napalm_proxmox.routing_mixin import ProxmoxRoutingMixin
|
||||
from napalm_proxmox.running_backups import ProxmoxRunningBackupsMixin
|
||||
from napalm_proxmox.scheduled_jobs import PVE_PLATFORM_SOURCES, ProxmoxScheduledJobsMixin
|
||||
from napalm_proxmox.sdn_mixin import ProxmoxSDNMixin
|
||||
from napalm_proxmox.storage_images import ProxmoxStorageImagesMixin
|
||||
from napalm_proxmox.system_mixin import ProxmoxSystemMixin
|
||||
from napalm_proxmox.time_sync import ProxmoxTimeSyncMixin
|
||||
from napalm_proxmox.update_history import ProxmoxUpdateHistoryMixin
|
||||
@@ -72,6 +75,7 @@ from napalm_proxmox.vm_migrate_mixin import ProxmoxVMMigrateMixin
|
||||
from napalm_proxmox.vm_mixin import ProxmoxVMMixin
|
||||
from napalm_proxmox.vm_provision_mixin import ProxmoxVMProvisionMixin
|
||||
from napalm_proxmox.vm_snapshot_mixin import ProxmoxVMSnapshotMixin
|
||||
from napalm_proxmox.web_login import ProxmoxWebLoginMixin
|
||||
from napalm_proxmox.zabbix_agent import ProxmoxZabbixAgentMixin
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -95,6 +99,7 @@ class ProxmoxDriver(
|
||||
ProxmoxVMMixin,
|
||||
ProxmoxVMContractMixin,
|
||||
ProxmoxVMSnapshotMixin,
|
||||
ProxmoxStorageImagesMixin,
|
||||
ProxmoxVMProvisionMixin,
|
||||
ProxmoxClusterMixin,
|
||||
ProxmoxVMMigrateMixin,
|
||||
@@ -108,6 +113,7 @@ class ProxmoxDriver(
|
||||
ServicePackagesMixin,
|
||||
ListeningSocketsMixin,
|
||||
LogSourcesMixin,
|
||||
LoginSessionsMixin,
|
||||
ServicesRestartMixin,
|
||||
SystemIdentityMixin,
|
||||
SystemdServicesMixin,
|
||||
@@ -116,11 +122,13 @@ class ProxmoxDriver(
|
||||
ProxmoxTimeSyncMixin,
|
||||
ProxmoxCertificatesMixin,
|
||||
ProxmoxCredentialExpiryMixin,
|
||||
ProxmoxWebLoginMixin,
|
||||
ProxmoxUpdateHistoryMixin,
|
||||
HostStatusMixin,
|
||||
LicenseMixin,
|
||||
SnmpAgentMixin,
|
||||
ProxmoxZabbixAgentMixin,
|
||||
CpuMicrocodeMixin,
|
||||
EnsurePackageMixin,
|
||||
AptProxyMixin,
|
||||
OpenSshServerMixin,
|
||||
@@ -141,6 +149,8 @@ class ProxmoxDriver(
|
||||
FULL_UPGRADE = True
|
||||
#: Proxmox VE's own timers and cron file are ``platform``.
|
||||
PLATFORM_SOURCES = PVE_PLATFORM_SOURCES
|
||||
#: Shows every user and their second factors (``web_login``).
|
||||
WEB_LOGIN_PRIVILEGE = ("/access/groups", ("Sys.Audit", "User.Modify"))
|
||||
#: ``/etc/cron.d/vzdump`` links into ``/etc/pve`` (pmxcfs); its lines are only run.
|
||||
RUN_ONLY_SOURCES = ("/etc/cron.d/vzdump",)
|
||||
PORT_SPECS = [
|
||||
|
||||
@@ -98,6 +98,12 @@ class ProxmoxHostMixin:
|
||||
the exec path, which runs as root either way."""
|
||||
return str(self._exec_ssh_command(command))
|
||||
|
||||
def _run_login_sessions_command(self, command: str) -> str:
|
||||
"""The transport for ``LoginSessionsMixin.get_login_sessions`` (NetOrk/netork#2881):
|
||||
the exec path, where ``SSH_CONNECTION`` names this driver's own address. wtmp is
|
||||
readable to every login. No stdin."""
|
||||
return str(self._exec_ssh_command(command))
|
||||
|
||||
def _run_log_sources_command(self, command: str, *, privileged: bool) -> str:
|
||||
"""The transport for ``LogSourcesMixin.get_log_sources``: the exec path,
|
||||
which runs as root either way."""
|
||||
@@ -261,6 +267,14 @@ class ProxmoxHostMixin:
|
||||
def _write_apt_file(self, path: str, content: str) -> FixStepOutcomeDict:
|
||||
return self._write_root_file(path, content)
|
||||
|
||||
def _reload_package_index(self) -> FixStepOutcomeDict:
|
||||
"""``CpuMicrocodeMixin``'s index load (NetOrk/netork#2838): ``apt-get update`` on the
|
||||
exec path, done when it returns. ``refresh_available_updates`` only starts the API's
|
||||
task, and the install that follows would race it."""
|
||||
return self._step(
|
||||
"DEBIAN_FRONTEND=noninteractive apt-get update", "package index loaded again"
|
||||
)
|
||||
|
||||
def _allow_sources(
|
||||
self, allowed: list[str], port: int, proto: str, purpose: str
|
||||
) -> FixStepOutcomeDict:
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
"""The images on the cluster's storages, and staging, checking and deleting them
|
||||
(NetOrk/netork#3176).
|
||||
|
||||
Read from ``GET /nodes/<node>/storage/<storage>/content`` for each storage whose
|
||||
content includes ``iso`` or ``import``: a shared one once, on the own node if it
|
||||
answers, else on the next node that does; a local one on every node that has it,
|
||||
each file with the nodes it is on. A storage that cannot be read whole is None, the
|
||||
way the backups are (``cluster_backups``): half a list would say a file is gone.
|
||||
|
||||
A single file is addressed as ``…/content/<volid>``, the volid URL-encoded into one
|
||||
path segment (proxmoxer splits a resource id on "/").
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
import shlex
|
||||
from typing import TYPE_CHECKING, Any
|
||||
from urllib.parse import quote
|
||||
|
||||
from napalm_proxmox.image_names import import_volume_name
|
||||
|
||||
if TYPE_CHECKING:
|
||||
# Type-only: newer than the napalm_device_types floor in pyproject.toml.
|
||||
from napalm_device_types import ClusterStorageDict, StorageImageDict
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_JsonDict = dict[str, Any]
|
||||
|
||||
#: napalm_device_types.STORAGE_IMAGE_CONTENT, kept here for the older floor.
|
||||
_IMAGE_CONTENT = ("iso", "import")
|
||||
|
||||
# The checksum algorithms with a coreutils "<algo>sum" on the node.
|
||||
_CHECKSUM_ALGORITHMS = frozenset({"md5", "sha1", "sha224", "sha256", "sha384", "sha512"})
|
||||
|
||||
# A file this driver downloaded: "netork-<12 hex of the URL>-<the URL's file name>".
|
||||
_STAGED = re.compile(r"^netork-[0-9a-f]{12}-(.+)$")
|
||||
|
||||
|
||||
def _content(api: Any, node: str, storage: str) -> list[_JsonDict]:
|
||||
return list(api.nodes(node).storage(storage).content.get() or [])
|
||||
|
||||
|
||||
def _shared_rows(api: Any, storage: str, nodes: list[str]) -> list[_JsonDict]:
|
||||
error: Exception | None = None
|
||||
for node in nodes:
|
||||
try:
|
||||
return _content(api, node, storage)
|
||||
except Exception as exc:
|
||||
logger.debug("Cannot read the content of %s from %s: %s", storage, node, exc)
|
||||
error = exc
|
||||
if error is not None:
|
||||
raise error
|
||||
return []
|
||||
|
||||
|
||||
def _rows_by_node(
|
||||
api: Any, storage: ClusterStorageDict, local: str
|
||||
) -> list[tuple[_JsonDict, list[str]]]:
|
||||
if storage["shared"]:
|
||||
order = sorted(storage["nodes"], key=lambda n: n != local)
|
||||
return [(row, list(storage["nodes"])) for row in _shared_rows(api, storage["name"], order)]
|
||||
return [(row, [n]) for n in storage["nodes"] for row in _content(api, n, storage["name"])]
|
||||
|
||||
|
||||
def _image(row: _JsonDict, nodes: list[str]) -> StorageImageDict:
|
||||
volid = str(row["volid"])
|
||||
return {
|
||||
"volid": volid,
|
||||
"name": volid.split(":", 1)[-1].rsplit("/", 1)[-1],
|
||||
"content": str(row.get("content")),
|
||||
"format": row.get("format") or None,
|
||||
"size": int(row["size"]) if row.get("size") is not None else None,
|
||||
"created": int(row["ctime"]) if row.get("ctime") is not None else None,
|
||||
"nodes": nodes,
|
||||
}
|
||||
|
||||
|
||||
def _storage_images(
|
||||
api: Any, storage: ClusterStorageDict, local: str
|
||||
) -> list[StorageImageDict] | None:
|
||||
if not storage["nodes"]:
|
||||
return None # available nowhere, an unmounted share: not read
|
||||
try:
|
||||
rows = _rows_by_node(api, storage, local)
|
||||
except Exception as exc:
|
||||
logger.warning("Cannot read the images on storage %s: %s", storage["name"], exc)
|
||||
return None
|
||||
images: dict[str, StorageImageDict] = {}
|
||||
for row, nodes in rows:
|
||||
if row.get("content") not in _IMAGE_CONTENT or not row.get("volid"):
|
||||
continue
|
||||
known = images.get(str(row["volid"]))
|
||||
if known is None:
|
||||
images[str(row["volid"])] = _image(row, nodes)
|
||||
else:
|
||||
known["nodes"] = [*known["nodes"], *(n for n in nodes if n not in known["nodes"])]
|
||||
return list(images.values())
|
||||
|
||||
|
||||
def read_images(api: Any, storages: list[ClusterStorageDict], local_node: str) -> None:
|
||||
"""Give each storage that holds iso or import content its ``images``, in place."""
|
||||
for storage in storages:
|
||||
if any(kind in storage["content"] for kind in _IMAGE_CONTENT):
|
||||
storage["images"] = _storage_images(api, storage, local_node)
|
||||
|
||||
|
||||
def _storage_of(volid: str) -> str:
|
||||
storage, sep, path = volid.partition(":")
|
||||
if not (storage and sep and path):
|
||||
raise ValueError(f"{volid!r} is not a volume id (<storage>:<path>)")
|
||||
return storage
|
||||
|
||||
|
||||
def volume(node_api: Any, node_name: str, volid: str) -> _JsonDict:
|
||||
"""The attributes of *volid* on the node *node_api* addresses (``path``, ``format``).
|
||||
|
||||
:raises ValueError: a volid without a storage, or a file the node does not have.
|
||||
"""
|
||||
storage = _storage_of(volid)
|
||||
try:
|
||||
return dict(node_api.storage(storage).content(quote(volid, safe="")).get() or {})
|
||||
except Exception as exc:
|
||||
raise ValueError(f"{volid} is not on a storage of {node_name}: {exc}") from exc
|
||||
|
||||
|
||||
def check_image_source(
|
||||
node_api: Any, node_name: str, image_url: str | None, image_volume: str | None
|
||||
) -> None:
|
||||
"""Exactly one image; a file named by its volid a disk image the node has."""
|
||||
if (image_url is None) == (image_volume is None):
|
||||
raise ValueError("Name the image by image_url or by image_volume, exactly one")
|
||||
if image_volume is not None:
|
||||
if image_volume.partition(":")[2].startswith("iso/"):
|
||||
raise ValueError(f"{image_volume} is installation media, not a disk image")
|
||||
volume(node_api, node_name, image_volume)
|
||||
|
||||
|
||||
class ProxmoxStorageImagesMixin:
|
||||
"""Stage, check and delete the images on this node's storages."""
|
||||
|
||||
_node_name: str
|
||||
_node_api: Any
|
||||
_run_node_command: Any
|
||||
_wait_for_task: Any
|
||||
_import_cloud_image: Any
|
||||
|
||||
@staticmethod
|
||||
def staged_image_name(image_url: str) -> str | None:
|
||||
return import_volume_name(image_url)
|
||||
|
||||
@staticmethod
|
||||
def staged_image_series(file_name: str) -> str | None:
|
||||
match = _STAGED.match(file_name)
|
||||
return match.group(1) if match else None
|
||||
|
||||
def _volume(self, volid: str) -> _JsonDict:
|
||||
"""The attributes of *volid* on this node (its ``path``, ``format``)."""
|
||||
return volume(self._node_api(), self._node_name, volid)
|
||||
|
||||
def stage_storage_image(
|
||||
self,
|
||||
storage: str,
|
||||
image_url: str,
|
||||
*,
|
||||
image_checksum: str | None = None,
|
||||
timeout: int = 1800,
|
||||
) -> str:
|
||||
name = import_volume_name(image_url)
|
||||
if name is None:
|
||||
raise ValueError(f"{image_url} cannot be staged: Proxmox imports no such file type")
|
||||
config = next(
|
||||
(s for s in self._node_api().storage.get() if s.get("storage") == storage), None
|
||||
)
|
||||
if config is None or "import" not in str(config.get("content", "")).split(","):
|
||||
raise ValueError(
|
||||
f"{self._node_name} has no storage {storage!r} for disk images to import"
|
||||
)
|
||||
if config.get("enabled", 1) == 0 or config.get("active", 1) == 0:
|
||||
raise ValueError(f"Storage {storage!r} is not active on {self._node_name}")
|
||||
return str(
|
||||
self._import_cloud_image(storage, name, image_url, image_checksum, timeout=timeout)
|
||||
)
|
||||
|
||||
def storage_image_checksum(
|
||||
self, volid: str, algorithm: str = "sha256", *, timeout: int = 3600
|
||||
) -> str:
|
||||
if algorithm not in _CHECKSUM_ALGORITHMS:
|
||||
raise ValueError(f"Unknown checksum algorithm {algorithm!r}")
|
||||
path = self._volume(volid).get("path")
|
||||
if not path:
|
||||
raise RuntimeError(f"{volid} has no path on {self._node_name}")
|
||||
out = self._run_node_command(f"{algorithm}sum {shlex.quote(str(path))}", timeout=timeout)
|
||||
return str(out).split()[0].lower()
|
||||
|
||||
def delete_storage_image(self, volid: str) -> None:
|
||||
self._volume(volid)
|
||||
content = self._node_api().storage(_storage_of(volid)).content(quote(volid, safe=""))
|
||||
upid = content.delete()
|
||||
if upid:
|
||||
self._wait_for_task(upid, timeout=120)
|
||||
@@ -28,6 +28,7 @@ from napalm_device_types.provisioning import (
|
||||
|
||||
from napalm_proxmox.image_names import cache_name, import_volume_name, split_checksum
|
||||
from napalm_proxmox.network_targets import bridge_targets, vnet_target
|
||||
from napalm_proxmox.storage_images import check_image_source
|
||||
from napalm_proxmox.utils import cpu_flags
|
||||
from napalm_proxmox.vm_mixin import qemu_status
|
||||
|
||||
@@ -364,27 +365,29 @@ class ProxmoxVMProvisionMixin:
|
||||
self,
|
||||
vmid: int,
|
||||
image_storage: str,
|
||||
image_url: str,
|
||||
image: tuple[str | None, str | None],
|
||||
image_checksum: str | None,
|
||||
download_timeout: int,
|
||||
timeout: int,
|
||||
) -> None:
|
||||
"""Get the cloud image onto the node and make it the VM's root disk.
|
||||
|
||||
Through an import storage when the node has one — Proxmox downloads,
|
||||
verifies and copies the image itself — and over SSH otherwise.
|
||||
) -> str | None:
|
||||
"""Make *image*, ``(image_url, image_volume)``, the VM's root disk; return
|
||||
the volid it came from, None over SSH. A URL goes through an import storage
|
||||
when the node has one (Proxmox downloads and verifies it), else over SSH.
|
||||
"""
|
||||
import_storage = self._find_import_storage()
|
||||
filename = import_volume_name(image_url) if import_storage else None
|
||||
if not import_storage or not filename:
|
||||
self._import_over_ssh(
|
||||
vmid, image_storage, image_url, image_checksum, download_timeout, timeout
|
||||
image_url, volid = image
|
||||
if volid is None:
|
||||
if image_url is None: # _check_image_source refuses this before any VM exists
|
||||
raise ValueError("a root disk needs image_url or image_volume")
|
||||
import_storage = self._find_import_storage()
|
||||
filename = import_volume_name(image_url) if import_storage else None
|
||||
if not import_storage or not filename:
|
||||
self._import_over_ssh(
|
||||
vmid, image_storage, image_url, image_checksum, download_timeout, timeout
|
||||
)
|
||||
return None
|
||||
volid = self._import_cloud_image(
|
||||
import_storage, filename, image_url, image_checksum, timeout=download_timeout
|
||||
)
|
||||
return
|
||||
|
||||
volid = self._import_cloud_image(
|
||||
import_storage, filename, image_url, image_checksum, timeout=download_timeout
|
||||
)
|
||||
_logger.info(f"Importing {volid} into VM {vmid} on storage {image_storage}")
|
||||
upid = (
|
||||
self._node_api()
|
||||
@@ -396,6 +399,7 @@ class ProxmoxVMProvisionMixin:
|
||||
)
|
||||
if upid:
|
||||
self._wait_for_task(upid, timeout=timeout)
|
||||
return str(volid)
|
||||
|
||||
def _find_default_image_storage(self) -> str:
|
||||
"""Find a storage suitable for VM root disks (content includes 'images').
|
||||
@@ -540,8 +544,12 @@ class ProxmoxVMProvisionMixin:
|
||||
|
||||
time.sleep(2)
|
||||
|
||||
def _check_placement(self, guest_os: str, node: str | None) -> None:
|
||||
"""Refuse a guest this driver cannot provision, or a node other than its own."""
|
||||
def _check_placement(
|
||||
self, guest_os: str, node: str | None, image_url: str | None, image_volume: str | None
|
||||
) -> None:
|
||||
"""Refuse a guest this driver cannot provision, a node other than its own, or
|
||||
an image that is not exactly one URL or one disk image this node has."""
|
||||
check_image_source(self._node_api(), self._node_name, image_url, image_volume)
|
||||
if guest_os not in self.GUEST_AGENTS:
|
||||
raise ValueError(
|
||||
f"Cannot provision a {guest_os!r} guest; this driver provisions "
|
||||
@@ -557,7 +565,8 @@ class ProxmoxVMProvisionMixin:
|
||||
self,
|
||||
name: str,
|
||||
*,
|
||||
image_url: str,
|
||||
image_url: str | None = None,
|
||||
image_volume: str | None = None,
|
||||
cpu: int,
|
||||
memory: int,
|
||||
nics: list[dict[str, Any]],
|
||||
@@ -578,8 +587,7 @@ class ProxmoxVMProvisionMixin:
|
||||
Steps:
|
||||
1. Get next available VMID from cluster
|
||||
2. Create an empty VM shell (no clone — no pre-existing template needed)
|
||||
3. Download the cloud image on the node (cached by filename) and
|
||||
import it as the VM's root disk
|
||||
3. Get the image onto the node (or take image_volume), import it as root disk
|
||||
4. Configure CPU, memory, and network interfaces
|
||||
5. Verify snippet storage exists
|
||||
6. Render cloud-init config to YAML and upload
|
||||
@@ -590,7 +598,7 @@ class ProxmoxVMProvisionMixin:
|
||||
|
||||
Args:
|
||||
name: new VM display name
|
||||
image_url: URL of the cloud image to download and use as root disk
|
||||
image_url / image_volume: a URL to download, or a volid on a storage; one of them
|
||||
cpu: number of vCPUs
|
||||
memory: RAM in MB
|
||||
nics: list of NIC config dicts (bridge, vlan_tag/trunk_vlan_tags, dhcp flag)
|
||||
@@ -613,7 +621,7 @@ class ProxmoxVMProvisionMixin:
|
||||
timeout: max seconds for the remaining provisioning steps
|
||||
|
||||
Returns:
|
||||
{"vmid": str, "name": str, "node": str}
|
||||
{"vmid": str, "name": str, "node": str, "image_volume": str | None}
|
||||
|
||||
Raises:
|
||||
VMProvisionIncomplete: any failure once the VM shell exists (download,
|
||||
@@ -626,10 +634,10 @@ class ProxmoxVMProvisionMixin:
|
||||
run, a guest_os it cannot provision, or another node (raised
|
||||
before anything is created)
|
||||
"""
|
||||
self._check_placement(guest_os, node)
|
||||
self._check_placement(guest_os, node, image_url, image_volume)
|
||||
created: int | None = None # the VMID once the shell exists on the node
|
||||
try:
|
||||
_logger.info(f"Creating {guest_os} VM '{name}' from image {image_url}")
|
||||
_logger.info(f"Creating {guest_os} VM '{name}'")
|
||||
cpu_model = self._resolve_cpu_type(cpu_type)
|
||||
|
||||
# Step 1: Get next VMID
|
||||
@@ -655,8 +663,13 @@ class ProxmoxVMProvisionMixin:
|
||||
|
||||
# Step 3: Download cloud image (cached) and import as root disk
|
||||
image_storage = storage or self._find_default_image_storage()
|
||||
self._attach_root_disk(
|
||||
vmid, image_storage, image_url, image_checksum, download_timeout, timeout
|
||||
vol = self._attach_root_disk(
|
||||
vmid,
|
||||
image_storage,
|
||||
(image_url, image_volume),
|
||||
image_checksum,
|
||||
download_timeout,
|
||||
timeout,
|
||||
)
|
||||
|
||||
# Step 4: Configure network interfaces (CPU/memory already set at shell creation)
|
||||
@@ -664,8 +677,7 @@ class ProxmoxVMProvisionMixin:
|
||||
self._node_api().qemu(vmid).config.post(**_nic_config_args(nics))
|
||||
|
||||
# Step 5: Verify snippet storage exists
|
||||
# (enabled is absent-not-falsy, and node-scoping matters — see
|
||||
# _find_default_image_storage)
|
||||
# (absent "enabled" is enabled; node-scoped: see _find_default_image_storage)
|
||||
_logger.info("Checking for snippet storage...")
|
||||
storages = self._node_api().storage.get()
|
||||
snippet_storage = None
|
||||
@@ -761,11 +773,7 @@ class ProxmoxVMProvisionMixin:
|
||||
self._wait_for_task(start_upid, timeout=timeout)
|
||||
|
||||
_logger.info(f"VM {vmid} ('{name}') provisioned successfully on {self._node_name}")
|
||||
return {
|
||||
"vmid": str(vmid),
|
||||
"name": name,
|
||||
"node": self._node_name,
|
||||
}
|
||||
return {"vmid": str(vmid), "name": name, "node": self._node_name, "image_volume": vol}
|
||||
|
||||
except Exception as e:
|
||||
_logger.exception(f"Failed to create VM '{name}': {e}")
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
"""How people log in to the web interface of Proxmox VE and PBS (NetOrk/netork#662).
|
||||
|
||||
napalm-device-types' ``WebLoginAuthDict``: the sources a login is checked against,
|
||||
each with what it asks for. Read only.
|
||||
|
||||
**A realm is a source.** Every login names its realm (``root@pam``, ``alice@pve``)
|
||||
and is checked by that realm alone, so each realm with someone who can log in is
|
||||
one source: ``{"name": "pam", "kind": "pam", "factors": "password"}``. The sources
|
||||
come in name order; the login box offers all of them.
|
||||
|
||||
**What a realm asks for** depends on its users. PVE and PBS ask every user for a
|
||||
second factor who has one: an enabled TOTP, WebAuthn, U2F or Yubico entry, or
|
||||
recovery keys (proxmox-tfa's ``TfaUserData::challenge``). Without one, the
|
||||
password alone gets in. So a realm is
|
||||
|
||||
- ``external`` when it is OpenID: the provider decides, and netOrk cannot see how;
|
||||
- ``unknown`` when it is of a kind this driver does not know;
|
||||
- ``password_otp`` when the PVE realm's own ``tfa`` is set (``oath`` or
|
||||
``yubico``): PVE then refuses a user without a second factor ("missing required
|
||||
2nd keys", ``PVE::AccessControl::authenticate_2nd_new_do``);
|
||||
- ``password_otp`` when every user of the realm who can log in has a second factor;
|
||||
- ``password`` otherwise. ``root@pam`` always exists and is often the one without.
|
||||
|
||||
The API says whether a user has a second factor, not whether it has a password, so
|
||||
an account that only holds API tokens counts as a login too. Giving it a second
|
||||
factor is the fix: its tokens do not ask for one.
|
||||
|
||||
A user who is disabled or whose account has expired cannot log in and does not
|
||||
count; a realm without anyone who can is no source (except OpenID, which can
|
||||
create its users at their first login). API tokens bypass the second factor by
|
||||
design; they are API access, not a web login, and are left out.
|
||||
|
||||
**The privilege the API login needs.** Both servers answer ``/access/users`` and
|
||||
``/access/tfa`` with the caller alone, not with a 403, when the caller may not
|
||||
see the others. A reading from such a login would judge the datacenter by one
|
||||
account, so the driver checks the privilege first (``/access/permissions``) and
|
||||
raises ``PermissionError`` without it:
|
||||
|
||||
- **Proxmox VE:** ``Sys.Audit`` or ``User.Modify`` on ``/access/groups``
|
||||
(``PVE/API2/User.pm`` and ``TFA.pm``), e.g. the ``PVEAuditor`` role on ``/``.
|
||||
- **PBS:** ``Sys.Audit`` on ``/access/users`` (``src/api2/access/user.rs`` and
|
||||
``tfa.rs``), e.g. the ``Audit`` role on ``/``.
|
||||
|
||||
A privilege-separated token needs it itself, not only its user.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from collections.abc import Iterable
|
||||
from typing import Any
|
||||
|
||||
from napalm_device_types import LoginFactors, LoginSourceDict, WebLoginAuthDict
|
||||
from proxmoxer.core import ResourceException
|
||||
|
||||
_JsonDict = dict[str, Any]
|
||||
|
||||
#: Realm kinds that check a password themselves, on PVE and PBS.
|
||||
PASSWORD_REALMS = frozenset({"pam", "pve", "pbs", "ldap", "ad"})
|
||||
#: The built-in realms, which PBS's ``/access/domains`` may leave out.
|
||||
BUILT_IN_REALMS = {"pam": "pam", "pve": "pve", "pbs": "pbs"}
|
||||
|
||||
|
||||
def _active(user: _JsonDict, now: int) -> bool:
|
||||
"""Whether *user* can log in: enabled (``1``/``true``, the default) and not expired."""
|
||||
expire = int(user.get("expire") or 0)
|
||||
return bool(user.get("enable", True)) and not (expire and expire <= now)
|
||||
|
||||
|
||||
def _with_second_factor(tfa: Iterable[_JsonDict]) -> set[str]:
|
||||
"""The users with at least one enabled TFA entry; ``enable`` is only sent when off."""
|
||||
return {
|
||||
str(user.get("userid"))
|
||||
for user in tfa
|
||||
if any(entry.get("enable", True) for entry in user.get("entries") or ())
|
||||
}
|
||||
|
||||
|
||||
def _realm_of(userid: str) -> str:
|
||||
return userid.rpartition("@")[2]
|
||||
|
||||
|
||||
def _factors(kind: str, realm_tfa: bool, members: list[str], second: set[str]) -> LoginFactors:
|
||||
if kind == "openid":
|
||||
return "external"
|
||||
if kind not in PASSWORD_REALMS:
|
||||
return "unknown"
|
||||
if realm_tfa or all(userid in second for userid in members):
|
||||
return "password_otp"
|
||||
return "password"
|
||||
|
||||
|
||||
def _users_by_realm(
|
||||
users: list[_JsonDict], now: int
|
||||
) -> tuple[dict[str, list[str]], dict[str, str]]:
|
||||
"""Each realm's users who can log in, and each realm's type as the user list names it."""
|
||||
members: dict[str, list[str]] = {}
|
||||
kinds: dict[str, str] = {}
|
||||
for user in users:
|
||||
userid = str(user.get("userid") or "")
|
||||
realm = _realm_of(userid)
|
||||
if user.get("realm-type"):
|
||||
kinds.setdefault(realm, str(user["realm-type"]))
|
||||
if userid and _active(user, now):
|
||||
members.setdefault(realm, []).append(userid)
|
||||
return members, kinds
|
||||
|
||||
|
||||
def web_login_sources(
|
||||
*,
|
||||
realms: list[_JsonDict],
|
||||
users: list[_JsonDict],
|
||||
tfa: list[_JsonDict],
|
||||
now: int,
|
||||
) -> list[LoginSourceDict]:
|
||||
"""The realms a login can name, each with what it asks for, by realm name.
|
||||
|
||||
*realms* is ``/access/domains``, *users* ``/access/users`` and *tfa*
|
||||
``/access/tfa``, each as the server answered; *now* is unix seconds.
|
||||
"""
|
||||
configured = {str(r.get("realm")): r for r in realms if r.get("realm")}
|
||||
members, kinds = _users_by_realm(users, now)
|
||||
second = _with_second_factor(tfa)
|
||||
sources: list[LoginSourceDict] = []
|
||||
for name in sorted(set(configured) | set(members)):
|
||||
config = configured.get(name, {})
|
||||
kind = str(config.get("type") or kinds.get(name) or BUILT_IN_REALMS.get(name, ""))
|
||||
logins = members.get(name, [])
|
||||
if not logins and kind in PASSWORD_REALMS:
|
||||
continue
|
||||
factors = _factors(kind, bool(config.get("tfa")), logins, second)
|
||||
sources.append({"name": name, "kind": kind, "factors": factors})
|
||||
return sources
|
||||
|
||||
|
||||
class ProxmoxWebLoginMixin:
|
||||
"""``get_web_login_auth`` for both drivers; each names the privilege its server
|
||||
filters the user lists by."""
|
||||
|
||||
_api: Any
|
||||
#: The ACL path and the privileges, any one of which shows every user.
|
||||
WEB_LOGIN_PRIVILEGE: tuple[str, tuple[str, ...]]
|
||||
|
||||
def get_web_login_auth(self) -> WebLoginAuthDict:
|
||||
"""The realms a login can name, each with what it asks for.
|
||||
|
||||
Example::
|
||||
|
||||
{"sources": [{"name": "pam", "kind": "pam", "factors": "password"}]}
|
||||
|
||||
:raises PermissionError: when the API login lacks the privilege that shows
|
||||
every user (see the module docstring), or a read is refused.
|
||||
"""
|
||||
self._require_user_audit()
|
||||
return {
|
||||
"sources": web_login_sources(
|
||||
realms=self._web_login_read("access/domains"),
|
||||
users=self._web_login_read("access/users"),
|
||||
tfa=self._web_login_read("access/tfa"),
|
||||
now=int(time.time()),
|
||||
)
|
||||
}
|
||||
|
||||
def _require_user_audit(self) -> None:
|
||||
path, privileges = self.WEB_LOGIN_PRIVILEGE
|
||||
held = self._web_login_read("access/permissions", path=path)
|
||||
granted = held.get(path) if isinstance(held, dict) else None
|
||||
if not any(privilege in (granted or {}) for privilege in privileges):
|
||||
raise PermissionError(
|
||||
f"the API login lacks {' or '.join(privileges)} on {path}; the server "
|
||||
"would list only the login's own user"
|
||||
)
|
||||
|
||||
def _web_login_read(self, endpoint: str, /, **params: Any) -> Any:
|
||||
try:
|
||||
return self._api.get(endpoint, **params) or []
|
||||
except ResourceException as exc:
|
||||
if exc.status_code in (401, 403):
|
||||
raise PermissionError(f"GET {endpoint} was refused: {exc}") from exc
|
||||
raise
|
||||
+2
-2
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "napalm-proxmox"
|
||||
version = "0.18.0"
|
||||
version = "0.22.0"
|
||||
description = "NAPALM drivers for Proxmox VE (classic Linux networking, SDN, OVS) and Proxmox Backup Server"
|
||||
readme = "README.md"
|
||||
license = "Apache-2.0"
|
||||
@@ -21,7 +21,7 @@ classifiers = [
|
||||
requires-python = ">=3.12"
|
||||
dependencies = [
|
||||
"napalm>=5.0.0",
|
||||
"napalm_device_types>=4.48.0", # HardeningMixin; ServicesRestartMixin with LXC left out
|
||||
"napalm_device_types>=4.61.0", # storage images
|
||||
"paramiko>=5.0.0", # CVE-2026-44405; imported directly for the node's SSH session (_base.py)
|
||||
"proxmoxer>=2.0.0",
|
||||
"netaddr>=0.9.0",
|
||||
|
||||
+4
-4
@@ -82,16 +82,16 @@ class FakePbsApi:
|
||||
raise AttributeError(name)
|
||||
return _Resource(self, name)
|
||||
|
||||
def get(self, path: str, **params: Any) -> Any:
|
||||
def get(self, path: str, /, **params: Any) -> Any:
|
||||
return self._answer("GET", path, params)
|
||||
|
||||
def post(self, path: str, **params: Any) -> Any:
|
||||
def post(self, path: str, /, **params: Any) -> Any:
|
||||
return self._answer("POST", path, params)
|
||||
|
||||
def put(self, path: str, **params: Any) -> Any:
|
||||
def put(self, path: str, /, **params: Any) -> Any:
|
||||
return self._answer("PUT", path, params)
|
||||
|
||||
def delete(self, path: str, **params: Any) -> Any:
|
||||
def delete(self, path: str, /, **params: Any) -> Any:
|
||||
return self._answer("DELETE", path, params)
|
||||
|
||||
|
||||
|
||||
@@ -519,7 +519,13 @@ class TestBackups:
|
||||
def test_storage_without_backup_content_is_not_read(self):
|
||||
api, calls = _storage_api()
|
||||
_report(api)
|
||||
assert not [key for key in calls if key[1] in ("ceph-vm", "local-lvm", "nfs-iso")]
|
||||
# The images on an iso storage are read on their own (storage_images).
|
||||
backup_reads = [
|
||||
key
|
||||
for key, res in calls.items()
|
||||
if any(c.kwargs.get("content") == "backup" for c in res.content.get.call_args_list)
|
||||
]
|
||||
assert not [key for key in backup_reads if key[1] in ("ceph-vm", "local-lvm", "nfs-iso")]
|
||||
|
||||
def test_entry_without_vmid_is_skipped(self):
|
||||
api, _ = _storage_api()
|
||||
|
||||
@@ -69,3 +69,69 @@ def test_output_without_a_report_raises(driver):
|
||||
with patch.object(driver, "_exec_ssh_command", return_value=""):
|
||||
with pytest.raises(ValueError):
|
||||
driver.get_hardening()
|
||||
|
||||
|
||||
class TestCpuMicrocode:
|
||||
"""``install_cpu_microcode`` (napalm-device-types ``CpuMicrocodeMixin``, NetOrk/netork#2838):
|
||||
a node runs on its own CPU, and Proxmox's own install enables no ``non-free-firmware``."""
|
||||
|
||||
SOURCES = "/etc/apt/sources.list.d/debian.sources"
|
||||
TEXT = (
|
||||
"Types: deb\nURIs: http://deb.debian.org/debian/\nSuites: trixie trixie-updates\n"
|
||||
"Components: main contrib\n"
|
||||
)
|
||||
|
||||
def _node(self, drv, *, virtualization="none"):
|
||||
import base64
|
||||
|
||||
ran: list[str] = []
|
||||
file_lines = "".join(f"|{line}\n" for line in self.TEXT.split("\n"))
|
||||
report = (
|
||||
"ARELEASE_BEGIN\n@@os\n|ID=debian\n|VERSION_CODENAME=trixie\n"
|
||||
f"@@file {self.SOURCES}\n{file_lines}ARELEASE_END\n"
|
||||
)
|
||||
|
||||
def exec_(command):
|
||||
ran.append(command)
|
||||
if command.startswith("base64 "):
|
||||
return base64.b64encode(self.TEXT.encode()).decode()
|
||||
if "ARELEASE_" in command:
|
||||
return report
|
||||
return "done\n__PVE_RC=0"
|
||||
|
||||
drv.get_hardening = lambda: {
|
||||
"os_ids": ["debian"],
|
||||
"virtualization": virtualization,
|
||||
"cpu_vendor": "GenuineIntel",
|
||||
}
|
||||
drv.get_packages = lambda: []
|
||||
drv.refresh_available_updates = lambda: pytest.fail("the API refresh does not wait")
|
||||
drv._exec_ssh_command = exec_
|
||||
return ran
|
||||
|
||||
@pytest.mark.parametrize("cls", [ProxmoxDriver, ProxmoxBackupDriver])
|
||||
def test_both_drivers_carry_it(self, cls):
|
||||
assert callable(getattr(cls, "install_cpu_microcode", None))
|
||||
|
||||
def test_the_component_then_apt_get_update_then_the_package(self, driver):
|
||||
ran = self._node(driver)
|
||||
|
||||
result = driver.install_cpu_microcode()
|
||||
|
||||
assert result["success"] is True, result["output"]
|
||||
assert result["sources_changed"] is True
|
||||
written = next(c for c in ran if "install -m 644" in c)
|
||||
assert self.SOURCES in written
|
||||
update = next(i for i, c in enumerate(ran) if "apt-get update" in c)
|
||||
install = next(i for i, c in enumerate(ran) if "apt-get install -y intel-microcode" in c)
|
||||
assert ran.index(written) < update < install
|
||||
|
||||
def test_a_virtual_backup_server_installs_nothing(self):
|
||||
drv = ProxmoxBackupDriver("192.0.2.80", "root", "", optional_args={"token_name": "a!b"})
|
||||
ran = self._node(drv, virtualization="kvm")
|
||||
|
||||
result = drv.install_cpu_microcode()
|
||||
|
||||
assert result["success"] is False
|
||||
assert "its host does" in result["output"]
|
||||
assert ran == []
|
||||
@@ -0,0 +1,63 @@
|
||||
"""`get_login_sessions`: the interactive logins a node recorded (NetOrk/netork#2881).
|
||||
|
||||
A shell on a node that did not go through the application -- someone's own ``ssh``, or
|
||||
the web interface's shell -- is in the node's wtmp. The command and its parse are
|
||||
napalm-device-types' (``LoginSessionsMixin``); both drivers carry the command over their
|
||||
own exec path, where ``SSH_CONNECTION`` names the driver's own address.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
from napalm_device_types import LoginSessionsMixin, LoginSessionsUnavailable
|
||||
|
||||
from napalm_proxmox.backup_driver import ProxmoxBackupDriver
|
||||
from napalm_proxmox.driver import ProxmoxDriver
|
||||
|
||||
WIRE = "\n".join(
|
||||
[
|
||||
"LOGSESSIONS_BEGIN",
|
||||
"[own]",
|
||||
"198.51.100.2",
|
||||
"[now]",
|
||||
"2026-11-30T12:00:00Z",
|
||||
"[wtmp since]",
|
||||
"root pts/0 192.0.2.10 2026-11-30T10:15:02+01:00 still logged in",
|
||||
"root pts/1 0.0.0.0 2026-11-29T09:00:00+01:00 - 2026-11-29T09:30:00+01:00 (00:30)",
|
||||
"LOGSESSIONS_END",
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cls", [ProxmoxDriver, ProxmoxBackupDriver])
|
||||
def test_both_drivers_declare_the_contract(cls):
|
||||
assert issubclass(cls, LoginSessionsMixin)
|
||||
assert hasattr(cls, "get_login_sessions")
|
||||
|
||||
|
||||
def test_the_node_runs_the_shared_command_over_its_exec_path(driver):
|
||||
with patch.object(driver, "_exec_ssh_command", return_value=WIRE) as exec_:
|
||||
reading = driver.get_login_sessions()
|
||||
|
||||
exec_.assert_called_once()
|
||||
assert exec_.call_args.args[0].startswith("sh -c ")
|
||||
assert reading["own_address"] == "198.51.100.2"
|
||||
assert [s["address"] for s in reading["sessions"]] == ["192.0.2.10", None]
|
||||
|
||||
|
||||
def test_the_backup_server_reads_it_the_same_way():
|
||||
drv = ProxmoxBackupDriver("192.0.2.80", "root", "", optional_args={"token_name": "a!b"})
|
||||
|
||||
with patch.object(drv, "_exec_ssh_command", return_value=WIRE):
|
||||
reading = drv.get_login_sessions()
|
||||
|
||||
assert reading["sessions"][0]["user"] == "root"
|
||||
|
||||
|
||||
def test_a_node_without_login_records_raises(driver):
|
||||
empty = "LOGSESSIONS_BEGIN\n[own]\n\n[now]\n2026-11-30T12:00:00Z\nLOGSESSIONS_END"
|
||||
with patch.object(driver, "_exec_ssh_command", return_value=empty):
|
||||
with pytest.raises(LoginSessionsUnavailable):
|
||||
driver.get_login_sessions()
|
||||
@@ -0,0 +1,432 @@
|
||||
"""The images on the cluster's storages, and staging, checking and deleting them
|
||||
(NetOrk/netork#3176).
|
||||
|
||||
Storage content rows follow ``GET /nodes/{node}/storage/{storage}/content``
|
||||
(pve-storage ``PVE/API2/Storage/Content.pm``): ``volid``, ``content``, ``format``,
|
||||
``size`` and ``ctime``. ``GET …/content/{volume}`` answers a file's ``path`` on the
|
||||
node (read live on PVE 9.2, 2026-12-06, with the volid URL-encoded as one segment).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
from unittest.mock import MagicMock, patch
|
||||
from urllib.parse import quote
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_proxmox.image_names import import_volume_name
|
||||
from napalm_proxmox.storage_images import ProxmoxStorageImagesMixin, read_images
|
||||
from napalm_proxmox.vm_provision_mixin import ProxmoxVMProvisionMixin
|
||||
from tests.test_clusters import _api, _by_name, _driver
|
||||
|
||||
_UBUNTU = (
|
||||
"https://cloud-images.ubuntu.com/releases/24.04/release-20261120/"
|
||||
"ubuntu-24.04-server-cloudimg-amd64.img"
|
||||
)
|
||||
_UBUNTU_NEXT = _UBUNTU.replace("20261120", "20261201")
|
||||
|
||||
|
||||
def _row(volid: str, content: str, fmt: str = "qcow2", size: int = 100, ctime: int = 1) -> dict:
|
||||
return {"volid": volid, "content": content, "format": fmt, "size": size, "ctime": ctime}
|
||||
|
||||
|
||||
def _storage(name: str, content: list[str], nodes: list[str], shared: bool) -> dict[str, Any]:
|
||||
return {"name": name, "type": "cifs" if shared else "dir", "shared": shared,
|
||||
"content": content, "nodes": nodes, "total": None, "used": None} # fmt: skip
|
||||
|
||||
|
||||
def _content_api(rows: dict[tuple[str, str], list[dict] | Exception]) -> MagicMock:
|
||||
"""``api.nodes(node).storage(storage).content.get()`` answers *rows*."""
|
||||
api = MagicMock()
|
||||
|
||||
def node(name: str) -> MagicMock:
|
||||
res = MagicMock()
|
||||
|
||||
def storage(sname: str) -> MagicMock:
|
||||
answer = rows.get((name, sname), [])
|
||||
st = MagicMock()
|
||||
if isinstance(answer, Exception):
|
||||
st.content.get.side_effect = answer
|
||||
else:
|
||||
st.content.get.return_value = answer
|
||||
return st
|
||||
|
||||
res.storage.side_effect = storage
|
||||
return res
|
||||
|
||||
api.nodes.side_effect = node
|
||||
return api
|
||||
|
||||
|
||||
# ── reading ──────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestReadImages:
|
||||
def test_a_shared_storage_is_read_once_on_the_own_node(self):
|
||||
software = _storage("software", ["import", "iso"], ["pve1", "pve2"], shared=True)
|
||||
api = _content_api(
|
||||
{
|
||||
("pve2", "software"): [
|
||||
_row("software:iso/virtio-win.iso", "iso", "iso", 877373440, 1790270490),
|
||||
_row("software:import/debian-13.qcow2", "import", "qcow2", 341508096, 17),
|
||||
]
|
||||
}
|
||||
)
|
||||
read_images(api, [software], "pve2")
|
||||
assert [c.args for c in api.nodes.call_args_list] == [("pve2",)]
|
||||
assert software["images"] == [
|
||||
{
|
||||
"volid": "software:iso/virtio-win.iso",
|
||||
"name": "virtio-win.iso",
|
||||
"content": "iso",
|
||||
"format": "iso",
|
||||
"size": 877373440,
|
||||
"created": 1790270490,
|
||||
"nodes": ["pve1", "pve2"],
|
||||
},
|
||||
{
|
||||
"volid": "software:import/debian-13.qcow2",
|
||||
"name": "debian-13.qcow2",
|
||||
"content": "import",
|
||||
"format": "qcow2",
|
||||
"size": 341508096,
|
||||
"created": 17,
|
||||
"nodes": ["pve1", "pve2"],
|
||||
},
|
||||
]
|
||||
|
||||
def test_a_shared_storage_the_own_node_cannot_read_is_read_on_the_next(self):
|
||||
software = _storage("software", ["iso"], ["pve1", "pve2"], shared=True)
|
||||
api = _content_api(
|
||||
{
|
||||
("pve1", "software"): ConnectionError("share not mounted"),
|
||||
("pve2", "software"): [_row("software:iso/a.iso", "iso", "iso")],
|
||||
}
|
||||
)
|
||||
read_images(api, [software], "pve1")
|
||||
assert [i["name"] for i in software["images"]] == ["a.iso"]
|
||||
|
||||
def test_a_local_storage_lists_each_file_with_the_nodes_it_is_on(self):
|
||||
local = _storage("local", ["iso", "vztmpl", "backup"], ["pve1", "pve2"], shared=False)
|
||||
api = _content_api(
|
||||
{
|
||||
("pve1", "local"): [_row("local:iso/a.iso", "iso", "iso")],
|
||||
("pve2", "local"): [
|
||||
_row("local:iso/a.iso", "iso", "iso"),
|
||||
_row("local:iso/b.iso", "iso", "iso"),
|
||||
],
|
||||
}
|
||||
)
|
||||
read_images(api, [local], "pve1")
|
||||
assert {i["name"]: i["nodes"] for i in local["images"]} == {
|
||||
"a.iso": ["pve1", "pve2"],
|
||||
"b.iso": ["pve2"],
|
||||
}
|
||||
|
||||
def test_other_content_is_left_out(self):
|
||||
local = _storage("local", ["iso", "vztmpl", "snippets", "backup"], ["pve1"], shared=False)
|
||||
api = _content_api(
|
||||
{
|
||||
("pve1", "local"): [
|
||||
_row("local:iso/a.iso", "iso", "iso"),
|
||||
_row("local:vztmpl/debian.tar.zst", "vztmpl", "tzst"),
|
||||
_row("local:snippets/101-user-data.yaml", "snippets", "snippet"),
|
||||
_row("local:backup/vzdump-qemu-100.vma.zst", "backup", "vma.zst"),
|
||||
]
|
||||
}
|
||||
)
|
||||
read_images(api, [local], "pve1")
|
||||
assert [i["name"] for i in local["images"]] == ["a.iso"]
|
||||
|
||||
def test_a_storage_without_images_gets_no_key_and_is_not_read(self):
|
||||
zfs = _storage("local-zfs", ["images", "rootdir"], ["pve1"], shared=False)
|
||||
api = _content_api({})
|
||||
read_images(api, [zfs], "pve1")
|
||||
assert "images" not in zfs
|
||||
api.nodes.assert_not_called()
|
||||
|
||||
def test_a_node_of_a_local_storage_that_does_not_answer_leaves_it_unread(self):
|
||||
"""Half a list would say the other node's files are gone."""
|
||||
local = _storage("local", ["iso"], ["pve1", "pve2"], shared=False)
|
||||
api = _content_api(
|
||||
{
|
||||
("pve1", "local"): [_row("local:iso/a.iso", "iso", "iso")],
|
||||
("pve2", "local"): ConnectionError("pve2 unreachable"),
|
||||
}
|
||||
)
|
||||
read_images(api, [local], "pve1")
|
||||
assert local["images"] is None
|
||||
|
||||
def test_a_shared_storage_no_node_can_read_is_unread(self):
|
||||
software = _storage("software", ["iso"], ["pve1"], shared=True)
|
||||
api = _content_api({("pve1", "software"): ConnectionError("down")})
|
||||
read_images(api, [software], "pve1")
|
||||
assert software["images"] is None
|
||||
|
||||
def test_a_storage_available_on_no_node_is_unread(self):
|
||||
"""An unmounted share is on no node: that is not a storage without files."""
|
||||
software = _storage("software", ["iso"], [], shared=True)
|
||||
api = _content_api({})
|
||||
read_images(api, [software], "pve1")
|
||||
assert software["images"] is None
|
||||
|
||||
def test_values_the_platform_leaves_out_are_none(self):
|
||||
software = _storage("software", ["iso"], ["pve1"], shared=True)
|
||||
api = _content_api(
|
||||
{("pve1", "software"): [{"volid": "software:iso/x.iso", "content": "iso"}]}
|
||||
)
|
||||
read_images(api, [software], "pve1")
|
||||
[image] = software["images"]
|
||||
assert (image["format"], image["size"], image["created"]) == (None, None, None)
|
||||
|
||||
def test_get_clusters_reports_the_images(self):
|
||||
api = _api()
|
||||
api.nodes("pve1").storage.side_effect = lambda name: MagicMock(
|
||||
content=MagicMock(
|
||||
get=MagicMock(
|
||||
return_value=[_row(f"{name}:iso/x.iso", "iso", "iso")]
|
||||
if name == "nfs-iso"
|
||||
else []
|
||||
)
|
||||
)
|
||||
)
|
||||
[cluster] = _driver(api).get_clusters()
|
||||
storages = _by_name(cluster["storages"])
|
||||
assert [i["volid"] for i in storages["nfs-iso"]["images"]] == ["nfs-iso:iso/x.iso"]
|
||||
assert "images" not in storages["ceph-vm"]
|
||||
|
||||
|
||||
# ── names ────────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestNames:
|
||||
def test_the_staged_name_is_the_import_name(self):
|
||||
assert ProxmoxStorageImagesMixin.staged_image_name(_UBUNTU) == import_volume_name(_UBUNTU)
|
||||
|
||||
def test_an_image_that_cannot_be_staged_has_no_name(self):
|
||||
assert ProxmoxStorageImagesMixin.staged_image_name("https://x.org/a.qcow2.xz") is None
|
||||
|
||||
def test_two_builds_of_one_image_are_one_series(self):
|
||||
series = ProxmoxStorageImagesMixin.staged_image_series
|
||||
first = ProxmoxStorageImagesMixin.staged_image_name(_UBUNTU)
|
||||
second = ProxmoxStorageImagesMixin.staged_image_name(_UBUNTU_NEXT)
|
||||
assert first != second
|
||||
assert series(first) == series(second) == "ubuntu-24.04-server-cloudimg-amd64.qcow2"
|
||||
|
||||
def test_a_file_netork_did_not_name_has_no_series(self):
|
||||
series = ProxmoxStorageImagesMixin.staged_image_series
|
||||
assert series("ubuntu-24.04.5-preinstalled-server-arm64.qcow2") is None
|
||||
assert series("netork-notahash-x.qcow2") is None
|
||||
|
||||
|
||||
# ── stage, checksum, delete ──────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _mixin(storages: list[dict] | None = None) -> tuple[Any, MagicMock]:
|
||||
class Mixin(ProxmoxStorageImagesMixin, ProxmoxVMProvisionMixin):
|
||||
pass
|
||||
|
||||
mixin = Mixin()
|
||||
mixin._node_name = "pve1"
|
||||
node = MagicMock()
|
||||
node.storage.get.return_value = storages if storages is not None else [
|
||||
{"storage": "software", "content": "import,iso", "active": 1, "enabled": 1},
|
||||
{"storage": "local", "content": "iso,vztmpl", "active": 1},
|
||||
] # fmt: skip
|
||||
node.tasks.return_value.status.get.return_value = {"status": "stopped", "exitstatus": "OK"}
|
||||
mixin._node_api = MagicMock(return_value=node)
|
||||
mixin._run_node_command = MagicMock(return_value="")
|
||||
return mixin, node
|
||||
|
||||
|
||||
class TestStage:
|
||||
def test_downloads_into_the_storage_under_its_name(self):
|
||||
mixin, _ = _mixin()
|
||||
mixin._import_cloud_image = MagicMock(return_value="software:import/x.qcow2")
|
||||
volid = mixin.stage_storage_image("software", _UBUNTU, image_checksum="sha256:ab")
|
||||
assert volid == "software:import/x.qcow2"
|
||||
mixin._import_cloud_image.assert_called_once_with(
|
||||
"software", import_volume_name(_UBUNTU), _UBUNTU, "sha256:ab", timeout=1800
|
||||
)
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"storage, url",
|
||||
[
|
||||
("software", "https://x.org/a.qcow2.xz"), # packed: only the SSH path unpacks
|
||||
("local", _UBUNTU), # takes no disk images to import
|
||||
("elsewhere", _UBUNTU), # not on this node
|
||||
],
|
||||
)
|
||||
def test_refuses_what_it_cannot_stage(self, storage: str, url: str):
|
||||
mixin, _ = _mixin()
|
||||
mixin._import_cloud_image = MagicMock()
|
||||
with pytest.raises(ValueError):
|
||||
mixin.stage_storage_image(storage, url)
|
||||
mixin._import_cloud_image.assert_not_called()
|
||||
|
||||
def test_refuses_an_inactive_storage(self):
|
||||
mixin, _ = _mixin([{"storage": "software", "content": "import", "active": 0}])
|
||||
with pytest.raises(ValueError, match="not active"):
|
||||
mixin.stage_storage_image("software", _UBUNTU)
|
||||
|
||||
|
||||
class TestChecksum:
|
||||
def test_hashes_the_file_on_the_node(self):
|
||||
mixin, node = _mixin()
|
||||
volid = "software:iso/virtio-win.iso"
|
||||
node.storage.return_value.content.return_value.get.return_value = {
|
||||
"path": "/mnt/pve/software/template/iso/virtio-win.iso"
|
||||
}
|
||||
mixin._run_node_command.return_value = (
|
||||
"ABCDEF /mnt/pve/software/template/iso/virtio-win.iso"
|
||||
)
|
||||
|
||||
assert mixin.storage_image_checksum(volid, "sha512", timeout=99) == "abcdef"
|
||||
node.storage.assert_any_call("software")
|
||||
node.storage.return_value.content.assert_called_with(quote(volid, safe=""))
|
||||
mixin._run_node_command.assert_called_once_with(
|
||||
"sha512sum /mnt/pve/software/template/iso/virtio-win.iso", timeout=99
|
||||
)
|
||||
|
||||
def test_an_unknown_algorithm_is_refused_before_anything_runs(self):
|
||||
mixin, _ = _mixin()
|
||||
with pytest.raises(ValueError):
|
||||
mixin.storage_image_checksum("software:iso/a.iso", "crc32")
|
||||
mixin._run_node_command.assert_not_called()
|
||||
|
||||
def test_a_file_not_on_this_node_is_refused(self):
|
||||
mixin, node = _mixin()
|
||||
node.storage.return_value.content.return_value.get.side_effect = RuntimeError(
|
||||
"500 no such volume"
|
||||
)
|
||||
with pytest.raises(ValueError, match="not on"):
|
||||
mixin.storage_image_checksum("software:iso/gone.iso")
|
||||
|
||||
def test_a_volid_without_a_storage_is_refused(self):
|
||||
mixin, _ = _mixin()
|
||||
with pytest.raises(ValueError):
|
||||
mixin.storage_image_checksum("gone.iso")
|
||||
|
||||
|
||||
class TestDelete:
|
||||
def test_deletes_the_file_and_waits_for_the_task(self):
|
||||
mixin, node = _mixin()
|
||||
volid = "software:import/netork-96bc7f0f1aa3-ubuntu-24.04-server-cloudimg-amd64.qcow2"
|
||||
content = node.storage.return_value.content.return_value
|
||||
content.get.return_value = {"path": "/mnt/pve/software/import/x"}
|
||||
content.delete.return_value = "UPID:pve1:delete"
|
||||
mixin._wait_for_task = MagicMock()
|
||||
|
||||
mixin.delete_storage_image(volid)
|
||||
|
||||
node.storage.return_value.content.assert_called_with(quote(volid, safe=""))
|
||||
content.delete.assert_called_once_with()
|
||||
mixin._wait_for_task.assert_called_once_with("UPID:pve1:delete", timeout=120)
|
||||
|
||||
def test_a_file_not_on_this_node_is_refused(self):
|
||||
mixin, node = _mixin()
|
||||
content = node.storage.return_value.content.return_value
|
||||
content.get.side_effect = RuntimeError("500")
|
||||
with pytest.raises(ValueError):
|
||||
mixin.delete_storage_image("software:iso/gone.iso")
|
||||
content.delete.assert_not_called()
|
||||
|
||||
|
||||
# ── a VM from a file already on a storage ────────────────────────────────────
|
||||
|
||||
|
||||
def _provisioner(storages: list[dict] | None = None) -> tuple[Any, MagicMock]:
|
||||
mixin, node = _mixin(
|
||||
storages
|
||||
if storages is not None
|
||||
else [
|
||||
{"storage": "local", "content": "iso,backup,vztmpl,snippets"},
|
||||
{"storage": "software", "content": "import,iso"},
|
||||
{"storage": "local-zfs", "content": "images,rootdir"},
|
||||
]
|
||||
)
|
||||
api = MagicMock()
|
||||
api.cluster.nextid.get.return_value = 101
|
||||
api.storage.return_value.get.return_value = {"path": "/var/lib/vz"}
|
||||
mixin._api = api
|
||||
mixin._download_cloud_image = MagicMock(return_value="/var/lib/vz/template/x.qcow2")
|
||||
vm = node.qemu.return_value
|
||||
vm.config.get.return_value = {"unused0": "local-zfs:vm-101-disk-0"}
|
||||
vm.config.post.return_value = None
|
||||
node.storage.return_value.content.get.return_value = []
|
||||
node.storage.return_value.content.return_value.get.return_value = {"path": "/mnt/pve/x"}
|
||||
return mixin, node
|
||||
|
||||
|
||||
def _create(mixin: Any, **image: Any) -> dict:
|
||||
with patch("time.sleep"):
|
||||
return dict(
|
||||
mixin.create_vm_from_cloud_init(
|
||||
name="vm",
|
||||
cpu=1,
|
||||
memory=1024,
|
||||
nics=[{"bridge": "vmbr0"}],
|
||||
cloud_init_config={"hostname": "vm"},
|
||||
storage="local-zfs",
|
||||
timeout=60,
|
||||
**image,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
class TestCreateFromAVolume:
|
||||
def test_the_file_becomes_the_root_disk_without_a_download(self):
|
||||
mixin, node = _provisioner()
|
||||
volid = "software:import/ubuntu-24.04.5-preinstalled-server-amd64.qcow2"
|
||||
|
||||
result = _create(mixin, image_volume=volid)
|
||||
|
||||
mixin._download_cloud_image.assert_not_called()
|
||||
node.storage.return_value.content.get.assert_not_called() # nothing looked up to download
|
||||
disk = next(
|
||||
c.kwargs
|
||||
for c in node.qemu.return_value.config.post.call_args_list
|
||||
if "scsi0" in c.kwargs
|
||||
)
|
||||
assert disk["scsi0"] == f"local-zfs:0,import-from={volid},discard=on"
|
||||
assert result["image_volume"] == volid
|
||||
|
||||
def test_a_download_names_the_file_it_staged(self):
|
||||
mixin, _ = _provisioner()
|
||||
result = _create(mixin, image_url=_UBUNTU)
|
||||
assert result["image_volume"] == f"software:import/{import_volume_name(_UBUNTU)}"
|
||||
|
||||
def test_the_ssh_path_keeps_no_file_on_a_storage(self):
|
||||
mixin, _ = _provisioner([{"storage": "local-zfs", "content": "images,rootdir"},
|
||||
{"storage": "local", "content": "snippets"}]) # fmt: skip
|
||||
result = _create(mixin, image_url=_UBUNTU)
|
||||
assert result["image_volume"] is None
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"image",
|
||||
[
|
||||
{},
|
||||
{"image_url": _UBUNTU, "image_volume": "software:import/x.qcow2"},
|
||||
{"image_volume": "software:iso/virtio-win.iso"},
|
||||
],
|
||||
ids=["neither", "both", "an-iso"],
|
||||
)
|
||||
def test_refuses_before_anything_is_created(self, image: dict):
|
||||
mixin, _ = _provisioner()
|
||||
with pytest.raises(ValueError):
|
||||
_create(mixin, **image)
|
||||
mixin._api.cluster.nextid.get.assert_not_called()
|
||||
|
||||
def test_refuses_a_file_this_node_does_not_have(self):
|
||||
mixin, node = _provisioner()
|
||||
node.storage.return_value.content.return_value.get.side_effect = RuntimeError("500")
|
||||
with pytest.raises(ValueError, match="not on"):
|
||||
_create(mixin, image_volume="local:import/elsewhere.qcow2")
|
||||
mixin._api.cluster.nextid.get.assert_not_called()
|
||||
|
||||
def test_the_root_disk_without_a_source_is_refused_even_past_the_check(self):
|
||||
"""The check refuses it first; the disk step refuses it too, never assumes it."""
|
||||
mixin, _ = _provisioner()
|
||||
with pytest.raises(ValueError, match="image_url or image_volume"):
|
||||
mixin._attach_root_disk(101, "local-zfs", (None, None), None, 60, 60)
|
||||
@@ -0,0 +1,259 @@
|
||||
"""get_web_login_auth: how the web interface lets people log in (NetOrk/netork#662).
|
||||
|
||||
A Proxmox login names its realm (``root@pam``, ``alice@pve``), so every realm
|
||||
with someone who can log in is a source. What a source asks for depends on its
|
||||
users: PVE and PBS ask for a second factor of every user who has one
|
||||
(``/access/tfa``), and a PVE realm whose ``tfa`` is set refuses users without
|
||||
one. OpenID hands the login to its provider.
|
||||
|
||||
The answers follow the API schema of pve-access-control (``PVE/API2/User.pm``,
|
||||
``TFA.pm``, ``Domains.pm``) and proxmox-backup (``src/api2/access/``). A TFA
|
||||
entry carries ``enable`` only when it is off (proxmox-tfa's ``TfaInfo``); PVE
|
||||
writes ``enable`` on a user as 0 or 1, PBS as a boolean or not at all.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from napalm_device_types import WebLoginAuthDict
|
||||
|
||||
from napalm_proxmox import ProxmoxBackupDriver, ProxmoxDriver
|
||||
from napalm_proxmox.web_login import web_login_sources
|
||||
from tests.pbs_fake import FakePbsApi, forbidden
|
||||
|
||||
NOW = 1_800_000_000
|
||||
PAST = NOW - 86_400
|
||||
FUTURE = NOW + 86_400
|
||||
|
||||
|
||||
def _user(userid: str, **fields: Any) -> dict[str, Any]:
|
||||
return {"userid": userid, "enable": 1, "expire": 0, **fields}
|
||||
|
||||
|
||||
def _totp(userid: str, **fields: Any) -> dict[str, Any]:
|
||||
entry = {"type": "totp", "id": "totp-1", "description": "phone", "created": PAST, **fields}
|
||||
return {"userid": userid, "entries": [entry]}
|
||||
|
||||
|
||||
def _source(name: str, kind: str, factors: str) -> dict[str, str]:
|
||||
return {"name": name, "kind": kind, "factors": factors}
|
||||
|
||||
|
||||
PVE_REALMS = [
|
||||
{"realm": "pve", "type": "pve", "comment": "Proxmox VE authentication server"},
|
||||
{"realm": "pam", "type": "pam", "comment": "Linux PAM standard authentication"},
|
||||
]
|
||||
|
||||
|
||||
def _sources(realms=PVE_REALMS, users=(), tfa=()) -> list:
|
||||
return web_login_sources(realms=list(realms), users=list(users), tfa=list(tfa), now=NOW)
|
||||
|
||||
|
||||
class TestRealms:
|
||||
def test_a_user_without_a_second_factor_makes_the_realm_a_password(self):
|
||||
assert _sources(users=[_user("root@pam")]) == [_source("pam", "pam", "password")]
|
||||
|
||||
def test_every_user_with_a_second_factor_makes_it_two_factors(self):
|
||||
users = [_user("root@pam"), _user("ops@pam")]
|
||||
tfa = [_totp("root@pam"), _totp("ops@pam")]
|
||||
|
||||
assert _sources(users=users, tfa=tfa) == [_source("pam", "pam", "password_otp")]
|
||||
|
||||
def test_one_user_without_is_enough_for_a_password(self):
|
||||
users = [_user("root@pam"), _user("ops@pam")]
|
||||
|
||||
assert _sources(users=users, tfa=[_totp("ops@pam")]) == [_source("pam", "pam", "password")]
|
||||
|
||||
def test_each_realm_with_a_user_is_a_source_in_name_order(self):
|
||||
users = [_user("root@pam"), _user("alice@pve")]
|
||||
|
||||
assert _sources(users=users, tfa=[_totp("alice@pve")]) == [
|
||||
_source("pam", "pam", "password"),
|
||||
_source("pve", "pve", "password_otp"),
|
||||
]
|
||||
|
||||
def test_a_realm_nobody_can_log_in_to_is_no_source(self):
|
||||
users = [_user("root@pam"), _user("old@pve", enable=0), _user("gone@pve", expire=PAST)]
|
||||
|
||||
assert _sources(users=users, tfa=[_totp("root@pam")]) == [
|
||||
_source("pam", "pam", "password_otp")
|
||||
]
|
||||
|
||||
def test_an_account_that_expires_later_still_logs_in(self):
|
||||
users = [_user("root@pam", expire=FUTURE)]
|
||||
|
||||
assert _sources(users=users) == [_source("pam", "pam", "password")]
|
||||
|
||||
def test_a_realm_that_requires_a_second_factor_counts_as_two(self):
|
||||
realms = [*PVE_REALMS, {"realm": "corp", "type": "ad", "tfa": "oath"}]
|
||||
users = [_user("root@pam"), _user("bob@corp")]
|
||||
|
||||
assert _sources(realms, users, [_totp("root@pam")]) == [
|
||||
_source("corp", "ad", "password_otp"),
|
||||
_source("pam", "pam", "password_otp"),
|
||||
]
|
||||
|
||||
def test_a_yubico_realm_requires_its_otp_too(self):
|
||||
realms = [{"realm": "pve", "type": "pve", "tfa": "yubico"}]
|
||||
|
||||
assert _sources(realms, [_user("bob@pve")]) == [_source("pve", "pve", "password_otp")]
|
||||
|
||||
def test_an_openid_realm_is_its_providers_call(self):
|
||||
realms = [*PVE_REALMS, {"realm": "sso", "type": "openid"}]
|
||||
users = [_user("root@pam")]
|
||||
|
||||
assert _sources(realms, users, [_totp("root@pam")]) == [
|
||||
_source("pam", "pam", "password_otp"),
|
||||
_source("sso", "openid", "external"),
|
||||
]
|
||||
|
||||
def test_an_unknown_realm_type_is_unknown(self):
|
||||
realms = [{"realm": "pam", "type": "pam"}, {"realm": "x", "type": "plugin"}]
|
||||
|
||||
assert _sources(realms, [_user("root@pam")], [_totp("root@pam")]) == [
|
||||
_source("pam", "pam", "password_otp"),
|
||||
_source("x", "plugin", "unknown"),
|
||||
]
|
||||
|
||||
def test_a_realm_missing_from_the_list_takes_the_users_realm_type(self):
|
||||
"""PVE names it on each user; PBS's domains.cfg may leave out pam and pbs."""
|
||||
users = [_user("root@pam"), _user("ci@pbs"), _user("x@gone", **{"realm-type": "ldap"})]
|
||||
|
||||
assert _sources([], users) == [
|
||||
_source("gone", "ldap", "password"),
|
||||
_source("pam", "pam", "password"),
|
||||
_source("pbs", "pbs", "password"),
|
||||
]
|
||||
|
||||
def test_a_realm_of_no_known_type_is_unknown(self):
|
||||
assert _sources([], [_user("x@where")]) == [_source("where", "", "unknown")]
|
||||
|
||||
|
||||
class TestSecondFactors:
|
||||
def test_a_disabled_entry_is_no_second_factor(self):
|
||||
tfa = [_totp("root@pam", enable=False)]
|
||||
|
||||
assert _sources(users=[_user("root@pam")], tfa=tfa) == [_source("pam", "pam", "password")]
|
||||
|
||||
@pytest.mark.parametrize("kind", ["totp", "webauthn", "u2f", "yubico", "recovery"])
|
||||
def test_every_kind_of_entry_is_a_second_factor(self, kind):
|
||||
tfa = [{"userid": "root@pam", "entries": [{"type": kind, "id": kind}]}]
|
||||
|
||||
assert _sources(users=[_user("root@pam")], tfa=tfa)[0]["factors"] == "password_otp"
|
||||
|
||||
def test_a_user_with_an_empty_entry_list_has_none(self):
|
||||
tfa = [{"userid": "root@pam", "entries": []}]
|
||||
|
||||
assert _sources(users=[_user("root@pam")], tfa=tfa)[0]["factors"] == "password"
|
||||
|
||||
def test_pbs_booleans_and_missing_fields(self):
|
||||
users = [{"userid": "root@pam"}, {"userid": "old@pbs", "enable": False}]
|
||||
|
||||
assert _sources([], users) == [_source("pam", "pam", "password")]
|
||||
|
||||
|
||||
class FakeApi(FakePbsApi):
|
||||
"""The same fake, without the recorded PBS answers."""
|
||||
|
||||
def __init__(self, **responses: Any) -> None:
|
||||
super().__init__()
|
||||
self.responses = responses
|
||||
|
||||
|
||||
def _pve(**responses: Any) -> ProxmoxDriver:
|
||||
drv = ProxmoxDriver("pve1", "netork@pve", "secret")
|
||||
drv._api = FakeApi(**responses)
|
||||
return drv
|
||||
|
||||
|
||||
def _pbs(**responses: Any) -> ProxmoxBackupDriver:
|
||||
drv = ProxmoxBackupDriver("pbs1", "netork@pbs", "secret")
|
||||
drv._api = FakePbsApi(**responses)
|
||||
return drv
|
||||
|
||||
|
||||
PVE_ANSWERS: dict[str, Any] = {
|
||||
"access/permissions?path=/access/groups": {"/access/groups": {"Sys.Audit": 1}},
|
||||
"access/domains": PVE_REALMS,
|
||||
"access/users": [_user("root@pam", **{"realm-type": "pam"})],
|
||||
"access/tfa": [_totp("root@pam")],
|
||||
}
|
||||
|
||||
PBS_ANSWERS: dict[str, Any] = {
|
||||
"access/permissions?path=/access/users": {"/access/users": {"Sys.Audit": True}},
|
||||
"access/domains": [
|
||||
{"realm": "pam", "type": "pam", "comment": "Linux PAM standard authentication"},
|
||||
{"realm": "pbs", "type": "pbs", "comment": "Proxmox Backup authentication server"},
|
||||
],
|
||||
"access/users": [{"userid": "root@pam", "enable": True, "expire": 0}],
|
||||
"access/tfa": [],
|
||||
}
|
||||
|
||||
|
||||
class TestProxmoxVe:
|
||||
def test_reads_users_their_second_factors_and_the_realms(self):
|
||||
drv = _pve(**PVE_ANSWERS)
|
||||
|
||||
reading: WebLoginAuthDict = drv.get_web_login_auth()
|
||||
|
||||
assert reading == {"sources": [_source("pam", "pam", "password_otp")]}
|
||||
assert [path for _, path, _ in drv._api.calls] == [
|
||||
"access/permissions",
|
||||
"access/domains",
|
||||
"access/users",
|
||||
"access/tfa",
|
||||
]
|
||||
|
||||
@pytest.mark.parametrize("privilege", ["Sys.Audit", "User.Modify"])
|
||||
def test_either_privilege_on_access_groups_shows_every_user(self, privilege):
|
||||
drv = _pve(
|
||||
**{
|
||||
**PVE_ANSWERS,
|
||||
"access/permissions?path=/access/groups": {"/access/groups": {privilege: 0}},
|
||||
}
|
||||
)
|
||||
|
||||
assert drv.get_web_login_auth()["sources"]
|
||||
|
||||
def test_without_the_privilege_the_lists_would_be_filtered_so_it_is_not_read(self):
|
||||
"""PVE answers ``/access/users`` and ``/access/tfa`` with the caller alone,
|
||||
not with a 403: a token that sees only itself must not pass for a datacenter."""
|
||||
drv = _pve(**{**PVE_ANSWERS, "access/permissions?path=/access/groups": {}})
|
||||
|
||||
with pytest.raises(PermissionError, match=r"Sys\.Audit.*/access/groups"):
|
||||
drv.get_web_login_auth()
|
||||
assert [path for _, path, _ in drv._api.calls] == ["access/permissions"]
|
||||
|
||||
def test_a_refused_read_is_a_permission_error(self):
|
||||
drv = _pve(**{**PVE_ANSWERS, "access/tfa": forbidden()})
|
||||
|
||||
with pytest.raises(PermissionError):
|
||||
drv.get_web_login_auth()
|
||||
|
||||
|
||||
class TestProxmoxBackupServer:
|
||||
def test_reads_users_their_second_factors_and_the_realms(self):
|
||||
drv = _pbs(**PBS_ANSWERS)
|
||||
|
||||
assert drv.get_web_login_auth() == {"sources": [_source("pam", "pam", "password")]}
|
||||
|
||||
def test_a_token_without_sys_audit_on_access_users_is_not_read(self):
|
||||
drv = _pbs(
|
||||
**{
|
||||
**PBS_ANSWERS,
|
||||
"access/permissions?path=/access/users": {"/access/users": {"User.Modify": True}},
|
||||
}
|
||||
)
|
||||
|
||||
with pytest.raises(PermissionError, match=r"Sys\.Audit.*/access/users"):
|
||||
drv.get_web_login_auth()
|
||||
|
||||
def test_another_failure_propagates(self):
|
||||
from proxmoxer.core import ResourceException
|
||||
|
||||
drv = _pbs(**{**PBS_ANSWERS, "access/users": ResourceException(500, "Error", "boom")})
|
||||
|
||||
with pytest.raises(ResourceException):
|
||||
drv.get_web_login_auth()
|
||||
Reference in new issue
Block a user