From 0f730a4b9d84ce74b79cf6cc7a8de8644c933fc9 Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Mon, 2 Nov 2026 08:37:06 +0100 Subject: [PATCH] fix(dhcp): raise when the Kea reservation search fails create_dhcp_reservation searched for an existing reservation so a retry updates it, but a failed search was logged at debug level and the add went ahead: a write based on a read that did not happen. Raise a RuntimeError naming searchReservation before anything is written. Closes #40 --- CHANGELOG.md | 5 +++++ napalm_opnsense/opnsense.py | 13 +++++++------ tests/unit/test_driver.py | 27 +++++++++++++++++++++++++++ 3 files changed, 39 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f8bbcf5..6e0655a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -43,6 +43,11 @@ All notable changes to this driver. The format follows Dnsmasq ran: a transient API error made the firewall look as if it had no DNS records. `sync_dns_zone()` raises that API error instead of "No active DNS service (Unbound or Dnsmasq) detected" (#39). +- `create_dhcp_reservation()` raises `RuntimeError` naming `searchReservation` when + the search for an existing reservation fails, and writes nothing. It used to add + the reservation anyway: a retry then failed with "Kea rejected DHCP reservation" + instead of the real error, or left two reservations for one address, which Kea + refuses to load (#40). ## [0.5.0] - 2026-10-23 diff --git a/napalm_opnsense/opnsense.py b/napalm_opnsense/opnsense.py index d6e4b5a..b421d1b 100644 --- a/napalm_opnsense/opnsense.py +++ b/napalm_opnsense/opnsense.py @@ -1453,7 +1453,8 @@ class OPNsenseDriver( :param hostname: optional hostname to record on the reservation. :raises ValueError: if no Kea subnet contains ``ip``. :raises RuntimeError: if Kea rejects the reservation (validation - errors), the Kea plugin isn't installed/enabled, or ``ip`` is + errors), the Kea plugin isn't installed/enabled, the search for an + existing reservation fails (nothing is written then), or ``ip`` is already reserved for another MAC (left untouched; the caller decides). """ try: @@ -1514,12 +1515,12 @@ class OPNsenseDriver( def _kea_own_reservation(self, ip: str, mac: str) -> dict[str, Any] | None: """*mac*'s reservation for *ip*, updated in place on a retry; raises if another - MAC holds *ip* (#26).""" + MAC holds *ip* (#26) or the search fails (#40).""" try: - own, other = split_by_mac(self._kea_reservations_at(ip), mac) - except Exception as exc: - logger.debug("Kea reservation search failed, proceeding to add: %s", exc) - return None + rows = self._kea_reservations_at(ip) + except RequestException as exc: + raise RuntimeError(f"Kea searchReservation for {ip} failed: {exc}") from exc + own, other = split_by_mac(rows, mac) if own is None and other: raise RuntimeError(f"Kea already reserves {ip} for {other}, not {normalize_mac(mac)}") return own diff --git a/tests/unit/test_driver.py b/tests/unit/test_driver.py index 62d1eee..9ce694b 100644 --- a/tests/unit/test_driver.py +++ b/tests/unit/test_driver.py @@ -2030,6 +2030,33 @@ class TestCreateDhcpReservation: driver.session.post.assert_not_called() + # The search is what makes a retry update its reservation instead of adding a + # second one for the address: a write must not follow a search that failed (#40). + + @pytest.mark.parametrize( + "error", + [ + requests.exceptions.HTTPError("500 Server Error"), + requests.exceptions.ConnectionError("reset by peer"), + ], + ids=["http-error", "connection-error"], + ) + def test_failed_reservation_search_raises_before_any_write(self, driver, error): + driver.session.get.return_value = _make_json_response(KEA_SUBNETS_RESPONSE) + driver.session.post.side_effect = [ + error, # searchReservation + _make_json_response({"result": "saved", "uuid": "new-uuid-123"}), + _make_json_response({"status": "ok"}), + ] + + with pytest.raises(RuntimeError, match="searchReservation") as raised: + driver.create_dhcp_reservation(mac="02:aa:bb:cc:dd:ee", ip="172.22.8.253") + + assert raised.value.__cause__ is error + assert [c.args[0] for c in driver.session.post.call_args_list] == [ + "https://opnsense.example.com/api/kea/dhcpv4/searchReservation" + ] + # --------------------------------------------------------------------------- # delete_dhcp_reservation_and_lease()