feat(access-point): declared AP writes, apply_ap_config and DHCP leases, 0.11.0 (NetOrk/netork#695) #55
No files matched your search
+5
-2
@@ -25,8 +25,11 @@ recorded here; their history is the git log.
|
||||
SSID's VLAN, bands, presence, encryption, key, flags, limits, MAC filter and 802.11r.
|
||||
It answers which parts it wrote, which it could not (`skipped`: unknown, or a keyed
|
||||
mode without its key), whether the AP restarts (a new bridge), and the script with
|
||||
every passphrase masked. `wireless/<ssid>/passphrase` now writes the key, where
|
||||
netOrk's own builder wrote nothing for it.
|
||||
every passphrase masked. The changes are staged by a script the call waits for: a
|
||||
change the AP refuses raises `CommandErrorException` naming its part, and nothing of
|
||||
the configuration is applied (#54); the commits, reloads and the restart run detached
|
||||
afterwards. `wireless/<ssid>/passphrase` now writes the key, where netOrk's own
|
||||
builder wrote nothing for it.
|
||||
- `get_dhcp_leases()` (`DhcpLeasesMixin`): dnsmasq's DHCPv4 leases from its lease file;
|
||||
`[]` where dnsmasq never ran, a raise where the file cannot be read.
|
||||
|
||||
|
||||
@@ -176,7 +176,7 @@ reverted, and nothing is committed or restarted.
|
||||
## AP configuration
|
||||
|
||||
`apply_ap_config(config, parts)` (napalm-device-types `ApConfigMixin`) writes the parts of
|
||||
an `ApConfigDict` the caller names as one shell script: the radios (country, 5 and 2.4
|
||||
an `ApConfigDict` the caller names as UCI changes: the radios (country, 5 and 2.4
|
||||
GHz `htmode`), remote syslog, LuCI (`uhttpd` enabled or stopped), dropbear's port and
|
||||
password logins, the `br-ap` bridge with VLAN filtering on `eth0` (every VLAN tagged, the
|
||||
management VLAN untagged where asked), one VLAN of it, its spanning tree, and per SSID its
|
||||
@@ -185,12 +185,21 @@ VLAN (`ap_vlan<vid>`), bands, presence, encryption and key, flags, limits, MAC f
|
||||
written without its key, a whitelist without MACs is written as no filter, and a part the
|
||||
driver does not know or whose values are missing comes back in `skipped`.
|
||||
|
||||
The script is written as root from stdin into a fresh `mktemp -d` directory
|
||||
(`/tmp/openwrt-apply.XXXXXX`) and run detached, since it may cut the session; its output
|
||||
stays in `apply.log` there. Rebuilding the bridge restarts the AP (`restarts`); otherwise
|
||||
the configs are committed and network, wifi, system, dropbear and the firewall reloaded as
|
||||
needed. The result carries the script with every passphrase masked. A step that fails
|
||||
inside the script is in the log, not raised: the script has left the session by then.
|
||||
Two scripts are written as root from stdin into a fresh `mktemp -d` directory
|
||||
(`/tmp/openwrt-apply.XXXXXX`):
|
||||
|
||||
- `stage.sh` stages the changes without committing them, so the running AP is untouched,
|
||||
and the call waits for it. A change `uci` refuses (`set`, `add`, `add_list`, `delete`,
|
||||
...) is recorded with its part; at the end every config is reverted and the call raises
|
||||
`CommandErrorException` naming each refused part and what `uci` said, passphrases
|
||||
masked. Nothing of the configuration is applied then (NAPALM/napalm-openwrt#54). A quiet
|
||||
`uci -q` call, such as deleting an option that may be missing, is no refusal. The script
|
||||
removes itself as it starts, since it holds the passphrases.
|
||||
- `apply.sh` commits, enables or stops LuCI, and reloads network, wifi, system, dropbear and
|
||||
the firewall as needed, or restarts the AP when the bridge was rebuilt (`restarts`). It
|
||||
runs detached, since it may cut the session; its output stays in `apply.log` there.
|
||||
|
||||
The result carries both scripts with every passphrase masked.
|
||||
|
||||
## Time sync
|
||||
|
||||
|
||||
@@ -13,9 +13,15 @@
|
||||
|
||||
"""The access point's configuration applied as desired state (``ApConfigMixin``).
|
||||
|
||||
The caller names the parts that differ; :func:`build_script` turns the values
|
||||
those parts need into one shell script of ``uci`` commands, the commits and the
|
||||
reloads that apply them. The script reconfigures the AP and may cut the session --
|
||||
The caller names the parts that differ; :func:`build_scripts` turns the values those
|
||||
parts need into two shell scripts:
|
||||
|
||||
* **stage** -- the ``uci`` changes, staged but not committed, so the running device
|
||||
is untouched. The call waits for it. A change ``uci`` refuses is recorded with its
|
||||
part; at the end every config is reverted and the script exits 3 with the
|
||||
refusals, so nothing of the configuration applies and the call raises (#54).
|
||||
* **apply** -- the commits, what changes the running device (LuCI's service), and the
|
||||
reloads or the restart. It reconfigures the AP and may cut the session --
|
||||
rebuilding the bridge restarts the AP -- so it runs detached, its output in a log
|
||||
on the AP.
|
||||
"""
|
||||
@@ -24,8 +30,10 @@ from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from napalm.base.exceptions import CommandErrorException
|
||||
from napalm_device_types import (
|
||||
ApConfigDict,
|
||||
ApConfigMixin,
|
||||
@@ -53,8 +61,31 @@ RESTARTING_PARTS = frozenset({"network/bridge"})
|
||||
WORKDIR_TEMPLATE = "/tmp/openwrt-apply.XXXXXX" # nosec B108 - on the AP, root's own 0700 dir
|
||||
_WORKDIR_RE = re.compile(r"/tmp/openwrt-apply\.[A-Za-z0-9]{6}") # nosec B108
|
||||
|
||||
#: What a passphrase shows as in the script the result carries.
|
||||
#: What a passphrase shows as in the script the result carries, quoted and as a word.
|
||||
MASK = "'********'"
|
||||
_MASK_WORD = "********"
|
||||
#: Seconds the stage script may take: a few hundred ``uci`` calls.
|
||||
STAGE_TIMEOUT = 120
|
||||
#: The stage script's exit status when ``uci`` refused a change.
|
||||
REFUSED = 3
|
||||
|
||||
#: The ``uci`` verbs that change a config; a refusal of any is a refused part. A read
|
||||
#: (``get``, ``show``) or a quiet ``-q`` call may fail on purpose, as a test.
|
||||
_STAGE_PRELUDE = """#!/bin/sh
|
||||
rm -f "$0"
|
||||
_refused="${0%/*}/refused"
|
||||
: > "$_refused"
|
||||
_part=''
|
||||
uci() {
|
||||
case "$1" in
|
||||
set|add|add_list|del_list|delete|rename|reorder) ;;
|
||||
*) command uci "$@"; return ;;
|
||||
esac
|
||||
_out=$(command uci "$@" 2>&1) && { [ -z "$_out" ] || echo "$_out"; return 0; }
|
||||
_rc=$?
|
||||
echo "$_part: uci $*: $_out" >> "$_refused"
|
||||
return $_rc
|
||||
}"""
|
||||
|
||||
_SHOW_WIRELESS = "uci -q show wireless"
|
||||
|
||||
@@ -73,6 +104,32 @@ _RELOADS = {
|
||||
}
|
||||
|
||||
|
||||
def _stage_epilogue(configs: set[str]) -> str:
|
||||
"""Revert every config and exit ``REFUSED`` with the refusals, if there were any."""
|
||||
reverts = " ".join(sorted(configs)) or "wireless"
|
||||
return "\n".join(
|
||||
[
|
||||
'if [ -s "$_refused" ]; then',
|
||||
f' for _c in {reverts}; do command uci revert "$_c"; done',
|
||||
' cat "$_refused" >&2',
|
||||
f" exit {REFUSED}",
|
||||
"fi",
|
||||
'rm -f "$_refused"',
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ApScripts:
|
||||
"""The stage and apply scripts of a configuration; both "" when it writes nothing."""
|
||||
|
||||
stage: str
|
||||
apply: str
|
||||
applied: list[str]
|
||||
skipped: list[str]
|
||||
restarts: bool
|
||||
|
||||
|
||||
def _build_part(part: str, config: ApConfigDict, radios: Radios, plan: Plan) -> None:
|
||||
if part.startswith("radio/"):
|
||||
radio_part(part, config, radios, plan)
|
||||
@@ -93,8 +150,9 @@ def build_commands(
|
||||
) -> tuple[Plan, list[str], list[str]]:
|
||||
"""The commands for *parts*, and which parts they write and which they cannot.
|
||||
|
||||
A VLAN is part of the bridge: with ``network/bridge`` among the parts, a
|
||||
``network/vlan/<vid>`` is written by it.
|
||||
Each part's commands follow a ``_part=`` line naming it, so the stage script
|
||||
can say which part a refused change belongs to. A VLAN is part of the bridge:
|
||||
with ``network/bridge`` among the parts, a ``network/vlan/<vid>`` is written by it.
|
||||
"""
|
||||
plan = Plan()
|
||||
applied: list[str] = []
|
||||
@@ -107,40 +165,47 @@ def build_commands(
|
||||
if rebuilds_bridge and ap_config_vlan_part(part) is not None:
|
||||
applied.append(part)
|
||||
continue
|
||||
before = len(plan.commands)
|
||||
before = len(plan.commands) + len(plan.actions)
|
||||
plan.commands.append(f"_part={sq(part)}")
|
||||
_build_part(part, config, radios, plan)
|
||||
(applied if len(plan.commands) > before else skipped).append(part)
|
||||
if len(plan.commands) + len(plan.actions) > before + 1:
|
||||
applied.append(part)
|
||||
else:
|
||||
plan.commands.pop()
|
||||
skipped.append(part)
|
||||
return plan, applied, skipped
|
||||
|
||||
|
||||
def build_script(
|
||||
config: ApConfigDict, parts: list[str], radios: Radios
|
||||
) -> tuple[str, list[str], list[str], bool]:
|
||||
"""The script for *parts*: ``(script, applied, skipped, restarts)``; "" when it writes nothing.
|
||||
|
||||
A script that restarts the AP reloads nothing first: the restart applies it all.
|
||||
"""
|
||||
plan, applied, skipped = build_commands(config, parts, radios)
|
||||
if not plan.commands:
|
||||
return "", applied, skipped, False
|
||||
restarts = bool(RESTARTING_PARTS & set(applied))
|
||||
lines = ["#!/bin/sh", *plan.commands]
|
||||
def _apply_script(plan: Plan, restarts: bool) -> str:
|
||||
"""The commits, then what is live, then the reloads -- or the restart, which applies it all."""
|
||||
lines = ["#!/bin/sh"]
|
||||
lines += [f"uci commit {config_name}" for config_name in sorted(plan.commits)]
|
||||
lines += plan.actions
|
||||
if restarts:
|
||||
lines.append("reboot")
|
||||
else:
|
||||
for config_name, reloads in _RELOADS.items():
|
||||
if config_name in plan.commits:
|
||||
lines += reloads
|
||||
return "\n".join(lines), applied, skipped, restarts
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def masked(script: str, config: ApConfigDict) -> str:
|
||||
"""*script* with every passphrase of *config* as ``MASK``."""
|
||||
def build_scripts(config: ApConfigDict, parts: list[str], radios: Radios) -> ApScripts:
|
||||
"""The stage and apply scripts for *parts*; see the module."""
|
||||
plan, applied, skipped = build_commands(config, parts, radios)
|
||||
if not applied:
|
||||
return ApScripts("", "", applied, skipped, False)
|
||||
restarts = bool(RESTARTING_PARTS & set(applied))
|
||||
stage = "\n".join([_STAGE_PRELUDE, *plan.commands, _stage_epilogue(plan.commits)])
|
||||
return ApScripts(stage, _apply_script(plan, restarts), applied, skipped, restarts)
|
||||
|
||||
|
||||
def masked(text: str, config: ApConfigDict) -> str:
|
||||
"""*text* with every passphrase of *config* masked: quoted as ``MASK``, bare as a word."""
|
||||
for ssid in config.get("ssids") or []:
|
||||
if key := ssid.get("key"):
|
||||
script = script.replace(sq(key), MASK)
|
||||
return script
|
||||
text = text.replace(sq(key), MASK).replace(key, _MASK_WORD)
|
||||
return text
|
||||
|
||||
|
||||
class OpenWrtApConfigMixin(ApConfigMixin, UciStepsMixin):
|
||||
@@ -159,60 +224,92 @@ class OpenWrtApConfigMixin(ApConfigMixin, UciStepsMixin):
|
||||
) -> CommandResult: ...
|
||||
|
||||
def apply_ap_config(self, config: ApConfigDict, parts: list[str]) -> ApConfigResultDict:
|
||||
"""Write the *parts* of *config* (``ApConfigMixin``) with one detached script.
|
||||
"""Write the *parts* of *config* (``ApConfigMixin``): staged, then applied detached.
|
||||
|
||||
The radios are read first (``uci show wireless``): the 5 GHz and 2.4 GHz
|
||||
ones by their ``band``. A part whose values *config* lacks, or that this
|
||||
driver does not know, is written not at all and comes back in ``skipped``.
|
||||
|
||||
:raises CommandErrorException: when the radios cannot be read.
|
||||
:raises RuntimeError: when the script cannot be written to the AP.
|
||||
:raises CommandErrorException: when the radios cannot be read, or the AP
|
||||
refused a change; then nothing of the configuration is applied, and the
|
||||
message names each refused part with what ``uci`` said (passphrases masked).
|
||||
:raises RuntimeError: when the scripts cannot be written to the AP.
|
||||
"""
|
||||
radios = radios_of(parse_uci_show(self._uci_step(_SHOW_WIRELESS)))
|
||||
script, applied, skipped, restarts = build_script(config, list(parts), radios)
|
||||
if not script:
|
||||
return {"applied": [], "skipped": skipped, "restarts": False, "commands": "", "log": ""}
|
||||
workdir = self._run_detached(script)
|
||||
scripts = build_scripts(config, list(parts), radios)
|
||||
if not scripts.stage:
|
||||
empty: ApConfigResultDict = {
|
||||
"applied": [],
|
||||
"skipped": scripts.skipped,
|
||||
"restarts": False,
|
||||
"commands": "",
|
||||
"log": "",
|
||||
}
|
||||
return empty
|
||||
workdir = self._write_scripts(scripts)
|
||||
self._stage(workdir, config)
|
||||
self._start_apply(workdir)
|
||||
return {
|
||||
"applied": applied,
|
||||
"skipped": skipped,
|
||||
"restarts": restarts,
|
||||
"commands": masked(script, config),
|
||||
"applied": scripts.applied,
|
||||
"skipped": scripts.skipped,
|
||||
"restarts": scripts.restarts,
|
||||
"commands": masked(f"{scripts.stage}\n{scripts.apply}", config),
|
||||
"log": f"{workdir}/apply.log",
|
||||
}
|
||||
|
||||
def _run_detached(self, script: str) -> str:
|
||||
"""Write *script* to the AP from stdin and run it detached; returns its directory.
|
||||
def _write_scripts(self, scripts: ApScripts) -> str:
|
||||
"""Write both scripts to the AP from stdin; returns their directory.
|
||||
|
||||
Root writes the script, passphrases and all, into a directory of its own
|
||||
(``mktemp -d``: mode 0700, a name nobody knows in advance), never to a fixed
|
||||
/tmp name another account could have placed or could swap between the write
|
||||
and the run. The script goes once it has run; the log stays.
|
||||
Root writes them, passphrases and all, into a directory of its own (``mktemp
|
||||
-d``: mode 0700, a name nobody knows in advance), never to a fixed /tmp name
|
||||
another account could have placed or could swap between the write and the run.
|
||||
"""
|
||||
written = self.run_command(
|
||||
f'umask 077 && d=$(mktemp -d {WORKDIR_TEMPLATE}) && cat > "$d/apply.sh" && echo "$d"',
|
||||
f'umask 077 && d=$(mktemp -d {WORKDIR_TEMPLATE}) && cat > "$d/stage.sh" && echo "$d"',
|
||||
privileged=True,
|
||||
stdin=script.encode(),
|
||||
)
|
||||
if written.exit_code:
|
||||
raise RuntimeError(
|
||||
f"{self.hostname}: could not write the configuration script: "
|
||||
f"{written.stderr.strip() or written.stdout.strip()}"
|
||||
stdin=scripts.stage.encode(),
|
||||
)
|
||||
self._check(written, "could not write the configuration script")
|
||||
workdir = written.stdout.strip()
|
||||
if not _WORKDIR_RE.fullmatch(workdir):
|
||||
raise RuntimeError(f"{self.hostname}: the AP named no work directory: {workdir!r}")
|
||||
self._check(
|
||||
self.run_command(
|
||||
f"umask 077 && cat > {workdir}/apply.sh",
|
||||
privileged=True,
|
||||
stdin=scripts.apply.encode(),
|
||||
),
|
||||
"could not write the configuration script",
|
||||
)
|
||||
return workdir
|
||||
|
||||
def _stage(self, workdir: str, config: ApConfigDict) -> None:
|
||||
"""Run the stage script and wait for it; a refusal raises, nothing applied."""
|
||||
staged = self.run_command(f"sh {workdir}/stage.sh", privileged=True, timeout=STAGE_TIMEOUT)
|
||||
if staged.exit_code == 0:
|
||||
return
|
||||
self.run_command(f"rm -rf {workdir}", privileged=True)
|
||||
said = staged.stderr.strip() or staged.stdout.strip() or f"exit status {staged.exit_code}"
|
||||
raise CommandErrorException(
|
||||
masked(
|
||||
f"{self.hostname}: the AP refused the configuration, nothing of it is applied: "
|
||||
f"{said}",
|
||||
config,
|
||||
)
|
||||
)
|
||||
|
||||
def _start_apply(self, workdir: str) -> None:
|
||||
"""Run the apply script detached: it may cut the session. The script goes once
|
||||
it has run; the log stays."""
|
||||
started = self.run_command(
|
||||
f"( sh {workdir}/apply.sh > {workdir}/apply.log 2>&1 < /dev/null; "
|
||||
f"rm -f {workdir}/apply.sh ) &",
|
||||
privileged=True,
|
||||
)
|
||||
if started.exit_code:
|
||||
raise RuntimeError(
|
||||
f"{self.hostname}: could not start the configuration script: "
|
||||
f"{started.stderr.strip() or started.stdout.strip()}"
|
||||
)
|
||||
logger.info(
|
||||
"%s: configuration script started; its log is %s/apply.log", self.hostname, workdir
|
||||
)
|
||||
return workdir
|
||||
self._check(started, "could not start the configuration script")
|
||||
logger.info("%s: configuration applying; its log is %s/apply.log", self.hostname, workdir)
|
||||
|
||||
def _check(self, result: CommandResult, what: str) -> None:
|
||||
if result.exit_code:
|
||||
said = result.stderr.strip() or result.stdout.strip()
|
||||
raise RuntimeError(f"{self.hostname}: {what}: {said}")
|
||||
@@ -47,10 +47,15 @@ def sq(value: object) -> str:
|
||||
|
||||
@dataclass
|
||||
class Plan:
|
||||
"""The commands built so far, and the configs they stage for a commit."""
|
||||
"""The commands built so far, the configs they stage for a commit, and what runs live.
|
||||
|
||||
``commands`` only stage UCI changes, which the device does not run until they are
|
||||
committed; ``actions`` change the running device and come after the commits.
|
||||
"""
|
||||
|
||||
commands: list[str] = field(default_factory=list)
|
||||
commits: set[str] = field(default_factory=set)
|
||||
actions: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
|
||||
@@ -70,9 +70,9 @@ def _web_ui(config: ApConfigDict, plan: Plan) -> None:
|
||||
if "web_ui" not in config:
|
||||
return
|
||||
if config["web_ui"]:
|
||||
plan.commands.append("/etc/init.d/uhttpd enable && /etc/init.d/uhttpd start")
|
||||
plan.actions.append("/etc/init.d/uhttpd enable && /etc/init.d/uhttpd start")
|
||||
else:
|
||||
plan.commands.append("/etc/init.d/uhttpd stop; /etc/init.d/uhttpd disable")
|
||||
plan.actions.append("/etc/init.d/uhttpd stop; /etc/init.d/uhttpd disable")
|
||||
|
||||
|
||||
def _ssh_port(config: ApConfigDict, plan: Plan) -> None:
|
||||
|
||||
+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