fix(transport): recover rover feedback and retained WireGuard routes

This commit is contained in:
DCCONSTRUCTIONS
2026-11-04 00:42:24 +03:00
parent f4cdf3744a
commit 1e77b198cb
12 changed files with 833 additions and 30 deletions
+65 -9
View File
@@ -94,6 +94,8 @@ class Manager:
self.path = self.root / "profiles.json"
self.profiles = json.loads(self.path.read_text()) if self.path.exists() else {}
self.children = {}
self.next_physical_route_check = 0.0
self.restore_retry = {}
def persist(self):
save(self.path, self.profiles)
@@ -146,14 +148,47 @@ class Manager:
return
# A migrated VPS has a new destination, so it needs a new /32 even when
# this profile owns a route to its previous VPS. Reboots may remove routes.
record = {"endpoint": endpoint, "gateway": gateway, "source": source, "interface": interface}
if is_host and prior == record:
return # Stable DHCP state: no route rewrite or tunnel reconfiguration.
command = "change" if is_host and prior else "add"
run("/sbin/route", "-n", command, "-host", endpoint, gateway, "-ifa", source)
record = {"endpoint": endpoint, "gateway": gateway, "source": source, "interface": interface}
owned[endpoint] = record
row["host_route"] = record
row["physical_endpoint"] = endpoint
self.persist()
def refresh_physical_routes(self):
"""Repair only our explicit VPS /32 after the selected Mac LAN changes.
WireGuard keepalives cannot repair a macOS route whose cached source is
an expired DHCP address. Leave peer keys, tunnel state, default routes,
foreign routes and the selected physical interface unchanged.
"""
if not DARWIN:
return
with self.lock:
now = time.monotonic()
if now < self.next_physical_route_check:
return
self.next_physical_route_check = now + 5
for row in self.profiles.values():
config = row.get("config")
endpoint = row.get("physical_endpoint")
if not config or not config.get("interface") or row.get("pending") or not endpoint:
continue
owned = row.get("host_routes", {})
legacy = row.get("host_route") or {}
if endpoint not in owned and legacy.get("endpoint") != endpoint:
continue
try:
self.physical_route(config, endpoint, row)
except (OSError, ValueError, IndexError, subprocess.SubprocessError):
# No DHCP lease, a foreign route or a transient failure must
# not disable the tunnel or prevent another profile's check.
# Retry on the next bounded pass without touching the VPN.
continue
def retire_physical_routes(self, row):
if not DARWIN:
return
@@ -238,7 +273,17 @@ class Manager:
if DARWIN:
result = run("/sbin/route", "-n", "get", route[:-3], check=False).stdout.decode()
fields = dict(line.strip().split(":", 1) for line in result.splitlines() if ":" in line)
exists = "HOST" in fields.get("flags", "")
flags = fields.get("flags", "")
# A scoped cache created from another VPN's default route is
# not an administrator's explicit host route. Retire only this
# exact cached fleet destination before adding our /32.
if "HOST" in flags and "WASCLONED" in flags:
cached_interface = fields.get("interface", "").strip()
if not re.fullmatch(r"(?:utun|en)[0-9]+", cached_interface):
raise ValueError("Unrecognized cached route interface")
run("/sbin/route", "-n", "delete", "-host", route[:-3], "-ifscope", cached_interface, check=False)
flags = ""
exists = "HOST" in flags
own = exists and fields.get("interface", "").strip() == name
else:
entries = json.loads(run("/usr/sbin/ip", "-j", "route", "show", "exact", route).stdout)
@@ -348,14 +393,24 @@ class Manager:
def restore(self, startup=False):
with self.lock:
for row in self.profiles.values():
for identity, row in self.profiles.items():
pending = row.get("pending")
if pending and (startup or pending["deadline"] <= time.time()):
self.apply(row, pending["previous"])
row["pending"] = None
self.persist()
elif startup and row.get("config"):
self.apply(row, row["config"])
rollback = pending and (startup or pending["deadline"] <= time.time())
if not (rollback or (row.get("config") and (startup or identity in self.restore_retry))):
continue
if not startup and time.monotonic() < self.restore_retry.get(identity, 0):
continue
try:
self.apply(row, pending["previous"] if rollback else row["config"])
if rollback:
row["pending"] = None
self.persist()
except Exception:
# A late DHCP lease or transient route failure at boot must
# not leave an apparently running helper permanently partial.
self.restore_retry[identity] = time.monotonic() + 5
else:
self.restore_retry.pop(identity, None)
class Handler(socketserver.StreamRequestHandler):
@@ -405,6 +460,7 @@ def main():
manager.restore()
except Exception:
pass
manager.refresh_physical_routes()
if __name__ == "__main__":
@@ -0,0 +1,223 @@
"""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