feat(access-point): SSID settings, radio channels, VLAN names, the AP configuration and DHCP leases through declared methods (NetOrk/netork#695)
push_ssid_config, set_radio_channels and set_vlan_name run as checked uci steps (#35): a refused step raises naming itself and reverts what was staged. set_radio_channels replaces the undeclared push_radio_channel. apply_ap_config takes napalm-device-types' ApConfigDict and the parts the caller found different and writes them as one detached script: the builder netOrk had in _uci_builders.py, moved here. It answers which parts it wrote and which it could not, whether the AP restarts, and the script with every passphrase masked. A passphrase part now writes the key. get_dhcp_leases reads dnsmasq's lease file. Needs napalm-device-types 4.54.0; CI pre-installs it from its branch until it is on PyPI.
This commit is contained in:
1 parent
dd3e3f1543
commit
634bc9c793
18 files changed
+2108
-40
No files matched your search
@@ -0,0 +1,552 @@
|
||||
"""``apply_ap_config``: an access point's desired configuration as one UCI script (NetOrk/netork#695).
|
||||
|
||||
netOrk built this script itself, from its AP profile, and uploaded it through the
|
||||
driver's ``run_command``. The builders moved here unchanged in what they write; what
|
||||
comes in is napalm-device-types' ``ApConfigDict`` and the parts the caller found
|
||||
different. ``uci -q show wireless`` is the shape of ``test_wireless_writes``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
from napalm_device_types import ApConfigDict, ApSsidConfigDict, CommandResult
|
||||
|
||||
from napalm_openwrt.ap_config import MASK, build_script, masked
|
||||
from napalm_openwrt.ap_config._common import Radios, radios_of
|
||||
from napalm_openwrt.uci_steps import parse_uci_show
|
||||
from tests.unit.test_wireless_writes import SHOW, WIRELESS, _driver
|
||||
|
||||
RADIOS = Radios(r5g="radio1", r2g="radio0")
|
||||
PSK = "correct horse battery"
|
||||
|
||||
|
||||
def _ssid(**fields: object) -> ApSsidConfigDict:
|
||||
ssid: dict[str, object] = {
|
||||
"name": "Corp",
|
||||
"vlan_id": 30,
|
||||
"bands": ["2.4 GHz", "5 GHz"],
|
||||
"encryption": "psk2",
|
||||
"key": PSK,
|
||||
"hidden": False,
|
||||
"enabled": True,
|
||||
"client_isolation": False,
|
||||
"max_clients": None,
|
||||
"disassoc_low_ack": None,
|
||||
"max_inactivity": None,
|
||||
"acl_mode": "off",
|
||||
"acl_macs": [],
|
||||
"fast_transition": False,
|
||||
}
|
||||
ssid.update(fields)
|
||||
return ssid # type: ignore[return-value]
|
||||
|
||||
|
||||
def _config(**fields: object) -> ApConfigDict:
|
||||
config: dict[str, object] = {
|
||||
"country_code": "DE",
|
||||
"htmode_5g": "VHT80",
|
||||
"htmode_2g": "HT20",
|
||||
"syslog_host": "192.0.2.10",
|
||||
"syslog_port": 1514,
|
||||
"web_ui": True,
|
||||
"ssh_port": 22,
|
||||
"ssh_password_auth": False,
|
||||
"management_vlan_id": 10,
|
||||
"management_untagged": False,
|
||||
"bridge_stp": True,
|
||||
"mobility_domain": "a1b2",
|
||||
"ft_over_ds": True,
|
||||
"ssids": [_ssid()],
|
||||
}
|
||||
config.update(fields)
|
||||
return config # type: ignore[return-value]
|
||||
|
||||
|
||||
def _build(parts: list[str], config: ApConfigDict | None = None, radios: Radios = RADIOS):
|
||||
script, applied, skipped, restarts = build_script(config or _config(), parts, radios)
|
||||
return script, applied, skipped, restarts
|
||||
|
||||
|
||||
def _script(parts: list[str], config: ApConfigDict | None = None, radios: Radios = RADIOS) -> str:
|
||||
return _build(parts, config, radios)[0]
|
||||
|
||||
|
||||
# -- the radios --------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_the_radios_are_found_by_their_band():
|
||||
assert radios_of(parse_uci_show(WIRELESS)) == Radios(r5g="radio1", r2g="radio0")
|
||||
|
||||
|
||||
def test_the_old_hwmode_names_the_band_too():
|
||||
text = "wireless.wl0=wifi-device\nwireless.wl0.hwmode='11a'\n"
|
||||
assert radios_of(parse_uci_show(text)) == Radios(r5g="wl0", r2g=None)
|
||||
|
||||
|
||||
# -- radio and system parts --------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_the_country_goes_to_both_radios():
|
||||
script = _script(["radio/country"])
|
||||
assert "uci set wireless.radio1.country='DE'" in script
|
||||
assert "uci set wireless.radio0.country='DE'" in script
|
||||
|
||||
|
||||
def test_the_country_goes_to_the_radios_there_are():
|
||||
script = _script(["radio/country"], radios=Radios(r2g="radio0"))
|
||||
assert "uci set wireless.radio0.country='DE'" in script
|
||||
assert "radio1" not in script
|
||||
|
||||
|
||||
def test_each_htmode_goes_to_its_radio():
|
||||
script = _script(["radio/5g_htmode", "radio/2g_htmode"])
|
||||
assert "uci set wireless.radio1.htmode='VHT80'" in script
|
||||
assert "uci set wireless.radio0.htmode='HT20'" in script
|
||||
|
||||
|
||||
def test_an_htmode_without_its_radio_is_skipped():
|
||||
_, applied, skipped, _ = _build(["radio/5g_htmode"], radios=Radios(r2g="radio0"))
|
||||
assert (applied, skipped) == ([], ["radio/5g_htmode"])
|
||||
|
||||
|
||||
def test_remote_syslog():
|
||||
script = _script(["system/syslog"])
|
||||
assert "uci set system.@system[0].log_ip='192.0.2.10'" in script
|
||||
assert "uci set system.@system[0].log_port='1514'" in script
|
||||
assert "uci set system.@system[0].log_remote='1'" in script
|
||||
|
||||
|
||||
def test_remote_syslog_defaults_to_port_514():
|
||||
assert "log_port='514'" in _script(["system/syslog"], _config(syslog_port=None))
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("on", "line"),
|
||||
[
|
||||
(True, "/etc/init.d/uhttpd enable && /etc/init.d/uhttpd start"),
|
||||
(False, "/etc/init.d/uhttpd stop; /etc/init.d/uhttpd disable"),
|
||||
],
|
||||
)
|
||||
def test_the_web_interface_is_the_service_state(on, line):
|
||||
assert line in _script(["system/web_ui"], _config(web_ui=on))
|
||||
|
||||
|
||||
def test_the_ssh_port():
|
||||
assert "uci set dropbear.@dropbear[0].Port='2222'" in _script(
|
||||
["system/ssh_port"], _config(ssh_port=2222)
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("allowed", "value"), [(True, "on"), (False, "off")])
|
||||
def test_password_logins(allowed, value):
|
||||
script = _script(["system/password_auth"], _config(ssh_password_auth=allowed))
|
||||
assert f"uci set dropbear.@dropbear[0].PasswordAuth='{value}'" in script
|
||||
assert f"uci set dropbear.@dropbear[0].RootPasswordAuth='{value}'" in script
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("part", "missing"),
|
||||
[
|
||||
("system/syslog", "syslog_host"),
|
||||
("system/web_ui", "web_ui"),
|
||||
("system/ssh_port", "ssh_port"),
|
||||
("system/password_auth", "ssh_password_auth"),
|
||||
("radio/country", "country_code"),
|
||||
],
|
||||
)
|
||||
def test_a_part_without_its_value_is_skipped(part, missing):
|
||||
config = _config()
|
||||
del config[missing] # type: ignore[misc]
|
||||
script, applied, skipped, _ = _build([part], config)
|
||||
assert (script, applied, skipped) == ("", [], [part])
|
||||
|
||||
|
||||
# -- network parts -----------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _ports(script: str, vid: int) -> str:
|
||||
line = next(c for c in script.splitlines() if f"apbr_vlan_{vid}.ports=" in c)
|
||||
return line.split("=", 1)[1]
|
||||
|
||||
|
||||
def test_the_bridge_trunks_every_vlan_tagged_by_default():
|
||||
script = _script(["network/bridge"])
|
||||
assert _ports(script, 10) == "'eth0:t'"
|
||||
assert _ports(script, 30) == "'eth0:t'"
|
||||
|
||||
|
||||
def test_the_management_vlan_untagged_when_asked():
|
||||
script = _script(["network/bridge"], _config(management_untagged=True))
|
||||
assert _ports(script, 10) == "'eth0:u*'"
|
||||
assert _ports(script, 30) == "'eth0:t'"
|
||||
|
||||
|
||||
def test_the_bridge_drops_foreign_vlan_sections_before_its_first_vlan():
|
||||
lines = _script(["network/bridge"]).split("\n")
|
||||
purge = lines.index(" uci delete network.@bridge-vlan[$n]")
|
||||
first = next(i for i, c in enumerate(lines) if "network.apbr_vlan_10=bridge-vlan" in c)
|
||||
assert purge < first
|
||||
|
||||
|
||||
def test_the_bridge_puts_the_networks_into_the_lan_zone():
|
||||
script = _script(["network/bridge"])
|
||||
assert "for net in $_mgmt_sec ap_vlan30; do" in script
|
||||
assert "uci set network.ap_vlan30.device='br-ap.30'" in script
|
||||
|
||||
|
||||
def test_the_bridge_restarts_the_ap_and_reloads_nothing():
|
||||
script, applied, _, restarts = _build(["network/bridge", "network/vlan/30"])
|
||||
lines = script.split("\n")
|
||||
assert restarts is True
|
||||
assert applied == ["network/bridge", "network/vlan/30"]
|
||||
assert lines[-1] == "reboot"
|
||||
assert "uci commit network" in lines
|
||||
assert not any(line.startswith(("wifi reload", "/etc/init.d/network")) for line in lines)
|
||||
|
||||
|
||||
def test_a_vlan_of_a_rebuilt_bridge_writes_nothing_of_its_own():
|
||||
script = _script(["network/bridge", "network/vlan/30"])
|
||||
assert "_found=$_i; break" not in script
|
||||
|
||||
|
||||
def test_one_vlan_reuses_the_section_that_carries_it():
|
||||
script = _script(["network/vlan/30"])
|
||||
assert "uci set network.@bridge-vlan[$_found].ports='eth0:t'" in script
|
||||
assert "uci set network.apbr_vlan_30=bridge-vlan" in script
|
||||
assert "uci set network.ap_vlan30.device='br-ap.30'" in script
|
||||
assert "uci delete network.@bridge-vlan[$n]" not in script
|
||||
|
||||
|
||||
def test_the_management_vlan_untagged_on_its_own():
|
||||
script = _script(["network/vlan/10"], _config(management_untagged=True))
|
||||
assert "uci set network.@bridge-vlan[$_found].ports='eth0:u*'" in script
|
||||
assert "uci set network.mgmt.device='br-ap.10'" in script
|
||||
|
||||
|
||||
def test_spanning_tree_on_the_section_named_br_ap():
|
||||
script = _script(["network/bridge_stp"], _config(bridge_stp=False))
|
||||
assert "= 'br-ap' ] || continue" in script
|
||||
assert "uci set network.$_s.stp='0'" in script
|
||||
|
||||
|
||||
# -- wireless parts ----------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _with(**fields: object) -> ApConfigDict:
|
||||
return _config(ssids=[_ssid(**fields)])
|
||||
|
||||
|
||||
def test_a_whitelist_sets_allow_and_rebuilds_the_list():
|
||||
script = _script(
|
||||
["wireless/Corp/acl"], _with(acl_mode="whitelist", acl_macs=["AA:BB:CC:DD:EE:02"])
|
||||
)
|
||||
assert "uci set $_s.macfilter='allow'" in script
|
||||
assert script.index("uci -q delete $_s.maclist") < script.index("uci add_list $_s.maclist")
|
||||
|
||||
|
||||
def test_a_blacklist_sets_deny_even_empty():
|
||||
script = _script(["wireless/Corp/acl"], _with(acl_mode="blacklist", acl_macs=[]))
|
||||
assert "uci set $_s.macfilter='deny'" in script
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("mode", "macs"), [("off", ["AA:BB:CC:DD:EE:02"]), ("whitelist", [])])
|
||||
def test_off_and_an_empty_whitelist_delete_the_filter(mode, macs):
|
||||
"""``macfilter='disable'`` puts netifd in a restart loop; off is the option left out."""
|
||||
script = _script(["wireless/Corp/acl"], _with(acl_mode=mode, acl_macs=macs))
|
||||
assert "uci -q delete $_s.macfilter" in script
|
||||
assert "macfilter='" not in script
|
||||
|
||||
|
||||
def test_a_missing_ssid_is_created_on_each_band_with_its_key():
|
||||
script = _script(["wireless/Corp/missing"])
|
||||
assert script.count("uci add wireless wifi-iface") == 2
|
||||
assert "uci set wireless.@wifi-iface[-1].device='radio0'" in script
|
||||
assert "uci set wireless.@wifi-iface[-1].network='ap_vlan30'" in script
|
||||
assert f"uci set wireless.@wifi-iface[-1].key='{PSK}'" in script
|
||||
|
||||
|
||||
def test_an_open_ssid_is_created_without_a_key():
|
||||
script = _script(["wireless/Corp/missing"], _with(encryption="none", key=""))
|
||||
assert "encryption='none'" in script
|
||||
assert ".key=" not in script
|
||||
|
||||
|
||||
@pytest.mark.parametrize("attribute", ["missing", "bands", "encryption"])
|
||||
def test_a_keyed_mode_without_its_key_is_not_written(attribute):
|
||||
"""Off the air with the mode alone, unprotected with ``none``: skipped instead."""
|
||||
config = _config(ssids=[{**_ssid(), "key": ""}])
|
||||
script, applied, skipped, _ = _build([f"wireless/Corp/{attribute}"], config)
|
||||
assert (script, applied, skipped) == ("", [], [f"wireless/Corp/{attribute}"])
|
||||
|
||||
|
||||
def test_the_bands_take_the_ssid_off_a_radio_and_add_it_where_missing():
|
||||
script = _script(["wireless/Corp/bands"], _with(bands=["5 GHz"]))
|
||||
assert "= 'radio0' ] || continue\n uci delete $_s" in script
|
||||
assert "if [ $_found = 0 ]; then\n uci add wireless wifi-iface" in script
|
||||
assert " uci set wireless.@wifi-iface[-1].device='radio1'" in script
|
||||
|
||||
|
||||
def test_the_encryption_with_its_key():
|
||||
script = _script(["wireless/Corp/encryption"])
|
||||
assert "uci set $_s.encryption='psk2'" in script
|
||||
assert f"uci set $_s.key='{PSK}'" in script
|
||||
|
||||
|
||||
def test_switching_encryption_off_needs_no_key():
|
||||
script = _script(["wireless/Corp/encryption"], _with(encryption="none", key=""))
|
||||
assert "uci set $_s.encryption='none'" in script
|
||||
assert ".key=" not in script
|
||||
|
||||
|
||||
def test_the_passphrase_alone():
|
||||
script = _script(["wireless/Corp/passphrase"])
|
||||
assert f"uci set $_s.key='{PSK}'" in script
|
||||
assert ".encryption=" not in script
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("attribute", "fields", "line"),
|
||||
[
|
||||
("hidden", {"hidden": True}, "uci set $_s.hidden='1'"),
|
||||
("enabled", {"enabled": False}, "uci set $_s.disabled='1'"),
|
||||
("enabled", {"enabled": True}, "uci set $_s.disabled='0'"),
|
||||
("client_isolation", {"client_isolation": True}, "uci set $_s.isolate='1'"),
|
||||
("max_clients", {"max_clients": 32}, "uci set $_s.maxassoc='32'"),
|
||||
("max_clients", {"max_clients": None}, "uci -q delete $_s.maxassoc 2>/dev/null; true"),
|
||||
("disassoc_low_ack", {"disassoc_low_ack": False}, "uci set $_s.disassoc_low_ack='0'"),
|
||||
("max_inactivity", {"max_inactivity": 300}, "uci set $_s.max_inactivity='300'"),
|
||||
("vlan", {"vlan_id": 40}, "uci set $_s.network='ap_vlan40'"),
|
||||
],
|
||||
)
|
||||
def test_one_setting_of_an_ssid(attribute, fields, line):
|
||||
assert line in _script([f"wireless/Corp/{attribute}"], _with(**fields))
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("attribute", "fields"),
|
||||
[
|
||||
("disassoc_low_ack", {"disassoc_low_ack": None}),
|
||||
("max_inactivity", {"max_inactivity": None}),
|
||||
("vlan", {"vlan_id": None}),
|
||||
],
|
||||
)
|
||||
def test_a_setting_left_to_the_device_is_skipped(attribute, fields):
|
||||
_, applied, skipped, _ = _build([f"wireless/Corp/{attribute}"], _with(**fields))
|
||||
assert (applied, skipped) == ([], [f"wireless/Corp/{attribute}"])
|
||||
|
||||
|
||||
def test_fast_transition_off_removes_it_without_a_domain():
|
||||
script = _script(["wireless/Corp/ft"], _config(mobility_domain="", ssids=[_ssid()]))
|
||||
assert "uci -q delete $_s.ieee80211r" in script
|
||||
assert "uci -q delete $_s.mobility_domain" in script
|
||||
|
||||
|
||||
def test_fast_transition_on_sets_the_domain():
|
||||
script = _script(["wireless/Corp/ft"], _with(fast_transition=True))
|
||||
assert "uci set $_s.ieee80211r='1'" in script
|
||||
assert "uci set $_s.mobility_domain='a1b2'" in script
|
||||
assert "uci set $_s.ft_over_ds='1'" in script
|
||||
|
||||
|
||||
def test_fast_transition_on_without_a_domain_is_skipped():
|
||||
config = _config(mobility_domain="", ssids=[_ssid(fast_transition=True)])
|
||||
assert _build(["wireless/Corp/ft"], config)[2] == ["wireless/Corp/ft"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"part", ["wireless/Nobody/hidden", "system/luci", "wireless/Corp/extra/x", "radio/power"]
|
||||
)
|
||||
def test_a_part_the_driver_cannot_write_is_skipped(part):
|
||||
assert _build([part]) == ("", [], [part], False)
|
||||
|
||||
|
||||
# -- the script --------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_commits_come_before_the_reloads_network_first():
|
||||
lines = _script(["system/ssh_port", "wireless/Corp/hidden", "network/vlan/30"]).split("\n")
|
||||
assert lines[0] == "#!/bin/sh"
|
||||
last_commit = max(i for i, c in enumerate(lines) if c.startswith("uci commit "))
|
||||
assert lines[last_commit - 2 : last_commit + 1] == [
|
||||
"uci commit dropbear",
|
||||
"uci commit network",
|
||||
"uci commit wireless",
|
||||
]
|
||||
assert lines[last_commit + 1 :] == [
|
||||
"/etc/init.d/network reload 2>/dev/null; true",
|
||||
"wifi reload 2>&1; true",
|
||||
"/etc/init.d/dropbear restart 2>/dev/null; true",
|
||||
]
|
||||
|
||||
|
||||
def test_the_system_reload_restarts_logd():
|
||||
assert "/etc/init.d/log restart 2>/dev/null; true" in _script(["system/syslog"])
|
||||
|
||||
|
||||
def test_nothing_to_write_is_no_script():
|
||||
assert _build([]) == ("", [], [], False)
|
||||
|
||||
|
||||
def test_every_passphrase_is_masked():
|
||||
script = _script(["wireless/Corp/encryption"])
|
||||
shown = masked(script, _config())
|
||||
assert PSK not in shown
|
||||
assert f"uci set $_s.key={MASK}" in shown
|
||||
|
||||
|
||||
# -- values reach uci as they are (NetOrk/netork#1463) -----------------------------------------
|
||||
|
||||
NASTY = [
|
||||
"Bob's WiFi",
|
||||
"a'; touch pwned; echo 'b",
|
||||
'$(id) `id` "quoted"',
|
||||
"semi;colon && pipe | back\\slash",
|
||||
]
|
||||
|
||||
|
||||
def _fake_uci(ssid: str) -> str:
|
||||
"""A shell ``uci`` that knows one interface with *ssid* and logs every set/add_list."""
|
||||
quoted = "'" + ssid.replace("'", "'\"'\"'") + "'"
|
||||
return (
|
||||
"uci() {\n"
|
||||
' case "$1" in\n'
|
||||
' show) echo "wireless.default_radio0.ssid=x" ;;\n'
|
||||
f' -q) [ "$3" = "wireless.default_radio0.ssid" ] && printf %s {quoted} ;;\n'
|
||||
' set|add_list) printf \'%s\\n\' "$2" >> "$LOG" ;;\n'
|
||||
" esac\n"
|
||||
"}\n"
|
||||
)
|
||||
|
||||
|
||||
def _run(command: str, ssid: str, tmp_path) -> list[str]:
|
||||
log = tmp_path / "uci.log"
|
||||
log.touch()
|
||||
subprocess.run( # nosec B603 - a fixed /bin/sh on the test's own text
|
||||
["/bin/sh", "-c", _fake_uci(ssid) + command],
|
||||
env={"LOG": str(log), "PATH": "/usr/bin:/bin"},
|
||||
check=True,
|
||||
cwd=tmp_path,
|
||||
)
|
||||
return log.read_text().splitlines()
|
||||
|
||||
|
||||
def _loop(script: str) -> str:
|
||||
"""The ssid loop of a one-part script: between the shebang and the commits."""
|
||||
lines = script.split("\n")
|
||||
end = next(i for i, c in enumerate(lines) if c.startswith("uci commit"))
|
||||
return "\n".join(lines[1:end])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", NASTY)
|
||||
def test_a_passphrase_arrives_as_it_is(value, tmp_path):
|
||||
script = _script(["wireless/Home/encryption"], _config(ssids=[_ssid(name="Home", key=value)]))
|
||||
assert _run(_loop(script), "Home", tmp_path) == [
|
||||
"wireless.default_radio0.encryption=psk2",
|
||||
f"wireless.default_radio0.key={value}",
|
||||
]
|
||||
assert not (tmp_path / "pwned").exists()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", NASTY)
|
||||
def test_an_ssid_name_is_matched_as_it_is(value, tmp_path):
|
||||
script = _script([f"wireless/{value}/hidden"], _config(ssids=[_ssid(name=value, hidden=True)]))
|
||||
assert _run(_loop(script), value, tmp_path) == ["wireless.default_radio0.hidden=1"]
|
||||
|
||||
|
||||
def test_a_mac_arrives_as_it_is(tmp_path):
|
||||
mac = "AA:BB:CC:DD:EE:01'; touch pwned; echo '"
|
||||
config = _config(ssids=[_ssid(name="Home", acl_mode="whitelist", acl_macs=[mac])])
|
||||
script = _script(["wireless/Home/acl"], config)
|
||||
assert _run(_loop(script), "Home", tmp_path)[-1] == f"wireless.default_radio0.maclist={mac}"
|
||||
assert not (tmp_path / "pwned").exists()
|
||||
|
||||
|
||||
# -- apply_ap_config ---------------------------------------------------------------------------
|
||||
|
||||
WORKDIR = "/tmp/openwrt-apply.Ab12Cd"
|
||||
|
||||
|
||||
class _ApplyAp:
|
||||
"""``run_command`` of an AP that answers the read and makes the work directory."""
|
||||
|
||||
def __init__(self, made: str = WORKDIR, write: CommandResult | None = None) -> None:
|
||||
self.made, self.write = made, write
|
||||
self.calls: list[tuple[str, bytes | None]] = []
|
||||
|
||||
def __call__(
|
||||
self,
|
||||
command: str,
|
||||
*,
|
||||
privileged: bool = False,
|
||||
timeout: float = 60,
|
||||
stdin: bytes | None = None,
|
||||
) -> CommandResult:
|
||||
self.calls.append((command, stdin))
|
||||
if command == SHOW:
|
||||
return CommandResult(WIRELESS, "", 0)
|
||||
if "mktemp -d" in command:
|
||||
return self.write or CommandResult(self.made + "\n", "", 0)
|
||||
return CommandResult("", "", 0)
|
||||
|
||||
|
||||
def test_the_script_is_written_from_stdin_into_a_fresh_directory_then_run_detached():
|
||||
ap = _ApplyAp()
|
||||
result = _driver(ap).apply_ap_config(_config(), ["radio/country", "wireless/Corp/encryption"])
|
||||
|
||||
(read, _), (write, script), (run, _) = ap.calls
|
||||
assert read == SHOW
|
||||
assert write.startswith("umask 077 && d=$(mktemp -d /tmp/openwrt-apply.XXXXXX)")
|
||||
assert script is not None and f"key='{PSK}'".encode() in script
|
||||
assert run == (
|
||||
f"( sh {WORKDIR}/apply.sh > {WORKDIR}/apply.log 2>&1 < /dev/null; "
|
||||
f"rm -f {WORKDIR}/apply.sh ) &"
|
||||
)
|
||||
assert result["applied"] == ["radio/country", "wireless/Corp/encryption"]
|
||||
assert result["skipped"] == []
|
||||
assert result["restarts"] is False
|
||||
assert result["log"] == f"{WORKDIR}/apply.log"
|
||||
assert (
|
||||
PSK not in result["commands"]
|
||||
and "uci set wireless.radio1.country='DE'" in result["commands"]
|
||||
)
|
||||
|
||||
|
||||
def test_nothing_to_write_sends_only_the_read():
|
||||
ap = _ApplyAp()
|
||||
result = _driver(ap).apply_ap_config(_config(), ["system/luci"])
|
||||
|
||||
assert [c for c, _ in ap.calls] == [SHOW]
|
||||
assert result == {
|
||||
"applied": [],
|
||||
"skipped": ["system/luci"],
|
||||
"restarts": False,
|
||||
"commands": "",
|
||||
"log": "",
|
||||
}
|
||||
|
||||
|
||||
def test_a_failed_write_runs_nothing():
|
||||
ap = _ApplyAp(write=CommandResult("", "mktemp: No space left on device\n", 1))
|
||||
with pytest.raises(RuntimeError, match="No space left"):
|
||||
_driver(ap).apply_ap_config(_config(), ["radio/country"])
|
||||
|
||||
assert len(ap.calls) == 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize("made", ["", "/tmp/provision.sh", "/tmp/openwrt-apply.XXXXXX; reboot"])
|
||||
def test_no_fresh_directory_reported_runs_nothing(made):
|
||||
ap = _ApplyAp(made=made)
|
||||
with pytest.raises(RuntimeError, match="no work directory"):
|
||||
_driver(ap).apply_ap_config(_config(), ["radio/country"])
|
||||
|
||||
assert len(ap.calls) == 2
|
||||
|
||||
|
||||
def test_a_bridge_rebuild_says_the_ap_restarts():
|
||||
ap = _ApplyAp()
|
||||
result = _driver(ap).apply_ap_config(_config(), ["network/bridge"])
|
||||
|
||||
assert result["restarts"] is True
|
||||
assert result["commands"].endswith("\nreboot")
|
||||
@@ -0,0 +1,177 @@
|
||||
"""``push_ssid_config`` and ``set_vlan_name`` (NetOrk/netork#695).
|
||||
|
||||
netOrk wrote both itself, as UCI through the driver's ``cli()``, and never looked at
|
||||
what came back. Here each is a checked step (NAPALM/napalm-openwrt#35): a refused one
|
||||
raises and reverts what was staged.
|
||||
|
||||
``uci -q show wireless`` is the shape of ``test_wireless_writes``; ``uci -q show
|
||||
network`` the shape OpenWrt 23.05 prints a DSA bridge in, with one anonymous and one
|
||||
named ``bridge-vlan`` section.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from napalm.base.exceptions import CommandErrorException
|
||||
from napalm_device_types import CommandResult
|
||||
|
||||
from tests.unit.test_wireless_writes import INVALID_ARGUMENT, SHOW, _Ap, _driver, _uci
|
||||
|
||||
SHOW_NETWORK = "uci -q show network"
|
||||
|
||||
NETWORK = """\
|
||||
network.loopback=interface
|
||||
network.loopback.device='lo'
|
||||
network.loopback.proto='static'
|
||||
network.apbr=device
|
||||
network.apbr.name='br-ap'
|
||||
network.apbr.type='bridge'
|
||||
network.apbr.ports='eth0'
|
||||
network.apbr.vlan_filtering='1'
|
||||
network.@bridge-vlan[0]=bridge-vlan
|
||||
network.@bridge-vlan[0].device='br-ap'
|
||||
network.@bridge-vlan[0].vlan='10'
|
||||
network.@bridge-vlan[0].ports='eth0:u*'
|
||||
network.apbr_vlan_20=bridge-vlan
|
||||
network.apbr_vlan_20.device='br-ap'
|
||||
network.apbr_vlan_20.vlan='20'
|
||||
network.apbr_vlan_20.ports='eth0:t'
|
||||
network.apbr_vlan_20.name='Guests'
|
||||
"""
|
||||
|
||||
|
||||
class _NetAp(_Ap):
|
||||
def __call__(self, command: str, **kwargs: object) -> CommandResult: # type: ignore[override]
|
||||
if command == SHOW_NETWORK and command not in self.refuse:
|
||||
self.commands.append(command)
|
||||
return CommandResult(NETWORK, "", 0)
|
||||
return super().__call__(command, **kwargs) # type: ignore[arg-type]
|
||||
|
||||
|
||||
# -- push_ssid_config --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_each_setting_is_written_to_every_section_with_the_ssid_then_wifi_reloads():
|
||||
ap = _Ap()
|
||||
_driver(ap).push_ssid_config(
|
||||
"CorpWiFi", {"hidden": True, "enabled": False, "max_inactivity": 300}
|
||||
)
|
||||
|
||||
assert ap.commands == [
|
||||
SHOW,
|
||||
_uci("set", "wireless.default_radio0.hidden=1"),
|
||||
_uci("set", "wireless.default_radio0.disabled=1"),
|
||||
_uci("set", "wireless.default_radio0.max_inactivity=300"),
|
||||
_uci("set", "wireless.default_radio1.hidden=1"),
|
||||
_uci("set", "wireless.default_radio1.disabled=1"),
|
||||
_uci("set", "wireless.default_radio1.max_inactivity=300"),
|
||||
_uci("commit", "wireless"),
|
||||
"wifi reload",
|
||||
]
|
||||
|
||||
|
||||
def test_encryption_and_key_are_written_as_given():
|
||||
"""Whether a keyed mode may go without its key is the caller's policy, not the driver's."""
|
||||
ap = _Ap()
|
||||
_driver(ap).push_ssid_config(
|
||||
"Bob's Guest", {"encryption": "sae", "key": "it's a secret", "disassoc_low_ack": False}
|
||||
)
|
||||
|
||||
assert ap.commands[1:4] == [
|
||||
_uci("set", "wireless.guest.encryption=sae"),
|
||||
_uci("set", "wireless.guest.key=it's a secret"),
|
||||
_uci("set", "wireless.guest.disassoc_low_ack=0"),
|
||||
]
|
||||
|
||||
|
||||
def test_enabled_is_written_as_disabled_off():
|
||||
ap = _Ap()
|
||||
_driver(ap).push_ssid_config("Bob's Guest", {"enabled": True})
|
||||
|
||||
assert _uci("set", "wireless.guest.disabled=0") in ap.commands
|
||||
|
||||
|
||||
def test_an_empty_config_sends_nothing():
|
||||
ap = _Ap()
|
||||
_driver(ap).push_ssid_config("CorpWiFi", {})
|
||||
|
||||
assert ap.commands == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"config",
|
||||
[
|
||||
{"colour": "blue"},
|
||||
{"max_inactivity": -1},
|
||||
{"max_inactivity": "300"},
|
||||
{"max_inactivity": True},
|
||||
],
|
||||
)
|
||||
def test_a_setting_the_ap_cannot_take_raises_before_anything_is_sent(config):
|
||||
ap = _Ap()
|
||||
with pytest.raises(ValueError):
|
||||
_driver(ap).push_ssid_config("CorpWiFi", config) # type: ignore[arg-type]
|
||||
|
||||
assert ap.commands == []
|
||||
|
||||
|
||||
def test_an_ssid_no_section_carries_raises_and_writes_nothing():
|
||||
ap = _Ap()
|
||||
with pytest.raises(CommandErrorException, match="no wifi-iface carries the SSID 'Nobody'"):
|
||||
_driver(ap).push_ssid_config("Nobody", {"hidden": True})
|
||||
|
||||
assert ap.commands == [SHOW]
|
||||
|
||||
|
||||
def test_a_refused_step_raises_reverts_and_does_not_reload():
|
||||
refused = _uci("set", "wireless.default_radio1.hidden=1")
|
||||
ap = _Ap({refused: INVALID_ARGUMENT})
|
||||
with pytest.raises(CommandErrorException, match="Invalid argument"):
|
||||
_driver(ap).push_ssid_config("CorpWiFi", {"hidden": True})
|
||||
|
||||
assert ap.commands[-2:] == [refused, _uci("revert", "wireless")]
|
||||
assert "wifi reload" not in ap.commands
|
||||
|
||||
|
||||
# -- set_vlan_name -----------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_a_vlan_name_is_set_on_its_bridge_vlan_and_committed():
|
||||
"""A label only: nothing restarts for it."""
|
||||
ap = _NetAp()
|
||||
assert _driver(ap).set_vlan_name(10, "Staff 'A'") is True
|
||||
|
||||
assert ap.commands == [
|
||||
SHOW_NETWORK,
|
||||
_uci("set", "network.@bridge-vlan[0].name=Staff 'A'"),
|
||||
_uci("commit", "network"),
|
||||
]
|
||||
|
||||
|
||||
def test_a_named_section_is_renamed_in_place():
|
||||
ap = _NetAp()
|
||||
assert _driver(ap).set_vlan_name(20, "Visitors") is True
|
||||
|
||||
assert _uci("set", "network.apbr_vlan_20.name=Visitors") in ap.commands
|
||||
|
||||
|
||||
def test_a_vlan_the_ap_does_not_carry_is_false_and_writes_nothing():
|
||||
ap = _NetAp()
|
||||
assert _driver(ap).set_vlan_name(30, "IoT") is False
|
||||
|
||||
assert ap.commands == [SHOW_NETWORK]
|
||||
|
||||
|
||||
def test_a_refused_name_raises_and_reverts():
|
||||
refused = _uci("set", "network.@bridge-vlan[0].name=Staff")
|
||||
ap = _NetAp({refused: INVALID_ARGUMENT})
|
||||
with pytest.raises(CommandErrorException, match="Invalid argument"):
|
||||
_driver(ap).set_vlan_name(10, "Staff")
|
||||
|
||||
assert ap.commands[-1] == _uci("revert", "network")
|
||||
|
||||
|
||||
def test_a_failed_read_raises():
|
||||
ap = _NetAp({SHOW_NETWORK: CommandResult("", "uci: Entry not found\n", 1)})
|
||||
with pytest.raises(CommandErrorException, match="Entry not found"):
|
||||
_driver(ap).set_vlan_name(10, "Staff")
|
||||
@@ -0,0 +1,84 @@
|
||||
"""``get_dhcp_leases``: dnsmasq's lease file (NetOrk/netork#695).
|
||||
|
||||
The text is dnsmasq 2.90's lease file on OpenWrt 23.05, anonymised: two DHCPv4 leases
|
||||
(one without a hostname, one that does not end), then the DHCPv6 part after its
|
||||
``duid`` line.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from napalm.base.exceptions import CommandErrorException
|
||||
from napalm_device_types import CommandResult
|
||||
|
||||
from napalm_openwrt.dhcp_leases_mixin import LEASES_COMMAND, parse_dnsmasq_leases
|
||||
from tests.unit.test_wireless_writes import _driver
|
||||
|
||||
LEASES = """\
|
||||
1764432000 00:00:5e:00:53:01 192.0.2.42 laptop 01:00:00:5e:00:53:01
|
||||
1764435600 00:00:5E:00:53:02 192.0.2.43 * *
|
||||
0 00:00:5e:00:53:03 192.0.2.44 printer *
|
||||
duid 00:01:00:01:2c:5e:9a:10:00:00:5e:00:53:ff
|
||||
1764432000 1234567 2001:db8::42 laptop 00:01:00:01:2c:5e:9a:11:00:00:5e:00:53:01
|
||||
"""
|
||||
|
||||
|
||||
def test_each_v4_lease_in_order():
|
||||
assert parse_dnsmasq_leases(LEASES) == [
|
||||
{
|
||||
"mac": "00:00:5e:00:53:01",
|
||||
"ip": "192.0.2.42",
|
||||
"hostname": "laptop",
|
||||
"lease_end": 1764432000,
|
||||
"state": "active",
|
||||
},
|
||||
{
|
||||
"mac": "00:00:5e:00:53:02",
|
||||
"ip": "192.0.2.43",
|
||||
"hostname": "",
|
||||
"lease_end": 1764435600,
|
||||
"state": "active",
|
||||
},
|
||||
{
|
||||
"mac": "00:00:5e:00:53:03",
|
||||
"ip": "192.0.2.44",
|
||||
"hostname": "printer",
|
||||
"lease_end": 0,
|
||||
"state": "active",
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("text", ["", "\n", "garbage\n", "x 00:00:5e:00:53:01 192.0.2.1 a *\n"])
|
||||
def test_nothing_that_is_no_lease(text):
|
||||
assert parse_dnsmasq_leases(text) == []
|
||||
|
||||
|
||||
class _Ap:
|
||||
def __init__(self, answer: CommandResult) -> None:
|
||||
self.answer = answer
|
||||
self.commands: list[str] = []
|
||||
|
||||
def __call__(self, command: str, **_: object) -> CommandResult:
|
||||
self.commands.append(command)
|
||||
return self.answer
|
||||
|
||||
|
||||
def test_the_driver_reads_the_lease_file_dnsmasq_is_set_to():
|
||||
ap = _Ap(CommandResult(LEASES, "", 0))
|
||||
leases = _driver(ap).get_dhcp_leases() # type: ignore[arg-type]
|
||||
|
||||
assert ap.commands == [LEASES_COMMAND]
|
||||
assert "uci -q get dhcp.@dnsmasq[0].leasefile" in LEASES_COMMAND
|
||||
assert [lease["ip"] for lease in leases] == ["192.0.2.42", "192.0.2.43", "192.0.2.44"]
|
||||
|
||||
|
||||
def test_an_ap_that_serves_no_leases_has_none():
|
||||
"""No lease file is no dnsmasq run since boot: an answer, not a failed read."""
|
||||
assert _driver(_Ap(CommandResult("", "", 0))).get_dhcp_leases() == [] # type: ignore[arg-type]
|
||||
|
||||
|
||||
def test_a_failed_read_raises():
|
||||
ap = _Ap(CommandResult("", "cat: can't open '/tmp/dhcp.leases': Permission denied\n", 1))
|
||||
with pytest.raises(CommandErrorException, match="Permission denied"):
|
||||
_driver(ap).get_dhcp_leases() # type: ignore[arg-type]
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Wireless writes: ``push_mac_acl`` and ``push_radio_channel`` (NAPALM/napalm-openwrt#35).
|
||||
"""Wireless writes: ``push_mac_acl`` and ``set_radio_channels`` (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
|
||||
@@ -248,13 +248,13 @@ def test_a_login_other_than_root_is_refused_before_anything_runs():
|
||||
drv.device.remote_conn_pre.get_transport.assert_not_called()
|
||||
|
||||
|
||||
# -- push_radio_channel ------------------------------------------------------------------------
|
||||
# -- set_radio_channels (NetOrk/netork#695) ---------------------------------------------------
|
||||
|
||||
|
||||
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)
|
||||
_driver(ap).set_radio_channels({"radio1": 44})
|
||||
|
||||
assert ap.commands == [
|
||||
_uci("set", "wireless.radio1.channel=44"),
|
||||
@@ -263,28 +263,71 @@ def test_a_channel_is_set_committed_and_wifi_restarted():
|
||||
]
|
||||
|
||||
|
||||
def test_every_radio_changes_in_one_commit_and_one_restart():
|
||||
ap = _Ap()
|
||||
_driver(ap).set_radio_channels({"radio0": 6, "radio1": 36})
|
||||
|
||||
assert ap.commands == [
|
||||
_uci("set", "wireless.radio0.channel=6"),
|
||||
_uci("set", "wireless.radio1.channel=36"),
|
||||
_uci("commit", "wireless"),
|
||||
"wifi",
|
||||
]
|
||||
|
||||
|
||||
def test_channel_zero_is_auto():
|
||||
ap = _Ap()
|
||||
_driver(ap).push_radio_channel("radio0", 0)
|
||||
_driver(ap).set_radio_channels({"radio0": 0})
|
||||
|
||||
assert ap.commands[0] == _uci("set", "wireless.radio0.channel=auto")
|
||||
|
||||
|
||||
def test_no_channels_send_nothing():
|
||||
ap = _Ap()
|
||||
_driver(ap).set_radio_channels({})
|
||||
|
||||
assert ap.commands == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"channels",
|
||||
[
|
||||
{"radio0; reboot": 6},
|
||||
{"wireless.radio0": 6},
|
||||
{"": 6},
|
||||
{"radio0": -1},
|
||||
{"radio0": "6"},
|
||||
{"radio0": True},
|
||||
],
|
||||
)
|
||||
def test_a_radio_or_channel_the_ap_cannot_take_raises_before_anything_is_sent(channels):
|
||||
ap = _Ap()
|
||||
with pytest.raises(ValueError):
|
||||
_driver(ap).set_radio_channels(channels)
|
||||
|
||||
assert ap.commands == []
|
||||
|
||||
|
||||
def test_a_refused_channel_raises_and_does_not_restart_wifi():
|
||||
"""The other radio's change is reverted with it: no radio changes."""
|
||||
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)
|
||||
_driver(ap).set_radio_channels({"radio0": 1, "radio9": 6})
|
||||
|
||||
assert refused in str(caught.value)
|
||||
assert "Invalid argument" in str(caught.value)
|
||||
assert ap.commands == [refused, _uci("revert", "wireless")]
|
||||
assert ap.commands == [
|
||||
_uci("set", "wireless.radio0.channel=1"),
|
||||
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)
|
||||
_driver(ap).set_radio_channels({"radio0": 6})
|
||||
|
||||
assert "wifi" not in ap.commands
|
||||
|
||||
@@ -292,7 +335,12 @@ def test_a_refused_channel_commit_does_not_restart_wifi():
|
||||
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)
|
||||
_driver(ap).set_radio_channels({"radio0": 6})
|
||||
|
||||
|
||||
def test_the_undeclared_channel_write_is_gone():
|
||||
"""``set_radio_channels`` replaces it; nothing calls a name the contract lacks."""
|
||||
assert not hasattr(OpenWrtDriver, "push_radio_channel")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mode", ["deny", "Blacklist", "disable", ""])
|
||||
|
||||
Reference in new issue
Block a user