feat(worker): supervise VPN connections and recover batched telemetry
This commit is contained in:
@@ -0,0 +1,144 @@
|
||||
import json
|
||||
import plistlib
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
|
||||
from k1link.compute_connections import tailscale_client as client
|
||||
from k1link.compute_connections.service import ConnectionService
|
||||
from k1link.compute_connections.store import ConnectionError
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def installed(monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
client,
|
||||
"installed_client",
|
||||
lambda: (Path("/Applications/Tailscale.app"), "/client", "1.102.3"),
|
||||
)
|
||||
command = Mock(
|
||||
return_value=b'{"BackendState":"Running","CurrentTailnet":{"MagicDNSSuffix":"one.ts.net"}}'
|
||||
)
|
||||
monkeypatch.setattr(client, "run", command)
|
||||
return command
|
||||
|
||||
|
||||
def test_bundled_cli_discovery_without_path_integration(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(client.sys, "platform", "darwin")
|
||||
app = tmp_path / "Tailscale.app"
|
||||
executable = app / "Contents/MacOS/Tailscale"
|
||||
executable.parent.mkdir(parents=True)
|
||||
executable.write_bytes(b"synthetic executable; never run")
|
||||
executable.chmod(0o700)
|
||||
(app / "Contents/Info.plist").write_bytes(
|
||||
plistlib.dumps(
|
||||
{
|
||||
"CFBundleIdentifier": "io.tailscale.ipn.macsys",
|
||||
"CFBundleShortVersionString": "9.99.1",
|
||||
}
|
||||
)
|
||||
)
|
||||
assert client.installed_client(app_dirs=(tmp_path,)) == (app, str(executable), "9.99.1")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"backend,state",
|
||||
[
|
||||
("Running", "connected"),
|
||||
("NeedsLogin", "needs_login"),
|
||||
("Stopped", "stopped"),
|
||||
("NeedsMachineAuth", "needs_approval"),
|
||||
("Starting", "starting"),
|
||||
("UnknownFutureState", "unavailable"),
|
||||
],
|
||||
)
|
||||
def test_client_states_and_no_automatic_mutations(installed, backend, state):
|
||||
installed.return_value = json.dumps(
|
||||
{"BackendState": backend, "AuthURL": "PRIVATE-LOGIN"}
|
||||
).encode()
|
||||
summary, _ = client.observe()
|
||||
assert summary["state"] == state
|
||||
assert "PRIVATE-LOGIN" not in json.dumps(summary)
|
||||
installed.assert_called_once_with(["/client", "status", "--json"], cli=True)
|
||||
|
||||
|
||||
def test_noninteractive_cli_mode_is_explicit_and_does_not_replace_parent_environment(monkeypatch):
|
||||
process = Mock(return_value=subprocess.CompletedProcess([], 0, b"{}", b""))
|
||||
monkeypatch.setattr(client.subprocess, "run", process)
|
||||
monkeypatch.delenv("TAILSCALE_BE_CLI", raising=False)
|
||||
monkeypatch.setenv("TEST_EXISTING_ENV", "preserve")
|
||||
client.run(["/client", "status", "--json"], cli=True)
|
||||
env = process.call_args.kwargs["env"]
|
||||
assert env["TAILSCALE_BE_CLI"] == "1"
|
||||
assert env["TEST_EXISTING_ENV"] == "preserve"
|
||||
assert "TAILSCALE_BE_CLI" not in client.os.environ
|
||||
client.run(["/usr/bin/open", "-a", "/Applications/Tailscale.app"])
|
||||
assert process.call_args.kwargs["env"] is None
|
||||
|
||||
|
||||
def test_missing_client_is_not_logged_out(monkeypatch):
|
||||
monkeypatch.setattr(client, "installed_client", lambda: (None, None, None))
|
||||
command = Mock()
|
||||
monkeypatch.setattr(client, "run", command)
|
||||
summary, status = client.observe()
|
||||
assert summary["state"] == "not_installed" and not summary["can_open"] and status is None
|
||||
command.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("response", [b"not JSON", b"[]", subprocess.TimeoutExpired("client", 4)])
|
||||
def test_failed_probe_is_bounded_and_unavailable(installed, response):
|
||||
if isinstance(response, Exception):
|
||||
installed.side_effect = response
|
||||
else:
|
||||
installed.return_value = response
|
||||
assert client.observe()[0]["state"] == "unavailable"
|
||||
|
||||
|
||||
def test_reopen_running_client_never_logs_out_or_switches(installed):
|
||||
assert client.open_client() == {"state": "opened"}
|
||||
assert [c.args[0] for c in installed.call_args_list] == [
|
||||
["/usr/bin/open", "-a", "/Applications/Tailscale.app"],
|
||||
["/client", "status", "--json"],
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"url,opened",
|
||||
[
|
||||
("https://login.tailscale.com/a/synthetic", True),
|
||||
("https://foreign.test/a/synthetic", False),
|
||||
("https://login.tailscale.com@foreign.test/a/synthetic", False),
|
||||
("file:///tmp/untrusted", False),
|
||||
],
|
||||
)
|
||||
def test_auth_reuses_only_official_client_login_url(installed, url, opened):
|
||||
installed.return_value = json.dumps({"BackendState": "NeedsLogin", "AuthURL": url}).encode()
|
||||
client.open_client()
|
||||
assert (["/usr/bin/open", url] in [c.args[0] for c in installed.call_args_list]) is opened
|
||||
|
||||
|
||||
def test_catalog_refresh_new_peer_and_account_change_without_store_mutation(tmp_path, installed):
|
||||
manager = ConnectionService(tmp_path, wireguard=lambda: [])
|
||||
first = manager.catalog()
|
||||
assert first["peers"] == [] and first["tailscale_client"]["state"] == "connected"
|
||||
installed.return_value = json.dumps(
|
||||
{
|
||||
"BackendState": "Running",
|
||||
"CurrentTailnet": {"MagicDNSSuffix": "one.ts.net"},
|
||||
"Peer": {"key": {"ID": "one", "DNSName": "worker.one.ts.net.", "Online": True}},
|
||||
}
|
||||
).encode()
|
||||
assert len(manager.catalog()["peers"]) == 1
|
||||
installed.return_value = (
|
||||
b'{"BackendState":"Running","CurrentTailnet":{"MagicDNSSuffix":"two.ts.net"}}'
|
||||
)
|
||||
assert manager.catalog()["available_profile_ids"] != first["available_profile_ids"]
|
||||
assert manager.catalog()["workers"] == []
|
||||
installed.return_value = b'{"BackendState":"NeedsLogin"}'
|
||||
logged_out = manager.catalog()
|
||||
assert logged_out["peers"] == [] and logged_out["available_profile_ids"] == []
|
||||
assert logged_out["tailscale_client"]["state"] == "needs_login"
|
||||
with pytest.raises(ConnectionError):
|
||||
client.running_status()
|
||||
Reference in New Issue
Block a user