fix(wireless): raise when a uci step of an ACL or channel push is refused
driver / standard (pull_request) Successful in 24s
driver / lint (pull_request) Successful in 24s
driver / types (pull_request) Successful in 1m28s
driver / test (3.13) (pull_request) Successful in 1m12s
driver / test (3.12) (pull_request) Successful in 1m21s
driver / lowest (pull_request) Successful in 29s
driver / build (pull_request) Successful in 30s
driver / security (pull_request) Successful in 1m0s
CI / driver (pull_request) Successful in 2m38s
driver / publish (pull_request) Skipped

push_mac_acl and push_radio_channel sent each step through the
interactive shell and never looked at the result: a refused uci set,
add_list, commit or wifi reload passed silently, an SSID no wifi-iface
carried did nothing, and wifi was restarted after a refused channel.

Each step now runs on an SSH exec channel of its own, as root, with its
exit status checked (uci_steps.UciStepsMixin). A refused step raises
CommandErrorException naming the command and what the router said; a
refusal before the commit reverts what was staged, so a later commit
does not apply half of it, and wifi is not restarted. push_mac_acl
reads the sections once, raises when none carries the SSID, and deletes
macfilter/maclist only where a section has them instead of hiding each
delete's status behind `|| true`.

Closes #35
This commit is contained in:
Christian Manivong committed 2026-11-12 19:01:07 +01:00
1 parent 522720f818
commit 0552663d53
6 files changed
+516 -164

No files matched your search

-143
View File
@@ -1444,47 +1444,6 @@ BSS aa:bb:cc:dd:01:ff(on wlan0)
assert entries[0]["frequency"] == 5975
class TestPushRadioChannel:
"""Tests for OpenWrtWirelessMixin.push_radio_channel()."""
def test_issues_uci_set(self, driver):
"""Must call 'uci set wireless.radio0.channel=11'."""
issued: list[str] = []
driver._send_command = lambda cmd, **kw: issued.append(cmd) or ""
driver.push_radio_channel("radio0", 11)
assert any("uci set wireless.radio0.channel=11" in c for c in issued)
def test_issues_uci_commit(self, driver):
issued: list[str] = []
driver._send_command = lambda cmd, **kw: issued.append(cmd) or ""
driver.push_radio_channel("radio0", 11)
assert any("uci commit wireless" in c for c in issued)
def test_issues_wifi_restart(self, driver):
"""Must call 'wifi' (full restart) — NOT just 'wifi reload'."""
issued: list[str] = []
driver._send_command = lambda cmd, **kw: issued.append(cmd) or ""
driver.push_radio_channel("radio1", 36)
# 'wifi' alone is a full restart; 'wifi reload' is insufficient for channel changes
assert any(c.strip() == "wifi" for c in issued)
def test_auto_channel_zero(self, driver):
"""channel=0 should set 'auto' in UCI."""
issued: list[str] = []
driver._send_command = lambda cmd, **kw: issued.append(cmd) or ""
driver.push_radio_channel("radio0", 0)
assert any("channel=auto" in c or "channel='auto'" in c for c in issued)
def test_commit_before_restart(self, driver):
"""UCI commit must happen before wifi restart."""
issued: list[str] = []
driver._send_command = lambda cmd, **kw: issued.append(cmd) or ""
driver.push_radio_channel("radio0", 6)
commit_idx = next(i for i, c in enumerate(issued) if "commit" in c)
wifi_idx = next(i for i, c in enumerate(issued) if c.strip() == "wifi")
assert commit_idx < wifi_idx
UCI_WIRELESS_ACL = """\
wireless.radio0=wifi-device
wireless.radio0.band='2g'
@@ -1550,108 +1509,6 @@ class TestGetSsidsAcl:
assert result["CorpWiFi"]["acl_mode"] == "blacklist"
class TestPushMacAcl:
"""Tests for OpenWrtWirelessMixin.push_mac_acl()."""
def _make_send(
self, sections="wireless.@wifi-iface[0]\nwireless.@wifi-iface[1]", ssid_by_section=None
):
ssid_by_section = ssid_by_section or {
"wireless.@wifi-iface[0]": "CorpWiFi",
"wireless.@wifi-iface[1]": "GuestNet",
}
issued: list[str] = []
def _send(cmd, **kw):
issued.append(cmd)
if "grep -oE" in cmd and "sort -u" in cmd:
return sections
for sec, ssid in ssid_by_section.items():
if f"uci -q get {sec}.ssid" in cmd:
return ssid
return ""
return _send, issued
def test_whitelist_sets_macfilter_allow(self, driver):
send, issued = self._make_send()
driver._send_command = send
driver.push_mac_acl("CorpWiFi", "whitelist", ["AA:BB:CC:DD:EE:01"])
assert any("wireless.@wifi-iface[0].macfilter='allow'" in c for c in issued)
def test_blacklist_sets_macfilter_deny(self, driver):
send, issued = self._make_send()
driver._send_command = send
driver.push_mac_acl("CorpWiFi", "blacklist", ["AA:BB:CC:DD:EE:01"])
assert any("wireless.@wifi-iface[0].macfilter='deny'" in c for c in issued)
def test_off_deletes_macfilter_option_instead_of_setting_disable(self, driver):
"""OpenWrt's validator rejects macfilter='disable' outright (confirmed on
real hardware — it puts netifd in a permanent restart crash loop with
the radio stuck down). "off" must delete the option, never set it."""
send, issued = self._make_send()
driver._send_command = send
driver.push_mac_acl("CorpWiFi", "off", [])
assert not any("macfilter='disable'" in c for c in issued)
assert any("delete wireless.@wifi-iface[0].macfilter" in c for c in issued)
assert any("delete wireless.@wifi-iface[0].maclist" in c for c in issued)
assert not any("add_list wireless.@wifi-iface[0].maclist" in c for c in issued)
def test_whitelist_with_zero_macs_treated_as_off(self, driver):
"""An empty whitelist blocks every client outright — must not be pushed
as macfilter='allow' with an empty list."""
send, issued = self._make_send()
driver._send_command = send
driver.push_mac_acl("CorpWiFi", "whitelist", [])
assert not any("macfilter='allow'" in c for c in issued)
assert any("delete wireless.@wifi-iface[0].macfilter" in c for c in issued)
def test_blacklist_with_zero_macs_still_pushed(self, driver):
"""An empty blacklist is safe (blocks nobody) — no guard needed."""
send, issued = self._make_send()
driver._send_command = send
driver.push_mac_acl("CorpWiFi", "blacklist", [])
assert any("macfilter='deny'" in c for c in issued)
def test_maclist_entries_added(self, driver):
send, issued = self._make_send()
driver._send_command = send
driver.push_mac_acl("CorpWiFi", "whitelist", ["AA:BB:CC:DD:EE:01", "AA:BB:CC:DD:EE:02"])
assert any(
"add_list wireless.@wifi-iface[0].maclist='AA:BB:CC:DD:EE:01'" in c for c in issued
)
assert any(
"add_list wireless.@wifi-iface[0].maclist='AA:BB:CC:DD:EE:02'" in c for c in issued
)
def test_maclist_cleared_before_readd(self, driver):
"""Full-rebuild: existing maclist must be deleted before new entries are added."""
send, issued = self._make_send()
driver._send_command = send
driver.push_mac_acl("CorpWiFi", "whitelist", ["AA:BB:CC:DD:EE:01"])
delete_idx = next(
i for i, c in enumerate(issued) if "delete wireless.@wifi-iface[0].maclist" in c
)
add_idx = next(
i for i, c in enumerate(issued) if "add_list wireless.@wifi-iface[0].maclist" in c
)
assert delete_idx < add_idx
def test_only_matching_ssid_sections_touched(self, driver):
"""GuestNet section must not be modified when pushing CorpWiFi's ACL."""
send, issued = self._make_send()
driver._send_command = send
driver.push_mac_acl("CorpWiFi", "whitelist", ["AA:BB:CC:DD:EE:01"])
assert not any("wireless.@wifi-iface[1].macfilter" in c for c in issued)
def test_issues_uci_commit_and_wifi_reload(self, driver):
send, issued = self._make_send()
driver._send_command = send
driver.push_mac_acl("CorpWiFi", "whitelist", ["AA:BB:CC:DD:EE:01"])
assert any("uci commit wireless" in c for c in issued)
assert any(c.strip() == "wifi reload" for c in issued)
# ---------------------------------------------------------------------------
# fix_snmp — firewall zone handling
# ---------------------------------------------------------------------------
+295
View File
@@ -0,0 +1,295 @@
"""Wireless writes: ``push_mac_acl`` and ``push_radio_channel`` (NAPALM/napalm-openwrt#35).
Each ``uci`` step runs on an exec channel of its own, with its exit status checked: a
refused step raises and names itself, nothing staged after a refusal is committed, and
wifi is not restarted for a change that never landed.
The device is a fake behind ``run_command``. ``uci -q show wireless`` answers in the
shape OpenWrt 23.05 prints it: the stock ``default_radioN`` sections, a list option on
one line with each value quoted, and a quote inside a value as ``'\\''``. The refusals
are uci's and wifi's own messages: ``uci: Invalid argument`` for an option set on a
section that does not exist, ``uci: I/O error`` for a commit that cannot write
``/etc/config``.
"""
from __future__ import annotations
import shlex
from unittest.mock import MagicMock, patch
import pytest
from napalm.base.exceptions import CommandErrorException
from napalm_device_types import CommandResult
from napalm_openwrt.openwrt import OpenWrtDriver
SHOW = "uci -q show wireless"
WIRELESS = """\
wireless.radio0=wifi-device
wireless.radio0.type='mac80211'
wireless.radio0.path='platform/ahb/18100000.wmac'
wireless.radio0.channel='1'
wireless.radio0.band='2g'
wireless.radio0.htmode='HT20'
wireless.radio0.cell_density='0'
wireless.default_radio0=wifi-iface
wireless.default_radio0.device='radio0'
wireless.default_radio0.network='lan'
wireless.default_radio0.mode='ap'
wireless.default_radio0.ssid='CorpWiFi'
wireless.default_radio0.encryption='psk2'
wireless.default_radio0.key='example-passphrase'
wireless.default_radio0.macfilter='deny'
wireless.default_radio0.maclist='00:00:5E:00:53:01' '00:00:5E:00:53:02'
wireless.radio1=wifi-device
wireless.radio1.type='mac80211'
wireless.radio1.path='pci0000:00/0000:00:00.0'
wireless.radio1.channel='36'
wireless.radio1.band='5g'
wireless.radio1.htmode='VHT80'
wireless.default_radio1=wifi-iface
wireless.default_radio1.device='radio1'
wireless.default_radio1.network='lan'
wireless.default_radio1.mode='ap'
wireless.default_radio1.ssid='CorpWiFi'
wireless.default_radio1.encryption='psk2'
wireless.default_radio1.key='example-passphrase'
wireless.guest=wifi-iface
wireless.guest.device='radio0'
wireless.guest.network='guest'
wireless.guest.mode='ap'
wireless.guest.ssid='Bob'\\''s Guest'
wireless.guest.encryption='none'
"""
INVALID_ARGUMENT = CommandResult("", "uci: Invalid argument\n", 1)
IO_ERROR = CommandResult("", "uci: I/O error\n", 1)
class _Ap:
"""``run_command`` of an AP: answers the read, refuses the commands in *refuse*."""
def __init__(self, refuse: dict[str, CommandResult] | None = None) -> None:
self.refuse = refuse or {}
self.commands: list[str] = []
def __call__(
self,
command: str,
*,
privileged: bool = False,
timeout: float = 60,
stdin: bytes | None = None,
) -> CommandResult:
self.commands.append(command)
if command in self.refuse:
return self.refuse[command]
if command == SHOW:
return CommandResult(WIRELESS, "", 0)
return CommandResult("", "", 0)
@property
def argv(self) -> list[list[str]]:
return [shlex.split(c) for c in self.commands]
def _driver(ap: _Ap) -> OpenWrtDriver:
with patch("napalm_openwrt.openwrt.ConnectHandler"):
drv = OpenWrtDriver(hostname="192.0.2.15", username="root", password="")
drv.device = MagicMock()
drv.run_command = ap # type: ignore[method-assign]
return drv
def _uci(*words: str) -> str:
return shlex.join(["uci", *words])
# -- push_mac_acl ------------------------------------------------------------------------------
def test_a_blacklist_is_written_to_every_section_with_the_ssid():
ap = _Ap()
_driver(ap).push_mac_acl("CorpWiFi", "blacklist", ["00:00:5E:00:53:0A"])
assert ap.commands == [
SHOW,
_uci("set", "wireless.default_radio0.macfilter=deny"),
_uci("delete", "wireless.default_radio0.maclist"),
_uci("add_list", "wireless.default_radio0.maclist=00:00:5E:00:53:0A"),
_uci("set", "wireless.default_radio1.macfilter=deny"),
_uci("add_list", "wireless.default_radio1.maclist=00:00:5E:00:53:0A"),
_uci("commit", "wireless"),
"wifi reload",
]
def test_a_whitelist_sets_allow():
ap = _Ap()
_driver(ap).push_mac_acl("CorpWiFi", "whitelist", ["00:00:5E:00:53:0A", "00:00:5E:00:53:0B"])
assert _uci("set", "wireless.default_radio1.macfilter=allow") in ap.commands
assert _uci("add_list", "wireless.default_radio1.maclist=00:00:5E:00:53:0B") in ap.commands
def test_off_deletes_only_the_options_a_section_has():
"""A delete of a missing option exits 1; it is not sent, and no step hides its status."""
ap = _Ap()
_driver(ap).push_mac_acl("CorpWiFi", "off", [])
assert ap.commands == [
SHOW,
_uci("delete", "wireless.default_radio0.macfilter"),
_uci("delete", "wireless.default_radio0.maclist"),
_uci("commit", "wireless"),
"wifi reload",
]
def test_a_whitelist_without_macs_is_off():
ap = _Ap()
_driver(ap).push_mac_acl("CorpWiFi", "whitelist", [])
assert not any("macfilter=allow" in c for c in ap.commands)
assert _uci("delete", "wireless.default_radio0.macfilter") in ap.commands
def test_an_ssid_with_a_quote_and_a_space_is_found():
ap = _Ap()
_driver(ap).push_mac_acl("Bob's Guest", "blacklist", ["00:00:5E:00:53:0A"])
assert _uci("set", "wireless.guest.macfilter=deny") in ap.commands
assert not any("default_radio" in c for c in ap.commands)
def test_no_section_with_the_ssid_raises_and_writes_nothing():
ap = _Ap()
with pytest.raises(CommandErrorException, match="Nowhere"):
_driver(ap).push_mac_acl("Nowhere", "blacklist", ["00:00:5E:00:53:0A"])
assert ap.commands == [SHOW]
def test_a_failed_read_raises_and_writes_nothing():
ap = _Ap({SHOW: CommandResult("", "uci: Entry not found\n", 1)})
with pytest.raises(CommandErrorException, match="Entry not found"):
_driver(ap).push_mac_acl("CorpWiFi", "blacklist", ["00:00:5E:00:53:0A"])
assert ap.commands == [SHOW]
@pytest.mark.parametrize(
"refused",
[
_uci("set", "wireless.default_radio0.macfilter=deny"),
_uci("delete", "wireless.default_radio0.maclist"),
_uci("add_list", "wireless.default_radio1.maclist=00:00:5E:00:53:0A"),
],
)
def test_a_refused_change_raises_naming_it_and_reverts_before_any_commit(refused):
ap = _Ap({refused: INVALID_ARGUMENT})
with pytest.raises(CommandErrorException) as caught:
_driver(ap).push_mac_acl("CorpWiFi", "blacklist", ["00:00:5E:00:53:0A"])
assert refused in str(caught.value)
assert "Invalid argument" in str(caught.value)
assert ap.commands[-1] == _uci("revert", "wireless")
assert _uci("commit", "wireless") not in ap.commands
assert "wifi reload" not in ap.commands
# Nothing after the refused step is sent.
assert ap.commands.index(refused) == len(ap.commands) - 2
def test_a_refused_commit_raises_and_does_not_reload_wifi():
ap = _Ap({_uci("commit", "wireless"): IO_ERROR})
with pytest.raises(CommandErrorException, match="I/O error"):
_driver(ap).push_mac_acl("CorpWiFi", "blacklist", ["00:00:5E:00:53:0A"])
assert ap.commands[-2:] == [_uci("commit", "wireless"), _uci("revert", "wireless")]
assert "wifi reload" not in ap.commands
def test_a_failed_wifi_reload_raises_naming_it():
ap = _Ap({"wifi reload": CommandResult("", "Command failed: Not found\n", 1)})
with pytest.raises(CommandErrorException, match="wifi reload") as caught:
_driver(ap).push_mac_acl("CorpWiFi", "blacklist", ["00:00:5E:00:53:0A"])
assert "Not found" in str(caught.value)
assert ap.commands[-1] == "wifi reload"
def test_a_failed_revert_keeps_the_refusal_as_the_error():
ap = _Ap(
{
_uci("set", "wireless.default_radio0.macfilter=deny"): INVALID_ARGUMENT,
_uci("revert", "wireless"): IO_ERROR,
}
)
with pytest.raises(CommandErrorException, match="Invalid argument"):
_driver(ap).push_mac_acl("CorpWiFi", "blacklist", ["00:00:5E:00:53:0A"])
def test_every_step_runs_as_root():
ap = MagicMock(side_effect=_Ap())
_driver(ap).push_mac_acl("CorpWiFi", "off", [])
assert ap.call_args_list
assert all(call.kwargs.get("privileged") for call in ap.call_args_list)
def test_a_login_other_than_root_is_refused_before_anything_runs():
with patch("napalm_openwrt.openwrt.ConnectHandler"):
drv = OpenWrtDriver(hostname="192.0.2.15", username="admin", password="")
drv.device = MagicMock()
with pytest.raises(PermissionError):
drv.push_mac_acl("CorpWiFi", "off", [])
drv.device.remote_conn_pre.get_transport.assert_not_called()
# -- push_radio_channel ------------------------------------------------------------------------
def test_a_channel_is_set_committed_and_wifi_restarted():
"""``wifi`` (a full restart), not ``wifi reload``: many radios keep the old channel."""
ap = _Ap()
_driver(ap).push_radio_channel("radio1", 44)
assert ap.commands == [
_uci("set", "wireless.radio1.channel=44"),
_uci("commit", "wireless"),
"wifi",
]
def test_channel_zero_is_auto():
ap = _Ap()
_driver(ap).push_radio_channel("radio0", 0)
assert ap.commands[0] == _uci("set", "wireless.radio0.channel=auto")
def test_a_refused_channel_raises_and_does_not_restart_wifi():
refused = _uci("set", "wireless.radio9.channel=6")
ap = _Ap({refused: INVALID_ARGUMENT})
with pytest.raises(CommandErrorException) as caught:
_driver(ap).push_radio_channel("radio9", 6)
assert refused in str(caught.value)
assert "Invalid argument" in str(caught.value)
assert ap.commands == [refused, _uci("revert", "wireless")]
def test_a_refused_channel_commit_does_not_restart_wifi():
ap = _Ap({_uci("commit", "wireless"): IO_ERROR})
with pytest.raises(CommandErrorException, match="I/O error"):
_driver(ap).push_radio_channel("radio0", 6)
assert "wifi" not in ap.commands
def test_a_failed_wifi_restart_raises_naming_it():
ap = _Ap({"wifi": CommandResult("", "", 1)})
with pytest.raises(CommandErrorException, match="`wifi`.*exit status 1"):
_driver(ap).push_radio_channel("radio0", 6)