feat(certificates): get_certificates on both drivers, with ACME (NetOrk/netork#2656)

The node's TLS certificates from GET /nodes/{node}/certificates/info (PBS:
/nodes/localhost/certificates/info) in netOrk's certificate contract,
{name, issuer, valid_from, valid_to, in_use_by} with Unix timestamps, so
netOrk's expiry warnings cover a node's web UI and API certificate.

One more call, the node's config, says whether ACME renews the certificate
the proxy serves (acme). The PEM is not returned; unreadable certificates
are [] and an unreadable config reads as no ACME.
This commit is contained in:
Christian Manivong committed 2026-11-26 17:59:35 +01:00
1 parent c2d9d7e75e
commit ff4ccc4818
6 files changed
+390

No files matched your search

+12
View File
@@ -7,6 +7,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
- `get_certificates()` on both drivers (NetOrk/netork#2656): the node's TLS certificates from
`GET /nodes/{node}/certificates/info` (PBS: `/nodes/localhost/certificates/info`) in
netOrk's certificate contract, `{name, issuer, valid_from, valid_to, in_use_by}` with Unix
timestamps, so netOrk's expiry warnings cover a node's web UI and API certificate.
`name` is the file name (`pve-root-ca.pem`, `pve-ssl.pem`, `pveproxy-ssl.pem`; `proxy.pem` on
PBS), `issuer` and `subject` the common names, `in_use_by` 1 for the certificate the proxy
serves. `acme` is true for the certificate ACME renews (`pveproxy-ssl.pem`, PBS `proxy.pem`)
when the node's config names a domain, read with one more call (`GET /nodes/{node}/config`);
an unreadable config reads as no ACME. The PEM is not returned. Unreadable certificates are
`[]`, as on OPNsense.
## [0.13.0] - 2026-11-26
### Added
+4
View File
@@ -131,6 +131,7 @@ device = driver(
| `put_scheduled_job(spec)` / `delete_scheduled_job(key, digest=)` | an application's own job, as a systemd timer |
| `get_time_sync` | chrony's sources, the ones DHCP gave apart (`dhcp_ntp_servers`), whether it is synchronised, the zone from `timedatectl`, in one round trip over SSH (napalm-device-types' `PosixTimeSyncMixin`); the zone from `GET /nodes/{node}/time` only where the host names none |
| `configure_time_sync(ntp_servers=, timezone=)` | servers to `/etc/chrony/sources.d/netork.sources`, every other configured source commented out (DHCP's `sourcedir` stays), then a reload or a restart of chrony; the zone through `PUT /nodes/{node}/time` (the token needs `Sys.Modify` on `/nodes/{node}`), so `/etc/timezone` and the web UI follow. Only this node: in a cluster each node keeps its own clock |
| `get_certificates` | `GET /nodes/{node}/certificates/info`, in netOrk's contract shape: `{name, issuer, valid_from, valid_to, in_use_by}` (Unix timestamps; the file name, the issuer's CN; `in_use_by` 1 for the one pveproxy serves, `pveproxy-ssl.pem` before `pve-ssl.pem`), plus `subject`, `fingerprint` and `acme`: true for `pveproxy-ssl.pem` when the node's config names an ACME domain (one more call, `GET /nodes/{node}/config`). Never the PEM. `[]` when unreadable |
**Not implemented** (raise `NotImplementedError`):
`get_bgp_config`, `get_bgp_neighbors`, `get_bgp_neighbors_detail`,
@@ -191,6 +192,7 @@ the disks and ZFS pools the server manages itself.
| packages, updates, services, kernel, listening sockets, sshd hardening, `reboot_host`, `shutdown_host` | as on Proxmox VE |
| scheduled jobs | as on Proxmox VE; `proxmox-backup*` units are `platform`. Verify, prune, sync and GC jobs are `get_backup_jobs`, not scheduled jobs |
| `get_time_sync`, `configure_time_sync`, `get_ntp_servers` | as on Proxmox VE, the zone through `/nodes/localhost/time` (writing it needs `Sys.Modify` on `/system/time`) |
| `get_certificates` | as on Proxmox VE, from `/nodes/localhost/certificates/info` and `/nodes/localhost/config`: one certificate, `proxy.pem`, which ACME renews where a domain is configured |
**API token rights.** Reading needs the role `Audit` on `/` (`Sys.Audit`,
`Datastore.Audit`); the remotes need `Remote.Audit` on `/remote` as well, which
@@ -235,6 +237,7 @@ napalm_proxmox/
├── backup_driver.py # ProxmoxBackupDriver (proxmox_backup)
├── pbs_backups.py # The backup-server role: datastores, groups, jobs, remotes, actions
├── pbs_host.py # The backup server as a host: facts, interfaces, disks, ZFS pools
├── certificates.py # get_certificates on both: the node's TLS certificates, and ACME
└── utils.py # MAC normalisation, CIDR parsing, ARP/OVS parsers
tests/
├── conftest.py # Shared fixtures and mock API payloads
@@ -246,6 +249,7 @@ tests/
├── test_ovs_and_arp.py # get_arp_table, get_mac_address_table, ARP/OVS utils
├── test_misc.py # NTP statistics, SNMP, users, config, ping, traceroute, CLI, LLDP
├── test_time_sync.py # get_time_sync / configure_time_sync on both drivers
├── test_certificates.py # get_certificates on both drivers
├── test_utils.py # Unit tests for napalm_proxmox.utils
├── fixtures/pbs_api.json # What a Proxmox Backup Server 4.2 answered (sanitised)
├── pbs_fake.py # A proxmoxer stand-in answering from that recording
+2
View File
@@ -38,6 +38,7 @@ except ImportError as exc: # pragma: no cover - proxmoxer is a dependency
raise ImportError("proxmoxer is required: pip install proxmoxer") from exc
from napalm_proxmox._base import ProxmoxBase
from napalm_proxmox.certificates import PbsCertificatesMixin
from napalm_proxmox.host_mixin import ProxmoxHostMixin
from napalm_proxmox.pbs_backups import ProxmoxBackupServerMixin
from napalm_proxmox.pbs_host import ProxmoxPbsHostMixin
@@ -59,6 +60,7 @@ class ProxmoxBackupDriver(
ProxmoxPbsHostMixin,
ProxmoxHostMixin,
ProxmoxTimeSyncMixin,
PbsCertificatesMixin,
BackupServerDriver,
StorageDriver,
KernelFactsMixin,
+115
View File
@@ -0,0 +1,115 @@
"""The node's TLS certificates and whether ACME renews them (NetOrk/netork#2656).
``get_certificates`` answers netOrk's certificate contract, the one the OPNsense
driver set: one ``{name, issuer, valid_from, valid_to, in_use_by}`` per
certificate, the validity as Unix timestamps. netOrk's expiry warnings read it
from every driver that has it.
Both products list their certificates at ``GET /nodes/{node}/certificates/info``
(PBS: ``/nodes/localhost/certificates/info``). Proxmox VE has three: its
cluster's CA (``pve-root-ca.pem``), the node certificate the CA signed
(``pve-ssl.pem``) and, where one was uploaded or ACME ordered one,
``pveproxy-ssl.pem``, which ``pveproxy`` then serves instead. A backup server has
one, ``proxy.pem``. ``in_use_by`` is 1 for the certificate the web UI and API
serve, 0 for the others.
One call more, the node's ``config``, says whether ACME renews the served
certificate (``acme``): a domain is configured (``acmedomain0``…, or
``domains=`` in the older ``acme`` property). The daily update job of either
product renews it 30 days before it runs out, so an ACME certificate close to
its end means the renewal failed. A config that cannot be read means no ACME.
``name`` is the file name, as the products' own certificate lists show it;
``issuer`` and ``subject`` are the common names. The PEM never leaves the node
reading: netOrk keeps only what it shows.
"""
from __future__ import annotations
import logging
import re
from typing import TYPE_CHECKING, Any, ClassVar
logger = logging.getLogger(__name__)
_JsonDict = dict[str, Any]
#: ``CN=x`` in either form the products print a name in: ``/O=y/CN=x`` (PVE) or
#: ``CN = x, O = y`` (PBS).
_COMMON_NAME = re.compile(r"(?:^|[/,])\s*CN\s*=\s*([^/,]+)")
def common_name(name: str | None) -> str:
"""The CN of a distinguished name as Proxmox prints it, else the name itself."""
if not name:
return ""
found = _COMMON_NAME.search(name)
return found.group(1).strip() if found else name.strip()
def _seconds(value: Any) -> int:
try:
return int(value or 0)
except (TypeError, ValueError):
return 0
def acme_configured(config: _JsonDict) -> bool:
"""Whether the node's config names a domain for ACME to order a certificate for."""
if any(key.startswith("acmedomain") and value for key, value in config.items()):
return True
return "domains=" in str(config.get("acme") or "")
class ProxmoxCertificatesMixin:
"""``get_certificates`` for a Proxmox VE node; the backup server sets its file names."""
#: The files the proxy serves, the first one present wins.
served_certificates: ClassVar[tuple[str, ...]] = ("pveproxy-ssl.pem", "pve-ssl.pem")
#: The file an ACME order writes.
acme_certificate: ClassVar[str] = "pveproxy-ssl.pem"
_node_name: str
if TYPE_CHECKING: # pragma: no cover - the driver's (napalm_proxmox._base)
def _node_api(self) -> Any: ...
def get_certificates(self) -> list[_JsonDict]:
"""The node's certificates in netOrk's contract shape; ``[]`` when unreadable."""
try:
rows = self._node_api().certificates.info.get() or []
except Exception as exc:
logger.warning("get_certificates() failed on %s: %s", self._node_name, exc)
return []
files = [row.get("filename") for row in rows]
served = next((f for f in self.served_certificates if f in files), None)
acme = self.acme_certificate in files and self._acme_configured()
return [self._certificate(row, served, acme) for row in rows]
def _acme_configured(self) -> bool:
try:
return acme_configured(self._node_api().config.get() or {})
except Exception as exc:
logger.debug("node config unreadable on %s: %s", self._node_name, exc)
return False
def _certificate(self, row: _JsonDict, served: str | None, acme: bool) -> _JsonDict:
filename = str(row.get("filename") or "")
return {
"name": filename,
"issuer": common_name(row.get("issuer")),
"valid_from": _seconds(row.get("notbefore")),
"valid_to": _seconds(row.get("notafter")),
"in_use_by": 1 if filename == served else 0,
"subject": common_name(row.get("subject")),
"fingerprint": row.get("fingerprint") or "",
"acme": acme and filename == self.acme_certificate,
}
class PbsCertificatesMixin(ProxmoxCertificatesMixin):
"""A backup server has one certificate, ``proxy.pem``, which ACME renews too."""
served_certificates: ClassVar[tuple[str, ...]] = ("proxy.pem",)
acme_certificate: ClassVar[str] = "proxy.pem"
+2
View File
@@ -49,6 +49,7 @@ except ImportError as exc:
raise ImportError("proxmoxer is required: pip install proxmoxer") from exc
from napalm_proxmox._base import ProxmoxBase
from napalm_proxmox.certificates import ProxmoxCertificatesMixin
from napalm_proxmox.cluster_mixin import ProxmoxClusterMixin
from napalm_proxmox.config_mixin import ProxmoxConfigMixin
from napalm_proxmox.host_mixin import ProxmoxHostMixin
@@ -103,6 +104,7 @@ class ProxmoxDriver(
ProxmoxScheduledJobsMixin,
ProxmoxRunningBackupsMixin,
ProxmoxTimeSyncMixin,
ProxmoxCertificatesMixin,
HostStatusMixin,
LicenseMixin,
SnmpAgentMixin,
+255
View File
@@ -0,0 +1,255 @@
"""The node's TLS certificates and whether ACME renews them (NetOrk/netork#2656).
``get_certificates`` answers netOrk's certificate contract, the one the OPNsense
driver set: ``{name, issuer, valid_from, valid_to, in_use_by}`` with Unix
timestamps, so netOrk's expiry warnings apply to a Proxmox node as to any device.
The source is ``GET /nodes/{node}/certificates/info`` (PBS:
``/nodes/localhost/certificates/info``), and one more call, the node's
``config``, tells whether ACME renews the certificate the proxy serves.
The responses are shaped as Proxmox VE 8 and PBS 3 answer (``pvenode cert info``,
``proxmox-backup-manager cert info``), the PEM left out.
"""
from __future__ import annotations
from typing import Any
from unittest.mock import patch
import pytest
from proxmoxer.core import ResourceException
from napalm_proxmox import ProxmoxBackupDriver, ProxmoxDriver
from tests.conftest import _build_mock_api
from tests.pbs_fake import FakePbsApi
ROOT_CA = {
"filename": "pve-root-ca.pem",
"fingerprint": "5E:41:...:0A",
"issuer": "/CN=Proxmox Virtual Environment/OU=2d4e8a1c-7b9f/O=PVE Cluster Manager CA",
"notafter": 2017526400,
"notbefore": 1702166400,
"public-key-bits": 2048,
"public-key-type": "rsaEncryption",
"san": [],
"subject": "/CN=Proxmox Virtual Environment/OU=2d4e8a1c-7b9f/O=PVE Cluster Manager CA",
}
PVE_SSL = {
"filename": "pve-ssl.pem",
"fingerprint": "A1:B2:...:C3",
"issuer": "/CN=Proxmox Virtual Environment/OU=2d4e8a1c-7b9f/O=PVE Cluster Manager CA",
"notafter": 1765238400,
"notbefore": 1702166400,
"public-key-bits": 2048,
"public-key-type": "rsaEncryption",
"san": [
"127.0.0.1",
"0000:0000:0000:0000:0000:0000:0000:0001",
"localhost",
"pve1",
"pve1.example.com",
],
"subject": "/OU=PVE Cluster Node/O=Proxmox Virtual Environment/CN=pve1.example.com",
}
PVEPROXY_SSL = {
"filename": "pveproxy-ssl.pem",
"fingerprint": "D4:E5:...:F6",
"issuer": "/C=US/O=Let's Encrypt/CN=R11",
"notafter": 1771977600,
"notbefore": 1764201600,
"public-key-bits": 2048,
"public-key-type": "rsaEncryption",
"san": ["pve1.example.com"],
"subject": "/CN=pve1.example.com",
}
ACME_CONFIG = {
"acme": "account=default",
"acmedomain0": "domain=pve1.example.com,plugin=cloudflare",
"digest": "4f0c...",
}
PROXY_PEM = {
"filename": "proxy.pem",
"fingerprint": "0A:1B:...:2C",
"issuer": "CN = pbs1.example.com, O = Proxmox Backup Server, OU = 4c6e1d2a",
"notafter": 2017526400,
"notbefore": 1702166400,
"public-key-bits": 4096,
"public-key-type": "rsaEncryption",
"san": ["IP Address:127.0.0.1", "DNS:localhost", "DNS:pbs1", "DNS:pbs1.example.com"],
"subject": "CN = pbs1.example.com, O = Proxmox Backup Server, OU = 4c6e1d2a",
}
def _pve(info: Any, config: Any = None) -> tuple[ProxmoxDriver, Any]:
driver = ProxmoxDriver(
"pve1.example.com", "root", "secret", optional_args={"verify_ssl": False}
)
api = _build_mock_api()
node = api.nodes.return_value
if isinstance(info, Exception):
node.certificates.info.get.side_effect = info
else:
node.certificates.info.get.return_value = info
if isinstance(config, Exception):
node.config.get.side_effect = config
else:
node.config.get.return_value = config or {}
with patch("napalm_proxmox.driver.ProxmoxAPI", return_value=api):
driver.open()
return driver, api
def _pbs(**responses: Any) -> tuple[ProxmoxBackupDriver, FakePbsApi]:
api = FakePbsApi(**responses)
driver = ProxmoxBackupDriver("pbs1.example.com", "root@pam", "secret")
with patch("napalm_proxmox.backup_driver.ProxmoxAPI", return_value=api):
driver.open()
return driver, api
# -- Proxmox VE -------------------------------------------------------------------------------
def test_every_certificate_of_the_node_in_the_contract_shape() -> None:
driver, api = _pve([ROOT_CA, PVE_SSL, PVEPROXY_SSL])
certs = driver.get_certificates()
api.nodes.assert_any_call("pve1")
assert certs == [
{
"name": "pve-root-ca.pem",
"issuer": "Proxmox Virtual Environment",
"valid_from": 1702166400,
"valid_to": 2017526400,
"in_use_by": 0,
"subject": "Proxmox Virtual Environment",
"fingerprint": "5E:41:...:0A",
"acme": False,
},
{
"name": "pve-ssl.pem",
"issuer": "Proxmox Virtual Environment",
"valid_from": 1702166400,
"valid_to": 1765238400,
"in_use_by": 0,
"subject": "pve1.example.com",
"fingerprint": "A1:B2:...:C3",
"acme": False,
},
{
"name": "pveproxy-ssl.pem",
"issuer": "R11",
"valid_from": 1764201600,
"valid_to": 1771977600,
"in_use_by": 1,
"subject": "pve1.example.com",
"fingerprint": "D4:E5:...:F6",
"acme": False,
},
]
def test_the_timestamps_are_integers() -> None:
driver, _ = _pve([{**PVE_SSL, "notafter": "1765238400", "notbefore": None}])
(cert,) = driver.get_certificates()
assert cert["valid_to"] == 1765238400
assert cert["valid_from"] == 0
def test_without_a_custom_certificate_pveproxy_serves_pve_ssl() -> None:
driver, _ = _pve([ROOT_CA, PVE_SSL])
in_use = {c["name"]: c["in_use_by"] for c in driver.get_certificates()}
assert in_use == {"pve-root-ca.pem": 0, "pve-ssl.pem": 1}
def test_acme_renews_the_certificate_pveproxy_serves() -> None:
driver, api = _pve([ROOT_CA, PVE_SSL, PVEPROXY_SSL], ACME_CONFIG)
acme = {c["name"]: c["acme"] for c in driver.get_certificates()}
assert acme == {"pve-root-ca.pem": False, "pve-ssl.pem": False, "pveproxy-ssl.pem": True}
# One call more than the certificates: the node's config.
api.nodes.return_value.config.get.assert_called_once_with()
def test_acme_in_its_older_form_names_the_domains_in_acme() -> None:
config = {"acme": "account=default,domains=pve1.example.com"}
driver, _ = _pve([PVE_SSL, PVEPROXY_SSL], config)
acme = {c["name"]: c["acme"] for c in driver.get_certificates()}
assert acme == {"pve-ssl.pem": False, "pveproxy-ssl.pem": True}
def test_an_acme_account_without_domains_renews_nothing() -> None:
driver, _ = _pve([PVE_SSL, PVEPROXY_SSL], {"acme": "account=default"})
assert not any(c["acme"] for c in driver.get_certificates())
def test_acme_never_renews_pve_ssl() -> None:
# Without pveproxy-ssl.pem there is no ACME certificate yet, even with domains set.
driver, _ = _pve([ROOT_CA, PVE_SSL], ACME_CONFIG)
assert not any(c["acme"] for c in driver.get_certificates())
def test_an_unreadable_config_reads_as_no_acme() -> None:
driver, _ = _pve([PVE_SSL, PVEPROXY_SSL], ResourceException(403, "Forbidden", "no Sys.Audit"))
certs = driver.get_certificates()
assert [c["name"] for c in certs] == ["pve-ssl.pem", "pveproxy-ssl.pem"]
assert not any(c["acme"] for c in certs)
def test_unreadable_certificates_are_none_rather_than_a_failed_poll() -> None:
driver, api = _pve(ResourceException(403, "Forbidden", "no Sys.Audit"))
assert driver.get_certificates() == []
api.nodes.return_value.config.get.assert_not_called()
# -- Proxmox Backup Server ---------------------------------------------------------------------
def test_the_backup_server_reads_localhost() -> None:
driver, api = _pbs(
**{"nodes/localhost/certificates/info": [PROXY_PEM], "nodes/localhost/config": {}}
)
assert driver.get_certificates() == [
{
"name": "proxy.pem",
"issuer": "pbs1.example.com",
"valid_from": 1702166400,
"valid_to": 2017526400,
"in_use_by": 1,
"subject": "pbs1.example.com",
"fingerprint": "0A:1B:...:2C",
"acme": False,
}
]
assert ("GET", "nodes/localhost/certificates/info", {}) in api.calls
def test_acme_renews_the_backup_servers_proxy_certificate() -> None:
config = {"acme": "account=default", "acmedomain0": "domain=pbs1.example.com"}
driver, _ = _pbs(
**{"nodes/localhost/certificates/info": [PROXY_PEM], "nodes/localhost/config": config}
)
(cert,) = driver.get_certificates()
assert cert["acme"] is True
@pytest.mark.parametrize("cls", [ProxmoxDriver, ProxmoxBackupDriver], ids=["pve", "pbs"])
def test_both_drivers_have_it(cls: type) -> None:
assert callable(getattr(cls, "get_certificates", None))