"""Simulation only: fake NM adapter never opens a bus or mutates host networking.""" import copy import sys from pathlib import Path import pytest sys.path.insert(0, str(Path(__file__).parent)) from uplink.transaction import Controller, dispatch # noqa: E402 A, B = "a" * 36, "b" * 36 class FakeNM: def __init__(self): self.generation = "boot:nm-1" self.current = A self.verified = True self.checkpoint_exists = False self.writes = [] self.fail_apply = self.fail_rollback = False self.disconnected = set() self.profiles = {i: dict(id=i, kind=k, saved=dict( autoconnect=True, metrics={"ipv4": 50, "ipv6": 50}, defaults={"ipv4": False, "ipv6": False})) for i,k in ((A,"wifi"),(B,"ethernet"))} def epoch(self): return self.generation def inspect(self, refresh=False, known=()): return dict( supported=True, revision="r1", current_id=self.current, candidates=[ dict(id=i, verified=(i == A or self.verified), interface="nic" + i[0], kind=self.profiles[i]["kind"], saved=copy.deepcopy(self.profiles[i]["saved"])) for i in (A, B) if i not in self.disconnected ], ) def public(self, value): return copy.deepcopy(value) def checkpoint(self, entries): self.checkpoint_exists = True self.writes.append("checkpoint") return "/checkpoint/1" def apply(self, entries, target): self.writes.append("apply") self.current = target if self.fail_apply: raise ValueError("simulated partial apply") def checkpoints(self): return {"/checkpoint/1"} if self.checkpoint_exists else set() def rollback(self, checkpoint): self.writes.append("rollback") if self.fail_rollback: raise ValueError("simulated rollback failure") self.current, self.checkpoint_exists = A, False self.disconnected = set() def confirm(self, checkpoint): assert self.checkpoint_exists self.writes.append("confirm") self.checkpoint_exists = False def select_only(self, entries, target): raise AssertionError('Never inhibit native autoconnect') def locally_changed(self, entries, target): return any(e.get('planned') and self.profiles.get(e['id'], {}).get('saved') != e['planned'] for e in entries if e['id'] in self.profiles) def reserves(self, entries): return [e for e in entries if e["id"] in self.disconnected] def activate(self, entry): self.disconnected.discard(entry["id"]) def profile_preferences(self): return copy.deepcopy(self.profiles) def release_reserves(self, entries, target, resume_wifi=True): if resume_wifi: self.disconnected.clear() def resume_autoconnect(self, entries): self.disconnected.clear() def prefer_observed(self, entries, target, profiles): self.writes.append("adopt") self.current=target self.persist_choice(profiles, target) return profiles def persist_choice(self, entries, target): self.persisted = target for entry in entries: self.profiles[entry["id"]]["saved"] = copy.deepcopy(entry["planned"]) def snapshot_profiles(self, entries, target): from uplink.preferences import choice result=copy.deepcopy(entries) for index,entry in enumerate(result): entry["saved"]=copy.deepcopy(self.profiles[entry["id"]]["saved"]) entry["planned"]=choice(entry,target,index) return result def restore_profiles(self, entries): self.persisted = A for entry in entries: if entry['id'] in self.profiles: self.profiles[entry['id']]['saved'] = copy.deepcopy(entry['saved']) def restore_metrics(self, entries): self.current = A class FakePath: def __init__(self): self.valid = True self.selected = None def select(self, policy): self.selected = policy.copy() def release(self): self.selected = None def prepare(self, peer, interface): return dict(peer=peer, interface=interface) def evidence(self, policy): return self.valid def heartbeat(c): return dispatch( c, dict(action="heartbeat", binding="pairing:runtime", peer="10.42.0.1", provider="netbird") ) @pytest.fixture def setup(tmp_path): now, adapter = [1000], FakeNM() c = Controller(tmp_path, adapter, lambda: now[0], FakePath()) heartbeat(c) return c, adapter, now def command(**changes): return dict( action="stage", id="a" * 32, binding="pairing:runtime", target=B, revision="r1", expires_at=1030, **changes, ) def ack(c): return {"action": "confirm", **{k: c.operation[k] for k in ("id", "binding", "nonce")}} def test_read_only_start_and_status(setup): c, nm, _ = setup assert dispatch(c, {"action": "status"})["current_id"] == A assert nm.writes == [] def test_confirm_keeps_selected_and_duplicate_never_reapplies(setup): c, nm, now = setup body = command() body["revision"] = c.status()["revision"] dispatch(c, body) settle(c, now) assert c.operation["phase"] == "verifying" body = command() body["revision"] = c.status()["revision"] dispatch(c, body) dispatch(c, ack(c)) dispatch(c, ack(c)) now[0] += 10 heartbeat(c) c.tick() assert nm.current == B and nm.writes == ["checkpoint", "apply", "confirm"] @pytest.mark.parametrize( "field,value", [("revision", "stale"), ("expires_at", 999), ("target", "unknown"), ("id", "malformed")], ) def test_stale_invalid_commands_have_zero_writes(setup, field, value): c, nm, _ = setup body = command() body["revision"] = c.status()["revision"] body[field] = value with pytest.raises(ValueError): dispatch(c, body) assert nm.writes == [] def test_unverified_link_and_ambiguous_default_are_not_candidates(setup): c, nm, _ = setup nm.verified = False with pytest.raises(ValueError): body = command() body["revision"] = c.status()["revision"] dispatch(c, body) nm.verified, nm.current = True, "" with pytest.raises(ValueError): body = command() body["revision"] = c.status()["revision"] dispatch(c, body) assert not nm.writes def test_lost_core_rolls_back_without_ack(setup): c, nm, now = setup body = command() body["revision"] = c.status()["revision"] dispatch(c, body) now[0] += 81 c.tick() assert nm.current == A and c.operation["phase"] == "recovering" with pytest.raises(ValueError): dispatch(c, ack(c)) def test_helper_restart_restores_pending_and_never_replays(setup): c, nm, now = setup body = command() body["revision"] = c.status()["revision"] dispatch(c, body) recovered = Controller(c.root, nm, lambda: now[0], c.path_adapter) assert recovered.operation["phase"] == "recovering" heartbeat(recovered) dispatch(recovered, body) assert nm.writes.count("apply") == 1 def test_partial_apply_rolls_back(setup): c, nm, _ = setup nm.fail_apply = True body = command() body["revision"] = c.status()["revision"] dispatch(c, body) assert c.operation["phase"] == "recovering" and nm.current == A def test_changed_binding_nonce_and_target_loss_cannot_confirm(setup): c, nm, now = setup body = command() body["revision"] = c.status()["revision"] dispatch(c, body) settle(c, now) for field in ("binding", "nonce", "id"): bad = ack(c) bad[field] = "x" with pytest.raises(ValueError): dispatch(c, bad) nm.verified = False dispatch(c, ack(c)) assert c.operation["phase"] == "verifying" def test_rollback_failure_is_never_success_and_blocks_new_writes(setup): c, nm, now = setup body = command() body["revision"] = c.status()["revision"] dispatch(c, body) nm.fail_rollback = True now[0] += 81 c.tick() assert c.operation["phase"] == "rollback_failed" body = command() body.update(id="b" * 32, expires_at=1100) with pytest.raises(ValueError): dispatch(c, body) assert nm.writes.count("apply") == 1 def test_automatic_nm_timeout_and_reboot_without_checkpoint(setup): c, nm, now = setup body = command() body["revision"] = c.status()["revision"] dispatch(c, body) nm.current, nm.checkpoint_exists = A, False now[0] += 91 c.tick() assert c.operation["phase"] == "recovering" def test_extra_fields_are_rejected(setup): c, nm, _ = setup for body in ({"action": "status", "shell": "x"}, {"action": "activate"}): with pytest.raises(ValueError): dispatch(c, body) assert not nm.writes def test_nm_reapply_changes_only_metrics_and_uses_version_cas(): from types import SimpleNamespace from uplink.network_manager import NetworkManager settings = { "connection": {"uuid": A}, "ipv4": {"method": "auto", "route-metric": 70}, "ipv6": {"method": "auto"}, "802-11-wireless": {"ssid": b"example"}, } original, writes = copy.deepcopy(settings), [] device = SimpleNamespace( GetAppliedConnection=lambda *args, **kwargs: (copy.deepcopy(settings), 7), Reapply=lambda data, version, flags, **kwargs: writes.append((data, version)), ) nm = NetworkManager.__new__(NetworkManager) nm.dbus = SimpleNamespace(Interface=lambda obj, _: obj, Int64=int, UInt32=int, Boolean=bool) nm.obj = lambda path: device nm.apply([{"id": A, "path": "/device/1", "version": 7}], A) sent, version = writes[0] assert version == 7 and sent["ipv4"]["route-metric"] == sent["ipv6"]["route-metric"] == 10 for family in ("ipv4", "ipv6"): sent[family].pop("route-metric") assert sent[family].pop("never-default") is False original[family].pop("route-metric", None) assert sent == original with pytest.raises(ValueError): nm.apply([{"id": A, "path": "/device/1", "version": 8}], A) assert len(writes) == 1 def test_restarted_nm_never_rolls_back_a_reused_foreign_checkpoint(setup): c, nm, now = setup body = command() body["revision"] = c.status()["revision"] dispatch(c, body) nm.generation = "boot:nm-2" nm.current = A # Another owner can now have the same object path in the new NM instance. recovered = Controller(c.root, nm, lambda: now[0], c.path_adapter) assert recovered.operation["phase"] == "recovering" assert "rollback" not in nm.writes and nm.checkpoint_exists def settle(c, now): """Next normal watchdog poll after asynchronous NM Reapply.""" now[0] += 6 c.tick() def select(c, now): body = command() body["revision"] = c.status()["revision"] dispatch(c, body) settle(c, now) return body def test_default_route_and_fresh_core_do_not_prove_vpn_path(setup): c, nm, now = setup select(c, now) c.path_adapter.valid = False assert nm.current == B heartbeat(c) dispatch(c, ack(c)) assert c.operation["phase"] == "verifying" assert not c.status()["operation"]["path_verified"] now[0] += 81 c.tick() assert nm.current == A and c.operation["phase"] == "recovering" def test_committed_selection_never_switches_after_lost_core(setup): c, nm, now = setup select(c, now) dispatch(c, ack(c)) assert not nm.disconnected assert {e["id"] for e in c.status()["candidates"]} == {A, B} writes = list(nm.writes) now[0] += 3600 c.tick() assert c.operation["phase"] == "applied" assert nm.current == B assert nm.writes == writes and not c.status()["path_verified"] def test_path_failure_enters_recovery_without_disconnecting(setup): c, nm, now = setup select(c, now) dispatch(c, ack(c)) c.path_adapter.valid = False for _ in range(4): now[0] += 5 heartbeat(c) assert c.operation["phase"] == "recovering" and nm.current == B assert not c.status()["path_verified"] def test_healthy_choice_does_not_promote_reserve(setup): c, nm, now = setup select(c, now) dispatch(c, ack(c)) for _ in range(20): now[0] += 5 heartbeat(c) assert nm.current == B and not nm.disconnected assert c.status()["path_verified"] def test_helper_restart_after_commit_does_not_switch(setup): c, nm, now = setup select(c, now) dispatch(c, ack(c)) recovered = Controller(c.root, nm, lambda: now[0], c.path_adapter) assert recovered.operation["phase"] == "applied" assert nm.current == B assert not recovered.status()["path_verified"] def test_original_journal_and_vpn_state_never_leak_through_ipc(setup): c, _, now = setup select(c, now) op = c.status()["operation"] assert not {"baseline", "policy", "checkpoint", "epoch"} & op.keys() def test_switch_back_can_activate_saved_disconnected_reserve(setup): c, nm, now = setup select(c, now) dispatch(c, ack(c)) now[0] += 5 heartbeat(c) body = command() body.update(id="b" * 32, target=A, revision=c.status()["revision"]) dispatch(c, body) settle(c, now) assert c.operation["phase"] == "verifying" dispatch(c, ack(c)) assert nm.current == A and not nm.disconnected def test_upgrade_does_not_trust_legacy_metric_only_applied_receipt(tmp_path): import json (tmp_path / "operation.json").write_text( json.dumps(dict(id="a" * 32, phase="applied", target=B)) ) nm = FakeNM() c = Controller(tmp_path, nm, lambda: 1000, FakePath()) heartbeat(c) assert c.operation["phase"] == "superseded" assert not c.status()["path_verified"] assert not nm.writes def test_wifi_selection_keeps_ethernet_lan_and_does_not_mutate_addresses(): from types import SimpleNamespace from uplink.network_manager import NetworkManager writes = [] states = { A: {"connection": {"uuid": A}, "ipv4": {"method": "auto", "address-data": ["lease"]}}, B: {"connection": {"uuid": B}, "ipv4": {"method": "auto", "address-data": ["router-lan"]}}, } devices = { identity: SimpleNamespace( GetAppliedConnection=lambda *a, i=identity, **k: (copy.deepcopy(states[i]), 1), Reapply=lambda data, *a, i=identity, **k: writes.append((i, data)), Disconnect=lambda *a, i=identity, **k: pytest.fail("Ethernet must stay connected"), ) for identity in (A, B) } nm = NetworkManager.__new__(NetworkManager) nm.dbus = SimpleNamespace(Interface=lambda obj, _: obj, Int64=int, UInt32=int, Boolean=bool) nm.obj = lambda path: devices[path] entries = [dict(id=A, path=A, version=1, kind="wifi"), dict(id=B, path=B, version=1, kind="ethernet")] nm.apply(entries, A) assert writes[0][1]["ipv4"]["never-default"] is False assert writes[1][1]["ipv4"]["never-default"] is False assert writes[1][1]["ipv4"]["address-data"] == ["router-lan"] @pytest.mark.parametrize("target", [A, B]) def test_saved_choice_retains_native_fallback(target): from uplink.network_manager import NetworkManager nm = NetworkManager.__new__(NetworkManager) values = {} nm.set_preference = lambda entry, value: values.update({entry["id"]: value}) nm.profile_preferences = lambda: {A: {"saved": {}}, B: {"saved": {}}} nm.persist_choice([dict(id=A, kind="wifi", saved={}), dict(id=B, kind="ethernet", saved={})], target) assert values[A]["autoconnect"] is True assert values[B]["autoconnect"] is True # Router LAN returns with its cable. assert values[B]["defaults"]["ipv4"] is False assert values[A]["defaults"]["ipv4"] is False def test_failed_manual_switch_returns_previous_and_then_stays_there(setup): c, nm, now = setup select(c, now) now[0] += 81 c.tick() now[0] += 1 heartbeat(c) now[0] += 11 heartbeat(c) assert c.operation["phase"] == "rolled_back" and nm.current == A before = list(nm.writes) now[0] += 3600 c.path_adapter.valid = False c.tick() assert nm.current == A and nm.writes == before