Compare commits

..
Author SHA1 Message Date
Christian Manivong 7e300c740e feat(hardening): install_cpu_microcode on PVE and PBS, 0.19.0 (NetOrk/netork#2838)
driver / lint (pull_request) Successful in 13s
driver / standard (pull_request) Successful in 18s
driver / test (3.12) (pull_request) Failing after 15s
driver / types (pull_request) Failing after 23s
driver / test (3.13) (pull_request) Failing after 13s
driver / lowest (pull_request) Failing after 16s
driver / build (pull_request) Successful in 27s
driver / security (pull_request) Failing after 34s
CI / driver (pull_request) Failing after 56s
driver / publish (pull_request) Skipped
Both drivers mix in napalm-device-types' CpuMicrocodeMixin (4.53.0). A Proxmox
install enables no non-free-firmware, where intel-microcode and
amd64-microcode live: it is added to Debian's own sources, never Proxmox's.
_reload_package_index runs apt-get update over the exec path and waits for
it, as the API's apt/update only starts a task the install would race.
2026-11-29 00:07:29 +01:00
10 changed files with 97 additions and 464 deletions

No files matched your search

+9 -13
View File
@@ -7,21 +7,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [0.20.0] - 2026-11-29
## [0.19.0] - 2026-11-28
### 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.
### Changed
- Needs napalm-device-types 4.50.0 or later (`WebLoginAuthDict`).
- `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
+4 -6
View File
@@ -17,7 +17,7 @@ It supports all three networking domains of Proxmox VE:
- Python ≥ 3.12
- NAPALM ≥ 5.0.0
- napalm-device-types ≥ 4.50.0
- napalm-device-types ≥ 4.22.0
- proxmoxer ≥ 2.0.0
- netaddr ≥ 0.9.0
- requests ≥ 2.31.0
@@ -135,8 +135,8 @@ 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_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 |
| `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 |
**Not implemented** (raise `NotImplementedError`):
`get_bgp_config`, `get_bgp_neighbors`, `get_bgp_neighbors_detail`,
@@ -198,7 +198,6 @@ 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
@@ -258,8 +257,7 @@ 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_web_login.py # get_web_login_auth on both drivers
├── test_hardening.py # get_hardening and install_cpu_microcode 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
+2 -4
View File
@@ -17,6 +17,7 @@ from typing import Any
from napalm_device_types import (
AptProxyMixin,
BackupServerDriver,
CpuMicrocodeMixin,
EnsurePackageMixin,
FingerprintRule,
HardeningMixin,
@@ -47,7 +48,6 @@ 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__)
@@ -64,7 +64,6 @@ class ProxmoxBackupDriver(
ProxmoxHostMixin,
ProxmoxTimeSyncMixin,
PbsCertificatesMixin,
ProxmoxWebLoginMixin,
BackupServerDriver,
StorageDriver,
KernelFactsMixin,
@@ -79,6 +78,7 @@ class ProxmoxBackupDriver(
HostStatusMixin,
LicenseMixin,
ProxmoxZabbixAgentMixin,
CpuMicrocodeMixin,
EnsurePackageMixin,
AptProxyMixin,
OpenSshServerMixin,
@@ -96,8 +96,6 @@ 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),
]
+2 -4
View File
@@ -27,6 +27,7 @@ from typing import Any
from napalm.base.exceptions import ConnectionException
from napalm_device_types import (
AptProxyMixin,
CpuMicrocodeMixin,
EnsurePackageMixin,
FingerprintRule,
HardeningMixin,
@@ -72,7 +73,6 @@ 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__)
@@ -117,12 +117,12 @@ class ProxmoxDriver(
ProxmoxTimeSyncMixin,
ProxmoxCertificatesMixin,
ProxmoxCredentialExpiryMixin,
ProxmoxWebLoginMixin,
ProxmoxUpdateHistoryMixin,
HostStatusMixin,
LicenseMixin,
SnmpAgentMixin,
ProxmoxZabbixAgentMixin,
CpuMicrocodeMixin,
EnsurePackageMixin,
AptProxyMixin,
OpenSshServerMixin,
@@ -143,8 +143,6 @@ 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 = [
+8
View File
@@ -261,6 +261,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:
-172
View File
@@ -1,172 +0,0 @@
"""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 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: 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)
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
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "napalm-proxmox"
version = "0.20.0"
version = "0.19.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.50.0", # WebLoginAuthDict; HardeningMixin
"napalm_device_types>=4.53.0", # CpuMicrocodeMixin; virtualization in the hardening
"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
View File
@@ -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)
+66
View File
@@ -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 == []
-259
View File
@@ -1,259 +0,0 @@
"""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()