diff --git a/CHANGELOG.md b/CHANGELOG.md index 2102f56..5389c02 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ Added: - **Internet schedule** (new page). Turn the internet off at set times of the week for chosen people (all their devices) or single devices: bedtime on school nights, study time, meal times. One click starts from a ready plan ("School nights", "Every night", "Study time", "Meal times"); a schedule can have several times, a time can run past midnight, and dates can be marked as days off (holidays, Eid). **Bonus time** gives a few extra minutes without changing the schedule. **Always allowed** sites (a school platform, a study site) keep working during every schedule. While a schedule is on, the device's card shows when the internet comes back, the home network (printer, shared drives, the dashboard) keeps working, and the cut is done by the gateway itself, so it works on any phone, tablet, TV or console with no app. Each device gets its end time in the system kernel, so it comes back online on time even if the gateway service restarts or stops. Sites on the "always allowed" list only open on devices that look names up through the gateway; a phone with Private DNS (or a browser with secure DNS) turned on keeps them blocked during a schedule. Contributed by @amr-elgharip2006. Closes #32. Fixed: +- A short hiccup while the gateway updated its list of cut-off devices could switch off counting and blocking for everyone until a restart, or let a cut-off device through for a moment. The list is now changed in one step: if that step fails, the old list stays in force and the gateway simply tries again 15 seconds later. Contributed by @compnew2006. - A guest who typed a valid code could get an error even though the code was accepted, and then be told the code was already used. The approval now always comes back, and a guest who retries gets the same approval again. Contributed by @compnew2006. - The security filter on the dashboard (for access from outside the home) now checks a request's size as it arrives and keeps its memory bounded, so a flood of large or never-ending requests can no longer slow the gateway down. Access from inside the home is unchanged. Contributed by @compnew2006. - README: a one-line, safe way to back up the gateway's data while it runs, plus a restore guide. Contributed by @compnew2006. diff --git a/api/app.py b/api/app.py index 850c58c..df77c09 100644 --- a/api/app.py +++ b/api/app.py @@ -855,6 +855,8 @@ async def _dashboard_payload() -> dict[str, Any]: "blocked_programmed": getattr(live, "gateway_blocked", None), "engine_available": bool( getattr(live, "engine_available", True)), + "engine_sync_error": str( + getattr(live, "engine_sync_error", "") or ""), }, "wan": live.wan_status, # The VPN-share switch + live kernel state ride the WS snapshot so diff --git a/quota/engine.py b/quota/engine.py index 64c9730..f6aec98 100644 --- a/quota/engine.py +++ b/quota/engine.py @@ -76,6 +76,8 @@ class EngineSnapshot: #: blocked in that state, so the dashboard must say so instead of implying #: enforcement is live. engine_available: bool = True + #: transient error from atomically syncing enforcement sets, if any + engine_sync_error: str = "" #: IPs of guest devices currently awaiting admin approval (for captive portal) pending_guests: set[str] = field(default_factory=set) ts: float = field(default_factory=time.time) diff --git a/quota/nftables.py b/quota/nftables.py index ef8161a..aa73229 100644 --- a/quota/nftables.py +++ b/quota/nftables.py @@ -57,6 +57,7 @@ import json import logging import re +import tempfile import time from ipaddress import ip_address, ip_network from typing import Any, Callable @@ -213,6 +214,35 @@ def _which_network(networks: list[str], host: str) -> str | None: _MAC_RE = re.compile(r"^[0-9a-fA-F]{2}(:[0-9a-fA-F]{2}){5}$") +def _valid_addresses(values: list[str], version: int) -> list[str]: + """Return sorted canonical IP literals of the requested address family.""" + valid: set[str] = set() + for value in values: + try: + address = ip_address(value) + except ValueError: + continue + if address.version == version and not getattr(address, "scope_id", None): + valid.add(str(address)) + return sorted(valid) + + +def _valid_ip_to_mac(ip_to_mac: dict[str, str]) -> dict[str, str]: + """Reject invalid and zone-scoped IPs before they enter nft rule syntax.""" + valid: dict[str, str] = {} + for ip, mac in ip_to_mac.items(): + try: + address = ip_address(ip) + except ValueError: + log.warning("ignoring invalid address in nft device map") + continue + if getattr(address, "scope_id", None): + log.warning("ignoring zone-scoped address in nft device map") + continue + valid[ip] = mac + return valid + + class NftablesEngine: """Linux (nftables) accounting + hard-block engine. @@ -267,14 +297,18 @@ def __init__( self.available = True self._warned = False + #: Last enforcement-set reconciliation error. A failed transaction is + #: observable without declaring the packet engine itself unavailable. + self.sync_error = "" + self.last_error = "" self._ip_to_mac: dict[str, str] = {} self._blocked: dict[str, bool] = {} #: IPs most recently programmed into the kernel `blocked` set. - self._last_blocked_ips: list[str] = [] + self._last_blocked_ips: list[str] | None = None ipv6_pfx = (getattr(dhcp_cfg, "ipv6_prefix", "fd00:da7a:2::/64") or "fd00:da7a:2::/64").strip() self._ipv6_prefix = ipv6_pfx self._local_networks6 = sorted({"fe80::/10", "fd00::/8", "ff00::/8", ipv6_pfx}) - self._last_blocked6_ips: list[str] = [] + self._last_blocked6_ips: list[str] | None = None #: Is the ISP's IPv6 reachable (probe verdict)? None = never programmed. #: While False the ``v6gate`` chain answers every client IPv6 packet #: bound for the internet with ICMPv6 "no route", so apps fall back to @@ -283,7 +317,7 @@ def __init__( #: MACs most recently programmed into the kernel `blocked_macs` set #: (lease-less / static-IP devices are cut by ethernet address — see #: :meth:`_sync_blocked_macs`). - self._last_blocked_macs: list[str] = [] + self._last_blocked_macs: list[str] | None = None #: IPs whose counter rules exist in the kernel. self._installed: set[str] = set() #: IPs whose LAN-monitoring counters exist; ``_last_lan`` is their @@ -312,7 +346,7 @@ def __init__( #: run.py sets the plain-HTTP side door here when the dashboard is HTTPS. self.portal_port: int | None = None #: IPs of pending guests programmed into the `pending_guests` captive portal set - self._last_pending_guests: list[str] = [] + self._last_pending_guests: list[str] | None = None # -- lifecycle ---------------------------------------------------------- @@ -329,9 +363,12 @@ def start(self) -> None: self._lan_installed = set() self._lan_carried = set() self._last_lan = {} - self._last_blocked_ips = [] - self._last_blocked6_ips = [] - self._last_blocked_macs = [] + # A table rebuild invalidates every set cache. Even a desired empty + # set must be flushed once so retained set objects cannot stay stale. + self._last_blocked_ips = None + self._last_blocked6_ips = None + self._last_blocked_macs = None + self._last_pending_guests = None self._ipv6_wan_active = None self._run(["add", "table", f"{FAMILY} {self.table}"]) self._run(["flush", "table", f"{FAMILY} {self.table}"]) @@ -443,6 +480,7 @@ def update_state(self, ip_to_mac: dict[str, str], blocked: dict[str, bool], pending_guests: list[str] | None = None) -> None: """Reconcile per-device counters + the blocked set with the service.""" + ip_to_mac = _valid_ip_to_mac(ip_to_mac) self._ip_to_mac = dict(ip_to_mac) self._blocked = dict(blocked) if not self.available: @@ -461,21 +499,15 @@ def update_state(self, ip_to_mac: dict[str, str], # lease is allowed even on ticks where the blocked set is unchanged. self._sync_known_ips(ip_to_mac) - # Rebuild the blocked set from the current blocked MACs -> their IPs, - # but only when the desired membership actually changed AND is not - # empty. Re-flushing an identical set every ~15 s re-opens a small - # unblock window for every blocked device on every tick (the chain's - # policy is accept between the flush and the last re-add), and a - # mid-rebuild nft failure leaves the later devices missing from the set - # — both silent enforcement gaps. The empty case is cheap (one - # subprocess, no devices affected) so it always runs to keep the kernel - # authoritative. + # Reconcile all enforcement sets in one transaction. Unknown caches + # (startup/restart) force an authoritative first sync, including empty + # sets; thereafter identical memberships cost no nft invocation. blocked_ips = sorted( ip for ip, mac in ip_to_mac.items() if blocked.get(mac)) - blocked_v4 = [ip for ip in blocked_ips if ":" not in ip] - blocked_v6 = [ip for ip in blocked_ips if ":" in ip] - self._sync_blocked_ips(blocked_v4) - self._sync_blocked6_ips(blocked_v6) + blocked_v4 = _valid_addresses( + [ip for ip in blocked_ips if ":" not in ip], 4) + blocked_v6 = _valid_addresses( + [ip for ip in blocked_ips if ":" in ip], 6) # MAC-based drops are the SECOND enforcement channel, keyed by the # device's ethernet address instead of its lease: they cut devices # whose IP never entered ``ip_to_mac`` — a lease-less quota-blocked @@ -483,42 +515,17 @@ def update_state(self, ip_to_mac: dict[str, str], # that routes through the box with no lease row. The IP set above # cannot see those; the ether set can (its traffic still crosses the # forward chain with its real saddr/daddr). - self._sync_blocked_macs(blocked) + blocked_macs = sorted(m for m, b in blocked.items() + if b and m != GATEWAY_MAC and _MAC_RE.fullmatch(m)) + desired = { + "blocked": (blocked_v4, self._last_blocked_ips), + "blocked6": (blocked_v6, self._last_blocked6_ips), + "blocked_macs": (blocked_macs, self._last_blocked_macs), + } if pending_guests is not None: - self._sync_pending_guests(pending_guests) - - def _sync_pending_guests(self, pending_guests: list[str]) -> None: - """Program the kernel ``pending_guests`` set for captive portal redirect.""" - pg_sorted = sorted(pending_guests) - if pg_sorted == self._last_pending_guests: - return - self._last_pending_guests = None - if self._run(["flush", "set", f"{FAMILY} {self.table} pending_guests"]): - ok = True - for ip in pg_sorted: - if not self._run(["add", "element", - f"{FAMILY} {self.table} pending_guests", - f"{{ {ip} }}"]): - ok = False - break - if ok: - self._last_pending_guests = pg_sorted - - def _sync_blocked_ips(self, blocked_ips: list[str]) -> None: - """Program the kernel ``blocked`` set for leased, quota-blocked IPs.""" - if blocked_ips and blocked_ips == self._last_blocked_ips: - return - self._last_blocked_ips = None # not yet committed; retry next tick if a step fails - if self._run(["flush", "set", f"{FAMILY} {self.table} blocked"]): - ok = True - for ip in blocked_ips: - if not self._run(["add", "element", - f"{FAMILY} {self.table} blocked", - f"{{ {ip} }}"]): - ok = False - break - if ok: - self._last_blocked_ips = blocked_ips + desired["pending_guests"] = ( + _valid_addresses(pending_guests, 4), self._last_pending_guests) + self._sync_enforcement_sets(desired) def set_ipv6_wan(self, active: bool) -> None: """Open (ISP IPv6 works) or close (it does not) the IPv6 WAN gate. @@ -548,48 +555,58 @@ def ipv6_wan_active(self) -> bool | None: """Last IPv6-WAN verdict pushed to the kernel (None = never).""" return self._ipv6_wan_active - def _sync_blocked6_ips(self, blocked6_ips: list[str]) -> None: - """Program the kernel ``blocked6`` set for leased, quota-blocked IPv6s.""" - if blocked6_ips and blocked6_ips == self._last_blocked6_ips: - return - self._last_blocked6_ips = None - if self._run(["flush", "set", f"{FAMILY} {self.table} blocked6"]): - ok = True - for ip in blocked6_ips: - if not self._run(["add", "element", - f"{FAMILY} {self.table} blocked6", - f"{{ {ip} }}"]): - ok = False - break - if ok: - self._last_blocked6_ips = blocked6_ips - - def _sync_blocked_macs(self, blocked: dict[str, bool]) -> None: - """Program the kernel ``blocked_macs`` set for every blocked device. + def _sync_enforcement_sets( + self, desired: dict[str, tuple[list[str], list[str] | None]], + ) -> None: + """Atomically replace only changed enforcement sets. - The set is ``ether_addr``-typed; the forward chain's drop rules match - ``ether saddr/daddr @blocked_macs`` (both directions, LAN-excluded). - The box's own sentinel MAC is never programmed (its packets never - cross the forward chain). Cache-gated exactly like the IP set: a - same-set re-flush every tick would open a short unblock window. + nft applies a ``-f`` file as one transaction. If validation/programming + fails, every prior set remains live and each cache still describes the + last successful kernel state, so the next maintenance tick retries. """ - # Only real MACs: one malformed entry makes `nft add element` fail with - # "Invalid LL address", which used to switch the whole engine off. - blocked_macs = sorted(m for m, b in blocked.items() - if b and m != GATEWAY_MAC and _MAC_RE.match(m)) - if blocked_macs and blocked_macs == self._last_blocked_macs: + changed = {name: (members, previous) + for name, (members, previous) in desired.items() + if members != previous} + if not changed: return - self._last_blocked_macs = None # not yet committed; retry next tick - if self._run(["flush", "set", f"{FAMILY} {self.table} blocked_macs"]): - ok = True - for mac in blocked_macs: - if not self._run(["add", "element", - f"{FAMILY} {self.table} blocked_macs", - f"{{ {mac} }}"]): - ok = False - break - if ok: - self._last_blocked_macs = blocked_macs + commands = [] + for name, (members, _previous) in changed.items(): + commands.append(f"flush set {FAMILY} {self.table} {name}") + if members: + commands.append( + f"add element {FAMILY} {self.table} {name} " + "{ " + ", ".join(members) + " }") + code, out = self._run_batch(commands) + if code == 0: + for name, (members, _previous) in changed.items(): + setattr(self, { + "blocked": "_last_blocked_ips", + "blocked6": "_last_blocked6_ips", + "blocked_macs": "_last_blocked_macs", + "pending_guests": "_last_pending_guests", + }[name], members) + self.sync_error = "" + return + + message = f"nft enforcement sync failed: {out.strip()}" + if code == 127 or any(term in out.lower() for term in ( + "permission denied", "operation not permitted")): + self._fail(message, command=["-f", ""]) + return + self.sync_error = message + log.error("%s; retaining last successful enforcement and retrying", message) + + def _run_batch(self, commands: list[str]) -> tuple[int, str]: + """Run an atomic nft batch from a temporary file using the injected runner.""" + try: + with tempfile.NamedTemporaryFile( + mode="w", encoding="utf-8", prefix="quota-nft-", + suffix=".nft", delete=True) as batch: + batch.write("\n".join(commands) + "\n") + batch.flush() + return self._run_command(["nft", "-f", batch.name]) + except OSError as exc: + return 1, str(exc) def _sync_known_ips(self, ip_to_mac: dict[str, str]) -> None: """Keep the kernel ``known_ips`` set == the currently leased client IPs. @@ -1100,6 +1117,8 @@ def _parse_counters(self, json_text: str) -> dict[str, int]: def _fail(self, reason: str, command: list[str] | None = None) -> None: self.available = False + self.sync_error = "" + self.last_error = reason if not self._warned: argv = f"nft {' '.join(command)}" if command else "nft " log.error("nftables engine unavailable: %s — no per-packet " diff --git a/run.py b/run.py index bde305a..ecdbd68 100644 --- a/run.py +++ b/run.py @@ -1700,6 +1700,7 @@ async def _maintenance_tick(self) -> None: except Exception: # noqa: BLE001 — never let a share problem stop the tick log.exception("disk shares: access sync failed") engine_available = False + engine_sync_error = "" gateway_blocked = None if self.engine is not None: # nft update_state + set_gateway_blocked shell out to `nft` @@ -1724,6 +1725,7 @@ async def _maintenance_tick(self) -> None: # getattr: some test fakes implement only the minimal engine # surface; the real engine always carries both attributes. engine_available = bool(getattr(self.engine, "available", True)) + engine_sync_error = str(getattr(self.engine, "sync_error", "") or "") # What the kernel actually holds for the box's cut (True/False), or # None if it was never programmed — copied into the snapshot so the # dashboard can show "Blocked in the UI but not cut at the kernel". @@ -1753,6 +1755,7 @@ async def _maintenance_tick(self) -> None: wan_status=wan_status, gateway_blocked=gateway_blocked, engine_available=engine_available, + engine_sync_error=engine_sync_error, pending_guests=pending_guests, interval_s=flush_interval, flows_by_mac=flows_by_mac, diff --git a/tests/test_api.py b/tests/test_api.py index 28236f1..d11846b 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -1748,7 +1748,8 @@ def test_gateway_payload_engine_programmed_but_ui_free(tmp_path): # import asyncio database = _db.Database(tmp_path / "gw.db") holder = SnapshotHolder() - holder.swap(EngineSnapshot(gateway_blocked=True, engine_available=True)) + holder.swap(EngineSnapshot(gateway_blocked=True, engine_available=True, + engine_sync_error="nft enforcement sync failed")) service = QuotaService(database, timezone="Africa/Cairo") _get_loop().run_until_complete(database.connect()) app = create_app(database, service, holder) @@ -1759,6 +1760,8 @@ def test_gateway_payload_engine_programmed_but_ui_free(tmp_path): assert dash["gateway"]["blocked_desired"] is False assert dash["gateway"]["blocked_programmed"] is True assert dash["gateway"]["engine_available"] is True + assert dash["gateway"]["engine_sync_error"] == \ + "nft enforcement sync failed" finally: _get_loop().run_until_complete(database.close()) diff --git a/tests/test_nftables.py b/tests/test_nftables.py index b216796..24477b5 100644 --- a/tests/test_nftables.py +++ b/tests/test_nftables.py @@ -41,6 +41,8 @@ def __init__(self) -> None: #: When True, ``nft add element`` fails — the gw_allowed whitelist #: must stay uncommitted (cache-gate -> retry next tick). self.reject_add_element: bool = False + #: Fail the next nft batch before mutating any set (transaction rollback). + self.reject_batch: bool = False #: table -> setname -> member IPs self._sets: dict[str, dict[str, set[str]]] = { "inet quota_gateway": {"blocked": set(), "known_ips": set(), @@ -79,6 +81,30 @@ def __call__(self, argv: list[str]) -> tuple[int, str]: self.calls.append(argv) if argv[0] != "nft": return 1, f"unknown binary {argv[0]}" + if argv[1:2] == ["-f"]: + with open(argv[2], encoding="utf-8") as batch_file: + commands = [line.strip() for line in batch_file if line.strip()] + if self.reject_batch: + self.reject_batch = False + return 1, "fake: batch rejected" + # Apply to a copy so a malformed command never leaves partial state. + updated = {table: {name: set(members) + for name, members in sets.items()} + for table, sets in self._sets.items()} + for line in commands: + words = line.split() + table, name = " ".join(words[2:4]), words[4] + members = updated.setdefault(table, {}).setdefault(name, set()) + if words[:2] == ["flush", "set"]: + members.clear() + elif words[:2] == ["add", "element"]: + for value in " ".join(words[5:]).strip("{} ").split(","): + if value.strip(): + members.add(value.strip()) + else: + return 1, f"fake: unsupported batch command {line}" + self._sets = updated + return 0, "" args = argv[1:] cmd = args[0] @@ -101,18 +127,15 @@ def __call__(self, argv: list[str]) -> tuple[int, str]: self.tables.add(args[2]) return 0, "" if cmd == "flush" and args[1] == "table": - # Real nft: a table flush removes rules/sets/chains but NOT named - # counter objects, which keep their byte totals. That is exactly the - # restart-resurrection bug the engine guards against, so the fake - # must preserve counters here too. Only the named table is flushed. + # Named counters keep their byte totals. The fake also preserves + # set contents across rebuilds to exercise the unknown-cache path + # when retained enforcement memberships are present. table = args[2] self._rules = [(t, e) for t, e in self._rules if t != table] self.chain_rules = { (t, h): v for (t, h), v in self.chain_rules.items() if t != table } - for s in self._sets.setdefault(table, {}): - self._sets[table][s].clear() return 0, "" if cmd == "add" and args[1] in ("chain", "set", "rule"): self._rules.append((self._table(args), args[-1])) @@ -222,8 +245,8 @@ def test_update_state_is_add_only(): eng.update_state({"192.168.2.111": "aa:bb:cc:dd:ee:01"}, {}) n_calls = len(fake.calls) eng.update_state({}, {}) # device gone - # only the three blocked-set flushes (IPv4 + IPv6 + MAC, all empty) — no deletes - assert len(fake.calls) == n_calls + 3 + # The table starts with empty enforcement sets; unchanged sets need no nft call. + assert len(fake.calls) == n_calls # counters still exist but are not surfaced (flush filters by ip_to_mac) assert "q_up_192_168_2_111" in fake.counters @@ -299,6 +322,136 @@ def test_unblock_removes_ip_from_set(): assert "192.168.2.111" not in fake.blocked +def test_transient_blocked_set_sync_failure_preserves_enforcement_and_retries(): + fake = FakeNft() + eng = _engine(fake) + eng.start() + ip_to_mac = {"192.168.2.111": "aa:bb:cc:dd:ee:01", + "2001:db8::111": "aa:bb:cc:dd:ee:01"} + eng.update_state(ip_to_mac, {"aa:bb:cc:dd:ee:01": True}, + pending_guests=["192.168.2.112"]) + assert len([call for call in fake.calls if call[1:2] == ["-f"]]) == 1 + assert fake.blocked == {"192.168.2.111"} + assert fake._sets["inet quota_gateway"]["blocked6"] == {"2001:db8::111"} + assert fake.blocked_macs == {"aa:bb:cc:dd:ee:01"} + assert fake._sets["inet quota_gateway"]["pending_guests"] == {"192.168.2.112"} + + fake.counters["q_up_192_168_2_111"] = 100 + assert eng.flush().by_ip["192.168.2.111"].up == 100 + fake.reject_batch = True + eng.update_state(ip_to_mac, {}, pending_guests=[]) + + assert eng.available + assert fake.blocked == {"192.168.2.111"} + assert fake._sets["inet quota_gateway"]["blocked6"] == {"2001:db8::111"} + assert fake.blocked_macs == {"aa:bb:cc:dd:ee:01"} + assert fake._sets["inet quota_gateway"]["pending_guests"] == {"192.168.2.112"} + assert "batch rejected" in eng.sync_error + + eng.update_state(ip_to_mac, {}, pending_guests=[]) + assert eng.available + assert fake.blocked == set() + assert fake._sets["inet quota_gateway"]["blocked6"] == set() + assert fake.blocked_macs == set() + assert fake._sets["inet quota_gateway"]["pending_guests"] == set() + assert eng.sync_error == "" + assert len([call for call in fake.calls if call[1:2] == ["-f"]]) == 3 + assert eng.flush().by_ip == {} + fake.counters["q_up_192_168_2_111"] = 150 + assert eng.flush().by_ip["192.168.2.111"].up == 50 + + +def test_start_flushes_retained_sets_when_desired_membership_is_empty(): + fake = FakeNft() + fake._sets["inet quota_gateway"].update({ + "blocked": {"192.168.2.99"}, + "blocked6": {"2001:db8::99"}, + "blocked_macs": {"aa:bb:cc:dd:ee:99"}, + "pending_guests": {"192.168.2.98"}, + }) + eng = _engine(fake) + eng.start() + eng.update_state({}, {}, pending_guests=[]) + + assert fake.blocked == set() + assert fake._sets["inet quota_gateway"]["blocked6"] == set() + assert fake.blocked_macs == set() + assert fake._sets["inet quota_gateway"]["pending_guests"] == set() + + +def test_restart_forces_empty_reconciliation_for_retained_sets(): + fake = FakeNft() + eng = _engine(fake) + eng.start() + eng.update_state({"192.168.2.111": "aa:bb:cc:dd:ee:01", + "2001:db8::111": "aa:bb:cc:dd:ee:01"}, + {"aa:bb:cc:dd:ee:01": True}, + pending_guests=["192.168.2.111"]) + eng.start() + # The restart resets the set caches to unknown. The fake retains all four + # memberships across table reconstruction; the next empty desired state wins. + eng.update_state({}, {}, pending_guests=[]) + + assert fake.blocked == set() + assert fake._sets["inet quota_gateway"]["blocked6"] == set() + assert fake.blocked_macs == set() + assert fake._sets["inet quota_gateway"]["pending_guests"] == set() + + +def test_missing_nft_during_enforcement_sync_marks_engine_unavailable(): + fake = FakeNft() + eng = _engine(fake) + eng.start() + original = fake.__call__ + + def nft_missing(argv): + if argv[1:2] == ["-f"]: + return 127, "nft: not found" + return original(argv) + + eng._run_command = nft_missing + eng.update_state({"192.168.2.111": "aa:bb:cc:dd:ee:01"}, + {"aa:bb:cc:dd:ee:01": True}) + assert not eng.available + assert "nft: not found" in eng.last_error + + +def test_set_apply_error_is_reported_but_does_not_disable_nft_engine(): + fake = FakeNft() + eng = _engine(fake) + eng.start() + original = fake.__call__ + + def missing_set(argv): + if argv[1:2] == ["-f"]: + return 1, "Error: No such file or directory" + return original(argv) + + eng._run_command = missing_set + eng.update_state({"192.168.2.111": "aa:bb:cc:dd:ee:01"}, + {"aa:bb:cc:dd:ee:01": True}) + assert eng.available + assert "No such file or directory" in eng.sync_error + + +def test_scoped_or_invalid_ips_never_reach_nft_device_rules(): + fake = FakeNft() + eng = _engine(fake) + eng.start() + eng.update_state({"fe80::1%eth0": "aa:bb:cc:dd:ee:01", + "bad-address": "aa:bb:cc:dd:ee:02"}, + {"aa:bb:cc:dd:ee:01": True, + "aa:bb:cc:dd:ee:02": True}, + pending_guests=["192.168.2.111%eth0"]) + assert eng.available + assert not eng._installed + assert fake.blocked == set() + assert fake._sets["inet quota_gateway"]["blocked6"] == set() + assert fake._sets["inet quota_gateway"]["pending_guests"] == set() + assert not any("fe80::1%eth0" in str(call) or "bad-address" in str(call) + for call in fake.calls) + + def test_flush_returns_delta_since_last_flush(): fake = FakeNft() eng = _engine(fake) diff --git a/tests/test_run_wiring.py b/tests/test_run_wiring.py index 55a6355..083d927 100644 --- a/tests/test_run_wiring.py +++ b/tests/test_run_wiring.py @@ -2649,6 +2649,26 @@ def __call__(self, argv: list[str]) -> tuple[int, str]: self.calls.append(argv) if argv[0] != "nft": return 1, f"unknown binary {argv[0]}" + if argv[1:2] == ["-f"]: + with open(argv[2], encoding="utf-8") as batch_file: + commands = [line.strip() for line in batch_file if line.strip()] + updated = {table: {name: set(members) + for name, members in sets.items()} + for table, sets in self._sets.items()} + for line in commands: + words = line.split() + table, name = " ".join(words[2:4]), words[4] + members = updated.setdefault(table, {}).setdefault(name, set()) + if words[:2] == ["flush", "set"]: + members.clear() + elif words[:2] == ["add", "element"]: + for ip in " ".join(words[5:]).strip("{} ").split(","): + if ip.strip(): + members.add(ip.strip()) + else: + return 1, f"unsupported batch command: {line}" + self._sets = updated + return 0, "" args = argv[1:] if args[0] == "-j": # nft -j list counters return self._list_counters()