"""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