refactor(config): take the revision contract from napalm-device-types
driver / standard (pull_request) Successful in 17s
driver / lint (pull_request) Successful in 15s
driver / types (pull_request) Successful in 1m0s
driver / test (3.12) (pull_request) Successful in 1m11s
driver / test (3.13) (pull_request) Successful in 1m3s
driver / lowest (pull_request) Successful in 35s
driver / build (pull_request) Successful in 29s
driver / security (pull_request) Successful in 1m1s
CI / driver (pull_request) Successful in 2m44s
driver / publish (pull_request) Skipped
driver / standard (pull_request) Successful in 17s
driver / lint (pull_request) Successful in 15s
driver / types (pull_request) Successful in 1m0s
driver / test (3.12) (pull_request) Successful in 1m11s
driver / test (3.13) (pull_request) Successful in 1m3s
driver / lowest (pull_request) Successful in 35s
driver / build (pull_request) Successful in 29s
driver / security (pull_request) Successful in 1m1s
CI / driver (pull_request) Successful in 2m44s
driver / publish (pull_request) Skipped
napalm-device-types 4.38.0 declares ConfigRevisionsMixin: the listing, the reading, ConfigRevisionDict and the exceptions, and the revert as a template. The driver keeps the device communication: the three backup API calls, the revert step, and config_revision_content(), which leaves out the <revision> block every save writes into config.xml and the indentation between elements. The template reads the newest revision after the revert and checks that it holds the revision's configuration. OPNsense answers "reverted" even when restoreBackup() could not load the file and kept the previous one; that now raises ConfigRevertFailed instead of passing. A refusal of the firewall raises ConfigRevertFailed too. An id the history does not list still never reaches a request path. Refs NetOrk/netork#2511
This commit is contained in:
1 parent
5a20023c54
commit
a65a3ed6e3
5 files changed
+174
-62
No files matched your search
@@ -1,5 +1,11 @@
|
||||
"""The firewall's own configuration history (NetOrk/netork#2511).
|
||||
|
||||
napalm-device-types' ``ConfigRevisionsMixin`` is the contract: it declares the listing
|
||||
and the reading and runs the revert as a template -- refuse an id that is not in the
|
||||
history, read the revision, revert, check that the newest revision holds it. This
|
||||
module talks to the firewall: the three API calls, and ``config_revision_content``,
|
||||
which leaves out the ``<revision>`` block every save writes into config.xml.
|
||||
|
||||
OPNsense keeps a copy of config.xml for every save, as ``/conf/backup/config-<unix
|
||||
time>.xml`` -- *System → Configuration → History*. It keeps ``<system><backupcount>``
|
||||
of them (100 when unset) and drops the oldest on the next save. The newest is the
|
||||
@@ -26,8 +32,19 @@ from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
|
||||
# config.xml as the firewall's own API hands it over; ElementTree resolves no external
|
||||
# entities, and expat limits entity expansion since 2.4.1.
|
||||
import xml.etree.ElementTree as ET # nosec B405
|
||||
from datetime import UTC, datetime
|
||||
from typing import TYPE_CHECKING, Any, TypedDict
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from napalm_device_types import (
|
||||
ConfigRevertFailed,
|
||||
ConfigRevisionDict,
|
||||
ConfigRevisionsMixin,
|
||||
UnknownConfigRevision,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -40,28 +57,13 @@ REVERT_PATH = "/api/core/backup/revert_backup/{revision_id}"
|
||||
#: What ``revert_backup`` answers for a revision it has no file for.
|
||||
_NOT_FOUND = "not_found"
|
||||
_REVERTED = "reverted"
|
||||
#: What every save writes into config.xml anew: who saved it, when, from where.
|
||||
_STAMP = "revision"
|
||||
#: A revision's file name in /conf/backup: its unix time, and ``_<ns>`` after a save
|
||||
#: within the same microsecond. Nothing else may reach a request path.
|
||||
_REVISION_ID = re.compile(r"config-([0-9]+(?:\.[0-9]+)?)(?:_[0-9]+)?\.xml")
|
||||
|
||||
|
||||
class ConfigRevisionDict(TypedDict):
|
||||
"""One revision of the firewall's configuration (``get_config_revisions``)."""
|
||||
|
||||
id: str # what get_config_revision and revert_config_revision take
|
||||
time: str | None # when it was saved, UTC ISO 8601; None when the firewall does not say
|
||||
description: str | None # what made the change, as the firewall records it; None: none
|
||||
user: str | None # who saved it ("root@192.0.2.20"); None when the firewall names nobody
|
||||
size: int | None # the file's size in bytes; None when not given
|
||||
|
||||
|
||||
class UnknownConfigRevision(ValueError):
|
||||
"""The firewall's configuration history has no revision of that id."""
|
||||
|
||||
def __init__(self, revision_id: object) -> None:
|
||||
super().__init__(f"no configuration revision {revision_id!r} in the firewall's history")
|
||||
|
||||
|
||||
def _checked_id(revision_id: object) -> str:
|
||||
if not isinstance(revision_id, str) or not _REVISION_ID.fullmatch(revision_id):
|
||||
raise UnknownConfigRevision(revision_id)
|
||||
@@ -121,7 +123,7 @@ def config_revisions(answer: Any) -> list[ConfigRevisionDict]:
|
||||
return revisions
|
||||
|
||||
|
||||
class OPNsenseConfigRevisionsMixin:
|
||||
class OPNsenseConfigRevisionsMixin(ConfigRevisionsMixin):
|
||||
"""List, read and revert to the firewall's configuration revisions; see the module."""
|
||||
|
||||
#: No API takes an uploaded config.xml (NAPALM's base stub would only raise).
|
||||
@@ -138,18 +140,6 @@ class OPNsenseConfigRevisionsMixin:
|
||||
def get_config_revisions(self) -> list[ConfigRevisionDict]:
|
||||
"""The firewall's configuration history, newest first; the first is in place now.
|
||||
|
||||
Example::
|
||||
|
||||
[
|
||||
{
|
||||
"id": "config-1794603885.1239.xml",
|
||||
"time": "2026-11-13T21:04:45+00:00",
|
||||
"description": "/api/firewall/filter/apply made changes",
|
||||
"user": "apiuser@192.0.2.10",
|
||||
"size": 58213,
|
||||
},
|
||||
]
|
||||
|
||||
:raises Exception: when the history cannot be read, e.g. by a key without the
|
||||
backup privilege.
|
||||
"""
|
||||
@@ -167,27 +157,36 @@ class OPNsenseConfigRevisionsMixin:
|
||||
raise UnknownConfigRevision(checked)
|
||||
return text
|
||||
|
||||
def revert_config_revision(self, revision_id: str) -> None:
|
||||
"""Make revision *revision_id* the firewall's configuration (``revert_backup``).
|
||||
def config_revision_content(self, text: str) -> str:
|
||||
"""config.xml without the root's ``<revision>`` block, canonical (XML C14N).
|
||||
|
||||
The revision is saved as config.xml and as the history's new newest entry;
|
||||
no service is reloaded and the firewall does not reboot (see the module).
|
||||
The indentation between elements does not count; a value's own blanks do.
|
||||
|
||||
:raises UnknownConfigRevision: for an id that is not in the history now.
|
||||
:raises RuntimeError: when the firewall refuses the revert, e.g. for a key
|
||||
that may not change the configuration.
|
||||
:raises Exception: when the firewall cannot be reached.
|
||||
:raises xml.etree.ElementTree.ParseError: for a text that is no XML.
|
||||
"""
|
||||
# The firewall's own config.xml: see the import.
|
||||
root = ET.fromstring(text) # nosec B314
|
||||
for stamp in root.findall(_STAMP):
|
||||
root.remove(stamp)
|
||||
for element in root.iter():
|
||||
if element.text is not None and not element.text.strip():
|
||||
element.text = None
|
||||
if element.tail is not None and not element.tail.strip():
|
||||
element.tail = None
|
||||
return ET.canonicalize(ET.tostring(root, encoding="unicode"))
|
||||
|
||||
def _revert_to_config_revision(self, revision_id: str) -> None:
|
||||
"""``revert_backup``: config.xml becomes the revision, saved as the newest one."""
|
||||
checked = _checked_id(revision_id)
|
||||
if checked not in {r["id"] for r in self.get_config_revisions()}:
|
||||
raise UnknownConfigRevision(checked)
|
||||
answer = self._post(REVERT_PATH.format(revision_id=checked))
|
||||
status = answer.get("status") if isinstance(answer, dict) else None
|
||||
if status == _NOT_FOUND:
|
||||
raise UnknownConfigRevision(checked)
|
||||
if status != _REVERTED:
|
||||
reason = answer.get("errorMessage") if isinstance(answer, dict) else None
|
||||
raise RuntimeError(f"The firewall did not revert to {checked}: {reason or status}")
|
||||
raise ConfigRevertFailed(
|
||||
f"The firewall did not revert to {checked}: {reason or status}"
|
||||
)
|
||||
|
||||
def _get_latest_backup_id(self) -> str | None:
|
||||
"""Return the ID of the most recent server-side config backup, or ``None``.
|
||||
|
||||
Reference in new issue
Block a user