feat(config): list, read and revert the firewall's config revisions
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
This commit is contained in:
Christian Manivong committed 2026-11-13 22:21:58 +01:00
1 parent 9d7cb64dac
commit 5a20023c54
7 files changed
+615 -17

No files matched your search

+1 -1
View File
@@ -55,7 +55,7 @@
"napalm_opnsense.resolver_mixin"
],
"python_file_lines": {
"napalm_opnsense/opnsense.py": 3035
"napalm_opnsense/opnsense.py": 3022
},
"untyped_public": [
"napalm_opnsense/opnsense.py::OPNsenseDriver.get_snmp_config"
@@ -0,0 +1,36 @@
{
"items": [
{
"time": "1794603885.12",
"time_iso": "2026-11-13T22:04:45+01:00",
"description": "/api/firewall/filter/apply made changes",
"username": "apiuser@192.0.2.10",
"filesize": 58213,
"id": "config-1794603885.1239.xml"
},
{
"time": "1794603482.87",
"time_iso": "2026-11-13T21:58:02+01:00",
"description": "/system_general.php made changes",
"username": "root@192.0.2.20",
"filesize": 58190,
"id": "config-1794603482.8721.xml"
},
{
"time": "1794475810.05",
"time_iso": "2026-11-12T10:30:10+01:00",
"description": "/api/core/backup/revert_backup/config-1793516400.0012.xml made changes",
"username": "apiuser@192.0.2.10",
"filesize": 57944,
"id": "config-1794475810.0548_123456789.xml"
},
{
"time": "1793516400.00",
"time_iso": "2026-11-01T08:00:00+01:00",
"description": "",
"username": "",
"filesize": 57944,
"id": "config-1793516400.0012.xml"
}
]
}
+316
View File
@@ -0,0 +1,316 @@
"""The firewall's own configuration history: list it, read a revision, revert to one.
NetOrk/netork#2511: OPNsense has no API that takes an uploaded config.xml, so an
application restores a configuration by finding the revision in the firewall's own
history whose content it wants and reverting to that one.
``core_backup_backups_this.json`` has the shape ``/api/core/backup/backups/this`` answers
with on 24.7 up to 26.7 and ``master`` (``OPNsense\\Core\\Api\\BackupController``):
newest first, ``time`` the revision's unix time with two decimals, ``time_iso`` the same
in the firewall's own zone (here +01:00), ``id`` the file name in ``/conf/backup``. The
values are made up; the oldest is a revision without description and user, as the
first configuration of a new install is.
"""
from __future__ import annotations
import json
from pathlib import Path
from unittest.mock import MagicMock, patch
import pytest
import requests
from napalm_opnsense.config_revisions import UnknownConfigRevision
from napalm_opnsense.opnsense import OPNsenseDriver
FIXTURES = Path(__file__).parent / "fixtures"
HISTORY = json.loads((FIXTURES / "core_backup_backups_this.json").read_text())
CONFIG_XML = (FIXTURES / "config_xml_sample.xml").read_text()
HISTORY_PATH = "/api/core/backup/backups/this"
NEWEST = "config-1794603885.1239.xml"
OLDEST = "config-1793516400.0012.xml"
WITH_SUFFIX = "config-1794475810.0548_123456789.xml"
class Firewall:
"""Answers as the firewall's backup API would; every request is recorded."""
def __init__(self, history=HISTORY, files=None, revert_answer=None):
self.history = history
self.files = files if files is not None else {OLDEST: CONFIG_XML}
self.revert_answer = revert_answer or {"status": "reverted"}
self.requests: list[tuple[str, str]] = []
def get(self, url, timeout=None):
path = url.removeprefix("https://fw")
self.requests.append(("GET", path))
response = MagicMock()
response.raise_for_status.return_value = None
if path == HISTORY_PATH:
if isinstance(self.history, Exception):
response.raise_for_status.side_effect = self.history
response.json.return_value = self.history
return response
prefix = "/api/core/backup/download/this/"
if path.startswith(prefix):
# BackupController::downloadAction sends nothing for a name it has no file for.
response.text = self.files.get(path.removeprefix(prefix), "")
response.json.side_effect = json.JSONDecodeError("Expecting value", "<", 0)
return response
raise AssertionError(f"unexpected GET {path}")
def post(self, url, json=None, timeout=None):
path = url.removeprefix("https://fw")
self.requests.append(("POST", path))
response = MagicMock()
response.raise_for_status.return_value = None
if isinstance(self.revert_answer, Exception):
response.raise_for_status.side_effect = self.revert_answer
response.json.return_value = self.revert_answer
return response
@property
def posts(self) -> list[str]:
return [path for method, path in self.requests if method == "POST"]
@pytest.fixture
def driver():
with patch("napalm_opnsense.opnsense.requests.Session"):
drv = OPNsenseDriver(
hostname="fw", username="k", password="s", optional_args={"verify": False}
)
drv.session = MagicMock()
yield drv
def _on(driver, firewall: Firewall) -> Firewall:
driver.session.get.side_effect = firewall.get
driver.session.post.side_effect = firewall.post
return firewall
class TestGetConfigRevisions:
def test_every_revision_newest_first(self, driver):
_on(driver, Firewall())
revisions = driver.get_config_revisions()
assert [r["id"] for r in revisions] == [
NEWEST,
"config-1794603482.8721.xml",
WITH_SUFFIX,
OLDEST,
]
def test_a_revision_as_the_firewall_describes_it(self, driver):
_on(driver, Firewall())
assert driver.get_config_revisions()[0] == {
"id": NEWEST,
"time": "2026-11-13T21:04:45+00:00",
"description": "/api/firewall/filter/apply made changes",
"user": "apiuser@192.0.2.10",
"size": 58213,
}
def test_the_time_is_utc_whatever_zone_the_firewall_runs_in(self, driver):
# time_iso is in the firewall's zone (+01:00 here); time is unix seconds.
_on(driver, Firewall())
times = [r["time"] for r in driver.get_config_revisions()]
assert times == [
"2026-11-13T21:04:45+00:00",
"2026-11-13T20:58:02+00:00",
"2026-11-12T09:30:10+00:00",
"2026-11-01T07:00:00+00:00",
]
def test_no_description_and_no_user_are_none(self, driver):
_on(driver, Firewall())
oldest = driver.get_config_revisions()[-1]
assert (oldest["description"], oldest["user"]) == (None, None)
def test_newest_first_even_when_the_answer_is_not_sorted(self, driver):
items = list(reversed(HISTORY["items"]))
_on(driver, Firewall(history={"items": items}))
assert driver.get_config_revisions()[0]["id"] == NEWEST
def test_without_a_time_the_file_name_tells_it(self, driver):
item = {"id": OLDEST, "description": "", "username": "", "filesize": 1}
_on(driver, Firewall(history={"items": [item]}))
assert driver.get_config_revisions()[0]["time"] == "2026-11-01T07:00:00+00:00"
def test_a_time_and_size_of_another_shape_are_none(self, driver):
item = {"id": "config-1.xml", "time": "soon", "filesize": "big", "description": 7}
_on(driver, Firewall(history={"items": [item, "noise"]}))
assert driver.get_config_revisions() == [
{
"id": "config-1.xml",
"time": "1970-01-01T00:00:01+00:00",
"description": None,
"user": None,
"size": None,
}
]
def test_an_entry_without_a_usable_id_is_left_out(self, driver):
# Nothing could read or revert it: the id goes into the request path.
items = [
{"id": "../config.xml", "time": "1"},
{"id": "config-1/../../x.xml", "time": "1"},
{"time": "1"},
HISTORY["items"][0],
]
_on(driver, Firewall(history={"items": items}))
assert [r["id"] for r in driver.get_config_revisions()] == [NEWEST]
def test_no_history_is_an_empty_list(self, driver):
_on(driver, Firewall(history={"items": []}))
assert driver.get_config_revisions() == []
def test_a_failed_read_raises(self, driver):
_on(driver, Firewall(history=requests.HTTPError("403 Forbidden")))
with pytest.raises(requests.HTTPError, match="403"):
driver.get_config_revisions()
@pytest.mark.parametrize("answer", [[], {"items": "x"}, {}], ids=["list", "items", "empty"])
def test_an_answer_of_another_shape_raises(self, driver, answer):
# "No history" would be a reading; this is none.
_on(driver, Firewall(history=answer))
with pytest.raises(ValueError, match="history"):
driver.get_config_revisions()
def test_a_reading_only_reads(self, driver):
firewall = _on(driver, Firewall())
driver.get_config_revisions()
assert firewall.requests == [("GET", HISTORY_PATH)]
class TestGetConfigRevision:
def test_the_revisions_config_xml(self, driver):
firewall = _on(driver, Firewall())
assert driver.get_config_revision(OLDEST) == CONFIG_XML
assert firewall.requests == [("GET", f"/api/core/backup/download/this/{OLDEST}")]
def test_a_revision_the_firewall_has_no_file_for_raises(self, driver):
# Rotated out of the history: the download answers with nothing.
_on(driver, Firewall(files={}))
with pytest.raises(UnknownConfigRevision, match=OLDEST):
driver.get_config_revision(OLDEST)
@pytest.mark.parametrize(
"revision_id",
["", "config.xml", "../config.xml", "config-1/../../x.xml", "config-1.xml?x=1", None],
)
def test_an_id_that_names_no_revision_is_refused_before_any_request(self, driver, revision_id):
firewall = _on(driver, Firewall())
with pytest.raises(UnknownConfigRevision):
driver.get_config_revision(revision_id)
assert firewall.requests == []
def test_a_failed_read_raises(self, driver):
resp = MagicMock()
resp.raise_for_status.side_effect = requests.HTTPError("403 Forbidden")
driver.session.get.return_value = resp
with pytest.raises(requests.HTTPError, match="403"):
driver.get_config_revision(OLDEST)
class TestRevertConfigRevision:
def test_reverts_through_the_backup_api(self, driver):
firewall = _on(driver, Firewall())
driver.revert_config_revision(OLDEST)
assert firewall.requests == [
("GET", HISTORY_PATH),
("POST", f"/api/core/backup/revert_backup/{OLDEST}"),
]
def test_an_id_with_the_suffix_of_a_fast_save(self, driver):
firewall = _on(driver, Firewall())
driver.revert_config_revision(WITH_SUFFIX)
assert firewall.posts == [f"/api/core/backup/revert_backup/{WITH_SUFFIX}"]
def test_a_revision_not_in_the_history_is_refused(self, driver):
firewall = _on(driver, Firewall())
with pytest.raises(UnknownConfigRevision, match="config-1000000000.5.xml"):
driver.revert_config_revision("config-1000000000.5.xml")
assert firewall.posts == []
@pytest.mark.parametrize("revision_id", ["", "../config.xml", "config-1.xml/x", None])
def test_an_id_that_names_no_revision_is_refused_before_any_request(self, driver, revision_id):
firewall = _on(driver, Firewall())
with pytest.raises(UnknownConfigRevision):
driver.revert_config_revision(revision_id)
assert firewall.requests == []
def test_a_history_that_cannot_be_read_reverts_nothing(self, driver):
firewall = _on(driver, Firewall(history=requests.HTTPError("403 Forbidden")))
with pytest.raises(requests.HTTPError):
driver.revert_config_revision(OLDEST)
assert firewall.posts == []
def test_a_revision_gone_by_the_time_of_the_revert_is_unknown(self, driver):
_on(driver, Firewall(revert_answer={"status": "not_found"}))
with pytest.raises(UnknownConfigRevision, match=OLDEST):
driver.revert_config_revision(OLDEST)
def test_a_key_that_may_not_write_is_refused_with_the_firewalls_reason(self, driver):
# user-config-readonly: throwReadOnly() answers with an errorMessage.
reason = "User apiuser denied for write access (user-config-readonly set)"
_on(driver, Firewall(revert_answer={"errorMessage": reason, "errorTitle": "Error"}))
with pytest.raises(RuntimeError, match="user-config-readonly"):
driver.revert_config_revision(OLDEST)
def test_any_other_answer_is_a_failed_revert(self, driver):
_on(driver, Firewall(revert_answer={"status": "failed"}))
with pytest.raises(RuntimeError, match="failed"):
driver.revert_config_revision(OLDEST)
def test_an_http_error_raises(self, driver):
_on(driver, Firewall(revert_answer=requests.HTTPError("500 Server Error")))
with pytest.raises(requests.HTTPError, match="500"):
driver.revert_config_revision(OLDEST)
class TestWhatTheDriverOffers:
def test_it_reads_and_reverts_revisions(self):
for name in ("get_config_revisions", "get_config_revision", "revert_config_revision"):
assert callable(getattr(OPNsenseDriver, name, None)), name
def test_it_replaces_no_configuration(self):
# No API takes an uploaded config.xml: an application asks for this and gets no.
assert getattr(OPNsenseDriver, "load_replace_candidate", None) is None