feat(core): persist viewer state and integrate Cesium services and profiles
This commit is contained in:
@@ -0,0 +1,133 @@
|
||||
"""Durable ownership and private credentials for portable egress services."""
|
||||
|
||||
import json
|
||||
import re
|
||||
import secrets
|
||||
import sqlite3
|
||||
import threading
|
||||
import time
|
||||
from collections.abc import Iterator
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from . import vps_transport
|
||||
from .trust import PairingError
|
||||
|
||||
Document = dict[str, Any]
|
||||
lock = threading.RLock()
|
||||
|
||||
|
||||
def invitation(document: str) -> Document:
|
||||
try:
|
||||
value = json.loads(document)
|
||||
if set(value) != {
|
||||
"schema",
|
||||
"server_id",
|
||||
"endpoint",
|
||||
"fingerprint",
|
||||
"bootstrap",
|
||||
"expires_at",
|
||||
}:
|
||||
raise ValueError
|
||||
if value["schema"] != "missioncore.egress-connect/v1":
|
||||
raise ValueError
|
||||
for key, pattern in (
|
||||
("server_id", r"eg_[a-f0-9]{32}"),
|
||||
("fingerprint", r"[a-f0-9]{64}"),
|
||||
("bootstrap", r"[A-Za-z0-9_-]{43}"),
|
||||
):
|
||||
if not isinstance(value[key], str) or not re.fullmatch(pattern, value[key]):
|
||||
raise ValueError
|
||||
if not time.time() < value["expires_at"] <= time.time() + 86500:
|
||||
raise PairingError("Приглашение службы маршрутизации просрочено. Скачайте новое с VPS.")
|
||||
vps_transport.destination(value["endpoint"])
|
||||
return dict(value)
|
||||
except (ValueError, TypeError, KeyError):
|
||||
raise PairingError("Файл приглашения Egress повреждён или просрочен.") from None
|
||||
|
||||
|
||||
class Egress:
|
||||
def __init__(self, root: Path):
|
||||
self.path = root / "egress.sqlite3"
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
with self.db() as db:
|
||||
db.execute(
|
||||
"CREATE TABLE IF NOT EXISTS services (id TEXT PRIMARY KEY, body TEXT NOT NULL)"
|
||||
)
|
||||
self.path.chmod(0o600)
|
||||
|
||||
@contextmanager
|
||||
def db(self) -> Iterator[sqlite3.Connection]:
|
||||
connection = sqlite3.connect(self.path)
|
||||
try:
|
||||
with connection:
|
||||
yield connection
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
def rows(self) -> list[Document]:
|
||||
with lock, self.db() as db:
|
||||
return [json.loads(r[0]) for r in db.execute("SELECT body FROM services")]
|
||||
|
||||
def listing(self) -> list[Document]:
|
||||
return [
|
||||
{k: r[k] for k in ("id", "endpoint", "state", "fingerprint")}
|
||||
for r in self.rows()
|
||||
if r["state"] == "connected"
|
||||
]
|
||||
|
||||
def save(self, row: Document) -> None:
|
||||
with self.db() as db:
|
||||
db.execute("INSERT OR REPLACE INTO services VALUES (?,?)", (row["id"], json.dumps(row)))
|
||||
|
||||
def find(self, identifier: str) -> Document:
|
||||
row = next(
|
||||
(r for r in self.rows() if r["id"] == identifier and r["state"] == "connected"), None
|
||||
)
|
||||
if not row:
|
||||
raise PairingError("Подключите службу маршрутизации на VPS.")
|
||||
return row
|
||||
|
||||
def pair(self, document: str, network_interface: str | None = None) -> Document:
|
||||
value = invitation(document)
|
||||
vps_transport.validate_interface(network_interface)
|
||||
with lock:
|
||||
row = next((r for r in self.rows() if r["id"] == value["server_id"]), None)
|
||||
if row and (
|
||||
row["fingerprint"] != value["fingerprint"] or row["endpoint"] != value["endpoint"]
|
||||
):
|
||||
raise PairingError("Идентичность службы маршрутизации изменилась.")
|
||||
if row is None:
|
||||
row = {
|
||||
"id": value["server_id"],
|
||||
"endpoint": value["endpoint"],
|
||||
"fingerprint": value["fingerprint"],
|
||||
"token": secrets.token_urlsafe(32),
|
||||
"core_id": "core_" + secrets.token_hex(16),
|
||||
"state": "pending",
|
||||
}
|
||||
row["network_interface"] = network_interface
|
||||
self.save(row) # Retry a lost claim reply using the same controller identity.
|
||||
result = vps_transport.request(
|
||||
row,
|
||||
"POST",
|
||||
"/v1/claim",
|
||||
{
|
||||
"core_id": row["core_id"],
|
||||
"bootstrap": value["bootstrap"],
|
||||
"credential": row["token"],
|
||||
},
|
||||
)
|
||||
if (
|
||||
result.get("server_id") != row["id"]
|
||||
or result.get("schema") != "missioncore.egress/v1"
|
||||
):
|
||||
raise PairingError("VPS вернул другую службу.")
|
||||
row["state"] = "connected"
|
||||
self.save(row)
|
||||
return {"id": row["id"], "state": "connected"}
|
||||
|
||||
def forget(self, identifiers: set[str]) -> None:
|
||||
with lock, self.db() as db:
|
||||
db.executemany("DELETE FROM services WHERE id=?", [(i,) for i in identifiers])
|
||||
@@ -0,0 +1,137 @@
|
||||
"""Pinned streaming transport shared by service clients; no persistent payloads."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import http.client
|
||||
import socket
|
||||
import ssl
|
||||
from collections.abc import AsyncIterator
|
||||
from contextlib import suppress
|
||||
from typing import Any
|
||||
from urllib.parse import urlencode
|
||||
|
||||
import httpx
|
||||
|
||||
from . import vps_transport
|
||||
from .trust import PairingError
|
||||
|
||||
|
||||
def open_response(
|
||||
binding: dict[str, Any], method: str, target: str, headers: dict[str, str], profile: str
|
||||
) -> tuple[http.client.HTTPConnection, http.client.HTTPResponse]:
|
||||
if profile != "cesium" or method not in {"GET", "HEAD"}:
|
||||
raise ValueError("Unsupported egress profile")
|
||||
name, port, address = vps_transport.destination(binding["endpoint"])
|
||||
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
|
||||
context.check_hostname = False
|
||||
context.verify_mode = (
|
||||
ssl.CERT_NONE
|
||||
) # Mandatory certificate pin checked BEFORE sending any bytes.
|
||||
context.minimum_version = ssl.TLSVersion.TLSv1_3
|
||||
connection = http.client.HTTPConnection(name, port, timeout=30)
|
||||
raw = vps_transport.connect(address, port, binding.get("network_interface"))
|
||||
try:
|
||||
connection.sock = context.wrap_socket(raw, server_hostname=name)
|
||||
if (
|
||||
hashlib.sha256(connection.sock.getpeercert(binary_form=True) or b"").hexdigest()
|
||||
!= binding["fingerprint"]
|
||||
):
|
||||
raise PairingError("Идентичность службы маршрутизации изменилась.")
|
||||
connection.sock.settimeout(30)
|
||||
forwarded = {
|
||||
k: v
|
||||
for k, v in headers.items()
|
||||
if k.lower() in {"accept", "range", "if-none-match", "if-modified-since"}
|
||||
}
|
||||
for key, value in headers.items():
|
||||
if key.lower() == "authorization":
|
||||
forwarded["X-Nodedc-Upstream-Authorization"] = value
|
||||
elif key.lower() == "referer":
|
||||
forwarded["X-Nodedc-Upstream-Referer"] = value
|
||||
forwarded["Authorization"] = "Bearer " + binding["token"]
|
||||
connection.request(
|
||||
method, "/v1/fetch/" + profile + "?" + urlencode({"url": target}), headers=forwarded
|
||||
)
|
||||
return connection, connection.getresponse()
|
||||
except BaseException:
|
||||
raw.close()
|
||||
connection.close()
|
||||
raise
|
||||
|
||||
|
||||
class RelayStream(httpx.AsyncByteStream):
|
||||
def __init__(
|
||||
self,
|
||||
connection: http.client.HTTPConnection,
|
||||
response: http.client.HTTPResponse,
|
||||
slots: asyncio.Semaphore,
|
||||
) -> None:
|
||||
self.connection, self.response, self.slots = connection, response, slots
|
||||
self.closed = False
|
||||
|
||||
async def __aiter__(self) -> AsyncIterator[bytes]:
|
||||
try:
|
||||
while data := await asyncio.to_thread(self.response.read, 65536):
|
||||
yield data
|
||||
if self.response.length not in (None, 0):
|
||||
raise http.client.IncompleteRead(b"", self.response.length)
|
||||
except (OSError, http.client.HTTPException) as exc:
|
||||
raise httpx.ReadError("Routing service stream interrupted") from exc
|
||||
finally:
|
||||
await self.aclose()
|
||||
|
||||
async def aclose(self) -> None:
|
||||
if not self.closed:
|
||||
self.closed = True
|
||||
try:
|
||||
if self.connection.sock is not None:
|
||||
with suppress(OSError):
|
||||
self.connection.sock.shutdown(socket.SHUT_RDWR)
|
||||
self.connection.close()
|
||||
await asyncio.to_thread(self.response.close)
|
||||
finally:
|
||||
self.slots.release()
|
||||
|
||||
|
||||
class EgressTransport:
|
||||
def __init__(self) -> None:
|
||||
self.slots = asyncio.Semaphore(16)
|
||||
|
||||
async def request(
|
||||
self,
|
||||
binding: dict[str, Any],
|
||||
method: str,
|
||||
target: str,
|
||||
headers: dict[str, str],
|
||||
profile: str = "cesium",
|
||||
) -> httpx.Response:
|
||||
await self.slots.acquire()
|
||||
task = asyncio.create_task(
|
||||
asyncio.to_thread(open_response, binding, method, target, headers, profile)
|
||||
)
|
||||
try:
|
||||
connection, response = await asyncio.shield(task)
|
||||
except asyncio.CancelledError:
|
||||
|
||||
def finish(done: asyncio.Task[Any]) -> None:
|
||||
try:
|
||||
conn, result = done.result()
|
||||
conn.close()
|
||||
result.close()
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
self.slots.release()
|
||||
|
||||
task.add_done_callback(finish)
|
||||
raise
|
||||
except (OSError, ValueError, http.client.HTTPException) as exc:
|
||||
self.slots.release()
|
||||
raise httpx.ConnectError("Routing service unavailable") from exc
|
||||
return httpx.Response(
|
||||
response.status,
|
||||
headers=response.getheaders(),
|
||||
stream=RelayStream(connection, response, self.slots),
|
||||
)
|
||||
@@ -11,9 +11,12 @@ from typing import Any
|
||||
|
||||
from k1link.compute_connections.store import ConnectionStore, Registry, WorkerBinding
|
||||
from k1link.fleet import network_client
|
||||
from k1link.fleet.egress import Egress
|
||||
from k1link.fleet.egress import lock as egress_lock
|
||||
from k1link.fleet.librespeed import LibreSpeed
|
||||
from k1link.fleet.librespeed import lock as speed_lock
|
||||
from k1link.fleet.server_catalog import Document, ServerCatalog, endpoint_address
|
||||
from k1link.maps.settings import CesiumSettingsStore, MapServiceError
|
||||
|
||||
|
||||
class ServerRemoval:
|
||||
@@ -30,6 +33,7 @@ class ServerRemoval:
|
||||
# cannot race retirement; fleet/connection revisions invalidate stale tabs.
|
||||
with (
|
||||
speed_lock,
|
||||
egress_lock,
|
||||
self.networks.import_lock,
|
||||
self.hosts.lock,
|
||||
self.networks.sync_lock,
|
||||
@@ -104,7 +108,28 @@ class ServerRemoval:
|
||||
for e in self.fleet.routers.pending.values()
|
||||
):
|
||||
blocked.append("Остановите замер скорости перед отключением VPS.")
|
||||
egress = [
|
||||
r
|
||||
for r in Egress(self.fleet.root).rows()
|
||||
if endpoint_address(r["endpoint"]) == host["address"]
|
||||
]
|
||||
if egress:
|
||||
try:
|
||||
selected = (
|
||||
CesiumSettingsStore(
|
||||
self.fleet.root.parent / "services" / "cesium-ion" / "settings.json"
|
||||
)
|
||||
.read()
|
||||
.egress_id
|
||||
)
|
||||
if selected in {r["id"] for r in egress}:
|
||||
blocked.append("Сначала выберите другой маршрут в настройках Cesium ion.")
|
||||
except MapServiceError:
|
||||
blocked.append("Не удалось проверить настройки маршрутизации Cesium ion.")
|
||||
signature = {
|
||||
"egress": [
|
||||
{k: r[k] for k in ("id", "endpoint", "fingerprint", "state")} for r in egress
|
||||
],
|
||||
"librespeed": [
|
||||
{k: r[k] for k in ("id", "endpoint", "fingerprint", "state")} for r in speed
|
||||
],
|
||||
@@ -138,7 +163,8 @@ class ServerRemoval:
|
||||
"blocked": blocked,
|
||||
"services": ["ARNavi"] * len(arnavi)
|
||||
+ ["WireGuard"] * len(wg)
|
||||
+ ["LibreSpeed"] * len(speed),
|
||||
+ ["LibreSpeed"] * len(speed)
|
||||
+ ["Маршрутизация трафика"] * len(egress),
|
||||
"vehicle_connections": len(affected),
|
||||
"worker_connections": sum(
|
||||
c.profile_id in profiles for w in registry.workers for c in w.connections
|
||||
@@ -235,5 +261,12 @@ class ServerRemoval:
|
||||
if endpoint_address(r["endpoint"]) == host["address"]
|
||||
}
|
||||
)
|
||||
Egress(self.fleet.root).forget(
|
||||
{
|
||||
r["id"]
|
||||
for r in Egress(self.fleet.root).rows()
|
||||
if endpoint_address(r["endpoint"]) == host["address"]
|
||||
}
|
||||
)
|
||||
self.catalog.remove(host["id"])
|
||||
return {"removed": True, "id": host["id"]}
|
||||
|
||||
Reference in New Issue
Block a user