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)