driver / lint (pull_request) Successful in 14s
driver / standard (pull_request) Successful in 17s
driver / types (pull_request) Successful in 57s
driver / test (3.13) (pull_request) Successful in 1m4s
driver / test (3.12) (pull_request) Successful in 1m10s
driver / lowest (pull_request) Successful in 30s
driver / build (pull_request) Successful in 29s
driver / security (pull_request) Successful in 1m4s
CI / driver (pull_request) Successful in 2m25s
driver / publish (pull_request) Skipped
OPNsense has no API that takes an uploaded config.xml: the backup API lists the history in /conf/backup, hands out a revision and reverts to one that is already on the firewall. A full replace exists only on the legacy page diag_backup.php. So an application restores a configuration by reverting to the revision that holds it (NetOrk/netork#2511). get_config_revisions() lists the history newest first: id, time in UTC (time_iso is in the firewall's zone), description, user and size. get_config_revision(id) returns one revision's config.xml. revert_config_revision(id) calls revert_backup and refuses an id that is not in the history now; an id that is no file name of the history never reaches a request path. A revert only saves config.xml as a new newest revision: no service is reloaded and the firewall does not reboot. load_replace_candidate is None instead of NAPALM's stub that raised, so a capability check sees that the driver replaces nothing. The helper that finds the newest backup for rollback() moves to the new module, which keeps opnsense.py under its recorded size. Refs NetOrk/netork#2511
206 lines
8.5 KiB
Python
206 lines
8.5 KiB
Python
"""The firewall's own configuration history (NetOrk/netork#2511).
|
|
|
|
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
|
|
from datetime import UTC, datetime
|
|
from typing import TYPE_CHECKING, Any, TypedDict
|
|
|
|
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"
|
|
#: 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)
|
|
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:
|
|
"""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.
|
|
|
|
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.
|
|
"""
|
|
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 revert_config_revision(self, revision_id: str) -> None:
|
|
"""Make revision *revision_id* the firewall's configuration (``revert_backup``).
|
|
|
|
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).
|
|
|
|
: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.
|
|
"""
|
|
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}")
|
|
|
|
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
|