224 lines
8.8 KiB
Python
224 lines
8.8 KiB
Python
"""Synthetic DHCP/route regression; never calls the host network tools."""
|
|
import importlib.util
|
|
from pathlib import Path
|
|
from types import SimpleNamespace
|
|
|
|
import pytest
|
|
|
|
|
|
@pytest.fixture
|
|
def network(tmp_path, monkeypatch):
|
|
spec = importlib.util.spec_from_file_location("route_recovery_helper", Path(__file__).with_name("helper.py"))
|
|
helper = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(helper)
|
|
monkeypatch.setattr(helper, "DARWIN", True)
|
|
manager = helper.Manager(tmp_path)
|
|
endpoint = "203.0.113.7"
|
|
old = dict(endpoint=endpoint, gateway="192.168.90.1", source="192.168.90.10", interface="en0")
|
|
row = dict(config={"interface": "en0"}, pending=None, physical_endpoint=endpoint,
|
|
host_route=dict(old), host_routes={endpoint: dict(old)}, interface="utun42")
|
|
manager.profiles["fleet"] = row
|
|
state = dict(source="192.168.90.20", gateway="192.168.90.1", actual=dict(old), now=100.0, lease=True)
|
|
calls = []
|
|
monkeypatch.setattr(helper.time, "monotonic", lambda: state["now"])
|
|
|
|
def run(*args, **kwargs):
|
|
calls.append(args)
|
|
if args[0] == "/usr/sbin/ipconfig":
|
|
if not state["lease"]:
|
|
raise helper.subprocess.CalledProcessError(1, args)
|
|
value = state["source"] if args[1] == "getifaddr" else state["gateway"]
|
|
elif args[:3] == ("/sbin/route", "-n", "get"):
|
|
actual = state["actual"]
|
|
value = ("flags: <UP,GATEWAY,HOST,STATIC>\ngateway: " + actual["gateway"] +
|
|
"\ninterface: " + actual["interface"] + "\n") if actual else "flags: <UP,GATEWAY>\n"
|
|
elif args[:3] in (("/sbin/route", "-n", "change"), ("/sbin/route", "-n", "add")):
|
|
assert args[3:5] == ("-host", endpoint)
|
|
state["actual"] = dict(endpoint=endpoint, gateway=args[5], source=args[7], interface="en0")
|
|
value = ""
|
|
else:
|
|
raise AssertionError("Unexpected system operation: " + repr(args))
|
|
return SimpleNamespace(stdout=value.encode(), returncode=0)
|
|
|
|
monkeypatch.setattr(helper, "run", run)
|
|
return SimpleNamespace(helper=helper, manager=manager, row=row, state=state, calls=calls, endpoint=endpoint)
|
|
|
|
|
|
def mutations(n):
|
|
return [c for c in n.calls if c[:3] in (("/sbin/route", "-n", "change"), ("/sbin/route", "-n", "add"))]
|
|
|
|
|
|
def test_dhcp_source_change_repairs_owned_host_route_without_resetting_tunnel(network):
|
|
n = network
|
|
n.manager.refresh_physical_routes()
|
|
assert mutations(n) == [("/sbin/route", "-n", "change", "-host", n.endpoint,
|
|
"192.168.90.1", "-ifa", "192.168.90.20")]
|
|
assert n.row["host_route"]["source"] == "192.168.90.20"
|
|
assert n.row["interface"] == "utun42"
|
|
assert not any("wg" in c[0] or "ifconfig" in c[0] for c in n.calls)
|
|
# Another periodic pass with stable DHCP makes no network mutation.
|
|
n.state["now"] += 6
|
|
n.manager.refresh_physical_routes()
|
|
assert len(mutations(n)) == 1
|
|
|
|
|
|
def test_checks_are_rate_limited_and_do_not_rewrite_stable_routes(network):
|
|
n = network
|
|
n.state["source"] = "192.168.90.10"
|
|
n.manager.refresh_physical_routes()
|
|
first = len(n.calls)
|
|
for _ in range(20):
|
|
n.manager.refresh_physical_routes()
|
|
assert len(n.calls) == first
|
|
assert not mutations(n)
|
|
|
|
|
|
def test_gateway_change_updates_only_the_previously_owned_host_route(network):
|
|
n = network
|
|
n.state.update(gateway="192.168.91.1", source="192.168.91.20")
|
|
n.manager.refresh_physical_routes()
|
|
assert mutations(n)[0][3:] == ("-host", n.endpoint, "192.168.91.1", "-ifa", "192.168.91.20")
|
|
|
|
|
|
def test_removed_owned_route_is_recreated_without_changing_default_route(network):
|
|
n = network
|
|
n.state["actual"] = None
|
|
n.manager.refresh_physical_routes()
|
|
assert mutations(n)[0][2:5] == ("add", "-host", n.endpoint)
|
|
|
|
|
|
def test_missing_wifi_lease_is_retried_after_reconnection(network):
|
|
n = network
|
|
n.state["lease"] = False
|
|
n.manager.refresh_physical_routes()
|
|
assert not mutations(n)
|
|
assert n.row["config"] == {"interface": "en0"}
|
|
n.state.update(lease=True, now=106.0)
|
|
n.manager.refresh_physical_routes()
|
|
assert len(mutations(n)) == 1
|
|
|
|
|
|
def test_foreign_replacement_is_preserved_and_a_later_pass_can_recover(network):
|
|
n = network
|
|
own = dict(n.state["actual"])
|
|
n.state["actual"] = dict(own, gateway="100.64.0.1", interface="utun9")
|
|
n.manager.refresh_physical_routes()
|
|
assert not mutations(n)
|
|
n.state.update(actual=own, now=106.0)
|
|
n.manager.refresh_physical_routes()
|
|
assert len(mutations(n)) == 1
|
|
|
|
|
|
@pytest.mark.parametrize("change", [
|
|
{"pending": {"id": "transaction"}}, {"config": None},
|
|
{"config": {}}, {"physical_endpoint": None}, {"host_route": None, "host_routes": {}},
|
|
])
|
|
def test_inactive_pending_and_unowned_profiles_are_not_changed(network, change):
|
|
n = network
|
|
n.row.update(change)
|
|
n.manager.refresh_physical_routes()
|
|
assert n.calls == []
|
|
|
|
|
|
def test_linux_underlay_is_not_managed_by_macos_recovery(network, monkeypatch):
|
|
n = network
|
|
monkeypatch.setattr(n.helper, "DARWIN", False)
|
|
n.manager.refresh_physical_routes()
|
|
assert n.calls == []
|
|
|
|
|
|
def test_legacy_owned_route_record_remains_recoverable(network):
|
|
n = network
|
|
n.row.pop("host_routes")
|
|
n.manager.refresh_physical_routes()
|
|
assert n.row["host_routes"][n.endpoint]["source"] == "192.168.90.20"
|
|
|
|
|
|
def test_one_unavailable_network_does_not_block_another_profile(network, monkeypatch):
|
|
n = network
|
|
second = dict(n.row)
|
|
n.manager.profiles["other"] = second
|
|
calls = []
|
|
def refresh(config, endpoint, row):
|
|
calls.append(row)
|
|
if row is n.row:
|
|
raise OSError("No DHCP lease")
|
|
monkeypatch.setattr(n.manager, "physical_route", refresh)
|
|
n.manager.refresh_physical_routes()
|
|
assert len(calls) == 2 and calls[1] is second
|
|
|
|
|
|
@pytest.mark.parametrize("cached", [True, False])
|
|
def test_peer_route_cache_from_another_vpn_is_distinct_from_a_foreign_static_route(tmp_path, monkeypatch, cached):
|
|
spec = importlib.util.spec_from_file_location("peer_route_helper", Path(__file__).with_name("helper.py"))
|
|
h = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(h)
|
|
monkeypatch.setattr(h, "DARWIN", True)
|
|
monkeypatch.setattr(h, "validate", lambda config: "203.0.113.7")
|
|
m = h.Manager(tmp_path)
|
|
monkeypatch.setattr(m, "physical_route", lambda *args: None)
|
|
monkeypatch.setattr(m, "retire_physical_routes", lambda *args: None)
|
|
row = dict(interface="utun42", public_key="synthetic-public", private_key="synthetic-private", routes=[])
|
|
config = dict(server_id="wg_" + "1" * 32, server_public_key="synthetic-server", address="10.203.45.2", allowed_ips=["10.203.45.3/32"])
|
|
calls = []
|
|
def run(*args, **kwargs):
|
|
calls.append(args)
|
|
if args[0] == "/usr/sbin/sysctl":
|
|
data = "0"
|
|
elif args[1:] == ("show", "utun42", "public-key"):
|
|
data = "synthetic-public"
|
|
elif args[:3] == ("/sbin/route", "-n", "get"):
|
|
flags = "UP,HOST,WASCLONED,IFSCOPE" if cached else "UP,HOST,STATIC"
|
|
data = "flags: <" + flags + ">\ninterface: utun9\n"
|
|
else:
|
|
data = ""
|
|
return SimpleNamespace(stdout=data.encode(), returncode=0)
|
|
monkeypatch.setattr(h, "run", run)
|
|
if cached:
|
|
m.apply(row, config)
|
|
assert ("/sbin/route", "-n", "delete", "-host", "10.203.45.3", "-ifscope", "utun9") in calls
|
|
assert ("/sbin/route", "-n", "add", "-host", "10.203.45.3", "-interface", "utun42") in calls
|
|
assert row["routes"] == ["10.203.45.3/32"]
|
|
else:
|
|
with pytest.raises(ValueError, match="conflicts"):
|
|
m.apply(row, config)
|
|
assert not any(c[:3] in (("/sbin/route", "-n", "delete"), ("/sbin/route", "-n", "add")) for c in calls)
|
|
|
|
|
|
def test_failed_startup_restore_retries_then_stops_without_resetting_healthy_tunnel(network, monkeypatch):
|
|
n = network
|
|
calls = []
|
|
def apply(row, config):
|
|
calls.append(config)
|
|
if len(calls) == 1:
|
|
raise OSError("Wi-Fi not ready during boot")
|
|
monkeypatch.setattr(n.manager, "apply", apply)
|
|
n.manager.restore(startup=True)
|
|
n.manager.restore()
|
|
assert len(calls) == 1
|
|
n.state["now"] += 6
|
|
n.manager.restore()
|
|
assert len(calls) == 2
|
|
assert not n.manager.restore_retry
|
|
n.state["now"] += 60
|
|
n.manager.restore()
|
|
assert len(calls) == 2
|
|
|
|
|
|
def test_failed_rollback_retains_transaction_and_retries_saved_previous_profile(network, monkeypatch):
|
|
n = network
|
|
previous = {"previous": True}
|
|
n.row["pending"] = {"deadline": 0, "previous": previous}
|
|
calls = []
|
|
def apply(row, config):
|
|
calls.append(config)
|
|
if len(calls) == 1:
|
|
raise OSError("Transient route failure")
|
|
monkeypatch.setattr(n.manager, "apply", apply)
|
|
n.manager.restore(startup=True)
|
|
assert n.row["pending"]
|
|
n.state["now"] += 6
|
|
n.manager.restore()
|
|
assert calls == [previous, previous]
|
|
assert n.row["pending"] is None
|