diff --git a/CHANGELOG.md b/CHANGELOG.md index c456b00..ae2257a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [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. + +### Changed +- Needs napalm-device-types 4.50.0 or later (`WebLoginAuthDict`). + ## [0.18.0] - 2026-11-28 ### Added diff --git a/README.md b/README.md index 8887b59..0c34bf2 100644 --- a/README.md +++ b/README.md @@ -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 @@ -136,6 +136,7 @@ device = driver( | `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`), `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 +198,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 @@ -257,6 +259,7 @@ tests/ ├── 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_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 diff --git a/napalm_proxmox/backup_driver.py b/napalm_proxmox/backup_driver.py index e86a7e9..90cc0f9 100644 --- a/napalm_proxmox/backup_driver.py +++ b/napalm_proxmox/backup_driver.py @@ -47,6 +47,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 +64,7 @@ class ProxmoxBackupDriver( ProxmoxHostMixin, ProxmoxTimeSyncMixin, PbsCertificatesMixin, + ProxmoxWebLoginMixin, BackupServerDriver, StorageDriver, KernelFactsMixin, @@ -94,6 +96,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), ] diff --git a/napalm_proxmox/driver.py b/napalm_proxmox/driver.py index 9b22be2..90d1dc2 100644 --- a/napalm_proxmox/driver.py +++ b/napalm_proxmox/driver.py @@ -72,6 +72,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__) @@ -116,6 +117,7 @@ class ProxmoxDriver( ProxmoxTimeSyncMixin, ProxmoxCertificatesMixin, ProxmoxCredentialExpiryMixin, + ProxmoxWebLoginMixin, ProxmoxUpdateHistoryMixin, HostStatusMixin, LicenseMixin, @@ -141,6 +143,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 = [ diff --git a/napalm_proxmox/web_login.py b/napalm_proxmox/web_login.py new file mode 100644 index 0000000..b86a0e8 --- /dev/null +++ b/napalm_proxmox/web_login.py @@ -0,0 +1,168 @@ +"""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. + +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 diff --git a/pyproject.toml b/pyproject.toml index caa4cf9..50ec361 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "napalm-proxmox" -version = "0.18.0" +version = "0.20.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.50.0", # WebLoginAuthDict; HardeningMixin "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", diff --git a/tests/pbs_fake.py b/tests/pbs_fake.py index d7de744..53df4e2 100644 --- a/tests/pbs_fake.py +++ b/tests/pbs_fake.py @@ -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) diff --git a/tests/test_web_login.py b/tests/test_web_login.py new file mode 100644 index 0000000..b905391 --- /dev/null +++ b/tests/test_web_login.py @@ -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()