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
205 lines
8.5 KiB
Python
205 lines
8.5 KiB
Python
"""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
|
|
copy of the configuration in place now.
|
|
|
|
No API takes an uploaded config.xml: the backup API (``/api/core/backup/``) lists the
|
|
history, hands out a revision and reverts to one, but only to a revision that is
|
|
already on the firewall; a full replace exists only on the legacy page
|
|
``diag_backup.php``. So the driver has no ``load_replace_candidate``, and an
|
|
application restores a configuration by reverting to the revision that holds it.
|
|
|
|
A revert (``revert_backup``) copies the revision over config.xml and saves it: the
|
|
history gets a new newest entry with the revision's content, described as
|
|
``/api/core/backup/revert_backup/<id> made changes`` and by the API key's user, and
|
|
the oldest entry may drop out. That is all, and it is done when the request returns:
|
|
OPNsense reloads no service and does not reboot, so the running firewall keeps the
|
|
state it had until a subsystem's settings are applied or it restarts. The ``config``
|
|
system hooks run afterwards (``/usr/local/etc/rc.syshook.d/config``, from syslog);
|
|
core installs none, a plugin such as git-backup does. The revert starts no HA
|
|
configuration sync.
|
|
"""
|
|
|
|
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
|
|
|
|
from napalm_device_types import (
|
|
ConfigRevertFailed,
|
|
ConfigRevisionDict,
|
|
ConfigRevisionsMixin,
|
|
UnknownConfigRevision,
|
|
)
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
#: The history of this firewall, newest first.
|
|
HISTORY_PATH = "/api/core/backup/backups/this"
|
|
#: One revision's config.xml; the answer is empty for a name with no file.
|
|
DOWNLOAD_PATH = "/api/core/backup/download/this/{revision_id}"
|
|
#: Copy a revision over config.xml and save it.
|
|
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")
|
|
|
|
|
|
def _checked_id(revision_id: object) -> str:
|
|
if not isinstance(revision_id, str) or not _REVISION_ID.fullmatch(revision_id):
|
|
raise UnknownConfigRevision(revision_id)
|
|
return revision_id
|
|
|
|
|
|
def _utc(value: Any) -> str | None:
|
|
try:
|
|
seconds = float(value)
|
|
except (TypeError, ValueError):
|
|
return None
|
|
return datetime.fromtimestamp(seconds, UTC).isoformat(timespec="seconds")
|
|
|
|
|
|
def _text(value: Any) -> str | None:
|
|
return value.strip() or None if isinstance(value, str) else None
|
|
|
|
|
|
def _stamp(revision: ConfigRevisionDict) -> float:
|
|
found = _REVISION_ID.fullmatch(revision["id"])
|
|
return float(found.group(1)) if found else 0.0
|
|
|
|
|
|
def _revision(item: Any) -> ConfigRevisionDict | None:
|
|
if not isinstance(item, dict):
|
|
return None
|
|
revision_id = item.get("id")
|
|
if not isinstance(revision_id, str):
|
|
return None
|
|
found = _REVISION_ID.fullmatch(revision_id)
|
|
if found is None:
|
|
return None
|
|
size = item.get("filesize")
|
|
return {
|
|
"id": revision_id,
|
|
# The revision's own time; the file name's when it has none.
|
|
"time": _utc(item.get("time")) or _utc(found.group(1)),
|
|
"description": _text(item.get("description")),
|
|
"user": _text(item.get("username")),
|
|
"size": size if isinstance(size, int) and not isinstance(size, bool) else None,
|
|
}
|
|
|
|
|
|
def config_revisions(answer: Any) -> list[ConfigRevisionDict]:
|
|
"""The revisions of a ``backups/this`` *answer*, newest first.
|
|
|
|
An entry without a usable id is left out: nothing could read or revert it.
|
|
|
|
:raises ValueError: for an answer that is no history, which is not "no revisions".
|
|
"""
|
|
items = answer.get("items") if isinstance(answer, dict) else None
|
|
if not isinstance(items, list):
|
|
raise ValueError("the firewall answered with no configuration history")
|
|
revisions = [r for r in map(_revision, items) if r is not None]
|
|
# By the file name's time, as OPNsense itself orders them.
|
|
revisions.sort(key=_stamp, reverse=True)
|
|
return revisions
|
|
|
|
|
|
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).
|
|
load_replace_candidate = None
|
|
|
|
if TYPE_CHECKING: # pragma: no cover - the driver's REST helpers
|
|
|
|
def _get(self, path: str) -> dict[str, Any]: ...
|
|
|
|
def _get_text(self, path: str) -> str: ...
|
|
|
|
def _post(self, path: str, data: dict[str, Any] | None = None) -> dict[str, Any]: ...
|
|
|
|
def get_config_revisions(self) -> list[ConfigRevisionDict]:
|
|
"""The firewall's configuration history, newest first; the first is in place now.
|
|
|
|
:raises Exception: when the history cannot be read, e.g. by a key without the
|
|
backup privilege.
|
|
"""
|
|
return config_revisions(self._get(HISTORY_PATH))
|
|
|
|
def get_config_revision(self, revision_id: str) -> str:
|
|
"""The config.xml of revision *revision_id*, as the firewall keeps it.
|
|
|
|
:raises UnknownConfigRevision: for an id that is not in the history.
|
|
:raises Exception: when the firewall cannot be read.
|
|
"""
|
|
checked = _checked_id(revision_id)
|
|
text = self._get_text(DOWNLOAD_PATH.format(revision_id=checked))
|
|
if not text.strip():
|
|
raise UnknownConfigRevision(checked)
|
|
return text
|
|
|
|
def config_revision_content(self, text: str) -> str:
|
|
"""config.xml without the root's ``<revision>`` block, canonical (XML C14N).
|
|
|
|
The indentation between elements does not count; a value's own blanks do.
|
|
|
|
: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)
|
|
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 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``.
|
|
|
|
Calls ``GET /api/core/backup/backups/this``. The response is sorted
|
|
newest-first by OPNsense. Returns ``None`` when no backups exist or
|
|
the request fails.
|
|
"""
|
|
try:
|
|
data = self._get(HISTORY_PATH)
|
|
items = data.get("items", [])
|
|
return items[0]["id"] if items else None
|
|
except Exception as exc:
|
|
logger.debug("No backup snapshots found: %s", exc)
|
|
return None
|