Compare commits

...
Author SHA1 Message Date
Christian Manivong 68a6087571 chore(release): 0.17.0
CI / driver (pull_request) Blocked by required conditions
driver / standard (pull_request) Blocked by required conditions
driver / lint (pull_request) Blocked by required conditions
driver / types (pull_request) Blocked by required conditions
driver / test (3.12) (pull_request) Blocked by required conditions
driver / test (3.13) (pull_request) Blocked by required conditions
driver / lowest (pull_request) Blocked by required conditions
driver / security (pull_request) Blocked by required conditions
driver / build (pull_request) Blocked by required conditions
2026-11-26 23:10:08 +01:00
Christian Manivong 87aca53ec2 fix(credentials): a token's expiry from the user it belongs to (NetOrk/netork#2728)
GET /access/users/{userid}/token/{tokenid} checks userid-param self, which a
token's request (user@realm!tokenid) never matches, so a token could not read
itself without User.Modify. GET /access/users/{userid} needs Sys.Audit on
/access/groups (PVEAuditor) and returns the user's expire and every token's.
One call now serves both logins; a 403 names the privilege.
2026-11-26 23:08:47 +01:00
Christian Manivong 707b24748b feat(updates): the update history before PVE 9.3 from apt's log over SSH (NetOrk/netork#2728)
Below 9.3 get_update_history reads apt's history log over the node's SSH session
with napalm-device-types' AptHistoryMixin, which names a transaction as
GET /nodes/{node}/apt/history does, so the ids stay when the node moves to 9.3.
A node without an SSH login still raises NotImplementedError. Requires
napalm-device-types 4.47.0.
2026-11-26 23:07:22 +01:00
7 changed files with 244 additions and 88 deletions

No files matched your search

+23
View File
@@ -7,6 +7,29 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [0.17.0] - 2026-11-26
### Added
- `get_update_history(since)` before PVE 9.3: apt's history log over the node's SSH
session, through napalm-device-types' `AptHistoryMixin` (NetOrk/netork#2728). A
transaction gets the id 9.3's `GET /nodes/{node}/apt/history` gives it (start time and
the index among those that started in the same second of the same log file), so a node
keeps its ids when it moves to 9.3; 9.3 and later still read the API. A node without an
SSH login raises `NotImplementedError`, a failed read `RuntimeError`.
### Changed
- Needs napalm-device-types 4.47.0 or later (`AptHistoryMixin`).
### Fixed
- `get_credential_expiry()` reads an API token's expiry from `GET /access/users/{userid}`
(`tokens[tokenid].expire`), in the same one call as the account's (NetOrk/netork#2728).
`GET /access/users/{userid}/token/{tokenid}` refused practically every token: a token's
request runs as `user@realm!tokenid`, which that endpoint's `userid-param self` check
never matches, and its alternative is `User.Modify`. `read_user` needs `Sys.Audit` on
`/access/groups` or a group of the user, which PVEAuditor on `/` gives; a 403 raises a
`PermissionError` that names it. A token without an expiry of its own expires with its
user, and one with its own stops working with its user too: the earlier counts.
## [0.16.0] - 2026-11-26
### Added
+4
View File
@@ -251,6 +251,10 @@ class ProxmoxBase:
f"Cannot run a command on {self.hostname} over SSH: {exc}"
) from exc
def _has_ssh_login(self) -> bool:
"""Whether the driver has something to log in to the node's SSH with."""
return bool(self._ssh_password or self.password or self._ssh_key)
def _node_ssh(self) -> Any: # paramiko.SSHClient; paramiko is imported lazily
"""The SSH session to the node on port 22, opened once.
+42 -29
View File
@@ -1,23 +1,28 @@
"""When the credential the Proxmox VE driver logs in with expires (NetOrk/netork#2728).
``CredentialExpiryMixin`` of napalm-device-types. The driver logs in either with
an API token (``user@realm!tokenid``) or with a user's password:
an API token (``user@realm!tokenid``) or with a user's password; both are read
with one ``GET /access/users/{userid}`` (``read_user``), which returns the
account's ``expire`` and ``tokens: {tokenid: {expire, privsep, comment}}``:
- a token: ``GET /access/users/{userid}/token/{tokenid}``, its ``expire``. A token
without one of its own expires with its user (the schema's default, "same as
user"), read as for a password;
- a password: ``GET /access/users/{userid}``, the account's ``expire``.
- a password: the account's ``expire``;
- a token: ``tokens[tokenid].expire``. A token without one of its own (``0`` or
none, "same as user") expires with its user; one with its own still stops
working when its user expires first, so the earlier of the two counts.
``0`` or no value is never. PVE 9.3's datacenter ``token-policy`` can require an
expiry on every token; the fields themselves are older, so every release is read.
PVE lets a user read itself and its tokens; a privilege-separated token may be
refused its user (``User.Modify`` or ``Sys.Audit`` on the user's group), and a
403 is a ``PermissionError``, as the contract says.
``read_user`` needs ``Sys.Audit`` (or ``User.Modify``) on ``/access/groups`` or on
a group of the user; PVEAuditor on ``/`` gives it. Not even a user may read
itself without it, and a 403 is a ``PermissionError`` that names the privilege,
as the contract says. ``GET /access/users/{userid}/token/{tokenid}`` is no way
round: a token's request runs as ``user@realm!tokenid``, which that endpoint's
``userid-param self`` check never matches, and its alternative is ``User.Modify``.
"""
from __future__ import annotations
from collections.abc import Callable
from typing import TYPE_CHECKING, Any
from napalm_device_types import CredentialExpiryDict, CredentialExpiryMixin
@@ -25,24 +30,19 @@ from proxmoxer.core import ResourceException
_JsonDict = dict[str, Any]
#: What ``GET /access/users/{userid}`` asks of the login, for a 403's message.
_PRIVILEGE = "Sys.Audit on /access/groups (PVEAuditor on / gives it)"
def _expires(value: Any) -> int | None:
"""PVE's ``expire``: unix seconds, ``0`` or none for never."""
return int(value or 0) or None
def _read(get: Callable[[], Any], what: str) -> _JsonDict:
"""``get()``'s answer; a refusal as ``PermissionError``, another failure as
``RuntimeError``."""
try:
answer = get()
except ResourceException as exc:
if exc.status_code == 403:
raise PermissionError(f"Proxmox VE will not tell {what}'s expiry: {exc}") from exc
raise RuntimeError(f"Cannot read the expiry of {what}: {exc}") from exc
except Exception as exc:
raise RuntimeError(f"Cannot read the expiry of {what}: {exc}") from exc
return dict(answer or {})
def _earliest(*values: int | None) -> int | None:
"""The earliest of *values* that is a time; None where none is."""
times = [v for v in values if v is not None]
return min(times) if times else None
class ProxmoxCredentialExpiryMixin(CredentialExpiryMixin):
@@ -58,16 +58,29 @@ class ProxmoxCredentialExpiryMixin(CredentialExpiryMixin):
"""The API token or the account this connection logged in with, and its expiry."""
login = self._api_kwargs()
userid = str(login["user"])
user = self._read_user(userid)
account = _expires(user.get("expire"))
if "token_value" not in login:
return {"kind": "account", "name": userid, "expires": self._user_expiry(userid)}
name = f"{userid}!{login['token_name']}"
token = _read(lambda: self._api.access.users(userid).token(login["token_name"]).get(), name)
expire = token.get("expire")
return {"kind": "account", "name": userid, "expires": account}
token_id = str(login["token_name"])
token = dict((user.get("tokens") or {}).get(token_id) or {})
return {
"kind": "api-token",
"name": name,
"expires": self._user_expiry(userid) if expire is None else _expires(expire),
"name": f"{userid}!{token_id}",
"expires": _earliest(_expires(token.get("expire")), account),
}
def _user_expiry(self, userid: str) -> int | None:
return _expires(_read(lambda: self._api.access.users(userid).get(), userid).get("expire"))
def _read_user(self, userid: str) -> _JsonDict:
"""``GET /access/users/{userid}``; a refusal as ``PermissionError``, another
failure as ``RuntimeError``."""
try:
answer = self._api.access.users(userid).get()
except ResourceException as exc:
if exc.status_code == 403:
raise PermissionError(
f"Proxmox VE will not tell {userid}'s expiry without {_PRIVILEGE}: {exc}"
) from exc
raise RuntimeError(f"Cannot read the expiry of {userid}: {exc}") from exc
except Exception as exc:
raise RuntimeError(f"Cannot read the expiry of {userid}: {exc}") from exc
return dict(answer or {})
+29 -10
View File
@@ -4,15 +4,23 @@ PVE 9.3 reads apt's history log for ``GET /nodes/{node}/apt/history``, newest
first, also the transactions netOrk did not start (an operator's ``apt``,
unattended-upgrades). A transaction is named by its ``start-time`` and its
``start-index`` among those that started in the same second of the same log
file. An older node has no such endpoint: the driver raises
``NotImplementedError`` and parses no log over SSH.
file. An older node has no such endpoint: the driver reads the same log over
its SSH session with napalm-device-types' ``AptHistoryMixin``, which names a
transaction the same way, so the ids stay when the node moves to 9.3. A node
without an SSH login raises ``NotImplementedError`` there.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Any, cast
from napalm_device_types import UpdateHistoryAction, UpdateHistoryDict, UpdateHistoryPackageDict
from napalm.base.exceptions import ConnectionException
from napalm_device_types import (
AptHistoryMixin,
UpdateHistoryAction,
UpdateHistoryDict,
UpdateHistoryPackageDict,
)
from napalm_proxmox.pve_values import PVE_9_3
@@ -46,8 +54,9 @@ def _transaction(row: _JsonDict) -> UpdateHistoryDict:
}
class ProxmoxUpdateHistoryMixin:
"""Relies on the driver's ``_node_api`` and ``_version_at_least``."""
class ProxmoxUpdateHistoryMixin(AptHistoryMixin):
"""Relies on the driver's ``_node_api``, ``_version_at_least``, ``_has_ssh_login``
and ``run_command``."""
_node_name: str
@@ -55,21 +64,31 @@ class ProxmoxUpdateHistoryMixin:
def _node_api(self) -> Any: ...
def _version_at_least(self, major: int, minor: int) -> bool: ...
def _has_ssh_login(self) -> bool: ...
def get_update_history(self, since: int | None = None) -> list[UpdateHistoryDict]:
"""The node's APT transactions, newest first, from ``since`` (unix seconds) on.
:raises NotImplementedError: before PVE 9.3, which has no history endpoint.
:raises NotImplementedError: before PVE 9.3 on a node without an SSH login.
:raises RuntimeError: the history could not be read; never an empty list.
"""
if not self._version_at_least(*PVE_9_3):
raise NotImplementedError(
f"Proxmox VE on {self._node_name} keeps no APT history its API reports "
"(from 9.3 on)"
)
return self._history_over_ssh(since)
params = {} if since is None else {"since": since}
try:
rows = self._node_api().apt.history.get(**params) or []
except Exception as exc:
raise RuntimeError(f"Cannot read the APT history of {self._node_name}: {exc}") from exc
return [_transaction(row) for row in rows]
def _history_over_ssh(self, since: int | None) -> list[UpdateHistoryDict]:
"""Before 9.3: apt's log over the SSH session, root's login."""
if not self._has_ssh_login():
raise NotImplementedError(
f"Proxmox VE on {self._node_name} reports its APT history from 9.3 on; "
"before that it is read over SSH, and the node has no SSH login"
)
try:
return super().get_update_history(since)
except (ConnectionException, ValueError) as exc:
raise RuntimeError(f"Cannot read the APT history of {self._node_name}: {exc}") from exc
+2 -2
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "napalm-proxmox"
version = "0.16.0"
version = "0.17.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.46.0", # ServicesRestartMixin with LXC left out; CredentialExpiryMixin
"napalm_device_types>=4.47.0", # AptHistoryMixin; ServicesRestartMixin with LXC left out
"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",
+66 -41
View File
@@ -1,11 +1,14 @@
"""When the credential the driver logs in with stops working (NetOrk/netork#2728).
PVE 9.3's datacenter ``token-policy`` can require an expiry on every API token;
the platform keeps one on every token and account anyway. A token is read with
``GET /access/users/{userid}/token/{tokenid}``; a token without an ``expire``
of its own expires with its user (``default: same as user``), read with
``GET /access/users/{userid}``, which is also where a password's account says
when it expires. ``0`` is never.
the platform keeps one on every token and account anyway. Both are read with one
``GET /access/users/{userid}`` (``read_user``): the account's ``expire`` and
``tokens: {tokenid: {expire, privsep, comment}}``. It needs ``Sys.Audit`` (or
``User.Modify``) on ``/access/groups`` or a group of the user, which PVEAuditor
on ``/`` gives. ``GET /access/users/{userid}/token/{tokenid}`` is not used: a
token's request runs as ``user@realm!tokenid``, which its ``userid-param self``
check never matches. ``0`` is never; a token without an expiry of its own
expires with its user, and one with its own stops working with its user too.
"""
from __future__ import annotations
@@ -33,83 +36,105 @@ def _token_driver(token_name: str = "netork@pve!poll") -> tuple[ProxmoxDriver, M
return _driver(token_name=token_name, token_value="s3cret", realm="pve")
def _user(api: MagicMock, expire: int | None = None, **tokens: dict[str, Any]) -> MagicMock:
"""``GET /access/users/{userid}`` answers with *expire* and *tokens*."""
answer: dict[str, Any] = {"userid": "netork@pve", "enable": 1}
if expire is not None:
answer["expire"] = expire
if tokens:
answer["tokens"] = tokens
get = api.access.users.return_value.get
get.return_value = answer
return get
def _forbidden() -> ResourceException:
return ResourceException(403, "Forbidden", "Permission check failed (/access, User.Modify)")
return ResourceException(
403, "Forbidden", "Permission check failed (/access/groups, User.Modify|Sys.Audit)"
)
class TestApiToken:
def test_the_tokens_own_expiry(self):
drv, api = _token_driver()
api.access.users.return_value.token.return_value.get.return_value = {
"expire": 1767225600,
"privsep": 1,
}
get = _user(api, 0, poll={"expire": 1767225600, "privsep": 1})
assert drv.get_credential_expiry() == {
"kind": "api-token",
"name": "netork@pve!poll",
"expires": 1767225600,
}
api.access.users.assert_called_with("netork@pve")
api.access.users.return_value.token.assert_called_once_with("poll")
api.access.users.assert_called_once_with("netork@pve")
get.assert_called_once_with()
def test_zero_never_expires(self):
def test_the_token_endpoint_is_not_asked(self):
drv, api = _token_driver()
api.access.users.return_value.token.return_value.get.return_value = {"expire": 0}
assert drv.get_credential_expiry()["expires"] is None
api.access.users.return_value.get.assert_not_called()
_user(api, 0, poll={"expire": 1767225600})
drv.get_credential_expiry()
api.access.users.return_value.token.assert_not_called()
def test_a_token_without_expiry_expires_with_its_user(self):
drv, api = _token_driver()
api.access.users.return_value.token.return_value.get.return_value = {"privsep": 1}
api.access.users.return_value.get.return_value = {
"userid": "netork@pve",
"expire": 1798761600,
}
_user(api, 1798761600, poll={"privsep": 1})
assert drv.get_credential_expiry()["expires"] == 1798761600
def test_a_token_whose_expiry_is_zero_expires_with_its_user(self):
drv, api = _token_driver()
_user(api, 1798761600, poll={"expire": 0})
assert drv.get_credential_expiry()["expires"] == 1798761600
def test_a_token_stops_working_with_its_user(self):
drv, api = _token_driver()
_user(api, 1767225600, poll={"expire": 1798761600})
assert drv.get_credential_expiry()["expires"] == 1767225600
def test_zero_on_both_never_expires(self):
drv, api = _token_driver()
_user(api, 0, poll={"expire": 0})
assert drv.get_credential_expiry()["expires"] is None
@pytest.mark.parametrize("tokens", [{}, {"other": {"expire": 1767225600}}])
def test_a_token_the_user_does_not_list_expires_with_its_user(self, tokens):
drv, api = _token_driver()
_user(api, 1798761600, **tokens)
assert drv.get_credential_expiry()["expires"] == 1798761600
def test_a_token_name_without_user_is_the_login_users(self):
drv, api = _token_driver(token_name="poll")
api.access.users.return_value.token.return_value.get.return_value = {"expire": 0}
assert drv.get_credential_expiry()["name"] == "netork@pve!poll"
api.access.users.assert_called_with("netork@pve")
_user(api, 0, poll={"expire": 1767225600})
assert drv.get_credential_expiry() == {
"kind": "api-token",
"name": "netork@pve!poll",
"expires": 1767225600,
}
api.access.users.assert_called_once_with("netork@pve")
def test_a_refused_read_is_a_permission_error(self):
def test_a_refused_read_names_the_privilege(self):
drv, api = _token_driver()
api.access.users.return_value.token.return_value.get.side_effect = _forbidden()
with pytest.raises(PermissionError, match="User.Modify"):
drv.get_credential_expiry()
def test_a_refused_read_of_the_user_is_a_permission_error(self):
drv, api = _token_driver()
api.access.users.return_value.token.return_value.get.return_value = {}
api.access.users.return_value.get.side_effect = _forbidden()
with pytest.raises(PermissionError):
with pytest.raises(PermissionError, match="Sys.Audit on /access/groups"):
drv.get_credential_expiry()
class TestAccount:
def test_a_password_login_reads_its_account(self):
drv, api = _driver()
api.access.users.return_value.get.return_value = {
"userid": "netork@pam",
"expire": 1767225600,
}
_user(api, 1767225600)
assert drv.get_credential_expiry() == {
"kind": "account",
"name": "netork@pam",
"expires": 1767225600,
}
api.access.users.assert_called_with("netork@pam")
api.access.users.assert_called_once_with("netork@pam")
def test_an_account_without_expiry_never_expires(self):
drv, api = _driver()
api.access.users.return_value.get.return_value = {"userid": "netork@pam", "enable": 1}
_user(api)
assert drv.get_credential_expiry()["expires"] is None
def test_a_refused_read_is_a_permission_error(self):
def test_a_refused_read_names_the_privilege(self):
drv, api = _driver()
api.access.users.return_value.get.side_effect = _forbidden()
with pytest.raises(PermissionError):
with pytest.raises(PermissionError, match="Sys.Audit on /access/groups"):
drv.get_credential_expiry()
@pytest.mark.parametrize(
+78 -6
View File
@@ -4,14 +4,21 @@ PVE 9.3 reads apt's history log for ``GET /nodes/{node}/apt/history``, newest
first. The payload below follows its schema: a transaction is identified by
``start-time`` with ``start-index`` (default 0) among those that started in the
same second; ``end-time`` is missing while it runs or after it was interrupted.
An older node has no such endpoint, and the driver parses no log over SSH.
An older node has no such endpoint: the driver reads the same log over its SSH
session with napalm-device-types' ``AptHistoryMixin``, which names a transaction
the same way, and a node without an SSH login has no history.
"""
from __future__ import annotations
from unittest.mock import MagicMock
from unittest.mock import MagicMock, patch
import pytest
from napalm.base.exceptions import ConnectionException
from napalm_device_types import APT_HISTORY_COMMAND, CommandResult
from napalm_proxmox.driver import ProxmoxDriver
from tests.conftest import _build_mock_api
HISTORY = [
{
@@ -117,8 +124,73 @@ class TestUpdateHistory:
with pytest.raises(RuntimeError, match="timed out"):
driver.get_update_history()
def test_an_older_node_has_no_history(self, driver, history):
driver._api.version.get.return_value = {"version": "9.2.4", "release": "9.2"}
with pytest.raises(NotImplementedError):
driver.get_update_history()
#: The node's log as AptHistoryMixin's command prints it: the transaction the API
#: names 1764158400-1 is the second to start in that second (12:00:00 UTC) of the file.
LOG = """\
### apt-history zone /usr/share/zoneinfo/Etc/UTC
### apt-history offset +0000
### apt-history file /var/log/apt/history.log
Start-Date: 2025-11-26 12:00:00
Commandline: apt-get update-kernel
Install: proxmox-kernel-6.17.2-1-pve-signed:amd64 (6.17.2-1, automatic)
End-Date: 2025-11-26 12:00:00
Start-Date: 2025-11-26 12:00:00
Commandline: apt-get -y dist-upgrade
Requested-By: admin (1000)
Upgrade: openssh-server:amd64 (1:10.0p1-7, 1:10.0p1-7+deb13u1)
Purge: ifupdown:amd64 (0.8.44)
End-Date: 2025-11-26 12:01:00
### apt-history status 0
### apt-history end
"""
@pytest.fixture
def older(driver, history) -> MagicMock:
"""A 9.2 node whose SSH session prints :data:`LOG`."""
driver._api.version.get.return_value = {"version": "9.2.4", "release": "9.2"}
run = MagicMock(return_value=CommandResult(LOG, "", 0))
driver.run_command = run
return run
class TestBeforeNineThree:
def test_the_log_is_read_over_ssh(self, driver, history, older):
newest, first = driver.get_update_history()
assert newest["id"] == "1764158400-1" # the API's id for the same transaction
assert newest["end"] == 1764158460
assert newest["requested_by"] == "admin"
assert [p["action"] for p in newest["packages"]] == ["upgrade", "purge"]
assert first["id"] == "1764158400-0"
older.assert_called_once()
assert older.call_args.args == (APT_HISTORY_COMMAND,)
history.assert_not_called()
def test_since_filters_the_log(self, driver, history, older):
assert driver.get_update_history(since=1764158401) == []
def test_a_failed_ssh_read_raises(self, driver, history, older):
older.side_effect = ConnectionException("Cannot run a command on pve1 over SSH: reset")
with pytest.raises(RuntimeError, match="reset"):
driver.get_update_history()
def test_a_log_cut_short_raises(self, driver, history, older):
older.return_value = CommandResult(LOG.replace("### apt-history end\n", ""), "", 0)
with pytest.raises(RuntimeError, match="cut short"):
driver.get_update_history()
def test_a_node_without_ssh_login_has_no_history(self):
drv = ProxmoxDriver(
"pve1", "netork", "", optional_args={"token_name": "poll", "token_value": "s3cret"}
)
api = _build_mock_api(version={"version": "9.2.4", "release": "9.2"})
with patch("napalm_proxmox.driver.ProxmoxAPI", return_value=api):
drv.open()
drv.run_command = MagicMock()
with pytest.raises(NotImplementedError, match="SSH"):
drv.get_update_history()
drv.run_command.assert_not_called()