From 6fdc3ff2c77c16a89e7da28800b94efe9ccec4bc Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Wed, 11 Nov 2026 15:20:29 +0100 Subject: [PATCH] feat(time-sync): read the time servers and zone of config.xml (NetOrk/netork#2363) netOrk aligns every device with one list of time servers and a zone per site (NetOrk/netork#2360) through napalm-device-types 4.35.0's TimeSyncMixin. OPNsense keeps both in config.xml, and , set on the legacy pages services_ntpd.php and system_general.php. No API controller reads or writes them, on 26.7 and on master, so get_time_sync() reads them from the configuration download get_config already uses and asks /api/ntpd/service/status whether ntpd follows a system peer. The driver writes neither value: time_sync_writes is empty and configure_time_sync is None. Restoring an edited config.xml or running the initial setup wizard would rewrite far more than the clock, on a box that is often the gateway and its LAN's time server. TIME_SERVERS_MENU and TIME_ZONE_MENU say where a person sets them, as SSH_SETTINGS_MENU does for the SSH algorithms. get_ntp_servers() now returns the same configured list. It read a "peers" field the status endpoint does not have (it answers with ntpq's associations as "rows") and so never found a server. --- CHANGELOG.md | 20 ++ README.md | 28 ++- napalm_opnsense/opnsense.py | 24 +- napalm_opnsense/time_sync.py | 115 +++++++++ pyproject.toml | 2 +- tests/quality_baseline.json | 2 +- tests/unit/fixtures/config_xml_sample.xml | 164 ++++++++++++ tests/unit/fixtures/ntpd_service_status.json | 12 + tests/unit/test_driver.py | 38 --- tests/unit/test_time_sync.py | 251 +++++++++++++++++++ 10 files changed, 592 insertions(+), 64 deletions(-) create mode 100644 napalm_opnsense/time_sync.py create mode 100644 tests/unit/fixtures/config_xml_sample.xml create mode 100644 tests/unit/fixtures/ntpd_service_status.json create mode 100644 tests/unit/test_time_sync.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 2f9431e..3a8e0c8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,26 @@ All notable changes to this driver. The format follows ## [Unreleased] +### Added +- Time sync (NetOrk/netork#2363): `get_time_sync()` from napalm-device-types 4.35.0's + `TimeSyncMixin` reads the time servers (``, in their order) and + the zone (``, an IANA name; none is the `Etc/UTC` OPNsense runs + then) from config.xml over `/api/core/backup/download/this`, and whether ntpd + follows a system peer from `/api/ntpd/service/status`. Both values are set on legacy + pages that no API controller reads or writes, up to 26.7 and on `master`, so the + driver writes neither: `time_sync_writes` is empty, `configure_time_sync` is None, + and `TIME_SERVERS_MENU` (*Services → Network Time → General*) and `TIME_ZONE_MENU` + (*System → Settings → General*) say where a person sets them. + +### Changed +- Requires napalm-device-types 4.35.0, which declares the time-sync contract. + +### Fixed +- `get_ntp_servers()` lists the configured servers of config.xml, the same list as + `get_time_sync()`. It read a `peers` field `/api/ntpd/service/status` does not + have -- the endpoint answers with ntpq's associations as `rows` -- and so found no + server. A failed read now raises instead of reading as "no servers". + ## [0.6.0] - 2026-11-07 ### Added diff --git a/README.md b/README.md index 81dbc47..2bfb827 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ NAPALM community driver for **OPNsense** firewalls (read-only, via REST API). |---|---| | Python | 3.12 | | NAPALM | 4.0 | -| napalm-device-types | 4.26.0 | +| napalm-device-types | 4.35.0 | | requests | 2.28 | ## Installation @@ -82,7 +82,8 @@ arguments. | `get_environment` | ✅ | `GET /api/diagnostics/system/system_resources` + `system_temperature` | | `get_lldp_neighbors` | ✅ ¹ | `GET /api/lldpd/service/neighbor` | | `get_lldp_neighbors_detail` | ✅ ¹ | `GET /api/lldpd/service/neighbor` | -| `get_ntp_servers` | ✅ | `GET /api/ntpd/service/status` | +| `get_ntp_servers` | ✅ ⁵ | `GET /api/core/backup/download/this`: `` of config.xml | +| `get_time_sync` | ✅ ⁵ | `GET /api/core/backup/download/this` (servers, zone) + `GET /api/ntpd/service/status` (system peer) | | `get_config` | ✅ | `GET /api/core/backup/download/this` (XML) | | `is_alive` | ✅ | TCP socket check | | `get_bgp_neighbors` | ✅ ² | `GET /api/quagga/bgp/get` + `GET /api/quagga/diagnostics/bgpneighbors` | @@ -101,6 +102,7 @@ arguments. > ² Requires the `os-frr` (FRR/Quagga) plugin. Returns empty dict if the plugin is not installed or FRR is not running. > ³ Overrides the generic per-host loop from `napalm-device-types`. > ⁴ See [Scheduled jobs](#scheduled-jobs). +> ⁵ See [Time sync](#time-sync). ### Ping @@ -161,6 +163,28 @@ algorithm lists instead: `SSH_SETTINGS_MENU` is the page's menu path and OpenSSH's defaults. In an HA pair the configuration sync carries the section to the backup when its "OpenSSH" item (`ssh`) is ticked. +### Time sync + +OPNsense keeps the time servers and the zone in config.xml: ``, +space-separated in the order of *Services → Network Time → General* +(`services_ntpd.php`), and ``, an IANA name set on *System → +Settings → General* (`system_general.php`). `get_time_sync()` reads both from the +configuration download `get_config` uses, and `get_ntp_servers()` returns the same +servers. An empty or missing zone reads as `Etc/UTC`, the zone OPNsense runs in +then. `synchronized` is whether `/api/ntpd/service/status` (`ntpq -pnw` as rows) has +a system peer (`*`): False without servers, since OPNsense does not run ntpd then, +and None when the status cannot be read. `daemon` is `ntpd`. The API key needs the +privilege to download the configuration, as for `get_config`. + +Both pages are legacy PHP, and no API controller reads or writes either value, up +to OPNsense 26.7 and on `master`; the initial setup wizard writes the zone only +together with the hostname, the interfaces and the root password. So the driver +writes neither: `time_sync_writes` is empty and `configure_time_sync` is None. +`TIME_SERVERS_MENU` and `TIME_ZONE_MENU` are the pages' menu paths, for telling a +person where to set them. Which interfaces ntpd serves time on is not touched. In an +HA pair the configuration sync carries the servers to the backup when its "Network +Time" item (`ntpd`) is ticked; the zone is not synchronised. + ## Config management OPNsense does not expose a single generic "push config" endpoint. Config is diff --git a/napalm_opnsense/opnsense.py b/napalm_opnsense/opnsense.py index e1be239..c061705 100644 --- a/napalm_opnsense/opnsense.py +++ b/napalm_opnsense/opnsense.py @@ -76,6 +76,7 @@ from napalm_opnsense.port_forwards import alias_index, port_forwards, wan_interf from napalm_opnsense.resolver_mixin import OPNsenseResolverMixin from napalm_opnsense.scheduled_jobs import OPNsenseScheduledJobsMixin from napalm_opnsense.ssh_settings import OPNsenseSshSettingsMixin +from napalm_opnsense.time_sync import OPNsenseTimeSyncMixin from napalm_opnsense.virtual_ips import carp_addresses, carp_master from napalm_opnsense.wireguard import wireguard_tunnels @@ -98,6 +99,7 @@ def _opnsense_version(versions: Any) -> str: class OPNsenseDriver( + OPNsenseTimeSyncMixin, OPNsenseScheduledJobsMixin, OPNsenseSshSettingsMixin, OPNsensePingMixin, @@ -774,28 +776,6 @@ class OPNsenseDriver( ) return details - def get_ntp_servers(self) -> dict[str, dict[str, Any]]: - """Return configured NTP servers. - - Calls ``GET /api/ntpd/service/status`` which includes the list of - configured peer addresses in the ``peers`` field. - - Returns a dict keyed by server address with an empty value dict - (NAPALM standard format). - """ - try: - data = self._get("/api/ntpd/service/status") - except Exception as exc: - logger.debug("NTP status fetch failed (plugin not installed?): %s", exc) - return {} - - servers: dict[str, dict[str, Any]] = {} - for peer in data.get("peers", []): - addr = peer.get("address") or peer.get("remote", "") - if addr: - servers[addr] = {} - return servers - def get_vlans(self) -> dict[str, dict[str, Any]]: """Return configured VLANs. diff --git a/napalm_opnsense/time_sync.py b/napalm_opnsense/time_sync.py new file mode 100644 index 0000000..0a0423e --- /dev/null +++ b/napalm_opnsense/time_sync.py @@ -0,0 +1,115 @@ +"""The firewall's time servers and time zone (napalm-device-types, NetOrk/netork#2363). + +OPNsense keeps both in config.xml: ````, space-separated in the +order of *Services → Network Time → General* (``services_ntpd.php``), and +````, an IANA name set on *System → Settings → General* +(``system_general.php``). An empty or missing zone runs as ``Etc/UTC`` +(``system_timezone_configure``); without time servers OPNsense does not run ntpd at +all (``ntpd_enabled``). Both pages are legacy PHP: no API controller reads or writes +either value, up to 26.7 and on ``master`` (the initial setup wizard writes the zone, +but only together with the hostname, the interfaces and the root password). + +So the driver reads both from config.xml -- the download ``get_config`` uses -- and +asks ntpd over ``/api/ntpd/service/status`` (``ntpq -pnw`` as rows) whether the clock +follows a system peer. It writes neither: ``time_sync_writes`` is empty, +``configure_time_sync`` is None, and :data:`TIME_SERVERS_MENU` and +:data:`TIME_ZONE_MENU` say, as data, where a person sets them. Nothing here touches +which interfaces ntpd serves time on. In an HA pair the configuration sync carries +the servers to the backup when its "Network Time" item (``ntpd``) is ticked; the +zone is not synchronised. +""" + +from __future__ import annotations + +# 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 typing import TYPE_CHECKING, Any, ClassVar + +from napalm_device_types import TimeSyncDict, TimeSyncMixin + +#: config.xml itself (the newest entry of the configuration history). +CONFIG_PATH = "/api/core/backup/download/this" +#: ntpd's associations, one row per line of ``ntpq -pnw``. +STATUS_PATH = "/api/ntpd/service/status" +#: The zone OPNsense runs in when config.xml names none. +DEFAULT_ZONE = "Etc/UTC" +#: How ``ntpq`` marks the system peer, the source the clock follows. +_SYSTEM_PEER = "*" + + +def time_settings(config_xml: str) -> tuple[list[str], str]: + """``(servers, zone)`` as *config_xml* names them; no zone is :data:`DEFAULT_ZONE`. + + :raises xml.etree.ElementTree.ParseError: for a text that is no XML. + """ + # The firewall's own config.xml: see the import. + system = ET.fromstring(config_xml).find("system") # nosec B314 + if system is None: + return [], DEFAULT_ZONE + servers = (system.findtext("timeservers") or "").split() + zone = (system.findtext("timezone") or "").strip() + return servers, zone or DEFAULT_ZONE + + +def follows_a_peer(status: Any) -> bool | None: + """Whether ntpd's *status* answer has a system peer; None for another shape.""" + rows = status.get("rows") if isinstance(status, dict) else None + if not isinstance(rows, list): + return None + return any(isinstance(row, dict) and row.get("status") == _SYSTEM_PEER for row in rows) + + +class OPNsenseTimeSyncMixin(TimeSyncMixin): + """Read the time servers and the zone; writing them is left to a person.""" + + #: Neither value has an API that writes it. + time_sync_writes: ClassVar[frozenset[str]] = frozenset() + configure_time_sync = None # type: ignore[assignment] + + #: The menu path to the page that lists the time servers ("Time servers"). + TIME_SERVERS_MENU: tuple[str, ...] = ("Services", "Network Time", "General") + #: The menu path to the page that sets the zone ("Time zone"). + TIME_ZONE_MENU: tuple[str, ...] = ("System", "Settings", "General") + + 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 _time_settings(self) -> tuple[list[str], str]: + return time_settings(self._get_text(CONFIG_PATH)) + + def get_time_sync(self) -> TimeSyncDict: + """The servers and zone of config.xml, and whether ntpd follows one of them. + + ``synchronized`` is False without servers (ntpd does not run then) and None + when ntpd's status cannot be read. + + :raises Exception: when config.xml cannot be read, e.g. by a key without + the backup privilege. + """ + servers, zone = self._time_settings() + synchronized: bool | None = False + if servers: + try: + synchronized = follows_a_peer(self._get(STATUS_PATH)) + except Exception: # the status is an extra; the settings were read + synchronized = None + return { + "ntp_servers": servers, + "timezone": zone, + "synchronized": synchronized, + "daemon": "ntpd", + } + + def get_ntp_servers(self) -> dict[str, dict[str, Any]]: + """The configured servers, in their order, each with an empty dict (NAPALM's shape). + + The same list as ``get_time_sync()["ntp_servers"]``. + + :raises Exception: when config.xml cannot be read. + """ + servers, _zone = self._time_settings() + return {server: {} for server in servers} diff --git a/pyproject.toml b/pyproject.toml index 803ebce..5e9d87b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -23,7 +23,7 @@ classifiers = [ ] dependencies = [ "napalm>=5.1", # older releases import pkg_resources, which a 3.12 venv lacks - "napalm-device-types>=4.27.0", + "napalm-device-types>=4.35.0", "requests>=2.28.0", ] diff --git a/tests/quality_baseline.json b/tests/quality_baseline.json index e9dfd78..f794000 100644 --- a/tests/quality_baseline.json +++ b/tests/quality_baseline.json @@ -55,7 +55,7 @@ "napalm_opnsense.resolver_mixin" ], "python_file_lines": { - "napalm_opnsense/opnsense.py": 3055 + "napalm_opnsense/opnsense.py": 3035 }, "untyped_public": [ "napalm_opnsense/opnsense.py::OPNsenseDriver.get_snmp_config" diff --git a/tests/unit/fixtures/config_xml_sample.xml b/tests/unit/fixtures/config_xml_sample.xml new file mode 100644 index 0000000..4bf2489 --- /dev/null +++ b/tests/unit/fixtures/config_xml_sample.xml @@ -0,0 +1,164 @@ + + + + opnsense + + normal + OPNsense + internal + 1 + + + admins + System Administrators + system + 1999 + 0 + page-all + + Etc/UTC + 0.opnsense.pool.ntp.org 1.opnsense.pool.ntp.org 2.opnsense.pool.ntp.org 3.opnsense.pool.ntp.org + + https + 1 + + yes + 1 + + 1 + hadp + hadp + hadp + + monthly + + 1 + 1 + + admins + + + + + 1 + mismatch1 + + + dhcp + dhcp6 + 1 + 1 + + 0 + + + 1 + mismatch0 + + + 192.168.1.1 + 24 + idassoc6 + wan + 0 + + + + 1 + 53053 + lan + + 1 + + + lan + 192.168.1.100 + 192.168.1.199 + + + lan + ::1000 + ::2000 + lan + slaac + + + + 1 + + + + automatic + + + + + + + + + 0.opnsense.pool.ntp.org + 0.opnsense.pool.ntp.org 1.opnsense.pool.ntp.org 2.opnsense.pool.ntp.org 3.opnsense.pool.ntp.org + + + + + + + 1 + keep + + 1 + pass + 1 + 0 + lan + in + inet + any + lan + 0 + + any + 0 + 0 + 0 + 0 + 0 + 0 + + 0 + Default allow LAN to any rule + + + 1 + keep + + 11 + pass + 1 + 0 + lan + in + inet6 + any + lan + 0 + any + 0 + 0 + 0 + 0 + 0 + 0 + 0 + Default allow LAN IPv6 to any rule + + + + + + + + + diff --git a/tests/unit/fixtures/ntpd_service_status.json b/tests/unit/fixtures/ntpd_service_status.json new file mode 100644 index 0000000..93f7798 --- /dev/null +++ b/tests/unit/fixtures/ntpd_service_status.json @@ -0,0 +1,12 @@ +{ + "total": 5, + "rowCount": 5, + "current": 1, + "rows": [ + {"status": "__pool", "server": "0.opnsense.pool.ntp.org", "refid": ".POOL.", "stratum": "16", "type": "p", "when": "-", "poll": "64", "reach": "0", "delay": "0.000", "offset": "+0.000", "jitter": "0.000"}, + {"status": "__pool", "server": "1.opnsense.pool.ntp.org", "refid": ".POOL.", "stratum": "16", "type": "p", "when": "-", "poll": "64", "reach": "0", "delay": "0.000", "offset": "+0.000", "jitter": "0.000"}, + {"status": "*", "server": "162.159.200.1", "refid": "10.217.8.4", "stratum": "3", "type": "u", "when": "33", "poll": "64", "reach": "377", "delay": "10.123", "offset": "-0.456", "jitter": "0.789"}, + {"status": "+", "server": "194.59.205.229", "refid": "192.53.103.103", "stratum": "2", "type": "u", "when": "12", "poll": "64", "reach": "377", "delay": "12.801", "offset": "+0.214", "jitter": "0.333"}, + {"status": "-", "server": "85.214.38.116", "refid": "131.188.3.222", "stratum": "2", "type": "u", "when": "41", "poll": "64", "reach": "377", "delay": "14.002", "offset": "+1.870", "jitter": "0.902"} + ] +} diff --git a/tests/unit/test_driver.py b/tests/unit/test_driver.py index c539b2d..e1e3394 100644 --- a/tests/unit/test_driver.py +++ b/tests/unit/test_driver.py @@ -798,44 +798,6 @@ class TestGetLldpNeighborsDetail: assert driver.get_lldp_neighbors_detail() == {} -# --------------------------------------------------------------------------- -# get_ntp_servers() -# --------------------------------------------------------------------------- - -NTP_STATUS_RESPONSE = { - "peers": [ - {"address": "pool.ntp.org", "state": "synced"}, - {"address": "time.cloudflare.com", "state": "candidate"}, - ] -} - - -class TestGetNtpServers: - def test_entry_count(self, driver): - driver._get = lambda path: NTP_STATUS_RESPONSE - servers = driver.get_ntp_servers() - assert len(servers) == 2 - - def test_server_addresses(self, driver): - driver._get = lambda path: NTP_STATUS_RESPONSE - servers = driver.get_ntp_servers() - assert "pool.ntp.org" in servers - assert "time.cloudflare.com" in servers - - def test_value_is_empty_dict(self, driver): - driver._get = lambda path: NTP_STATUS_RESPONSE - for v in driver.get_ntp_servers().values(): - assert v == {} - - def test_endpoint_failure_returns_empty(self, driver): - driver._get = lambda path: (_ for _ in ()).throw(Exception("service not running")) - assert driver.get_ntp_servers() == {} - - def test_empty_peers(self, driver): - driver._get = lambda path: {"peers": []} - assert driver.get_ntp_servers() == {} - - # --------------------------------------------------------------------------- # get_vlans() # --------------------------------------------------------------------------- diff --git a/tests/unit/test_time_sync.py b/tests/unit/test_time_sync.py new file mode 100644 index 0000000..d9b58da --- /dev/null +++ b/tests/unit/test_time_sync.py @@ -0,0 +1,251 @@ +"""Time sync on OPNsense: the time servers and the zone of config.xml (NetOrk/netork#2363). + +OPNsense keeps both in its configuration: ````, space-separated +in the order of *Services -> Network Time -> General*, and ````, an +IANA name set on *System -> Settings -> General*. No API controller reads or writes +either, up to 26.7 and on ``master``: both pages are legacy PHP. So the driver reads +them from config.xml (``/api/core/backup/download/this``, as ``get_config`` does), +asks ntpd over ``/api/ntpd/service/status`` whether the clock follows a peer, and +writes nothing: ``time_sync_writes`` is empty and ``configure_time_sync`` is None. + +``config_xml_sample.xml`` is OPNsense's own ``src/etc/config.xml.sample`` (core +``master``, 2026-11) without the default root user. ``ntpd_service_status.json`` is +the answer of ``/api/ntpd/service/status`` in its 26.7 shape: ``ntpq -pnw`` as rows, +the pool associations marked ``__pool``, the system peer ``*``. +""" + +from __future__ import annotations + +import json +from pathlib import Path +from unittest.mock import MagicMock, patch +from xml.etree.ElementTree import ParseError + +import pytest +import requests +from napalm_device_types import TimeSyncMixin + +from napalm_opnsense.opnsense import OPNsenseDriver + +FIXTURES = Path(__file__).parent / "fixtures" +CONFIG_XML = (FIXTURES / "config_xml_sample.xml").read_text() +NTPD_STATUS = json.loads((FIXTURES / "ntpd_service_status.json").read_text()) + +CONFIG_PATH = "/api/core/backup/download/this" +STATUS_PATH = "/api/ntpd/service/status" +POOLS = [f"{n}.opnsense.pool.ntp.org" for n in range(4)] + + +def _configured(servers: str | None = None, zone: str | None = None) -> str: + """The sample config.xml with other time servers or another zone ("" = element empty, + None = as the sample has it).""" + xml = CONFIG_XML + if servers is not None: + xml = xml.replace(" ".join(POOLS), servers) + if zone is not None: + xml = xml.replace("Etc/UTC", f"{zone}") + return xml + + +def _without(element: str, xml: str = CONFIG_XML) -> str: + start = xml.index(f"<{element}>") + end = xml.index(f"") + len(f"") + return xml[:start] + xml[end:] + + +class Firewall: + """Answers GETs as the firewall's API would; every request is recorded.""" + + def __init__(self, config=CONFIG_XML, status=NTPD_STATUS, status_error=None): + self.config = config + self.status = status + self.status_error = status_error + self.paths: list[str] = [] + + def get(self, url, timeout=None): + path = url.removeprefix("https://fw") + self.paths.append(path) + response = MagicMock() + response.raise_for_status.return_value = None + if path == CONFIG_PATH: + if isinstance(self.config, Exception): + response.raise_for_status.side_effect = self.config + response.text = self.config + response.json.side_effect = json.JSONDecodeError("Expecting value", "<", 0) + return response + if path == STATUS_PATH: + if self.status_error is not None: + response.raise_for_status.side_effect = self.status_error + response.json.return_value = self.status + return response + raise AssertionError(f"unexpected GET {path}") + + +@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 + return firewall + + +class TestGetTimeSync: + def test_the_servers_and_zone_of_config_xml(self, driver): + _on(driver, Firewall()) + + assert driver.get_time_sync() == { + "ntp_servers": POOLS, + "timezone": "Etc/UTC", + "synchronized": True, + "daemon": "ntpd", + } + + def test_the_servers_in_the_order_the_firewall_keeps_them(self, driver): + _on(driver, Firewall(config=_configured("10.0.0.1 ptbtime1.ptb.de time.cloudflare.com"))) + + assert driver.get_time_sync()["ntp_servers"] == [ + "10.0.0.1", + "ptbtime1.ptb.de", + "time.cloudflare.com", + ] + + def test_the_zone_by_its_iana_name(self, driver): + _on(driver, Firewall(config=_configured(zone="Europe/Berlin"))) + + assert driver.get_time_sync()["timezone"] == "Europe/Berlin" + + @pytest.mark.parametrize( + "config", [_configured(zone=""), _without("timezone")], ids=["empty", "missing"] + ) + def test_no_zone_is_the_utc_opnsense_runs_then(self, driver, config): + # system_timezone_configure() puts Etc/UTC in place for an empty or missing zone. + _on(driver, Firewall(config=config)) + + assert driver.get_time_sync()["timezone"] == "Etc/UTC" + + @pytest.mark.parametrize( + "config", [_configured(servers=""), _without("timeservers")], ids=["empty", "missing"] + ) + def test_no_servers_is_an_unsynchronised_clock_and_ntpd_is_not_asked(self, driver, config): + # Without OPNsense does not run ntpd (ntpd_enabled()). + firewall = _on(driver, Firewall(config=config)) + + sync = driver.get_time_sync() + + assert sync["ntp_servers"] == [] + assert sync["synchronized"] is False + assert STATUS_PATH not in firewall.paths + + def test_a_configuration_without_a_system_section(self, driver): + _on(driver, Firewall(config=_without("system"))) + + sync = driver.get_time_sync() + + assert (sync["ntp_servers"], sync["timezone"]) == ([], "Etc/UTC") + + def test_no_system_peer_is_an_unsynchronised_clock(self, driver): + rows = [ + dict(row, status="+" if row["status"] == "*" else row["status"]) + for row in NTPD_STATUS["rows"] + ] + _on(driver, Firewall(status={**NTPD_STATUS, "rows": rows})) + + assert driver.get_time_sync()["synchronized"] is False + + def test_ntpd_without_peers_yet_is_an_unsynchronised_clock(self, driver): + _on(driver, Firewall(status={"total": 0, "rowCount": 0, "current": 1, "rows": []})) + + assert driver.get_time_sync()["synchronized"] is False + + @pytest.mark.parametrize("status", [None, [], {"rows": "x"}], ids=["null", "list", "rows"]) + def test_a_status_of_another_shape_is_unknown(self, driver, status): + _on(driver, Firewall(status=status)) + + assert driver.get_time_sync()["synchronized"] is None + + def test_a_failed_status_read_is_unknown_and_keeps_the_rest(self, driver): + _on(driver, Firewall(status_error=requests.HTTPError("403 Forbidden"))) + + sync = driver.get_time_sync() + + assert sync["synchronized"] is None + assert sync["ntp_servers"] == POOLS + assert sync["timezone"] == "Etc/UTC" + + def test_a_failed_configuration_read_raises(self, driver): + # "No servers" would be a reading; a key without the backup privilege is none. + _on(driver, Firewall(config=requests.HTTPError("403 Forbidden"))) + + with pytest.raises(requests.HTTPError, match="403"): + driver.get_time_sync() + + def test_a_configuration_that_is_no_xml_raises(self, driver): + _on(driver, Firewall(config="Login")) + + with pytest.raises(ParseError): + driver.get_time_sync() + + def test_a_reading_only_reads(self, driver): + firewall = _on(driver, Firewall()) + + driver.get_time_sync() + + assert firewall.paths == [CONFIG_PATH, STATUS_PATH] + driver.session.post.assert_not_called() + + +class TestGetNtpServers: + def test_the_configured_servers_as_napalm_keys_them(self, driver): + _on(driver, Firewall()) + + servers = driver.get_ntp_servers() + + assert servers == {name: {} for name in POOLS} + assert list(servers) == POOLS + + def test_the_same_servers_as_get_time_sync(self, driver): + _on(driver, Firewall(config=_configured("10.0.0.1 ptbtime1.ptb.de"))) + + assert list(driver.get_ntp_servers()) == driver.get_time_sync()["ntp_servers"] + + def test_only_the_configuration_is_read(self, driver): + firewall = _on(driver, Firewall()) + + driver.get_ntp_servers() + + assert firewall.paths == [CONFIG_PATH] + + def test_no_servers_configured(self, driver): + _on(driver, Firewall(config=_without("timeservers"))) + + assert driver.get_ntp_servers() == {} + + def test_a_failed_read_raises_instead_of_reading_as_no_servers(self, driver): + _on(driver, Firewall(config=requests.HTTPError("403 Forbidden"))) + + with pytest.raises(requests.HTTPError): + driver.get_ntp_servers() + + +class TestWhatTheDriverOffers: + def test_it_reads_time_sync(self): + assert issubclass(OPNsenseDriver, TimeSyncMixin) + assert callable(getattr(OPNsenseDriver, "get_time_sync", None)) + + def test_it_writes_nothing(self): + # Both values are set on legacy pages; no API controller writes them. + assert OPNsenseDriver.time_sync_writes == frozenset() + assert getattr(OPNsenseDriver, "configure_time_sync", None) is None + + def test_where_a_person_sets_the_servers(self): + assert OPNsenseDriver.TIME_SERVERS_MENU == ("Services", "Network Time", "General") + + def test_where_a_person_sets_the_zone(self): + assert OPNsenseDriver.TIME_ZONE_MENU == ("System", "Settings", "General") -- 2.54.1