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
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:
1 parent
522720f818
commit
0552663d53
6 files changed
+516
-164
No files matched your search
@@ -70,6 +70,15 @@ recorded here; their history is the git log.
|
||||
`manage_service("lldpd", "enable")` and `manage_service("lldpd", "start")` (#8).
|
||||
|
||||
### Fixed
|
||||
- `push_mac_acl()` and `push_radio_channel()` raise when the router refuses a step
|
||||
(`CommandErrorException`, naming the `uci` command or the wifi restart and what the
|
||||
router said). They used to return normally after a refused `uci set`, `add_list`,
|
||||
`commit` or `wifi reload`, so an ACL that never landed looked applied. Each step runs
|
||||
on an SSH exec channel of its own and as root, with its exit status checked; a
|
||||
refused change reverts what was staged, so nothing of it is committed by a later
|
||||
write, and wifi is not restarted for it. `push_mac_acl()` raises when no wifi-iface
|
||||
carries the SSID, where it did nothing, and deletes `macfilter`/`maclist` only where
|
||||
a section has them instead of hiding every delete's status behind `|| true` (#35).
|
||||
- `get_ntp_servers()` names every server of the `system.ntp.server` list; it kept only
|
||||
the first, as uci prints a list as `'a' 'b' 'c'` on one line.
|
||||
- `get_lldp_neighbors()` and `get_lldp_neighbors_detail()` keep an interface name with
|
||||
|
||||
@@ -116,6 +116,16 @@ to the interfaces given, enables it at boot and restarts it. A VLAN device such
|
||||
`br-ap.10` is written as the device under it (`br-ap`): lldpd sends on the L2 device.
|
||||
Which interfaces is the caller's choice; at least one is required.
|
||||
|
||||
## Wireless writes
|
||||
|
||||
`push_mac_acl(ssid_name, mode, macs)` (napalm-device-types `MacAclMixin`) rewrites the
|
||||
MAC filter of every wifi-iface carrying the SSID and reloads wifi;
|
||||
`push_radio_channel(radio, channel)` sets a radio's channel (`0` is `auto`) and restarts
|
||||
wifi in full. Each `uci` step runs on an SSH exec channel of its own, as root, with its
|
||||
exit status checked: a refused step raises `CommandErrorException` naming it, what was
|
||||
staged is reverted, and nothing is committed or restarted. An SSID no wifi-iface
|
||||
carries raises too.
|
||||
|
||||
## Time sync
|
||||
|
||||
`configure_time_sync(ntp_servers=, timezone=)` (napalm-device-types `TimeSyncMixin`)
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""UCI writes run step by step, each step's exit status checked (#35).
|
||||
|
||||
A write stages its changes with one ``uci`` command each, commits the config, then
|
||||
restarts what reads it. Every step runs on an SSH exec channel of its own, so its exit
|
||||
status is the command's own -- nothing is hidden behind ``|| true`` or a shell prompt.
|
||||
|
||||
A refused step raises :class:`CommandErrorException` naming the step and what the
|
||||
device said. A refusal before the commit reverts what was staged, so the next commit
|
||||
of the config -- by any write -- does not apply half a change; nothing is restarted.
|
||||
A refused restart comes after the commit: the change is saved, and the error says so.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
import shlex
|
||||
from collections.abc import Sequence
|
||||
from dataclasses import dataclass, field
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from napalm.base.exceptions import CommandErrorException
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - typing only
|
||||
from napalm_device_types import CommandResult
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
#: Seconds one step may take; ``wifi`` brings every radio down and up again.
|
||||
UCI_STEP_TIMEOUT = 60
|
||||
|
||||
#: ``config.section=type`` or ``config.section.option=value`` of ``uci show``.
|
||||
_SHOW_LINE = re.compile(
|
||||
r"^(?P<config>[^.=\s]+)\.(?P<section>[^.=\s]+)(?:\.(?P<option>[^=\s]+))?=(?P<value>.*)$"
|
||||
)
|
||||
|
||||
|
||||
def uci(*words: str) -> str:
|
||||
"""A ``uci`` command line, every word quoted for the shell where it needs it."""
|
||||
return shlex.join(["uci", *words])
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class UciSection:
|
||||
"""One section of ``uci show``: its name (``default_radio0``, ``@wifi-iface[0]``),
|
||||
its type and its options, each a list of values (one for an option, more for a list).
|
||||
"""
|
||||
|
||||
config: str
|
||||
name: str
|
||||
type: str
|
||||
options: dict[str, list[str]] = field(default_factory=dict)
|
||||
|
||||
@property
|
||||
def ref(self) -> str:
|
||||
"""The section as ``uci`` addresses it: ``wireless.default_radio0``."""
|
||||
return f"{self.config}.{self.name}"
|
||||
|
||||
|
||||
def _values(raw: str) -> list[str]:
|
||||
"""``'a' 'b'`` as uci prints it, a quote inside a value as ``'\\''``."""
|
||||
try:
|
||||
return shlex.split(raw)
|
||||
except ValueError:
|
||||
return [raw]
|
||||
|
||||
|
||||
def parse_uci_show(text: str) -> list[UciSection]:
|
||||
"""The sections of ``uci show <config>``, in the order printed."""
|
||||
sections: dict[str, UciSection] = {}
|
||||
for line in text.splitlines():
|
||||
m = _SHOW_LINE.match(line.strip())
|
||||
if not m:
|
||||
continue
|
||||
key = f"{m['config']}.{m['section']}"
|
||||
if m["option"] is None:
|
||||
sections[key] = UciSection(m["config"], m["section"], m["value"].strip())
|
||||
elif key in sections:
|
||||
sections[key].options[m["option"]] = _values(m["value"])
|
||||
return list(sections.values())
|
||||
|
||||
|
||||
class UciStepsMixin:
|
||||
"""Run a UCI write as checked steps; see the module."""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - the driver's
|
||||
hostname: str
|
||||
|
||||
def run_command(
|
||||
self,
|
||||
command: str,
|
||||
*,
|
||||
privileged: bool = False,
|
||||
timeout: float = 60,
|
||||
stdin: bytes | None = None,
|
||||
) -> CommandResult: ...
|
||||
|
||||
def _uci_step(self, command: str) -> str:
|
||||
"""Run one step as root and return what it printed.
|
||||
|
||||
:raises CommandErrorException: when it exits non-zero, naming the step.
|
||||
:raises PermissionError: for a login other than root, before it runs.
|
||||
"""
|
||||
result = self.run_command(command, privileged=True, timeout=UCI_STEP_TIMEOUT)
|
||||
if result.exit_code != 0:
|
||||
said = result.stderr.strip() or result.stdout.strip()
|
||||
said = said or f"exit status {result.exit_code}"
|
||||
raise CommandErrorException(f"{self.hostname}: `{command}` failed: {said}")
|
||||
return result.stdout
|
||||
|
||||
def _uci_apply(self, config: str, changes: Sequence[str], restart: str) -> None:
|
||||
"""Stage *changes* to *config*, commit it, then run *restart*.
|
||||
|
||||
:raises CommandErrorException: for the first step refused; see the module.
|
||||
"""
|
||||
try:
|
||||
for change in changes:
|
||||
self._uci_step(change)
|
||||
self._uci_step(uci("commit", config))
|
||||
except Exception:
|
||||
self._uci_revert(config)
|
||||
raise
|
||||
try:
|
||||
self._uci_step(restart)
|
||||
except CommandErrorException as exc:
|
||||
raise CommandErrorException(
|
||||
f"{exc} -- the {config} change is committed and applies at the next restart"
|
||||
) from exc
|
||||
|
||||
def _uci_revert(self, config: str) -> None:
|
||||
"""Drop what is staged for *config*; a failure is logged, the refusal stays the error."""
|
||||
try:
|
||||
self._uci_step(uci("revert", config))
|
||||
except Exception as exc:
|
||||
logger.warning("%s: staged %s changes not reverted: %s", self.hostname, config, exc)
|
||||
@@ -16,10 +16,38 @@ import logging
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from napalm.base.exceptions import CommandErrorException
|
||||
|
||||
from napalm_openwrt.uci_steps import UciSection, UciStepsMixin, parse_uci_show, uci
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_WIRELESS = "wireless"
|
||||
_SHOW_WIRELESS = "uci -q show wireless"
|
||||
#: Re-applies the config; enough for a MAC filter.
|
||||
_WIFI_RELOAD = "wifi reload"
|
||||
#: A full down/up of every radio; a channel needs it (see ``push_radio_channel``).
|
||||
_WIFI_RESTART = "wifi"
|
||||
_ACL_OPTIONS = ("macfilter", "maclist")
|
||||
|
||||
class OpenWrtWirelessMixin:
|
||||
|
||||
def _mac_acl_changes(sec: UciSection, mode: str, macs: list[str]) -> list[str]:
|
||||
"""The ``uci`` changes that give *sec* the ACL *mode* with *macs*.
|
||||
|
||||
"off" deletes both options; there is no value for it. Otherwise the list is
|
||||
rebuilt: deleted where the section has one, then each MAC added.
|
||||
"""
|
||||
present = [opt for opt in _ACL_OPTIONS if opt in sec.options]
|
||||
if mode == "off":
|
||||
return [uci("delete", f"{sec.ref}.{opt}") for opt in present]
|
||||
changes = [uci("set", f"{sec.ref}.macfilter={'allow' if mode == 'whitelist' else 'deny'}")]
|
||||
if "maclist" in present:
|
||||
changes.append(uci("delete", f"{sec.ref}.maclist"))
|
||||
changes += [uci("add_list", f"{sec.ref}.maclist={mac}") for mac in macs]
|
||||
return changes
|
||||
|
||||
|
||||
class OpenWrtWirelessMixin(UciStepsMixin):
|
||||
"""Mixin providing wireless/radio NAPALM getters."""
|
||||
|
||||
def get_ssids(self) -> dict[str, Any]:
|
||||
@@ -569,13 +597,17 @@ class OpenWrtWirelessMixin:
|
||||
the physical channel on many hardware/driver combinations; a full
|
||||
restart is required for channel changes to take effect.
|
||||
|
||||
Each step's exit status is checked (:mod:`napalm_openwrt.uci_steps`): a
|
||||
refused ``uci set`` (a radio that does not exist) raises, and wifi is not
|
||||
restarted for it.
|
||||
|
||||
:param radio: UCI radio name, e.g. ``"radio0"``.
|
||||
:param channel: Channel number to set; ``0`` sets UCI ``auto``.
|
||||
:raises CommandErrorException: when a step is refused, naming it.
|
||||
"""
|
||||
ch_val = "auto" if channel == 0 else str(channel)
|
||||
self._send_command(f"uci set wireless.{radio}.channel={ch_val}")
|
||||
self._send_command("uci commit wireless")
|
||||
self._send_command("wifi")
|
||||
change = uci("set", f"{_WIRELESS}.{radio}.channel={ch_val}")
|
||||
self._uci_apply(_WIRELESS, [change], _WIFI_RESTART)
|
||||
|
||||
def push_mac_acl(self, ssid_name: str, mode: str, macs: list[str]) -> None:
|
||||
"""Rewrite macfilter mode + maclist entries on every wifi-iface matching *ssid_name*.
|
||||
@@ -592,31 +624,33 @@ class OpenWrtWirelessMixin:
|
||||
A whitelist ("allow") with zero MACs blocks every client outright, so
|
||||
it is treated as equivalent to "off" instead of being pushed as-is.
|
||||
|
||||
Each step's exit status is checked (:mod:`napalm_openwrt.uci_steps`): a
|
||||
refused step raises naming itself, what was staged is reverted, and
|
||||
nothing is committed or reloaded. An option is deleted only where the
|
||||
section has it, since deleting a missing one is refused too.
|
||||
|
||||
:param ssid_name: SSID name to match against ``option ssid`` on each wifi-iface section.
|
||||
:param mode: ``"off"`` | ``"whitelist"`` | ``"blacklist"``.
|
||||
:param macs: MAC addresses to set as the maclist. Only the entries for the
|
||||
active mode's list are ever passed in — the caller resolves whitelist
|
||||
vs. blacklist before calling.
|
||||
:raises CommandErrorException: when no wifi-iface carries *ssid_name*, or
|
||||
when a step is refused.
|
||||
"""
|
||||
effective_mode = "off" if (mode == "whitelist" and not macs) else mode
|
||||
sections = self._send_command(
|
||||
"uci show wireless | grep -oE '^wireless\\.[^.]+' | sort -u"
|
||||
).split()
|
||||
sections = [
|
||||
sec
|
||||
for sec in parse_uci_show(self._uci_step(_SHOW_WIRELESS))
|
||||
if sec.type == "wifi-iface" and sec.options.get("ssid") == [ssid_name]
|
||||
]
|
||||
if not sections:
|
||||
raise CommandErrorException(
|
||||
f"{self.hostname}: no wifi-iface carries the SSID {ssid_name!r}"
|
||||
)
|
||||
changes: list[str] = []
|
||||
for sec in sections:
|
||||
ssid_val = self._send_command(f"uci -q get {sec}.ssid 2>/dev/null || true").strip()
|
||||
if ssid_val != ssid_name:
|
||||
continue
|
||||
if effective_mode == "off":
|
||||
self._send_command(f"uci -q delete {sec}.macfilter || true")
|
||||
self._send_command(f"uci -q delete {sec}.maclist || true")
|
||||
continue
|
||||
uci_mode = "allow" if effective_mode == "whitelist" else "deny"
|
||||
self._send_command(f"uci set {sec}.macfilter='{uci_mode}'")
|
||||
self._send_command(f"uci delete {sec}.maclist 2>/dev/null || true")
|
||||
for mac in macs:
|
||||
self._send_command(f"uci add_list {sec}.maclist='{mac}'")
|
||||
self._send_command("uci commit wireless")
|
||||
self._send_command("wifi reload")
|
||||
changes += _mac_acl_changes(sec, effective_mode, macs)
|
||||
self._uci_apply(_WIRELESS, changes, _WIFI_RELOAD)
|
||||
|
||||
def get_radio_status(self) -> dict[str, Any]:
|
||||
"""Return radio status from UCI and iwinfo.
|
||||
|
||||
@@ -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
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@@ -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)
|
||||
Reference in new issue
Block a user