fix(access-point): a change the AP refuses in apply_ap_config is raised, and nothing applied (#54)
driver / standard (pull_request) Successful in 16s
driver / lint (pull_request) Successful in 11s
driver / lowest (pull_request) Successful in 28s
driver / types (pull_request) Successful in 1m4s
driver / test (3.13) (pull_request) Successful in 54s
driver / test (3.12) (pull_request) Successful in 1m8s
driver / build (pull_request) Successful in 28s
driver / security (pull_request) Successful in 59s
CI / driver (pull_request) Successful in 2m8s
driver / publish (pull_request) Skipped
driver / standard (pull_request) Successful in 16s
driver / lint (pull_request) Successful in 11s
driver / lowest (pull_request) Successful in 28s
driver / types (pull_request) Successful in 1m4s
driver / test (3.13) (pull_request) Successful in 54s
driver / test (3.12) (pull_request) Successful in 1m8s
driver / build (pull_request) Successful in 28s
driver / security (pull_request) Successful in 59s
CI / driver (pull_request) Successful in 2m8s
driver / publish (pull_request) Skipped
The configuration ran as one detached script, so a refused uci step only reached its log while the call reported the part as applied. The changes are now staged by a script the call waits for: a uci wrapper records each refused set, add, add_list or delete with its part, and at the end every config is reverted and the script exits 3, which raises CommandErrorException naming each part, passphrases masked. Quiet -q calls stay tests. The commits, LuCI's service, the reloads and the restart run detached afterwards, as before. Closes #54
This commit is contained in:
1 parent
f71c12dfb6
commit
9bac9bd1af
6 files changed
+350
-98
No files matched your search
+164
-26
@@ -1,9 +1,13 @@
|
||||
"""``apply_ap_config``: an access point's desired configuration as one UCI script (NetOrk/netork#695).
|
||||
"""``apply_ap_config``: an access point's desired configuration as UCI scripts (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``.
|
||||
|
||||
The changes are staged by a script the call waits for, so a step the AP refuses is
|
||||
raised and nothing of it applied (#54); the commits, reloads and the restart run
|
||||
detached afterwards, since they may cut the session.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -11,9 +15,10 @@ from __future__ import annotations
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
from napalm.base.exceptions import CommandErrorException
|
||||
from napalm_device_types import ApConfigDict, ApSsidConfigDict, CommandResult
|
||||
|
||||
from napalm_openwrt.ap_config import MASK, build_script, masked
|
||||
from napalm_openwrt.ap_config import MASK, build_commands, build_scripts, 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
|
||||
@@ -65,8 +70,10 @@ def _config(**fields: object) -> ApConfigDict:
|
||||
|
||||
|
||||
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
|
||||
"""``(stage + apply, applied, skipped, restarts)``; "" when nothing is written."""
|
||||
scripts = build_scripts(config or _config(), parts, radios)
|
||||
script = f"{scripts.stage}\n{scripts.apply}" if scripts.stage else ""
|
||||
return script, scripts.applied, scripts.skipped, scripts.restarts
|
||||
|
||||
|
||||
def _script(parts: list[str], config: ApConfigDict | None = None, radios: Radios = RADIOS) -> str:
|
||||
@@ -432,17 +439,16 @@ def _run(command: str, ssid: str, tmp_path) -> list[str]:
|
||||
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])
|
||||
def _loop(parts: list[str], config: ApConfigDict) -> str:
|
||||
"""The commands of the parts, without the stage script's own lines around them."""
|
||||
plan = build_commands(config, parts, RADIOS)[0]
|
||||
return "\n".join(c for c in plan.commands if not c.startswith("_part="))
|
||||
|
||||
|
||||
@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) == [
|
||||
config = _config(ssids=[_ssid(name="Home", key=value)])
|
||||
assert _run(_loop(["wireless/Home/encryption"], config), "Home", tmp_path) == [
|
||||
"wireless.default_radio0.encryption=psk2",
|
||||
f"wireless.default_radio0.key={value}",
|
||||
]
|
||||
@@ -451,28 +457,136 @@ def test_a_passphrase_arrives_as_it_is(value, tmp_path):
|
||||
|
||||
@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"]
|
||||
config = _config(ssids=[_ssid(name=value, hidden=True)])
|
||||
loop = _loop([f"wireless/{value}/hidden"], config)
|
||||
assert _run(loop, 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}"
|
||||
loop = _loop(["wireless/Home/acl"], config)
|
||||
assert _run(loop, "Home", tmp_path)[-1] == f"wireless.default_radio0.maclist={mac}"
|
||||
assert not (tmp_path / "pwned").exists()
|
||||
|
||||
|
||||
# -- the stage script: a refused step is reported, and nothing applied (#54) -----------------
|
||||
|
||||
#: A ``uci`` on PATH that knows one interface serving Corp, logs every call, and
|
||||
#: refuses those whose words hold $REFUSE.
|
||||
_FAKE_UCI_BIN = """#!/bin/sh
|
||||
echo "$*" >> "$LOG"
|
||||
if [ -n "$REFUSE" ] && echo "$*" | grep -qF -- "$REFUSE"; then
|
||||
echo "uci: Invalid argument" >&2
|
||||
exit 1
|
||||
fi
|
||||
case "$1" in
|
||||
show) echo "wireless.default_radio0.ssid='Corp'" ;;
|
||||
-q) [ "$2" = get ] || exit 0
|
||||
[ "$3" = wireless.default_radio0.ssid ] && { echo Corp; exit 0; }
|
||||
exit 1 ;;
|
||||
esac
|
||||
exit 0
|
||||
"""
|
||||
|
||||
|
||||
def _stage(tmp_path, parts: list[str], refuse: str = "", config: ApConfigDict | None = None):
|
||||
"""Run the stage script of *parts* through /bin/sh against the fake ``uci``."""
|
||||
bin_dir = tmp_path / "bin"
|
||||
bin_dir.mkdir(exist_ok=True)
|
||||
fake = bin_dir / "uci"
|
||||
fake.write_text(_FAKE_UCI_BIN)
|
||||
fake.chmod(0o755)
|
||||
log = tmp_path / "uci.log"
|
||||
log.touch()
|
||||
script = tmp_path / "stage.sh"
|
||||
script.write_text(build_scripts(config or _config(), parts, RADIOS).stage)
|
||||
done = subprocess.run( # nosec B603 - a fixed /bin/sh on the test's own script
|
||||
["/bin/sh", str(script)],
|
||||
env={"LOG": str(log), "REFUSE": refuse, "PATH": f"{bin_dir}:/usr/bin:/bin"},
|
||||
capture_output=True,
|
||||
text=True,
|
||||
cwd=tmp_path,
|
||||
)
|
||||
return done, log.read_text().splitlines()
|
||||
|
||||
|
||||
def test_a_stage_that_goes_through_commits_nothing(tmp_path):
|
||||
"""The commits are the detached script's; staging leaves the device running as it is."""
|
||||
done, calls = _stage(tmp_path, ["system/ssh_port", "wireless/Corp/hidden"])
|
||||
|
||||
assert done.returncode == 0, done.stderr
|
||||
assert "set dropbear.@dropbear[0].Port=22" in calls
|
||||
assert not any(c.startswith(("commit", "revert")) for c in calls)
|
||||
|
||||
|
||||
def test_a_refused_step_reverts_every_config_and_names_its_part(tmp_path):
|
||||
done, calls = _stage(
|
||||
tmp_path, ["system/ssh_port", "radio/country"], refuse="dropbear.@dropbear[0].Port"
|
||||
)
|
||||
|
||||
assert done.returncode == 3
|
||||
assert "system/ssh_port: uci set dropbear.@dropbear[0].Port=22" in done.stderr
|
||||
assert "uci: Invalid argument" in done.stderr
|
||||
assert "radio/country" not in done.stderr
|
||||
assert {"revert dropbear", "revert wireless"} <= set(calls)
|
||||
assert not any(c.startswith("commit") for c in calls)
|
||||
|
||||
|
||||
def test_every_refused_part_is_named(tmp_path):
|
||||
done, _ = _stage(tmp_path, ["radio/country", "radio/5g_htmode"], refuse="radio1")
|
||||
|
||||
assert "radio/country: uci set wireless.radio1.country=DE" in done.stderr
|
||||
assert "radio/5g_htmode: uci set wireless.radio1.htmode=VHT80" in done.stderr
|
||||
|
||||
|
||||
def test_a_quiet_delete_of_a_missing_option_is_no_refusal(tmp_path):
|
||||
"""``uci -q delete`` of an option the section lacks exits 1; the builders count on it."""
|
||||
config = _config(ssids=[_ssid(acl_mode="off")])
|
||||
done, calls = _stage(tmp_path, ["wireless/Corp/acl"], refuse="-q delete", config=config)
|
||||
|
||||
assert done.returncode == 0, done.stderr
|
||||
assert "-q delete wireless.default_radio0.macfilter" in calls
|
||||
assert not any(c.startswith("revert") for c in calls)
|
||||
|
||||
|
||||
def test_the_stage_script_removes_itself(tmp_path):
|
||||
"""It holds the passphrases; the AP keeps it no longer than it runs."""
|
||||
_stage(tmp_path, ["wireless/Corp/encryption"])
|
||||
|
||||
assert not (tmp_path / "stage.sh").exists()
|
||||
|
||||
|
||||
def test_the_detached_script_commits_reloads_and_starts_what_is_live():
|
||||
scripts = build_scripts(
|
||||
_config(web_ui=False), ["system/web_ui", "wireless/Corp/hidden"], RADIOS
|
||||
)
|
||||
|
||||
assert "uhttpd" not in scripts.stage
|
||||
assert scripts.apply.split("\n") == [
|
||||
"#!/bin/sh",
|
||||
"uci commit wireless",
|
||||
"/etc/init.d/uhttpd stop; /etc/init.d/uhttpd disable",
|
||||
"wifi reload 2>&1; true",
|
||||
]
|
||||
|
||||
|
||||
# -- apply_ap_config ---------------------------------------------------------------------------
|
||||
|
||||
WORKDIR = "/tmp/openwrt-apply.Ab12Cd"
|
||||
STAGE = f"sh {WORKDIR}/stage.sh"
|
||||
|
||||
|
||||
class _ApplyAp:
|
||||
"""``run_command`` of an AP that answers the read and makes the work directory."""
|
||||
"""``run_command`` of an AP: answers the read, makes the work directory, stages."""
|
||||
|
||||
def __init__(self, made: str = WORKDIR, write: CommandResult | None = None) -> None:
|
||||
self.made, self.write = made, write
|
||||
def __init__(
|
||||
self,
|
||||
made: str = WORKDIR,
|
||||
write: CommandResult | None = None,
|
||||
stage: CommandResult | None = None,
|
||||
) -> None:
|
||||
self.made, self.write, self.stage = made, write, stage
|
||||
self.calls: list[tuple[str, bytes | None]] = []
|
||||
|
||||
def __call__(
|
||||
@@ -488,18 +602,27 @@ class _ApplyAp:
|
||||
return CommandResult(WIRELESS, "", 0)
|
||||
if "mktemp -d" in command:
|
||||
return self.write or CommandResult(self.made + "\n", "", 0)
|
||||
if command == STAGE:
|
||||
return self.stage or CommandResult("", "", 0)
|
||||
return CommandResult("", "", 0)
|
||||
|
||||
@property
|
||||
def commands(self) -> list[str]:
|
||||
return [c for c, _ in self.calls]
|
||||
|
||||
def test_the_script_is_written_from_stdin_into_a_fresh_directory_then_run_detached():
|
||||
|
||||
def test_the_changes_are_staged_and_waited_for_then_applied_detached():
|
||||
ap = _ApplyAp()
|
||||
result = _driver(ap).apply_ap_config(_config(), ["radio/country", "wireless/Corp/encryption"])
|
||||
|
||||
(read, _), (write, script), (run, _) = ap.calls
|
||||
(read, _), (write, stage), (write_apply, apply), (run, _), (start, _) = 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 == (
|
||||
assert stage is not None and f"key='{PSK}'".encode() in stage
|
||||
assert write_apply == f"umask 077 && cat > {WORKDIR}/apply.sh"
|
||||
assert apply is not None and b"uci commit wireless" in apply and PSK.encode() not in apply
|
||||
assert run == STAGE
|
||||
assert start == (
|
||||
f"( sh {WORKDIR}/apply.sh > {WORKDIR}/apply.log 2>&1 < /dev/null; "
|
||||
f"rm -f {WORKDIR}/apply.sh ) &"
|
||||
)
|
||||
@@ -507,17 +630,32 @@ def test_the_script_is_written_from_stdin_into_a_fresh_directory_then_run_detach
|
||||
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"]
|
||||
assert PSK not in result["commands"]
|
||||
assert "uci set wireless.radio1.country='DE'" in result["commands"]
|
||||
|
||||
|
||||
def test_a_refused_step_raises_names_it_and_applies_nothing():
|
||||
said = (
|
||||
f"wireless/Corp/encryption: uci set wireless.default_radio0.key={PSK}: "
|
||||
"uci: Invalid argument\n"
|
||||
)
|
||||
ap = _ApplyAp(stage=CommandResult("", said, 3))
|
||||
with pytest.raises(CommandErrorException) as caught:
|
||||
_driver(ap).apply_ap_config(_config(), ["radio/country", "wireless/Corp/encryption"])
|
||||
|
||||
message = str(caught.value)
|
||||
assert "wireless/Corp/encryption" in message and "Invalid argument" in message
|
||||
assert "nothing of it is applied" in message
|
||||
assert PSK not in message
|
||||
assert not any("apply.sh >" in c for c in ap.commands)
|
||||
assert ap.commands[-1] == f"rm -rf {WORKDIR}"
|
||||
|
||||
|
||||
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 ap.commands == [SHOW]
|
||||
assert result == {
|
||||
"applied": [],
|
||||
"skipped": ["system/luci"],
|
||||
|
||||
Reference in new issue
Block a user