feat(worker): supervise VPN connections and recover batched telemetry
This commit is contained in:
@@ -0,0 +1,159 @@
|
||||
from threading import RLock
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
import k1link.web.compute_connection_api as api
|
||||
from k1link.compute_connections.store import Connection, NetworkProfile, Registry, WorkerBinding
|
||||
from k1link.web.fleet_api import local_operator
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def operator(tmp_path, monkeypatch):
|
||||
profile = NetworkProfile(
|
||||
id="network-one", name="Test", provider="tailscale", network_id="test.ts.net"
|
||||
)
|
||||
path = Connection(
|
||||
id="path-one", profile_id=profile.id, endpoint="worker.test.ts.net", peer_id="peer-one"
|
||||
)
|
||||
worker = WorkerBinding(
|
||||
contour_id="worker-seven",
|
||||
transport_id="worker-key",
|
||||
host_key_sha256="SHA256:" + "x" * 43,
|
||||
connections=(path,),
|
||||
active_connection_id=path.id,
|
||||
)
|
||||
registry = Registry(profiles=(profile,), workers=(worker,))
|
||||
manager = SimpleNamespace(
|
||||
lock=RLock(),
|
||||
store=SimpleNamespace(read=Mock(return_value=registry)),
|
||||
transport=SimpleNamespace(
|
||||
binding=Mock(return_value=SimpleNamespace(platform="windows")),
|
||||
execute=Mock(return_value=b"accepted\r\n"),
|
||||
),
|
||||
check=Mock(return_value={}),
|
||||
verify=Mock(return_value={}),
|
||||
catalog=Mock(return_value={}),
|
||||
)
|
||||
monkeypatch.setattr(api, "ConnectionService", lambda *_a, **_kw: manager)
|
||||
clock = [100.0]
|
||||
monkeypatch.setattr(api.time, "monotonic", lambda: clock[0])
|
||||
app = FastAPI()
|
||||
app.include_router(api.build_compute_connection_router(lambda: tmp_path))
|
||||
app.dependency_overrides[local_operator] = lambda: SimpleNamespace()
|
||||
with TestClient(app) as client:
|
||||
yield client, manager, worker, registry, clock, app
|
||||
|
||||
|
||||
def prepare(client):
|
||||
response = client.post("/api/v1/system/connections/worker-seven/power/prepare", json={})
|
||||
assert response.status_code == 200
|
||||
return response.json()["confirmation"]
|
||||
|
||||
|
||||
def test_shutdown_is_single_attempt(operator):
|
||||
client, manager, *_ = operator
|
||||
token = prepare(client)
|
||||
request = dict(confirmation=token)
|
||||
url = "/api/v1/system/connections/worker-seven/power/shutdown"
|
||||
assert client.post(url, json=request).json()["state"] == "accepted"
|
||||
assert client.post(url, json=request).status_code == 409
|
||||
manager.transport.execute.assert_called_once()
|
||||
|
||||
|
||||
def test_shutdown_expired_confirmation_never_executes(operator):
|
||||
client, manager, _, _, clock, _ = operator
|
||||
token = prepare(client)
|
||||
clock[0] += 31
|
||||
assert (
|
||||
client.post(
|
||||
"/api/v1/system/connections/worker-seven/power/shutdown", json=dict(confirmation=token)
|
||||
).status_code
|
||||
== 409
|
||||
)
|
||||
manager.transport.execute.assert_not_called()
|
||||
|
||||
|
||||
def test_shutdown_rebinding_invalidates_confirmation(operator):
|
||||
client, manager, worker, registry, *_ = operator
|
||||
token = prepare(client)
|
||||
manager.store.read.return_value = registry.model_copy(
|
||||
update={"workers": (worker.model_copy(update={"revision": 1}),)}
|
||||
)
|
||||
assert (
|
||||
client.post(
|
||||
"/api/v1/system/connections/worker-seven/power/shutdown", json=dict(confirmation=token)
|
||||
).status_code
|
||||
== 409
|
||||
)
|
||||
manager.transport.execute.assert_not_called()
|
||||
|
||||
|
||||
def test_shutdown_wrong_worker_is_rejected(operator):
|
||||
client, manager, *_ = operator
|
||||
token = prepare(client)
|
||||
assert (
|
||||
client.post(
|
||||
"/api/v1/system/connections/worker-other/power/shutdown", json=dict(confirmation=token)
|
||||
).status_code
|
||||
== 409
|
||||
)
|
||||
manager.transport.execute.assert_not_called()
|
||||
|
||||
|
||||
def test_uncertain_shutdown_has_no_retry(operator):
|
||||
from k1link.compute_connections.store import ConnectionError
|
||||
|
||||
client, manager, *_ = operator
|
||||
token = prepare(client)
|
||||
manager.transport.execute.side_effect = ConnectionError("Lost response")
|
||||
for _ in range(2):
|
||||
response = client.post(
|
||||
"/api/v1/system/connections/worker-seven/power/shutdown", json=dict(confirmation=token)
|
||||
)
|
||||
assert response.status_code == 409
|
||||
manager.transport.execute.assert_called_once()
|
||||
|
||||
|
||||
def test_worker_api_rejects_foreign_origin_and_non_loopback(operator):
|
||||
_, manager, _, _, _, app = operator
|
||||
app.dependency_overrides.clear()
|
||||
app.state.fleet = SimpleNamespace()
|
||||
with TestClient(app, base_url="http://localhost", client=("127.0.0.1", 3000)) as client:
|
||||
assert (
|
||||
client.get(
|
||||
"/api/v1/system/connections", headers={"Origin": "https://foreign.test"}
|
||||
).status_code
|
||||
== 403
|
||||
)
|
||||
assert client.get("/api/v1/system/connections").status_code == 200
|
||||
with TestClient(app, base_url="http://localhost", client=("10.1.2.3", 3000)) as client:
|
||||
assert client.get("/api/v1/system/connections").status_code == 403
|
||||
manager.transport.execute.assert_not_called()
|
||||
|
||||
|
||||
def test_open_client_requires_local_operator_and_is_never_called_by_catalog(operator, monkeypatch):
|
||||
_, _, _, _, _, app = operator
|
||||
opened = Mock(return_value={"state": "opened"})
|
||||
monkeypatch.setattr(api, "open_client", opened)
|
||||
app.dependency_overrides.clear()
|
||||
app.state.fleet = SimpleNamespace()
|
||||
with TestClient(app, base_url="http://localhost", client=("127.0.0.1", 3000)) as client:
|
||||
assert client.get("/api/v1/system/connections").status_code == 200
|
||||
opened.assert_not_called()
|
||||
assert (
|
||||
client.post(
|
||||
"/api/v1/system/connections/tailscale/open",
|
||||
json={},
|
||||
headers={"Origin": "https://foreign.test"},
|
||||
).status_code
|
||||
== 403
|
||||
)
|
||||
opened.assert_not_called()
|
||||
assert client.post("/api/v1/system/connections/tailscale/open", json={}).json() == {
|
||||
"state": "opened"
|
||||
}
|
||||
opened.assert_called_once()
|
||||
@@ -0,0 +1,187 @@
|
||||
import base64
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from k1link.compute_connections.service import ConnectionService
|
||||
from k1link.compute_connections.store import (
|
||||
Connection,
|
||||
ConnectionError,
|
||||
ConnectionStore,
|
||||
NetworkProfile,
|
||||
WorkerBinding,
|
||||
)
|
||||
from k1link.compute_connections.transport import (
|
||||
SshTransport,
|
||||
TransportBinding,
|
||||
tailscale_profile,
|
||||
validate_path,
|
||||
)
|
||||
|
||||
KEY = (
|
||||
"ssh-ed25519 "
|
||||
+ base64.b64encode(b"\x00\x00\x00\x0bssh-ed25519\x00\x00\x00\x20" + b"x" * 32).decode()
|
||||
)
|
||||
STATUS = dict(
|
||||
BackendState="Running",
|
||||
CurrentTailnet=dict(MagicDNSSuffix="test.ts.net"),
|
||||
Peer={"pk": dict(ID="peer-one", DNSName="worker.test.ts.net.", HostName="WORKER", Online=True)},
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def setup(tmp_path):
|
||||
profile = tailscale_profile(STATUS)
|
||||
connection = Connection(
|
||||
id="path-one", profile_id=profile.id, endpoint="worker.test.ts.net", peer_id="peer-one"
|
||||
)
|
||||
binding = TransportBinding(
|
||||
id="trusted-worker",
|
||||
contour_id="worker-seven",
|
||||
display_name="Worker seven",
|
||||
expected_hostname="WORKER",
|
||||
platform="windows",
|
||||
ssh_alias="prepared-worker",
|
||||
host_key=KEY,
|
||||
)
|
||||
worker = WorkerBinding(
|
||||
contour_id=binding.contour_id,
|
||||
transport_id=binding.id,
|
||||
host_key_sha256=binding.fingerprint,
|
||||
connections=(connection,),
|
||||
active_connection_id=connection.id,
|
||||
)
|
||||
root = tmp_path / "worker-bindings"
|
||||
root.mkdir(mode=0o700)
|
||||
private = root / (binding.id + ".json")
|
||||
private.write_text(binding.model_dump_json())
|
||||
private.chmod(0o600)
|
||||
(root / (binding.id + ".known_hosts")).write_text(binding.id + " " + KEY + "\n")
|
||||
return profile, connection, binding, worker
|
||||
|
||||
|
||||
def test_registry_rejects_corruption_and_stale_mutation(tmp_path, setup):
|
||||
profile, connection, _, worker = setup
|
||||
store = ConnectionStore(tmp_path)
|
||||
store.enroll(profile, worker, expected_revision=0)
|
||||
with pytest.raises(ConnectionError, match="изменились"):
|
||||
store.enroll(profile, worker, expected_revision=0)
|
||||
before = store.path.read_bytes()
|
||||
with pytest.raises(ConnectionError, match="не подготовлено"):
|
||||
store.select(worker.contour_id, "unknown", expected_revision=0)
|
||||
assert store.path.read_bytes() == before
|
||||
store.path.write_text("{broken")
|
||||
with pytest.raises(ConnectionError, match="прочитать"):
|
||||
store.read()
|
||||
assert store.path.read_text() == "{broken"
|
||||
|
||||
|
||||
def test_tailscale_requires_same_network_and_peer_address(setup):
|
||||
profile, connection, _, _ = setup
|
||||
validate_path(profile, connection, status=STATUS)
|
||||
for status in [
|
||||
dict(STATUS, CurrentTailnet=dict(MagicDNSSuffix="other.ts.net")),
|
||||
dict(STATUS, Peer={}),
|
||||
dict(STATUS, Peer={"pk": dict(STATUS["Peer"]["pk"], Online=False)}),
|
||||
]:
|
||||
with pytest.raises(ConnectionError):
|
||||
validate_path(profile, connection, status=status)
|
||||
wrong = connection.model_copy(update={"endpoint": "unrelated.test.ts.net"})
|
||||
with pytest.raises(ConnectionError, match="не принадлежит"):
|
||||
validate_path(profile, wrong, status=STATUS)
|
||||
|
||||
|
||||
def test_binding_pins_key_and_endpoint_without_shell_interpolation(tmp_path, setup):
|
||||
_, connection, binding, worker = setup
|
||||
transport = SshTransport(tmp_path / "worker-bindings")
|
||||
args = transport.arguments(worker, connection)
|
||||
assert "HostName=worker.test.ts.net" in args
|
||||
assert "StrictHostKeyChecking=yes" in args
|
||||
assert "HostKeyAlias=trusted-worker" in args
|
||||
assert args[-1] == "prepared-worker"
|
||||
path = transport.root / (binding.id + ".known_hosts")
|
||||
path.write_text("other-key\n")
|
||||
with pytest.raises(ConnectionError, match="Ключ"):
|
||||
transport.arguments(worker, connection)
|
||||
|
||||
|
||||
def test_attach_does_not_activate_or_touch_other_worker(tmp_path, setup, monkeypatch):
|
||||
profile, connection, _, worker = setup
|
||||
manager = ConnectionService(tmp_path, wireguard=lambda: [], tailscale=lambda: STATUS)
|
||||
manager.store.enroll(profile, worker, expected_revision=0)
|
||||
other = worker.model_copy(update={"contour_id": "worker-eight"})
|
||||
manager.store.enroll(profile, other, expected_revision=1)
|
||||
reserve = NetworkProfile(
|
||||
id="wg-reserve", name="Reserve", provider="wireguard", network_id="server-two"
|
||||
)
|
||||
path = Connection(
|
||||
id="path-two", profile_id=reserve.id, endpoint="10.203.1.3", peer_id="worker-seven"
|
||||
)
|
||||
monkeypatch.setattr(manager, "candidate", lambda *_: (reserve, path))
|
||||
monkeypatch.setattr(manager.transport, "probe", lambda *_: {})
|
||||
updated = manager.attach(worker.contour_id, reserve.id, path.peer_id, 0)
|
||||
assert updated.active_connection_id == connection.id
|
||||
assert len(updated.connections) == 2
|
||||
assert manager.store.read().worker(other.contour_id) == other
|
||||
|
||||
|
||||
def test_failed_identity_never_attaches_or_switches(tmp_path, setup, monkeypatch):
|
||||
profile, _, _, worker = setup
|
||||
manager = ConnectionService(tmp_path, wireguard=lambda: [], tailscale=lambda: STATUS)
|
||||
manager.store.enroll(profile, worker, expected_revision=0)
|
||||
before = manager.store.path.read_bytes()
|
||||
|
||||
def mismatch(*_):
|
||||
raise ConnectionError("Identity mismatch")
|
||||
|
||||
monkeypatch.setattr(manager.transport, "probe", mismatch)
|
||||
with pytest.raises(ConnectionError, match="mismatch"):
|
||||
manager.attach(worker.contour_id, profile.id, "peer-one", 0)
|
||||
assert manager.store.path.read_bytes() == before
|
||||
|
||||
|
||||
def test_catalog_never_discloses_provider_credentials(tmp_path, setup):
|
||||
manager = ConnectionService(
|
||||
tmp_path,
|
||||
wireguard=lambda: [
|
||||
dict(
|
||||
server_id="wg_one",
|
||||
name="VPS",
|
||||
subnet="10.203.1.0/24",
|
||||
status={"peers": []},
|
||||
token="DO-NOT-RETURN",
|
||||
)
|
||||
],
|
||||
tailscale=lambda: STATUS,
|
||||
)
|
||||
catalog = json.dumps(manager.catalog())
|
||||
assert "DO-NOT-RETURN" not in catalog
|
||||
assert "host_key" not in catalog
|
||||
assert "prepared-worker" not in catalog
|
||||
assert "Worker seven" in catalog
|
||||
|
||||
|
||||
def test_wireguard_does_not_admit_board_as_worker(tmp_path, setup):
|
||||
manager = ConnectionService(
|
||||
tmp_path,
|
||||
wireguard=lambda: [
|
||||
dict(
|
||||
server_id="wg_one",
|
||||
name="VPS",
|
||||
subnet="10.203.1.0/24",
|
||||
status={"peers": [dict(id="board", kind="node", address="10.203.1.3")]},
|
||||
)
|
||||
],
|
||||
tailscale=lambda: STATUS,
|
||||
)
|
||||
profile = next(x for x in manager.catalog()["profiles"] if x["provider"] == "wireguard")
|
||||
with pytest.raises(ConnectionError, match="воркер не найден"):
|
||||
manager.candidate(profile["id"], "board")
|
||||
|
||||
|
||||
def test_private_binding_permission_enforced(tmp_path, setup):
|
||||
_, _, binding, worker = setup
|
||||
transport = SshTransport(tmp_path / "worker-bindings")
|
||||
(transport.root / (binding.id + ".json")).chmod(0o644)
|
||||
with pytest.raises(ConnectionError, match="Права"):
|
||||
transport.binding(worker)
|
||||
@@ -108,6 +108,7 @@ class FakeTransport:
|
||||
failures: list[tuple[str, str, str]] = field(default_factory=list)
|
||||
renewals: list[int] = field(default_factory=list)
|
||||
renewed: Event | None = None
|
||||
contour_id: str = WORKER_006_CONTOUR_ID
|
||||
|
||||
def claim_next(
|
||||
self,
|
||||
@@ -133,7 +134,7 @@ class FakeTransport:
|
||||
job_id: str,
|
||||
claim_token: str,
|
||||
) -> Mapping[str, object]:
|
||||
assert claimant_id == WORKER_006_CONTOUR_ID
|
||||
assert claimant_id == self.contour_id
|
||||
self.starts.append(job_id)
|
||||
return self.queue.start(job_id, claim_token=claim_token).as_dict()
|
||||
|
||||
@@ -146,7 +147,7 @@ class FakeTransport:
|
||||
claim_generation: int,
|
||||
heartbeat_sequence: int,
|
||||
) -> Mapping[str, object]:
|
||||
assert claimant_id == WORKER_006_CONTOUR_ID
|
||||
assert claimant_id == self.contour_id
|
||||
renewed = self.queue.renew_claim(
|
||||
job_id,
|
||||
claim_token=claim_token,
|
||||
@@ -167,7 +168,7 @@ class FakeTransport:
|
||||
result_id: str,
|
||||
result_sha256: str,
|
||||
) -> Mapping[str, object]:
|
||||
assert claimant_id == WORKER_006_CONTOUR_ID
|
||||
assert claimant_id == self.contour_id
|
||||
self.successes.append((job_id, result_id, result_sha256))
|
||||
return self.queue.succeed(
|
||||
job_id,
|
||||
@@ -185,7 +186,7 @@ class FakeTransport:
|
||||
error_code: str,
|
||||
message: str,
|
||||
) -> Mapping[str, object]:
|
||||
assert claimant_id == WORKER_006_CONTOUR_ID
|
||||
assert claimant_id == self.contour_id
|
||||
self.failures.append((job_id, error_code, message))
|
||||
return self.queue.fail(
|
||||
job_id,
|
||||
@@ -347,7 +348,7 @@ class FailingRenewTransport(FakeTransport):
|
||||
claim_generation: int,
|
||||
heartbeat_sequence: int,
|
||||
) -> Mapping[str, object]:
|
||||
assert claimant_id == WORKER_006_CONTOUR_ID
|
||||
assert claimant_id == self.contour_id
|
||||
assert job_id
|
||||
assert claim_token
|
||||
assert claim_generation == 1
|
||||
@@ -515,6 +516,7 @@ def test_executor_error_is_reported_as_bounded_failure(tmp_path: Path) -> None:
|
||||
class BlockingEmptyTransport:
|
||||
entered: Event
|
||||
release: Event
|
||||
contour_id: str = "worker-006"
|
||||
|
||||
def claim_next(
|
||||
self,
|
||||
@@ -523,7 +525,7 @@ class BlockingEmptyTransport:
|
||||
claim_request_id: str,
|
||||
supported_executor_identities: tuple[ObservatoryWorkerExecutorIdentity, ...],
|
||||
) -> Mapping[str, object] | None:
|
||||
assert claimant_id == WORKER_006_CONTOUR_ID
|
||||
assert claimant_id == self.contour_id
|
||||
assert claim_request_id == "worker-006:overlap-test"
|
||||
assert supported_executor_identities == ()
|
||||
self.entered.set()
|
||||
@@ -594,3 +596,41 @@ def test_worker_agent_allows_only_one_claim_cycle_at_a_time() -> None:
|
||||
|
||||
assert not first.is_alive()
|
||||
assert len(reports) == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("contour_id", ["worker-007", "field-compute-20"])
|
||||
def test_enrolled_worker_executes_without_006_identity(tmp_path: Path, contour_id: str) -> None:
|
||||
queue = _queue(tmp_path)
|
||||
job_id = _enqueue(queue)
|
||||
transport = FakeTransport(queue, contour_id=contour_id)
|
||||
executor = FakeExecutor()
|
||||
agent = ObservatoryWorkerAgent(
|
||||
transport=transport,
|
||||
executors=ObservatoryWorkerExecutorRegistry((
|
||||
ObservatoryWorkerExecutorRegistration(identity=_identity(), adapter=executor),
|
||||
)),
|
||||
contour_id=contour_id,
|
||||
)
|
||||
report = agent.run_once()
|
||||
assert report.state == "succeeded"
|
||||
assert report.job_id == job_id
|
||||
assert report.claim_request_id.startswith(contour_id + ":")
|
||||
assert transport.starts == [job_id]
|
||||
|
||||
|
||||
def test_enrolled_worker_rejects_a_different_claimant(tmp_path: Path) -> None:
|
||||
queue = _queue(tmp_path)
|
||||
_enqueue(queue)
|
||||
def substitute(payload):
|
||||
return {**payload, "claimant_id": "worker-006"}
|
||||
transport = FakeTransport(queue, contour_id="worker-007", claim_mutator=substitute)
|
||||
executor = FakeExecutor()
|
||||
agent = ObservatoryWorkerAgent(
|
||||
transport=transport,
|
||||
executors=ObservatoryWorkerExecutorRegistry((
|
||||
ObservatoryWorkerExecutorRegistration(identity=_identity(), adapter=executor),
|
||||
)),
|
||||
contour_id="worker-007",
|
||||
)
|
||||
assert agent.run_once().state == "rejected"
|
||||
assert not executor.jobs
|
||||
|
||||
@@ -36,6 +36,17 @@ def _endpoint(router: APIRouter, path: str, method: str) -> Callable[..., Any]:
|
||||
raise AssertionError(f"{method} {path} route is missing")
|
||||
|
||||
|
||||
def test_pipeline_only_snapshot_does_not_claim_host_metrics_or_zero_network(tmp_path):
|
||||
service = WorkerTelemetryService(WorkerProfileStore(tmp_path))
|
||||
probe = _probe()
|
||||
probe["raw"] = {"node_id": EXPECTED_NODE_ID, "observed_at_utc": "2026-07-27T12:00:00Z"}
|
||||
snapshot = service._telemetry_document(service.store.read(), probe, 1.0)
|
||||
assert snapshot["connection"]["reachable"] is True
|
||||
assert snapshot["connection"]["error_code"] == "telemetry-host-incomplete"
|
||||
assert snapshot["network"]["aggregate"] is None
|
||||
assert snapshot["node"]["memory"]["used_percent"] is None
|
||||
|
||||
|
||||
def _probe(
|
||||
*,
|
||||
node_id: str = EXPECTED_NODE_ID,
|
||||
|
||||
@@ -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()
|
||||
@@ -54,6 +54,28 @@ def test_normalizer_accepts_native_telegraf_host_metric() -> None:
|
||||
assert row[7] == "telegraf.metric-json/v1"
|
||||
|
||||
|
||||
def test_topic_batch_preserves_individual_measurements_and_timestamps() -> None:
|
||||
normalizer = _normalizer()
|
||||
topic = "mission-core/v1/contours/test/agents/test/host"
|
||||
metrics = [
|
||||
{"name": name, "fields": {"value": i}, "tags": {"node_id": "test"},
|
||||
"timestamp": 1_785_179_600 + i}
|
||||
for i, name in enumerate(("cpu", "mem", "net"))
|
||||
]
|
||||
rows = normalizer.normalize_message(topic, json.dumps({"metrics": metrics}).encode())
|
||||
assert rows == [normalizer._normalize(topic, json.dumps(x).encode()) for x in metrics]
|
||||
assert normalizer.normalize_message(topic, json.dumps(metrics[0]).encode()) == [rows[0]]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("metrics", [[], [None], [{"metrics": []}], [{}] * 513])
|
||||
def test_invalid_batches_are_rejected(metrics) -> None:
|
||||
with pytest.raises(ValueError):
|
||||
_normalizer().normalize_message(
|
||||
"mission-core/v1/contours/test/agents/test/host",
|
||||
json.dumps({"metrics": metrics}).encode(),
|
||||
)
|
||||
|
||||
|
||||
def test_normalizer_keeps_same_timestamp_host_measurements_distinct() -> None:
|
||||
normalizer = _normalizer()
|
||||
rows = [
|
||||
|
||||
@@ -120,6 +120,21 @@ def test_ready_receiver_is_not_restarted(monkeypatch, tmp_path):
|
||||
assert manager.reconcile(tmp_path) == "ready"
|
||||
|
||||
|
||||
def test_old_installer_cannot_replace_managed_connection(tmp_path, monkeypatch):
|
||||
stack, repo, agents = setup(tmp_path, monkeypatch)
|
||||
tunnel = agents / (manager.TUNNEL + ".plist")
|
||||
payload = plistlib.dumps(
|
||||
{
|
||||
"Label": manager.TUNNEL,
|
||||
"ProgramArguments": ["python", "-m", "k1link.compute_connections.link"],
|
||||
}
|
||||
)
|
||||
tunnel.write_bytes(payload)
|
||||
with pytest.raises(ValueError, match="Connection registry owns"):
|
||||
manager.plan(stack, "worker-test", repo, agents)
|
||||
assert tunnel.read_bytes() == payload
|
||||
|
||||
|
||||
def test_old_lan_binding_is_reconciled_even_when_receiver_healthy(monkeypatch, tmp_path):
|
||||
calls = []
|
||||
bindings = iter((False, True))
|
||||
|
||||
Reference in New Issue
Block a user