fix(radius): the getters raise when the firewall does not answer (#49) #50
No files matched your search
@@ -37,6 +37,10 @@ All notable changes to this driver. The format follows
|
||||
uploaded config.xml.
|
||||
|
||||
### Fixed
|
||||
- `get_radius_clients()` and `get_radius_users()` raise when the firewall does not
|
||||
answer or the answer holds no `rows`, instead of returning `[]`, so an empty list
|
||||
means FreeRADIUS has none (#49). `RADIUS_READS_RAISE = True` on the driver says so.
|
||||
A saved add whose id lookup fails still answers `success`, with no id.
|
||||
- `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
|
||||
|
||||
+29
-16
@@ -99,6 +99,14 @@ def _opnsense_version(versions: Any) -> str:
|
||||
return ""
|
||||
|
||||
|
||||
def _search_rows(data: Any, search: str) -> list[dict[str, Any]]:
|
||||
"""The ``rows`` of a FreeRADIUS search answer; raises for an answer without them."""
|
||||
rows = data.get("rows") if isinstance(data, dict) else None
|
||||
if not isinstance(rows, list):
|
||||
raise RuntimeError(f"FreeRADIUS {search} answered without rows: {data!r:.200}")
|
||||
return [row for row in rows if isinstance(row, dict)]
|
||||
|
||||
|
||||
class OPNsenseDriver(
|
||||
OPNsenseConfigRevisionsMixin,
|
||||
OPNsenseTimeSyncMixin,
|
||||
@@ -117,6 +125,9 @@ class OPNsenseDriver(
|
||||
DRIVER_NAME = "opnsense"
|
||||
# Everything runs over the REST API; there is no SSH session to open.
|
||||
USES_SSH = False
|
||||
# get_radius_clients()/get_radius_users() raise when the firewall does not answer,
|
||||
# so an empty list is its answer (#49): a caller may take it as "none there".
|
||||
RADIUS_READS_RAISE = True
|
||||
SNMP_FINGERPRINT = [
|
||||
FingerprintRule("opnsense", weight=8.0, mandatory=True),
|
||||
]
|
||||
@@ -1206,13 +1217,11 @@ class OPNsenseDriver(
|
||||
def get_radius_clients(self) -> list[dict[str, Any]]:
|
||||
"""Return configured FreeRADIUS NAS clients.
|
||||
|
||||
Calls ``GET /api/freeradius/client/search_client``.
|
||||
Calls ``GET /api/freeradius/client/search_client``. Raises when the
|
||||
request fails or the answer holds no ``rows`` list: an empty list means
|
||||
the firewall has no clients, never that it did not answer (#49).
|
||||
"""
|
||||
try:
|
||||
data = self._get("/api/freeradius/client/search_client")
|
||||
except Exception as exc:
|
||||
logger.warning("get_radius_clients() failed: %s", exc)
|
||||
return []
|
||||
data = self._get("/api/freeradius/client/search_client")
|
||||
return [
|
||||
{
|
||||
"id": row.get("uuid", ""),
|
||||
@@ -1220,7 +1229,7 @@ class OPNsenseDriver(
|
||||
"ip": row.get("ip", ""),
|
||||
"enabled": row.get("enabled") == "1",
|
||||
}
|
||||
for row in data.get("rows", [])
|
||||
for row in _search_rows(data, "search_client")
|
||||
]
|
||||
|
||||
def create_radius_client(self, name: str, ip: str, secret: str) -> dict[str, Any]:
|
||||
@@ -1238,7 +1247,11 @@ class OPNsenseDriver(
|
||||
if result.get("result") != "saved":
|
||||
return {"success": False, "validations": result.get("validations", {})}
|
||||
self._post("/api/freeradius/service/reconfigure")
|
||||
created = next((c for c in self.get_radius_clients() if c["name"] == name), None)
|
||||
try:
|
||||
created = next((c for c in self.get_radius_clients() if c["name"] == name), None)
|
||||
except Exception as exc: # the add went through; only its id is unknown
|
||||
logger.warning("create_radius_client(): looking up the new client failed: %s", exc)
|
||||
created = None
|
||||
return {"success": True, "id": created["id"] if created else None}
|
||||
|
||||
def delete_radius_client(self, client_id: str) -> dict[str, Any]:
|
||||
@@ -1253,20 +1266,16 @@ class OPNsenseDriver(
|
||||
"""Return configured FreeRADIUS users.
|
||||
|
||||
Calls ``GET /api/freeradius/user/search_user``. Never includes the
|
||||
password field.
|
||||
password field. Raises like ``get_radius_clients()`` (#49).
|
||||
"""
|
||||
try:
|
||||
data = self._get("/api/freeradius/user/search_user")
|
||||
except Exception as exc:
|
||||
logger.warning("get_radius_users() failed: %s", exc)
|
||||
return []
|
||||
data = self._get("/api/freeradius/user/search_user")
|
||||
return [
|
||||
{
|
||||
"id": row.get("uuid", ""),
|
||||
"username": row.get("username", ""),
|
||||
"enabled": row.get("enabled") == "1",
|
||||
}
|
||||
for row in data.get("rows", [])
|
||||
for row in _search_rows(data, "search_user")
|
||||
]
|
||||
|
||||
def create_radius_user(self, username: str, password: str) -> dict[str, Any]:
|
||||
@@ -1283,7 +1292,11 @@ class OPNsenseDriver(
|
||||
if result.get("result") != "saved":
|
||||
return {"success": False, "validations": result.get("validations", {})}
|
||||
self._post("/api/freeradius/service/reconfigure")
|
||||
created = next((u for u in self.get_radius_users() if u["username"] == username), None)
|
||||
try:
|
||||
created = next((u for u in self.get_radius_users() if u["username"] == username), None)
|
||||
except Exception as exc: # the add went through; only its id is unknown
|
||||
logger.warning("create_radius_user(): looking up the new user failed: %s", exc)
|
||||
created = None
|
||||
return {"success": True, "id": created["id"] if created else None}
|
||||
|
||||
def delete_radius_user(self, user_id: str) -> dict[str, Any]:
|
||||
|
||||
@@ -1251,12 +1251,33 @@ class TestGetRadiusClients:
|
||||
driver.get_radius_clients()
|
||||
assert calls == ["/api/freeradius/client/search_client"]
|
||||
|
||||
def test_api_error_returns_empty_list(self, driver):
|
||||
def test_a_failed_read_raises_rather_than_answering_none(self, driver):
|
||||
"""An empty list must mean the firewall has none (#49)."""
|
||||
driver._get = lambda path: (_ for _ in ()).throw(Exception("404"))
|
||||
with pytest.raises(Exception, match="404"):
|
||||
driver.get_radius_clients()
|
||||
|
||||
def test_an_answer_without_rows_raises(self, driver):
|
||||
driver._get = lambda path: {"error": "plugin not installed"}
|
||||
with pytest.raises(RuntimeError, match="rows"):
|
||||
driver.get_radius_clients()
|
||||
|
||||
def test_no_clients_is_an_empty_list(self, driver):
|
||||
driver._get = lambda path: {"rows": [], "total": 0}
|
||||
assert driver.get_radius_clients() == []
|
||||
|
||||
def test_the_driver_says_its_reads_raise(self, driver):
|
||||
assert type(driver).RADIUS_READS_RAISE is True
|
||||
|
||||
|
||||
class TestCreateRadiusClient:
|
||||
def test_a_saved_add_whose_lookup_fails_is_still_a_success(self, driver):
|
||||
"""The add went through: its id is unknown, the add is not undone (#49)."""
|
||||
driver._post = lambda path, data=None: {"result": "saved"}
|
||||
driver._get = lambda path: (_ for _ in ()).throw(Exception("timeout"))
|
||||
result = driver.create_radius_client("ap-lobby", "10.0.0.5/32", "s3cr3t")
|
||||
assert result == {"success": True, "id": None}
|
||||
|
||||
def test_success_returns_remote_id(self, driver):
|
||||
driver._post = lambda path, data=None: {"result": "saved"}
|
||||
driver._get = lambda path: RADIUS_CLIENTS_RESPONSE
|
||||
@@ -1337,12 +1358,28 @@ class TestGetRadiusUsers:
|
||||
driver.get_radius_users()
|
||||
assert calls == ["/api/freeradius/user/search_user"]
|
||||
|
||||
def test_api_error_returns_empty_list(self, driver):
|
||||
def test_a_failed_read_raises_rather_than_answering_none(self, driver):
|
||||
driver._get = lambda path: (_ for _ in ()).throw(Exception("404"))
|
||||
with pytest.raises(Exception, match="404"):
|
||||
driver.get_radius_users()
|
||||
|
||||
def test_an_answer_without_rows_raises(self, driver):
|
||||
driver._get = lambda path: {"error": "plugin not installed"}
|
||||
with pytest.raises(RuntimeError, match="rows"):
|
||||
driver.get_radius_users()
|
||||
|
||||
def test_no_users_is_an_empty_list(self, driver):
|
||||
driver._get = lambda path: {"rows": [], "total": 0}
|
||||
assert driver.get_radius_users() == []
|
||||
|
||||
|
||||
class TestCreateRadiusUser:
|
||||
def test_a_saved_add_whose_lookup_fails_is_still_a_success(self, driver):
|
||||
driver._post = lambda path, data=None: {"result": "saved"}
|
||||
driver._get = lambda path: (_ for _ in ()).throw(Exception("timeout"))
|
||||
result = driver.create_radius_user("jdoe", "hunter2")
|
||||
assert result == {"success": True, "id": None}
|
||||
|
||||
def test_success_returns_remote_id(self, driver):
|
||||
driver._post = lambda path, data=None: {"result": "saved"}
|
||||
driver._get = lambda path: RADIUS_USERS_RESPONSE
|
||||
|
||||
Reference in new issue
Block a user