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.
This commit is contained in:
1 parent
707b24748b
commit
87aca53ec2
3 files changed
+118
-70
No files matched your search
@@ -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 {})
|
||||
Reference in new issue
Block a user