feat(login): get_web_login_auth on PVE and PBS, a source per realm, 0.20.0 (NetOrk/netork#662)
driver / standard (pull_request) Failing after 17s
driver / lint (pull_request) Successful in 18s
driver / types (pull_request) Successful in 56s
driver / lowest (pull_request) Successful in 37s
driver / test (3.12) (pull_request) Successful in 1m6s
driver / test (3.13) (pull_request) Successful in 1m3s
driver / security (pull_request) Successful in 53s
driver / build (pull_request) Successful in 49s
CI / driver (pull_request) Failing after 2m8s
driver / publish (pull_request) Skipped

A Proxmox login names its realm, so each realm with someone who can log in
is a source of napalm-device-types' WebLoginAuthDict. It asks for a password
and a one-time code when the PVE realm's own tfa is set, or when every
enabled, unexpired user of it has an enabled second factor (/access/tfa);
a password alone when one user has none; OpenID is external.

Both servers list only the caller in /access/users and /access/tfa when the
login may not see the others, so the driver checks /access/permissions
first: Sys.Audit or User.Modify on /access/groups on PVE, Sys.Audit on
/access/users on PBS. Without it the read raises PermissionError rather
than judge the server by one account.

Needs napalm-device-types 4.50.0.
This commit is contained in:
Christian Manivong committed 2026-11-29 00:19:52 +01:00
1 parent 0598a183df
commit f554e2cc79
8 files changed
+461 -7

No files matched your search

+4
View File
@@ -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),
]
+4
View File
@@ -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 = [
+168
View File
@@ -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