feat(worker): supervise VPN connections and recover batched telemetry
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
"""Device identity, network attachments and verified connection selection.
|
||||
|
||||
VPN membership and application capabilities are independent. An address is
|
||||
never a device identity; changing a path never grants a new execution capability.
|
||||
"""
|
||||
@@ -0,0 +1,164 @@
|
||||
"""One installed channel, following a device's active connection.
|
||||
|
||||
Launchd/systemd owns this process. No commands are queued or retried here: only
|
||||
authenticated TCP forwarding is re-established. Every retry re-reads identity.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
from threading import Event
|
||||
|
||||
from .store import ConnectionError, ConnectionStore
|
||||
from .transport import SshTransport, bounded_run, validate_path
|
||||
|
||||
|
||||
def read_wireguard_profile(root: Path, network_id: str) -> dict | None:
|
||||
path = root.parent / "mission-core/fleet/networks/profiles.json"
|
||||
try:
|
||||
value = json.loads(path.read_bytes()).get(network_id)
|
||||
if isinstance(value, dict):
|
||||
# Only provider identity and public peer addresses enter this layer.
|
||||
return {key: value.get(key) for key in ("server_id", "subnet", "status")}
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def selected(store: ConnectionStore, contour_id: str):
|
||||
registry = store.read()
|
||||
worker = registry.worker(contour_id)
|
||||
connection = next((x for x in worker.connections if x.id == worker.active_connection_id), None)
|
||||
if connection is None:
|
||||
raise ConnectionError("Активное подключение не выбрано.")
|
||||
return worker, connection, registry.profile(connection.profile_id)
|
||||
|
||||
|
||||
def write_state(path: Path, value: dict) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
temporary = path.with_suffix(f".{os.getpid()}.tmp")
|
||||
try:
|
||||
temporary.write_text(json.dumps({**value, "observed_at": time.time(), "pid": os.getpid()}))
|
||||
os.chmod(temporary, 0o600)
|
||||
os.replace(temporary, path)
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def stop_child(child: subprocess.Popen | None) -> None:
|
||||
if child is None or child.poll() is not None:
|
||||
return
|
||||
child.terminate()
|
||||
try:
|
||||
child.wait(timeout=4)
|
||||
except subprocess.TimeoutExpired:
|
||||
child.kill()
|
||||
child.wait(timeout=2)
|
||||
|
||||
|
||||
def run(root: Path, contour_id: str, channel_id: str, stop: Event) -> None:
|
||||
store = ConnectionStore(root)
|
||||
transport = SshTransport(root / "worker-bindings")
|
||||
path = root / "connection-status" / contour_id / f"{channel_id}.json"
|
||||
child = None
|
||||
while not stop.is_set():
|
||||
connection_id = None
|
||||
control_dir = None
|
||||
try:
|
||||
worker, connection, profile = selected(store, contour_id)
|
||||
connection_id = connection.id
|
||||
validate_path(
|
||||
profile,
|
||||
connection,
|
||||
wireguard_profile=read_wireguard_profile(root, profile.network_id),
|
||||
)
|
||||
binding = transport.binding(worker)
|
||||
channel = next(x for x in binding.channels if x.id == channel_id)
|
||||
arguments = transport.arguments(worker, connection)
|
||||
control_dir = tempfile.TemporaryDirectory(prefix="ndc-link-", dir="/tmp")
|
||||
control_path = str(Path(control_dir.name) / "control")
|
||||
child = subprocess.Popen(
|
||||
[
|
||||
arguments[0],
|
||||
"-o",
|
||||
"ControlMaster=yes",
|
||||
"-o",
|
||||
"ControlPath=" + control_path,
|
||||
*arguments[1:-1],
|
||||
"-N",
|
||||
"-o",
|
||||
"ExitOnForwardFailure=yes",
|
||||
*channel.arguments,
|
||||
arguments[-1],
|
||||
],
|
||||
stdin=subprocess.DEVNULL,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
)
|
||||
started = time.monotonic()
|
||||
while not stop.wait(1):
|
||||
if child.poll() is not None:
|
||||
raise ConnectionError("Канал восстанавливается.")
|
||||
current, active, _ = selected(store, contour_id)
|
||||
if active.id != connection.id or current.host_key_sha256 != worker.host_key_sha256:
|
||||
break
|
||||
# Control master appears only after authenticated setup and forward binding.
|
||||
try:
|
||||
bounded_run(
|
||||
[
|
||||
"/usr/bin/ssh",
|
||||
"-F",
|
||||
"/dev/null",
|
||||
"-S",
|
||||
control_path,
|
||||
"-O",
|
||||
"check",
|
||||
binding.ssh_alias,
|
||||
],
|
||||
timeout=2,
|
||||
)
|
||||
except ConnectionError:
|
||||
if time.monotonic() - started >= 15:
|
||||
raise
|
||||
write_state(path, {"connection_id": connection.id, "state": "connecting"})
|
||||
continue
|
||||
write_state(
|
||||
path,
|
||||
{
|
||||
"connection_id": connection.id,
|
||||
"state": "running",
|
||||
"uptime_seconds": round(time.monotonic() - started),
|
||||
},
|
||||
)
|
||||
except (OSError, ValueError, StopIteration):
|
||||
write_state(path, {"connection_id": connection_id, "state": "reconnecting"})
|
||||
stop.wait(3)
|
||||
finally:
|
||||
stop_child(child)
|
||||
child = None
|
||||
if control_dir is not None:
|
||||
control_dir.cleanup()
|
||||
write_state(path, {"connection_id": None, "state": "stopped"})
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--root", type=Path, required=True)
|
||||
parser.add_argument("--contour", required=True)
|
||||
parser.add_argument("--channel", required=True)
|
||||
args = parser.parse_args()
|
||||
stop = Event()
|
||||
signal.signal(signal.SIGTERM, lambda *_: stop.set())
|
||||
signal.signal(signal.SIGINT, lambda *_: stop.set())
|
||||
run(args.root, args.contour, args.channel, stop)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,256 @@
|
||||
"""Provider discovery, identity-bound admission and verified path selection."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import threading
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
|
||||
from .store import Connection, ConnectionError, ConnectionStore, NetworkProfile, WorkerBinding
|
||||
from .tailscale_client import ClientUnavailable, describe
|
||||
from .transport import (
|
||||
SshTransport,
|
||||
TransportBinding,
|
||||
tailscale_profile,
|
||||
tailscale_status,
|
||||
validate_path,
|
||||
)
|
||||
|
||||
|
||||
class ConnectionService:
|
||||
def __init__(
|
||||
self,
|
||||
root: Path,
|
||||
*,
|
||||
wireguard: Callable[[], list[dict]],
|
||||
tailscale: Callable[[], dict] = tailscale_status,
|
||||
transport: SshTransport | None = None,
|
||||
):
|
||||
self.store = ConnectionStore(root)
|
||||
self.transport = transport or SshTransport(root / "worker-bindings")
|
||||
self.wireguard = wireguard
|
||||
self.tailscale = tailscale
|
||||
self.lock = threading.RLock()
|
||||
|
||||
def networks(self) -> tuple[list[NetworkProfile], dict | None, list[dict], str | None, dict]:
|
||||
profiles = []
|
||||
status = None
|
||||
message = None
|
||||
client = describe(state="unavailable")
|
||||
try:
|
||||
status = self.tailscale()
|
||||
profiles.append(tailscale_profile(status))
|
||||
client = describe(status)
|
||||
except ClientUnavailable as exc:
|
||||
message = str(exc)
|
||||
client = exc.client
|
||||
except ConnectionError as exc:
|
||||
message = str(exc)
|
||||
rows = self.wireguard()
|
||||
for row in rows:
|
||||
profiles.append(
|
||||
NetworkProfile(
|
||||
id="wg-" + hashlib.sha256(row["server_id"].encode()).hexdigest()[:24],
|
||||
name=row.get("name") or "WireGuard",
|
||||
provider="wireguard",
|
||||
network_id=row["server_id"],
|
||||
)
|
||||
)
|
||||
return profiles, status, rows, message, client
|
||||
|
||||
def catalog(self) -> dict:
|
||||
registry = self.store.read()
|
||||
profiles, status, rows, message, client = self.networks()
|
||||
peers = []
|
||||
for profile in profiles:
|
||||
if profile.provider == "tailscale" and status:
|
||||
for peer in (status.get("Peer") or {}).values():
|
||||
if peer.get("ID") and peer.get("DNSName"):
|
||||
peers.append(
|
||||
dict(
|
||||
profile_id=profile.id,
|
||||
id=peer["ID"],
|
||||
name=peer.get("HostName") or peer["DNSName"],
|
||||
online=bool(peer.get("Online")),
|
||||
)
|
||||
)
|
||||
elif profile.provider == "wireguard":
|
||||
row = next(x for x in rows if x["server_id"] == profile.network_id)
|
||||
for peer in row.get("status", {}).get("peers", []):
|
||||
if peer.get("kind") == "worker":
|
||||
peers.append(
|
||||
dict(
|
||||
profile_id=profile.id,
|
||||
id=peer["id"],
|
||||
name=peer.get("name") or peer["id"],
|
||||
online=None,
|
||||
)
|
||||
)
|
||||
prepared = []
|
||||
for path in sorted(self.transport.root.glob("*.json")):
|
||||
if path.is_symlink() or path.stat().st_mode & 0o077:
|
||||
continue
|
||||
try:
|
||||
binding = TransportBinding.model_validate_json(path.read_bytes())
|
||||
if binding.id != path.stem:
|
||||
continue
|
||||
prepared.append(
|
||||
dict(
|
||||
id=binding.id,
|
||||
contour_id=binding.contour_id,
|
||||
name=binding.display_name,
|
||||
hostname=binding.expected_hostname,
|
||||
platform=binding.platform,
|
||||
)
|
||||
)
|
||||
except (OSError, ValueError):
|
||||
continue
|
||||
known = {x.id: x for x in registry.profiles}
|
||||
known.update({x.id: x for x in profiles})
|
||||
return dict(
|
||||
revision=registry.revision,
|
||||
profiles=[x.model_dump() for x in known.values()],
|
||||
available_profile_ids=[x.id for x in profiles],
|
||||
peers=peers,
|
||||
workers=[x.model_dump() for x in registry.workers],
|
||||
prepared=prepared,
|
||||
notice=message,
|
||||
tailscale_client=client,
|
||||
)
|
||||
|
||||
def candidate(self, profile_id: str, peer_id: str) -> tuple[NetworkProfile, Connection]:
|
||||
profiles, status, rows, _, _ = self.networks()
|
||||
profile = next((x for x in profiles if x.id == profile_id), None)
|
||||
if profile is None:
|
||||
raise ConnectionError("Подключите выбранную VPN-сеть на этом компьютере.")
|
||||
row = None
|
||||
if profile.provider == "tailscale":
|
||||
peer = next(
|
||||
(x for x in (status or {}).get("Peer", {}).values() if x.get("ID") == peer_id), None
|
||||
)
|
||||
endpoint = str((peer or {}).get("DNSName", "")).rstrip(".")
|
||||
else:
|
||||
row = next(x for x in rows if x["server_id"] == profile.network_id)
|
||||
peer = next(
|
||||
(
|
||||
x
|
||||
for x in row.get("status", {}).get("peers", [])
|
||||
if x.get("id") == peer_id and x.get("kind") == "worker"
|
||||
),
|
||||
None,
|
||||
)
|
||||
endpoint = (peer or {}).get("address", "")
|
||||
if not endpoint:
|
||||
raise ConnectionError("Подготовленный воркер не найден в выбранной сети.")
|
||||
connection = Connection(
|
||||
id="path-" + hashlib.sha256((profile_id + peer_id).encode()).hexdigest()[:24],
|
||||
profile_id=profile.id,
|
||||
peer_id=peer_id,
|
||||
endpoint=endpoint,
|
||||
)
|
||||
validate_path(profile, connection, status=status, wireguard_profile=row)
|
||||
return profile, connection
|
||||
|
||||
def verify(self, worker: WorkerBinding, connection: Connection) -> dict:
|
||||
profile, candidate = self.candidate(connection.profile_id, connection.peer_id)
|
||||
if candidate.endpoint != connection.endpoint:
|
||||
raise ConnectionError("Адрес устройства изменился. Повторите привязку подключения.")
|
||||
return self.transport.probe(worker, connection)
|
||||
|
||||
def enroll(
|
||||
self, binding_id: str, profile_id: str, peer_id: str, revision: int
|
||||
) -> WorkerBinding:
|
||||
# binding_id is schema-validated by the API; private files are installer-owned.
|
||||
with self.lock:
|
||||
path = self.transport.root / (binding_id + ".json")
|
||||
if path.is_symlink() or path.stat().st_mode & 0o077:
|
||||
raise ConnectionError("Привязка устройства ещё не подготовлена.")
|
||||
binding = TransportBinding.model_validate_json(path.read_bytes())
|
||||
if binding.id != binding_id:
|
||||
raise ConnectionError("Некорректная привязка устройства.")
|
||||
profile, connection = self.candidate(profile_id, peer_id)
|
||||
worker = WorkerBinding(
|
||||
contour_id=binding.contour_id,
|
||||
transport_id=binding.id,
|
||||
host_key_sha256=binding.fingerprint,
|
||||
connections=(connection,),
|
||||
active_connection_id=connection.id,
|
||||
)
|
||||
self.transport.probe(worker, connection)
|
||||
self.store.enroll(profile, worker, expected_revision=revision)
|
||||
return worker
|
||||
|
||||
def attach(
|
||||
self, contour_id: str, profile_id: str, peer_id: str, revision: int
|
||||
) -> WorkerBinding:
|
||||
with self.lock:
|
||||
worker = self.store.read().worker(contour_id)
|
||||
if worker.revision != revision:
|
||||
raise ConnectionError("Подключения изменились. Обновите список.")
|
||||
profile, connection = self.candidate(profile_id, peer_id)
|
||||
self.transport.probe(worker, connection)
|
||||
return self.store.attach(contour_id, profile, connection, expected_revision=revision)
|
||||
|
||||
def link_states(self, worker: WorkerBinding) -> list[dict]:
|
||||
binding = self.transport.binding(worker)
|
||||
states = []
|
||||
for channel in binding.channels:
|
||||
path = (
|
||||
self.store.root / "connection-status" / worker.contour_id / (channel.id + ".json")
|
||||
)
|
||||
try:
|
||||
value = json.loads(path.read_bytes())
|
||||
alive = (
|
||||
0 <= time.time() - value["observed_at"] < 6
|
||||
and value.get("connection_id") == worker.active_connection_id
|
||||
and value.get("state") == "running"
|
||||
)
|
||||
except (OSError, ValueError, KeyError, TypeError):
|
||||
alive = False
|
||||
states.append(dict(id=channel.id, label=channel.label, connected=alive))
|
||||
return states
|
||||
|
||||
def check(self, contour_id: str, connection_id: str) -> dict:
|
||||
worker = self.store.read().worker(contour_id)
|
||||
connection = next((x for x in worker.connections if x.id == connection_id), None)
|
||||
if connection is None:
|
||||
raise ConnectionError("Подключение не найдено.")
|
||||
identity = self.verify(worker, connection)
|
||||
return dict(
|
||||
identity=identity,
|
||||
channels=self.link_states(worker),
|
||||
active=worker.active_connection_id == connection_id,
|
||||
)
|
||||
|
||||
def activate(self, contour_id: str, connection_id: str, revision: int) -> WorkerBinding:
|
||||
with self.lock:
|
||||
worker = self.store.read().worker(contour_id)
|
||||
if worker.revision != revision:
|
||||
raise ConnectionError("Подключения изменились. Обновите список.")
|
||||
connection = next((x for x in worker.connections if x.id == connection_id), None)
|
||||
if connection is None:
|
||||
raise ConnectionError("Подключение не найдено.")
|
||||
self.verify(worker, connection)
|
||||
if worker.active_connection_id == connection_id:
|
||||
return worker
|
||||
channels = self.transport.binding(worker).channels
|
||||
if not channels:
|
||||
raise ConnectionError("Рабочие каналы ещё не установлены на этом компьютере.")
|
||||
# Supervisors follow one atomic selection; all paths retain the same host key.
|
||||
updated = self.store.select(contour_id, connection_id, expected_revision=revision)
|
||||
deadline = time.monotonic() + 18
|
||||
while time.monotonic() < deadline:
|
||||
states = self.link_states(updated)
|
||||
if states and all(x["connected"] for x in states):
|
||||
return updated
|
||||
time.sleep(0.4)
|
||||
if worker.active_connection_id is not None:
|
||||
self.store.select(
|
||||
contour_id, worker.active_connection_id, expected_revision=updated.revision
|
||||
)
|
||||
raise ConnectionError(
|
||||
"Рабочие каналы не восстановились. Возвращено прежнее подключение."
|
||||
)
|
||||
@@ -0,0 +1,240 @@
|
||||
"""Atomic operator-owned registry. No credentials or observed health on disk."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import fcntl
|
||||
import os
|
||||
import re
|
||||
import tempfile
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
||||
|
||||
ID = r"^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$"
|
||||
|
||||
|
||||
class ConnectionError(ValueError):
|
||||
"""A bounded product failure; never substitute an empty registry."""
|
||||
|
||||
|
||||
class Record(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", frozen=True)
|
||||
|
||||
|
||||
class NetworkProfile(Record):
|
||||
id: str = Field(pattern=ID)
|
||||
name: str = Field(min_length=1, max_length=80)
|
||||
provider: Literal["tailscale", "wireguard"]
|
||||
# Provider identity, not an account password or a bootstrap credential.
|
||||
network_id: str = Field(min_length=1, max_length=180)
|
||||
|
||||
|
||||
class Connection(Record):
|
||||
id: str = Field(pattern=ID)
|
||||
profile_id: str = Field(pattern=ID)
|
||||
endpoint: str = Field(min_length=1, max_length=253)
|
||||
# Different network paths of one host must all prove this same host key.
|
||||
peer_id: str = Field(min_length=1, max_length=180)
|
||||
|
||||
@field_validator("endpoint")
|
||||
@classmethod
|
||||
def safe_endpoint(cls, value: str) -> str:
|
||||
if re.fullmatch(r"[a-zA-Z0-9][a-zA-Z0-9.:-]{0,252}", value) is None:
|
||||
raise ValueError("Invalid connection endpoint")
|
||||
return value
|
||||
|
||||
|
||||
class WorkerBinding(Record):
|
||||
contour_id: str = Field(pattern=ID)
|
||||
host_key_sha256: str = Field(pattern=r"^SHA256:[A-Za-z0-9+/]{43}$")
|
||||
# Owned transport binding, resolved server-side; never executable user input.
|
||||
transport_id: str = Field(pattern=ID)
|
||||
connections: tuple[Connection, ...] = ()
|
||||
active_connection_id: str | None = None
|
||||
revision: int = Field(default=0, ge=0)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def unique_connections(self) -> WorkerBinding:
|
||||
ids = [x.id for x in self.connections]
|
||||
profiles = [x.profile_id for x in self.connections]
|
||||
if len(set(ids)) != len(ids) or len(set(profiles)) != len(profiles):
|
||||
raise ValueError("Duplicate device connection")
|
||||
if self.active_connection_id is not None and self.active_connection_id not in ids:
|
||||
raise ValueError("Active connection is not attached")
|
||||
return self
|
||||
|
||||
|
||||
class Registry(Record):
|
||||
schema_version: Literal["missioncore.device-connections/v1"] = (
|
||||
"missioncore.device-connections/v1"
|
||||
)
|
||||
revision: int = Field(default=0, ge=0)
|
||||
profiles: tuple[NetworkProfile, ...] = ()
|
||||
workers: tuple[WorkerBinding, ...] = ()
|
||||
|
||||
@model_validator(mode="after")
|
||||
def references(self) -> Registry:
|
||||
profiles = {x.id for x in self.profiles}
|
||||
if len(profiles) != len(self.profiles):
|
||||
raise ValueError("Duplicate network profile")
|
||||
if len({x.contour_id for x in self.workers}) != len(self.workers):
|
||||
raise ValueError("Duplicate worker binding")
|
||||
for worker in self.workers:
|
||||
if any(x.profile_id not in profiles for x in worker.connections):
|
||||
raise ValueError("Connection references a missing network profile")
|
||||
return self
|
||||
|
||||
def worker(self, contour_id: str) -> WorkerBinding:
|
||||
for worker in self.workers:
|
||||
if worker.contour_id == contour_id:
|
||||
return worker
|
||||
raise ConnectionError("Воркер ещё не привязан. Подключите подготовленное устройство.")
|
||||
|
||||
def profile(self, profile_id: str) -> NetworkProfile:
|
||||
for profile in self.profiles:
|
||||
if profile.id == profile_id:
|
||||
return profile
|
||||
raise ConnectionError("Сетевой профиль отсутствует.")
|
||||
|
||||
|
||||
class ConnectionStore:
|
||||
def __init__(self, root: Path):
|
||||
self.root = root
|
||||
self.path = root / "device-connections.json"
|
||||
|
||||
@contextmanager
|
||||
def locked(self):
|
||||
self.root.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
lock = self.root / "device-connections.lock"
|
||||
fd = os.open(lock, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
|
||||
try:
|
||||
fcntl.flock(fd, fcntl.LOCK_EX)
|
||||
yield
|
||||
finally:
|
||||
fcntl.flock(fd, fcntl.LOCK_UN)
|
||||
os.close(fd)
|
||||
|
||||
def read(self) -> Registry:
|
||||
if self.path.is_symlink():
|
||||
raise ConnectionError("Хранилище подключений требует проверки.")
|
||||
try:
|
||||
return Registry.model_validate_json(self.path.read_bytes())
|
||||
except FileNotFoundError:
|
||||
return Registry()
|
||||
except (OSError, ValueError) as exc:
|
||||
raise ConnectionError(
|
||||
"Не удалось прочитать подключения. Сохранённые данные не изменены."
|
||||
) from exc
|
||||
|
||||
def _write(self, registry: Registry) -> Registry:
|
||||
Registry.model_validate(registry.model_dump())
|
||||
fd, name = tempfile.mkstemp(prefix=".device-connections-", dir=self.root)
|
||||
try:
|
||||
with os.fdopen(fd, "w") as stream:
|
||||
stream.write(registry.model_dump_json(indent=2))
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.replace(name, self.path)
|
||||
directory = os.open(self.root, os.O_RDONLY)
|
||||
try:
|
||||
os.fsync(directory)
|
||||
finally:
|
||||
os.close(directory)
|
||||
finally:
|
||||
Path(name).unlink(missing_ok=True)
|
||||
return registry
|
||||
|
||||
def enroll(
|
||||
self, profile: NetworkProfile, binding: WorkerBinding, *, expected_revision: int
|
||||
) -> Registry:
|
||||
"""Caller must first verify the transport and obtain operator enrollment."""
|
||||
with self.locked():
|
||||
current = self.read()
|
||||
if current.revision != expected_revision:
|
||||
raise ConnectionError("Подключения изменились. Обновите список.")
|
||||
for existing in current.workers:
|
||||
if existing.contour_id == binding.contour_id:
|
||||
raise ConnectionError("Воркер уже привязан; повторная регистрация запрещена.")
|
||||
profiles = list(current.profiles)
|
||||
prior = next((x for x in profiles if x.id == profile.id), None)
|
||||
if prior is not None and prior != profile:
|
||||
raise ConnectionError("Идентичность сетевого профиля изменилась.")
|
||||
if prior is None:
|
||||
profiles.append(profile)
|
||||
return self._write(
|
||||
Registry(
|
||||
revision=current.revision + 1,
|
||||
profiles=tuple(profiles),
|
||||
workers=(*current.workers, binding),
|
||||
)
|
||||
)
|
||||
|
||||
def attach(
|
||||
self,
|
||||
contour_id: str,
|
||||
profile: NetworkProfile,
|
||||
connection: Connection,
|
||||
*,
|
||||
expected_revision: int,
|
||||
) -> WorkerBinding:
|
||||
with self.locked():
|
||||
current = self.read()
|
||||
worker = current.worker(contour_id)
|
||||
if worker.revision != expected_revision:
|
||||
raise ConnectionError("Подключения воркера изменились. Обновите список.")
|
||||
if connection.profile_id != profile.id:
|
||||
raise ConnectionError("Подключение относится к другой сети.")
|
||||
profiles = list(current.profiles)
|
||||
prior = next((x for x in profiles if x.id == profile.id), None)
|
||||
if prior is not None and prior != profile:
|
||||
raise ConnectionError("Идентичность сетевого профиля изменилась.")
|
||||
if prior is None:
|
||||
profiles.append(profile)
|
||||
updated = WorkerBinding.model_validate(
|
||||
{
|
||||
**worker.model_dump(),
|
||||
"connections": [*worker.connections, connection],
|
||||
"revision": worker.revision + 1,
|
||||
}
|
||||
)
|
||||
self._write(
|
||||
Registry(
|
||||
revision=current.revision + 1,
|
||||
profiles=tuple(profiles),
|
||||
workers=tuple(
|
||||
updated if x.contour_id == contour_id else x for x in current.workers
|
||||
),
|
||||
)
|
||||
)
|
||||
return updated
|
||||
|
||||
def select(
|
||||
self, contour_id: str, connection_id: str, *, expected_revision: int
|
||||
) -> WorkerBinding:
|
||||
"""Called only after a successful path transaction; never implies health."""
|
||||
with self.locked():
|
||||
current = self.read()
|
||||
worker = current.worker(contour_id)
|
||||
if worker.revision != expected_revision:
|
||||
raise ConnectionError("Подключения воркера изменились. Обновите список.")
|
||||
if connection_id not in {x.id for x in worker.connections}:
|
||||
raise ConnectionError("Подключение не подготовлено на этом устройстве.")
|
||||
updated = WorkerBinding.model_validate(
|
||||
{
|
||||
**worker.model_dump(),
|
||||
"active_connection_id": connection_id,
|
||||
"revision": worker.revision + 1,
|
||||
}
|
||||
)
|
||||
self._write(
|
||||
Registry(
|
||||
revision=current.revision + 1,
|
||||
profiles=current.profiles,
|
||||
workers=tuple(
|
||||
updated if x.contour_id == contour_id else x for x in current.workers
|
||||
),
|
||||
)
|
||||
)
|
||||
return updated
|
||||
@@ -0,0 +1,150 @@
|
||||
"""Observe the operator's official client; authentication stays with Tailscale."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import plistlib
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from .store import ConnectionError
|
||||
|
||||
APP_IDS = {"io.tailscale.ipn.macsys", "io.tailscale.ipn.macos"}
|
||||
MESSAGES = {
|
||||
"not_installed": "Tailscale не установлен на этом компьютере.",
|
||||
"unavailable": (
|
||||
"Tailscale установлен, но не отвечает. Откройте приложение и проверьте подключение."
|
||||
),
|
||||
"needs_login": (
|
||||
"Войдите в Tailscale. После подключения сеть и устройства появятся здесь автоматически."
|
||||
),
|
||||
"stopped": "Tailscale отключён. Включите подключение в приложении.",
|
||||
"needs_approval": (
|
||||
"Доступ этого компьютера ожидает подтверждения администратора сети Tailscale."
|
||||
),
|
||||
"starting": "Tailscale запускается. Список обновится автоматически.",
|
||||
"connected": "",
|
||||
}
|
||||
|
||||
|
||||
def installed_client(
|
||||
*, app_dirs: tuple[Path, ...] | None = None
|
||||
) -> tuple[Path | None, str | None, str | None]:
|
||||
"""Prefer the installed app's own CLI; no install, downgrade or second daemon."""
|
||||
app = None
|
||||
version = None
|
||||
if sys.platform == "darwin":
|
||||
for directory in app_dirs or (Path("/Applications"), Path.home() / "Applications"):
|
||||
candidate = directory / "Tailscale.app"
|
||||
try:
|
||||
info = plistlib.loads((candidate / "Contents/Info.plist").read_bytes())
|
||||
if info.get("CFBundleIdentifier") not in APP_IDS:
|
||||
continue
|
||||
app = candidate
|
||||
value = info.get("CFBundleShortVersionString")
|
||||
version = value[:80] if isinstance(value, str) else None
|
||||
break
|
||||
except (OSError, ValueError, plistlib.InvalidFileException):
|
||||
continue
|
||||
candidates = ([app / "Contents/MacOS/Tailscale"] if app else []) + [
|
||||
Path("/usr/local/bin/tailscale"),
|
||||
Path("/opt/homebrew/bin/tailscale"),
|
||||
]
|
||||
found = shutil.which("tailscale")
|
||||
if found:
|
||||
candidates.append(Path(found))
|
||||
binary = next((str(p) for p in candidates if p.is_file() and os.access(p, os.X_OK)), None)
|
||||
return app, binary, version
|
||||
|
||||
|
||||
def run(args: list[str], *, cli: bool = False) -> bytes:
|
||||
# Official Tailscale CLI contract: force CLI mode in non-interactive hosts.
|
||||
# Do not propagate it to the explicit native-app /usr/bin/open action.
|
||||
env = {**os.environ, "TAILSCALE_BE_CLI": "1"} if cli else None
|
||||
result = subprocess.run(args, capture_output=True, timeout=4, check=False, env=env)
|
||||
if result.returncode or len(result.stdout) > 4 * 1024 * 1024:
|
||||
raise ValueError("Client command failed")
|
||||
return result.stdout
|
||||
|
||||
|
||||
def describe(
|
||||
status: dict[str, Any] | None = None, *, state: str | None = None
|
||||
) -> dict[str, Any]:
|
||||
app, _, version = installed_client()
|
||||
states = {
|
||||
"Running": "connected",
|
||||
"NeedsLogin": "needs_login",
|
||||
"Stopped": "stopped",
|
||||
"NeedsMachineAuth": "needs_approval",
|
||||
"Starting": "starting",
|
||||
"NoState": "starting",
|
||||
}
|
||||
backend = (status or {}).get("BackendState")
|
||||
state = state or (
|
||||
states.get(backend, "unavailable") if isinstance(backend, str) else "unavailable"
|
||||
)
|
||||
daemon_version = (status or {}).get("Version")
|
||||
return dict(
|
||||
state=state,
|
||||
message=MESSAGES[state],
|
||||
can_open=app is not None,
|
||||
version=version or (daemon_version[:80] if isinstance(daemon_version, str) else None),
|
||||
)
|
||||
|
||||
|
||||
def observe() -> tuple[dict[str, Any], dict[str, Any] | None]:
|
||||
app, binary, _ = installed_client()
|
||||
if binary is None:
|
||||
return describe(state="unavailable" if app else "not_installed"), None
|
||||
try:
|
||||
status = json.loads(run([binary, "status", "--json"], cli=True))
|
||||
if not isinstance(status, dict):
|
||||
raise ValueError("Invalid client response")
|
||||
return describe(status), status
|
||||
except (OSError, ValueError, subprocess.TimeoutExpired):
|
||||
return describe(state="unavailable"), None
|
||||
|
||||
|
||||
class ClientUnavailable(ConnectionError):
|
||||
def __init__(self, client: dict[str, Any]):
|
||||
super().__init__(client["message"])
|
||||
self.client = client
|
||||
|
||||
|
||||
def running_status() -> dict[str, Any]:
|
||||
client, status = observe()
|
||||
if client["state"] != "connected" or status is None:
|
||||
raise ClientUnavailable(client)
|
||||
return status
|
||||
|
||||
|
||||
def open_client() -> dict[str, str]:
|
||||
app, _, _ = installed_client()
|
||||
if app is None:
|
||||
raise ConnectionError("Приложение Tailscale не найдено на этом компьютере.")
|
||||
try:
|
||||
# Reopening an existing app does not switch accounts, reset routes or force login.
|
||||
run(["/usr/bin/open", "-a", str(app)])
|
||||
client, status = observe()
|
||||
if client["state"] == "needs_login":
|
||||
url = (status or {}).get("AuthURL")
|
||||
parsed = urlsplit(url) if isinstance(url, str) and len(url) <= 2048 else None
|
||||
if (
|
||||
isinstance(url, str)
|
||||
and parsed
|
||||
and parsed.scheme == "https"
|
||||
and parsed.netloc == "login.tailscale.com"
|
||||
and parsed.path.startswith("/a/")
|
||||
and not parsed.fragment
|
||||
):
|
||||
run(["/usr/bin/open", url])
|
||||
return dict(state="opened")
|
||||
except (OSError, ValueError, subprocess.TimeoutExpired) as exc:
|
||||
raise ConnectionError(
|
||||
"Не удалось открыть Tailscale. Запустите его из списка приложений."
|
||||
) from exc
|
||||
@@ -0,0 +1,266 @@
|
||||
"""Existing SSH transport behind enrolled identities and provider-owned paths.
|
||||
|
||||
SSH is an explicit migration adapter, not a VPN provider. Credentials and host
|
||||
trust belong to the installed binding. UI requests cannot supply commands,
|
||||
users, private keys or arbitrary destination addresses.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import ipaddress
|
||||
import json
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import Field, model_validator
|
||||
|
||||
from .store import ID, Connection, ConnectionError, NetworkProfile, Record, WorkerBinding
|
||||
from .tailscale_client import running_status
|
||||
|
||||
|
||||
class Channel(Record):
|
||||
id: str = Field(pattern=ID)
|
||||
label: str = Field(min_length=1, max_length=80)
|
||||
direction: Literal["local", "remote"]
|
||||
listen_port: int = Field(ge=1, le=65535)
|
||||
target_port: int = Field(ge=1, le=65535)
|
||||
|
||||
@property
|
||||
def arguments(self) -> list[str]:
|
||||
return [
|
||||
"-L" if self.direction == "local" else "-R",
|
||||
f"127.0.0.1:{self.listen_port}:127.0.0.1:{self.target_port}",
|
||||
]
|
||||
|
||||
|
||||
class TransportBinding(Record):
|
||||
schema_version: Literal["missioncore.worker-ssh-binding/v1"] = (
|
||||
"missioncore.worker-ssh-binding/v1"
|
||||
)
|
||||
id: str = Field(pattern=ID)
|
||||
contour_id: str = Field(pattern=ID)
|
||||
display_name: str = Field(min_length=1, max_length=80)
|
||||
expected_hostname: str = Field(min_length=1, max_length=128)
|
||||
ssh_alias: str = Field(pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,100}$")
|
||||
platform: Literal["windows", "linux"]
|
||||
host_key: str = Field(min_length=20, max_length=4096)
|
||||
ssh_port: int = Field(default=22, ge=1, le=65535)
|
||||
channels: tuple[Channel, ...] = ()
|
||||
|
||||
@model_validator(mode="after")
|
||||
def unique_channels(self) -> TransportBinding:
|
||||
if len({x.id for x in self.channels}) != len(self.channels):
|
||||
raise ValueError("Duplicate channel")
|
||||
if len({(x.direction, x.listen_port) for x in self.channels}) != len(self.channels):
|
||||
raise ValueError("Duplicate listener")
|
||||
return self
|
||||
|
||||
@property
|
||||
def fingerprint(self) -> str:
|
||||
try:
|
||||
algorithm, encoded = self.host_key.split()
|
||||
if algorithm != "ssh-ed25519":
|
||||
raise ValueError
|
||||
key = base64.b64decode(encoded, validate=True)
|
||||
# SSH wire blob: string algorithm + string 32-byte key.
|
||||
if len(key) != 51 or key[:19] != b"\x00\x00\x00\x0bssh-ed25519\x00\x00\x00\x20":
|
||||
raise ValueError
|
||||
except (ValueError, TypeError) as exc:
|
||||
raise ConnectionError("Повреждён ключ привязки воркера.") from exc
|
||||
return "SHA256:" + base64.b64encode(hashlib.sha256(key).digest()).decode().rstrip("=")
|
||||
|
||||
|
||||
def bounded_run(args: list[str], *, data: bytes | None = None, timeout: float = 8) -> bytes:
|
||||
try:
|
||||
result = subprocess.run(
|
||||
args,
|
||||
input=data,
|
||||
capture_output=True,
|
||||
timeout=timeout,
|
||||
check=False,
|
||||
)
|
||||
except (OSError, subprocess.SubprocessError) as exc:
|
||||
raise ConnectionError("Устройство недоступно. Проверьте сетевое подключение.") from exc
|
||||
if result.returncode or len(result.stdout) > 4 * 1024 * 1024:
|
||||
raise ConnectionError("Подключение не подтверждено. Сохранённый профиль не изменён.")
|
||||
return result.stdout
|
||||
|
||||
|
||||
def tailscale_status() -> dict:
|
||||
return running_status()
|
||||
|
||||
|
||||
def tailscale_profile(status: dict) -> NetworkProfile:
|
||||
network = status.get("CurrentTailnet", {}).get("MagicDNSSuffix")
|
||||
if not isinstance(network, str) or not network.endswith(".ts.net"):
|
||||
raise ConnectionError("Tailscale не подтвердил идентичность сети.")
|
||||
return NetworkProfile(
|
||||
id="ts-" + hashlib.sha256(network.encode()).hexdigest()[:24],
|
||||
name="Tailscale · " + network,
|
||||
provider="tailscale",
|
||||
network_id=network,
|
||||
)
|
||||
|
||||
|
||||
def validate_path(
|
||||
profile: NetworkProfile,
|
||||
connection: Connection,
|
||||
*,
|
||||
status: dict | None = None,
|
||||
wireguard_profile: dict | None = None,
|
||||
) -> None:
|
||||
if profile.id != connection.profile_id:
|
||||
raise ConnectionError("Подключение относится к другой сети.")
|
||||
if profile.provider == "tailscale":
|
||||
status = tailscale_status() if status is None else status
|
||||
if tailscale_profile(status).network_id != profile.network_id:
|
||||
raise ConnectionError("На этом компьютере выбрана другая сеть Tailscale.")
|
||||
peers = status.get("Peer") or {}
|
||||
peer = next((x for x in peers.values() if x.get("ID") == connection.peer_id), None)
|
||||
if not peer or not peer.get("Online"):
|
||||
raise ConnectionError("Устройство недоступно в выбранной сети Tailscale.")
|
||||
names = {str(peer.get("DNSName", "")).rstrip("."), *peer.get("TailscaleIPs", [])}
|
||||
if connection.endpoint not in names:
|
||||
raise ConnectionError("Адрес больше не принадлежит привязанному устройству.")
|
||||
else:
|
||||
row = wireguard_profile
|
||||
if not row or row.get("server_id") != profile.network_id:
|
||||
raise ConnectionError("Профиль WireGuard не найден.")
|
||||
try:
|
||||
network = ipaddress.ip_network(row["subnet"])
|
||||
if ipaddress.ip_address(connection.endpoint) not in network:
|
||||
raise ValueError
|
||||
peer = next(
|
||||
(
|
||||
x
|
||||
for x in row.get("status", {}).get("peers", [])
|
||||
if x.get("id") == connection.peer_id
|
||||
),
|
||||
None,
|
||||
)
|
||||
if not peer or peer.get("address") != connection.endpoint:
|
||||
raise ValueError
|
||||
except (KeyError, ValueError) as exc:
|
||||
raise ConnectionError(
|
||||
"Устройство ещё не зарегистрировано в этом WireGuard-профиле."
|
||||
) from exc
|
||||
|
||||
|
||||
WINDOWS_IDENTITY = (
|
||||
"[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding; "
|
||||
"$ErrorActionPreference='Stop'; "
|
||||
"@{hostname=$env:COMPUTERNAME;platform='windows'} | ConvertTo-Json -Compress"
|
||||
)
|
||||
LINUX_IDENTITY = (
|
||||
"python3 -c 'import json,socket; "
|
||||
'print(json.dumps(dict(hostname=socket.gethostname(),platform="linux")))\''
|
||||
)
|
||||
|
||||
|
||||
class SshTransport:
|
||||
def __init__(self, root: Path):
|
||||
self.root = root
|
||||
|
||||
def binding(self, worker: WorkerBinding) -> TransportBinding:
|
||||
path = self.root / (worker.transport_id + ".json")
|
||||
if path.is_symlink() or path.stat().st_mode & 0o077:
|
||||
raise ConnectionError("Права привязки воркера требуют проверки.")
|
||||
binding = TransportBinding.model_validate_json(path.read_bytes())
|
||||
if (
|
||||
binding.id != worker.transport_id
|
||||
or binding.contour_id != worker.contour_id
|
||||
or binding.fingerprint != worker.host_key_sha256
|
||||
):
|
||||
raise ConnectionError("Идентичность воркера изменилась. Переключение запрещено.")
|
||||
return binding
|
||||
|
||||
def arguments(self, worker: WorkerBinding, connection: Connection) -> list[str]:
|
||||
binding = self.binding(worker)
|
||||
known = self.root / (binding.id + ".known_hosts")
|
||||
expected = (binding.id + " " + binding.host_key + "\n").encode()
|
||||
if known.is_symlink() or known.read_bytes() != expected:
|
||||
raise ConnectionError("Ключ подключения не совпал с привязкой воркера.")
|
||||
return [
|
||||
"/usr/bin/ssh",
|
||||
"-F",
|
||||
str(Path.home() / ".ssh/config"),
|
||||
"-o",
|
||||
"BatchMode=yes",
|
||||
"-o",
|
||||
"StrictHostKeyChecking=yes",
|
||||
"-o",
|
||||
"UserKnownHostsFile=" + str(known),
|
||||
"-o",
|
||||
"GlobalKnownHostsFile=/dev/null",
|
||||
"-o",
|
||||
"HostKeyAlias=" + binding.id,
|
||||
"-o",
|
||||
"HostKeyAlgorithms=ssh-ed25519",
|
||||
"-o",
|
||||
"UpdateHostKeys=no",
|
||||
"-o",
|
||||
"ForwardAgent=no",
|
||||
"-o",
|
||||
"PermitLocalCommand=no",
|
||||
"-o",
|
||||
"ControlMaster=no",
|
||||
"-o",
|
||||
"ControlPath=none",
|
||||
"-o",
|
||||
"RequestTTY=no",
|
||||
"-o",
|
||||
"ProxyCommand=none",
|
||||
"-o",
|
||||
"ProxyJump=none",
|
||||
"-o",
|
||||
"ConnectTimeout=8",
|
||||
"-o",
|
||||
"ServerAliveInterval=10",
|
||||
"-o",
|
||||
"ServerAliveCountMax=3",
|
||||
"-o",
|
||||
"HostName=" + connection.endpoint,
|
||||
"-p",
|
||||
str(binding.ssh_port),
|
||||
binding.ssh_alias,
|
||||
]
|
||||
|
||||
def execute(self, worker: WorkerBinding, connection: Connection, command: str) -> bytes:
|
||||
# Commands are constants owned by this adapter, never request fields.
|
||||
binding = self.binding(worker)
|
||||
if binding.platform == "windows":
|
||||
command = (
|
||||
"powershell.exe -NoLogo -NoProfile -NonInteractive -EncodedCommand "
|
||||
+ base64.b64encode(command.encode("utf-16le")).decode()
|
||||
)
|
||||
return bounded_run(
|
||||
[
|
||||
*self.arguments(worker, connection)[:-1],
|
||||
"-o",
|
||||
"ClearAllForwardings=yes",
|
||||
binding.ssh_alias,
|
||||
command,
|
||||
],
|
||||
timeout=12,
|
||||
)
|
||||
|
||||
def probe(self, worker: WorkerBinding, connection: Connection) -> dict:
|
||||
binding = self.binding(worker)
|
||||
command = WINDOWS_IDENTITY if binding.platform == "windows" else LINUX_IDENTITY
|
||||
try:
|
||||
value = json.loads(self.execute(worker, connection, command))
|
||||
if (
|
||||
value.get("platform") != binding.platform
|
||||
or value.get("hostname", "").casefold() != binding.expected_hostname.casefold()
|
||||
):
|
||||
raise ValueError
|
||||
except (ValueError, OSError) as exc:
|
||||
raise ConnectionError("Устройство не подтвердило свою конфигурацию.") from exc
|
||||
return {
|
||||
"hostname": value["hostname"],
|
||||
"platform": value["platform"],
|
||||
"host_key_sha256": binding.fingerprint,
|
||||
}
|
||||
Reference in New Issue
Block a user