Files
napalm-proxmox/tests/test_web_login.py
T
Christian Manivong f554e2cc79
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
feat(login): get_web_login_auth on PVE and PBS, a source per realm, 0.20.0 (NetOrk/netork#662)
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.
2026-11-29 00:19:52 +01:00

260 lines
9.7 KiB
Python

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