feat(core): persist viewer state and integrate Cesium services and profiles

This commit is contained in:
DCCONSTRUCTIONS
2026-11-17 17:20:15 +03:00
parent 9cbdd4ea5c
commit 29ef038a43
52 changed files with 2943 additions and 72 deletions
+133
View File
@@ -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])
+137
View File
@@ -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),
)
+34 -1
View File
@@ -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"]}
+1
View File
@@ -0,0 +1 @@
"""Shared map service configuration and optional, diskless provider transport."""
+316
View File
@@ -0,0 +1,316 @@
from __future__ import annotations
import asyncio
import base64
import json
import re
import time
from collections.abc import AsyncIterator, Awaitable, Callable
from dataclasses import dataclass, field
from typing import Any
from urllib.parse import parse_qsl, unquote, urlencode, urlsplit, urlunsplit
import httpx
from .settings import MapServiceError
ASSETS = {1: "TERRAIN", 2: "IMAGERY", 96188: "3DTILES"}
BING_HOSTS = {
"dev.virtualearth.net",
"ecn.tiles.virtualearth.net",
*(f"ecn.t{n}.tiles.virtualearth.net" for n in range(4)),
}
ION_HOSTS = {"assets.ion.cesium.com", "assets.cesium.com"}
SECRET_KEYS = {"key", "access_token", "token", "authorization", "signature", "sig"}
MAX_JSON = 2 * 1024 * 1024
class JsonStream(httpx.AsyncByteStream):
def __init__(self, payload: bytes) -> None:
self.payload = payload
async def __aiter__(self) -> AsyncIterator[bytes]:
yield self.payload
def json_response(document: dict[str, Any], status: int = 200) -> httpx.Response:
return httpx.Response(
status,
headers={"content-type": "application/json", "cache-control": "no-store"},
stream=JsonStream(json.dumps(document).encode()),
)
def safe_url(raw: str) -> str:
try:
url = urlsplit(raw)
if (
url.scheme != "https"
or url.hostname not in ION_HOSTS | BING_HOSTS
or url.port not in (None, 443)
or url.username
or url.password
or url.fragment
or len(raw) > 8192
):
raise ValueError
decoded = unquote(url.path)
if "\\" in decoded or any(part in (".", "..") for part in decoded.split("/")):
raise ValueError
# Encoded separators must not broaden the credential scope downstream.
if re.search(r"%2f|%5c|%25", url.path, re.I):
raise ValueError
return urlunsplit(
(
url.scheme,
url.netloc,
url.path,
urlencode(
[
(k, v)
for k, v in parse_qsl(url.query, keep_blank_values=True)
if k.lower() not in SECRET_KEYS
and not k.lower().startswith("nodedc_cache_")
]
),
"",
)
)
except ValueError as exc:
raise MapServiceError("cesium_resource_not_allowed", 403) from exc
def in_scope(target: str, root: str) -> bool:
url, base = urlsplit(target), urlsplit(root)
if (url.scheme, url.netloc) != (base.scheme, base.netloc):
return False
if url.path == base.path:
return True
directory = base.path.rsplit("/", 1)[0] + "/"
return directory != "/" and url.path.startswith(directory)
async def read_json(response: httpx.Response) -> dict[str, Any]:
try:
payload = bytearray()
async for chunk in response.aiter_bytes():
payload.extend(chunk)
if len(payload) > MAX_JSON:
raise ValueError
document = json.loads(payload)
if not isinstance(document, dict):
raise ValueError
return document
except (ValueError, UnicodeError) as exc:
raise MapServiceError("cesium_provider_invalid_response", 502) from exc
except httpx.HTTPError as exc:
raise MapServiceError("cesium_provider_unavailable", 503) from exc
finally:
await response.aclose()
@dataclass
class Endpoint:
public: dict[str, Any]
root: str
credential: str = field(repr=False)
expires: float = 0
class DirectCesium:
"""Official providers through Core. Only three credentials/metadata live in RAM.
No tile cache, private token in a browser URL, alternate renderer or NAS mutation.
Endpoint-derived credentials are scoped to the exact provider asset directory.
"""
def __init__(
self,
token: str,
client: httpx.AsyncClient,
provider_request: Callable[..., Awaitable[httpx.Response]] | None = None,
) -> None:
self.provider_request = provider_request
self._token = token
self.client = client
self.endpoints: dict[int, Endpoint] = {}
self.locks = {asset: asyncio.Lock() for asset in ASSETS}
async def endpoint(self, asset: int, *, refresh: bool = False) -> Endpoint:
if asset not in ASSETS:
raise MapServiceError("cesium_asset_not_allowed", 404)
if not self._token:
raise MapServiceError("cesium_token_required", 503)
async with self.locks[asset]:
cached = self.endpoints.get(asset)
if not refresh and cached and cached.expires > time.time():
return cached
response = await self._request(
"GET",
f"https://api.cesium.com/v1/assets/{asset}/endpoint",
headers={"Authorization": f"Bearer {self._token}"},
)
await self._require_success(response)
body = await read_json(response)
if body.get("type") != ASSETS[asset]:
raise MapServiceError("cesium_provider_contract_mismatch", 502)
public: dict[str, Any] = {
"assetId": str(asset),
"type": ASSETS[asset],
"credentialMode": "gateway",
"attributions": self._attributions(body.get("attributions")),
}
if asset == 2:
options = body.get("options")
if body.get("externalType") != "BING" or not isinstance(options, dict):
raise MapServiceError("cesium_provider_contract_mismatch", 502)
root = safe_url(str(options.get("url", "")))
if urlsplit(root).hostname != "dev.virtualearth.net":
raise MapServiceError("cesium_provider_contract_mismatch", 502)
credential = options.get("key")
public.update(
externalType="BING",
options={"url": root, "mapStyle": str(options.get("mapStyle", "Aerial"))},
)
else:
root = safe_url(str(body.get("url", "")))
if urlsplit(root).hostname not in ION_HOSTS:
raise MapServiceError("cesium_provider_contract_mismatch", 502)
credential = body.get("accessToken")
public["url"] = root
if not isinstance(credential, str) or not credential or len(credential) > 16384:
raise MapServiceError("cesium_provider_contract_mismatch", 502)
expiry = time.time() + 900
if asset != 2:
try:
segment = credential.split(".")[1]
jwt = json.loads(base64.urlsafe_b64decode(segment + "=" * (-len(segment) % 4)))
expiry = min(expiry, float(jwt["exp"]) - 60)
except (ValueError, KeyError, IndexError, TypeError):
pass
result = Endpoint(public, root, credential, expiry)
self.endpoints[asset] = result
return result
async def verify(self) -> dict[str, Any]:
async def check(asset: int) -> tuple[str, dict[str, Any]]:
try:
await self.endpoint(asset)
return str(asset), {"ok": True}
except MapServiceError as exc:
return str(asset), {"ok": False, "code": exc.code}
results = dict(await asyncio.gather(*(check(asset) for asset in ASSETS)))
return {"ok": all(value["ok"] for value in results.values()), "assets": results}
async def resource(self, method: str, target: str, headers: dict[str, str]) -> httpx.Response:
target = safe_url(target)
is_bing = urlsplit(target).hostname in BING_HOSTS
# A page can have been initialized through NAS before its outage. Resolve
# only the relevant asset(s); failure of imagery cannot block terrain.
asset_ids = (2,) if is_bing else (1, 96188)
endpoint = None
matched_asset = None
last_error = None
for asset in asset_ids:
try:
candidate = await self.endpoint(asset)
except MapServiceError as exc:
last_error = exc
continue
if is_bing or in_scope(target, candidate.root):
endpoint, matched_asset = candidate, asset
break
if endpoint is None or matched_asset is None:
raise last_error or MapServiceError("cesium_resource_outside_asset", 403)
for attempt in range(2):
outgoing = dict(headers)
outgoing["accept-encoding"] = "identity"
url = target
if is_bing:
# httpx request logging must not emit this URL (see transport).
url += ("&" if urlsplit(url).query else "?") + urlencode(
{"key": endpoint.credential}
)
else:
outgoing["authorization"] = f"Bearer {endpoint.credential}"
response = await self._request(method, url, headers=outgoing)
if response.status_code in (401, 403) and attempt == 0:
await response.aclose()
endpoint = await self.endpoint(matched_asset, refresh=True)
if not is_bing and not in_scope(target, endpoint.root):
raise MapServiceError("cesium_endpoint_changed", 409)
continue
await self._require_success(response)
response.headers["cache-control"] = "no-store"
response.headers["x-nodedc-map-route"] = "direct"
if (
method != "HEAD"
and response.status_code not in (204, 304)
and (
"json" in response.headers.get("content-type", "")
or urlsplit(target).path.endswith(".json")
)
):
document = self._sanitize(await read_json(response), endpoint.credential)
result = json_response(document, response.status_code)
result.headers["x-nodedc-map-route"] = "direct"
return result
return response
raise MapServiceError("cesium_provider_unauthorized", 401)
async def _request(self, method: str, url: str, *, headers: dict[str, str]) -> httpx.Response:
try:
# Core has one canonical operator origin. Keep URL-restricted ion
# tokens usable without accepting a caller-supplied provider origin.
headers = {**headers, "referer": "http://127.0.0.1:8000/"}
if self.provider_request is not None:
return await self.provider_request(method, url, headers=headers)
request = self.client.build_request(
method, url, headers=headers, timeout=httpx.Timeout(20, connect=4)
)
return await self.client.send(request, stream=True, follow_redirects=False)
except httpx.HTTPError as exc:
raise MapServiceError("cesium_provider_unavailable", 503) from exc
@staticmethod
async def _require_success(response: httpx.Response) -> None:
if response.status_code in (200, 206, 204, 304):
return
status = response.status_code
code = response.headers.get("x-nodedc-egress-error")
await response.aclose()
if code == "upstream_region_denied":
raise MapServiceError("cesium_egress_region_denied", 403)
if code:
raise MapServiceError("cesium_egress_unavailable", 503)
if status in (401, 403):
raise MapServiceError("cesium_provider_unauthorized", status)
if status == 429:
raise MapServiceError("cesium_provider_rate_limited", 429)
raise MapServiceError("cesium_provider_unavailable", 502)
@staticmethod
def _attributions(value: object) -> list[dict[str, Any]]:
if not isinstance(value, list):
return []
return [
{"html": str(item.get("html", "")), "collapsible": bool(item.get("collapsible"))}
for item in value[:100]
if isinstance(item, dict)
]
@classmethod
def _sanitize(cls, value: Any, credential: str) -> Any:
if isinstance(value, dict):
return {
key: cls._sanitize(item, credential)
for key, item in value.items()
if key.lower().replace("_", "")
not in {"key", "token", "accesstoken", "authorization"}
}
if isinstance(value, list):
return [cls._sanitize(item, credential) for item in value]
if isinstance(value, str):
return value.replace(credential, "nodedc-gateway")
return value
+37
View File
@@ -0,0 +1,37 @@
"""Signed request-scoped cache egress. Secrets stay between Core and Gateway."""
from __future__ import annotations
import base64
import hashlib
import hmac
import json
import re
import time
from pathlib import Path
from typing import Any
from .settings import MapServiceError
def gateway_headers(
key_path: Path, binding: dict[str, Any], method: str, path: str
) -> dict[str, str]:
try:
if key_path.is_symlink() or key_path.stat().st_size > 128:
raise ValueError()
key = key_path.read_text().strip()
if not re.fullmatch(r"[a-f0-9]{64}", key):
raise ValueError()
except (OSError, ValueError) as exc:
raise MapServiceError("cesium_egress_gateway_not_ready", 503) from exc
value = {k: binding[k] for k in ("endpoint", "fingerprint", "token")}
value.update(schema="nodedc.map-egress/v1", timestamp=int(time.time()), profile="cesium")
payload = (
base64.urlsafe_b64encode(json.dumps(value, separators=(",", ":")).encode())
.decode()
.rstrip("=")
)
message = f"nodedc.map-egress/v1\n{method}\n{path}\n{payload}"
signature = hmac.new(bytes.fromhex(key), message.encode(), hashlib.sha256).hexdigest()
return {"x-nodedc-map-egress": payload, "x-nodedc-map-egress-signature": signature}
+269
View File
@@ -0,0 +1,269 @@
from __future__ import annotations
import asyncio
import logging
import re
import time
from collections.abc import Callable
from pathlib import Path
from typing import Any, cast
import httpx
from k1link.fleet.egress import Egress
from k1link.fleet.egress import lock as egress_lock
from k1link.fleet.egress_transport import EgressTransport
from k1link.fleet.trust import PairingError
from .direct import DirectCesium, json_response, read_json
from .egress import gateway_headers
from .settings import CesiumSettings, CesiumSettingsStore, MapServiceError, RouteMode
class _ProviderLogFilter(logging.Filter):
def filter(self, record: logging.LogRecord) -> bool:
# Bing requires a query credential. Never put provider URLs into HTTP
# client diagnostic logs, including when another feature enables INFO.
message = record.getMessage()
if "virtualearth.net" in message or "cesium.com" in message:
record.msg = "Map provider HTTP request (URL omitted)"
record.args = ()
return True
class MapServiceRoutes:
def __init__(
self,
store: CesiumSettingsStore,
gateway_url: str | None,
client: httpx.AsyncClient,
*,
fleet_root: Path | None = None,
clock: Callable[[], float] = time.monotonic,
) -> None:
self.store, self.gateway_url, self.client, self.clock = store, gateway_url, client, clock
self.fleet_root = fleet_root
self.egress_transport = EgressTransport()
self.gateway_egress = False
self.commit_lock = asyncio.Lock()
self.probe_lock = asyncio.Lock()
self.gateway_available: bool | None = None
self.next_probe = 0.0
self.active_route = "unknown"
self._direct: DirectCesium | None = None
self._revision = -1
self._settings: CesiumSettings | None = None
logger = logging.getLogger("httpx")
if not any(isinstance(item, _ProviderLogFilter) for item in logger.filters):
logger.addFilter(_ProviderLogFilter())
@property
def settings(self) -> CesiumSettings:
if self._settings is None:
self._settings = self.store.read()
return self._settings
@property
def configured(self) -> bool:
try:
return bool(self.settings.token) or bool(self.gateway_url)
except MapServiceError:
return bool(self.gateway_url)
def binding(self, identifier: str) -> dict[str, Any]:
try:
if not self.fleet_root:
raise PairingError("not configured")
return Egress(self.fleet_root).find(identifier)
except PairingError as exc:
raise MapServiceError("cesium_egress_unavailable", 503) from exc
def provider(self, token: str, identifier: str) -> DirectCesium:
if not identifier:
return DirectCesium(token, self.client)
binding = self.binding(identifier)
async def request(method: str, target: str, *, headers: dict[str, str]) -> httpx.Response:
return await self.egress_transport.request(binding, method, target, headers)
return DirectCesium(token, self.client, request)
def direct(self) -> DirectCesium:
settings = self.settings
if self._direct is None or self._revision != settings.revision:
self._direct = self.provider(settings.token, settings.egress_id)
self._revision = settings.revision
return self._direct
def status(self) -> dict[str, Any]:
return {
"schema_version": "missioncore.cesium-service/v1",
**self.settings.public(),
"gateway_configured": bool(self.gateway_url),
"gateway_available": self.gateway_available,
"active_route": self.active_route,
}
async def gateway_ready(self) -> bool:
if not self.gateway_url:
self.gateway_available = False
return False
if self.clock() < self.next_probe:
return self.gateway_available is True
async with self.probe_lock:
if self.clock() < self.next_probe:
return self.gateway_available is True
try:
response = await self.client.send(
self.client.build_request(
"GET",
f"{self.gateway_url}/healthz",
timeout=2.0,
headers={"x-nodedc-user-id": "mission-core-loopback-operator"},
),
stream=True,
)
if response.status_code != 200:
await response.aclose()
raise MapServiceError("map_gateway_unavailable")
value = await read_json(response)
self.gateway_egress = value.get("egressContract") == "nodedc.map-egress/v1"
self.gateway_available = (
value.get("ok") is True and value.get("service") == "nodedc-map-gateway"
)
except (httpx.HTTPError, MapServiceError):
self.gateway_available = False
self.next_probe = self.clock() + 15.0
return self.gateway_available
async def send(
self, method: str, path: str, query: dict[str, str] | None, headers: dict[str, str]
) -> httpx.Response:
mode = self.settings.mode
if mode != "direct" and await self.gateway_ready():
forwarded = dict(headers)
if self.settings.egress_id:
if not self.gateway_egress:
raise MapServiceError("cesium_egress_gateway_not_ready", 503)
forwarded.update(
gateway_headers(
self.store.path.parent / "egress-signing.key",
self.binding(self.settings.egress_id),
method,
path,
)
)
try:
response = await self.client.send(
self.client.build_request(
method,
f"{self.gateway_url}{path}",
params=query,
headers=forwarded,
timeout=httpx.Timeout(30.0, connect=2.0),
),
stream=True,
)
# A cache-policy refusal, auth failure or absent resource is not
# evidence that NAS is down. Preserve that server's decision.
if response.status_code not in (502, 503):
self.active_route = "gateway"
response.headers["x-nodedc-map-route"] = "gateway"
return response
await response.aclose()
except httpx.HTTPError:
self.gateway_available = False
self.next_probe = self.clock() + 15.0
# An upstream 502/503 is not an outage of the cache server.
# Other requests must still be able to read its warm tiles.
if mode == "gateway":
self.active_route = "unavailable"
raise MapServiceError("map_gateway_unavailable")
direct = self.direct()
if not self.settings.token:
self.active_route = "unavailable"
raise MapServiceError("cesium_token_required")
if path == "/healthz":
verification = await direct.verify()
self.active_route = "direct" if verification["ok"] else "unavailable"
return json_response(
{
"service": "missioncore-map-direct",
**verification,
"route": "direct",
"cache": None,
},
200 if verification["ok"] else 503,
)
match = re.fullmatch(r"/api/map/ion/assets/(\d+)/endpoint", path)
if match:
endpoint = await direct.endpoint(int(match[1]))
self.active_route = "direct"
response = json_response(endpoint.public)
elif path == "/api/map/cache" and query:
forwarded = {
key: value
for key, value in headers.items()
if key.lower() in {"accept", "range", "if-none-match", "if-modified-since"}
}
response = await direct.resource(method, query["url"], forwarded)
self.active_route = "direct"
else:
raise MapServiceError("map_route_not_allowed", 404)
response.headers["x-nodedc-map-route"] = "direct"
return response
async def verify(
self, token: str | None = None, egress_id: str | None = None
) -> dict[str, Any]:
candidate = self.provider(
token if token is not None else self.settings.token,
self.settings.egress_id if egress_id is None else egress_id,
)
return await candidate.verify()
async def save(
self,
expected: int,
mode: str,
token: str | None,
*,
remove: bool = False,
egress_id: str | None = None,
) -> dict[str, Any]:
# Validate without replacing the working token. Check revision again
# after awaited provider I/O; a stale tab cannot overwrite newer settings.
candidate = None
selected = self.settings.egress_id if egress_id is None else egress_id
if not remove and (token is not None or selected != self.settings.egress_id):
candidate = self.provider(token if token is not None else self.settings.token, selected)
result = await candidate.verify()
if not result["ok"]:
first = next(item["code"] for item in result["assets"].values() if not item["ok"])
raise MapServiceError(first, 422)
async with self.commit_lock:
if selected and mode != "direct" and self.gateway_url:
if await self.gateway_ready() and not self.gateway_egress:
raise MapServiceError("cesium_egress_gateway_not_ready", 503)
gateway_headers(
self.store.path.parent / "egress-signing.key",
self.binding(selected),
"GET",
"/healthz",
)
previous = self.store.read()
next_settings = CesiumSettings(
expected,
cast(RouteMode, mode),
"" if remove else (previous.token if token is None else token),
selected,
)
with egress_lock:
if selected:
self.binding(selected)
self._settings = self.store.save(next_settings, expected)
self._direct = candidate
self._revision = self._settings.revision
self.next_probe = 0
self.active_route = "unknown"
return self.status()
+123
View File
@@ -0,0 +1,123 @@
from __future__ import annotations
import json
import os
import re
import tempfile
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Literal
RouteMode = Literal["auto", "direct", "gateway"]
MODES = {"auto", "direct", "gateway"}
class MapServiceError(Exception):
def __init__(self, code: str, status: int = 503) -> None:
self.code = code
self.status = status
super().__init__(code)
@dataclass(frozen=True)
class CesiumSettings:
revision: int = 0
mode: RouteMode = "auto"
token: str = field(default="", repr=False)
egress_id: str = ""
def public(self) -> dict[str, Any]:
return {
"revision": self.revision,
"mode": self.mode,
"token_configured": bool(self.token),
"egress_id": self.egress_id,
}
def validate_egress(value: object) -> str:
if not isinstance(value, str) or (value and not re.fullmatch(r"eg_[a-f0-9]{32}", value)):
raise MapServiceError("cesium_egress_invalid", 422)
return value
def validate_token(value: object) -> str:
if not isinstance(value, str) or not 1 <= len(value.strip()) <= 8192:
raise MapServiceError("cesium_token_invalid", 422)
token = value.strip()
if not token.isascii() or any(character.isspace() for character in token):
raise MapServiceError("cesium_token_invalid", 422)
return token
class CesiumSettingsStore:
"""One installation-owned secret document; never exposed as a profile or cache."""
def __init__(self, path: Path) -> None:
self.path = path
def read(self) -> CesiumSettings:
try:
if self.path.is_symlink() or self.path.stat().st_size > 16384:
raise ValueError
value = json.loads(self.path.read_text())
if (
value.get("schema_version") != "missioncore.cesium-service/v1"
or type(value.get("revision")) is not int
or value["revision"] < 1
or value.get("mode") not in MODES
):
raise ValueError
token = validate_token(value["token"]) if value.get("token") else ""
return CesiumSettings(
value["revision"], value["mode"], token, validate_egress(value.get("egress_id", ""))
)
except FileNotFoundError:
return CesiumSettings()
except (OSError, ValueError, KeyError, TypeError, AttributeError) as exc:
raise MapServiceError("cesium_settings_unreadable", 503) from exc
def save(self, settings: CesiumSettings, expected_revision: int) -> CesiumSettings:
# The owner serializes commits, including the revision check, in one lock.
if self.read().revision != expected_revision:
raise MapServiceError("cesium_settings_conflict", 409)
directory = self.path.parent
try:
directory.mkdir(parents=True, exist_ok=True, mode=0o700)
if directory.resolve() != directory or self.path.is_symlink():
raise MapServiceError("cesium_settings_unwritable", 503)
os.chmod(directory, 0o700)
descriptor, temporary = tempfile.mkstemp(prefix=".cesium-", dir=directory)
except OSError as exc:
raise MapServiceError("cesium_settings_unwritable", 503) from exc
next_value = CesiumSettings(
expected_revision + 1,
settings.mode,
settings.token,
validate_egress(settings.egress_id),
)
payload = {
"schema_version": "missioncore.cesium-service/v1",
"revision": next_value.revision,
"mode": next_value.mode,
"token": next_value.token,
"egress_id": next_value.egress_id,
}
try:
with os.fdopen(descriptor, "w") as output:
os.fchmod(output.fileno(), 0o600)
json.dump(payload, output)
output.flush()
os.fsync(output.fileno())
os.replace(temporary, self.path)
directory_fd = os.open(directory, os.O_RDONLY)
try:
os.fsync(directory_fd)
finally:
os.close(directory_fd)
except OSError as exc:
raise MapServiceError("cesium_settings_unwritable", 503) from exc
finally:
Path(temporary).unlink(missing_ok=True)
return next_value
+25
View File
@@ -5,6 +5,7 @@ from __future__ import annotations
import fcntl
import hashlib
import json
import math
import os
from contextlib import contextmanager
from datetime import UTC, datetime
@@ -19,6 +20,8 @@ KINDS = {
"battery-ui": "missioncore.battery-ui/v1",
"battery-view": "missioncore.battery-view/v1",
"environments": "missioncore.environment-library/v1",
"observation-map": "missioncore.observation-map/v1",
"rover-view": "missioncore.rover-view/v1",
}
_lock = RLock()
@@ -44,6 +47,28 @@ def validate_document(kind: str, document: Any) -> None:
height = document.get("height")
if type(height) not in (int, float) or not 360 <= height <= 2160:
raise ValueError("Неверная высота окна.")
elif kind == "observation-map":
camera, layers = document.get("camera"), document.get("layers")
limits = {"longitude": (-180, 180), "latitude": (-90, 90),
"height": (-100_000, 1_000_000_000), "heading": (-360, 360),
"pitch": (-90, 90), "roll": (-360, 360)}
if set(document) != {"schema", "camera", "layers"} or (
camera is not None and (
not isinstance(camera, dict) or set(camera) != set(limits)
or any(type(camera[k]) not in (float, int) or not math.isfinite(camera[k])
or not low <= camera[k] <= high for k, (low, high) in limits.items())
)
):
raise ValueError("Неверное положение камеры карты.")
if not isinstance(layers, dict) or set(layers) != {
"imagery", "terrain", "buildings", "grid", "targets"
} or any(type(v) is not bool for v in layers.values()):
raise ValueError("Неверная видимость слоёв карты.")
elif kind == "rover-view":
if set(document) != {"schema", "model"} or document.get("model") not in (
"", "dcd006-v022"
):
raise ValueError("Неверная модель аппарата.")
else:
profiles = document.get("profiles")
if not isinstance(profiles, list) or len(profiles) > 64:
+5 -1
View File
@@ -540,7 +540,11 @@ try:
except (OSError, ValueError):
lab_gateway_configuration = None
laboratory_worker_gateway = LaboratoryWorkerGateway(lab_gateway_configuration)
map_gateway_proxy = MapGatewayProxy(MapGatewayConfiguration.from_environment())
map_gateway_proxy = MapGatewayProxy(
MapGatewayConfiguration.from_environment(),
settings_path=session_store.data_dir / "services" / "cesium-ion" / "settings.json",
fleet_root=session_store.data_dir / "fleet",
)
recording_reconciler_readiness = BackgroundReconcilerReadiness()
+2 -1
View File
@@ -14,8 +14,9 @@ from k1link.web.fleet_api import local_operator
router = APIRouter(prefix="/api/v1/fleet/installers", tags=["installers"])
Fleet = Annotated[FleetRegistry, Depends(local_operator)]
KINDS = {"node", "vps-arnavi", "vps-wireguard", "vps-netbird", "vps-librespeed"}
KINDS = {"node", "vps-arnavi", "vps-wireguard", "vps-netbird", "vps-librespeed", "vps-egress"}
DOWNLOAD_NAMES = {
"vps-egress": "mission-core-egress-vps.pyz",
"vps-librespeed": "mission-core-librespeed-vps.pyz",
"node": "mission-core-node-install.pyz",
"vps-arnavi": "mission-core-vps-install.pyz",
+25 -1
View File
@@ -5,6 +5,7 @@ import re
from collections.abc import AsyncIterator, Mapping
from dataclasses import dataclass
from ipaddress import ip_address
from pathlib import Path as FilePath
from typing import Annotated, Any, Final
from urllib.parse import parse_qsl, urlsplit
@@ -12,6 +13,11 @@ import httpx
from fastapi import APIRouter, HTTPException, Path, Query, Request
from fastapi.responses import JSONResponse, Response, StreamingResponse
from k1link.maps.direct import json_response
from k1link.maps.routing import MapServiceRoutes
from k1link.maps.settings import CesiumSettingsStore, MapServiceError
from k1link.web.map_services_api import build_map_services_router
MAP_GATEWAY_URL_ENV: Final = "MISSIONCORE_MAP_GATEWAY_INTERNAL_URL"
MAP_SANDBOX_HIDE_CREDITS_ENV: Final = "MISSIONCORE_MAP_SANDBOX_HIDE_CREDITS"
MAP_SCHEMA_VERSION: Final = "missioncore.map-gateway/v1"
@@ -46,6 +52,7 @@ RESPONSE_HEADER_ALLOWLIST: Final = frozenset(
"expires",
"last-modified",
"vary",
"x-nodedc-map-route",
}
)
SENSITIVE_JSON_KEYS: Final = frozenset(
@@ -100,6 +107,8 @@ class MapGatewayProxy:
configuration: MapGatewayConfiguration,
*,
client: httpx.AsyncClient | None = None,
settings_path: FilePath | None = None,
fleet_root: FilePath | None = None,
) -> None:
self._configuration = configuration
self._owns_client = client is None
@@ -117,10 +126,14 @@ class MapGatewayProxy:
keepalive_expiry=30.0,
),
)
self.routes = (MapServiceRoutes(CesiumSettingsStore(settings_path),
configuration.internal_url, self._client, fleet_root=fleet_root)
if settings_path is not None else None)
@property
def configured(self) -> bool:
return self._configuration.internal_url is not None
return (self.routes.configured if self.routes is not None
else self._configuration.internal_url is not None)
def runtime_configuration(self) -> Response:
if not self.configured:
@@ -249,6 +262,15 @@ class MapGatewayProxy:
query: Mapping[str, str] | None = None,
) -> httpx.Response:
_require_loopback_request(request)
if self.routes is not None:
headers = {name: value for name, value in request.headers.items()
if name.lower() in REQUEST_HEADER_ALLOWLIST}
headers["x-nodedc-user-id"] = MAP_GATEWAY_SUBJECT
try:
return await self.routes.send(request.method, upstream_path,
dict(query) if query else None, headers)
except MapServiceError as exc:
return json_response({"code": exc.code, "retryable": exc.status >= 500}, exc.status)
base_url = self._configuration.internal_url
if base_url is None:
raise HTTPException(
@@ -452,6 +474,8 @@ def _filtered_response_headers(headers: httpx.Headers) -> dict[str, str]:
def build_map_router(service: MapGatewayProxy) -> APIRouter:
router = APIRouter(prefix="/api/v1/map", tags=["map"])
if service.routes is not None:
router.include_router(build_map_services_router(service.routes, _require_loopback_request))
@router.get("/runtime-config")
async def runtime_config(request: Request) -> Response:
+102
View File
@@ -0,0 +1,102 @@
from __future__ import annotations
import json
from collections.abc import Callable
from typing import Any
from urllib.parse import urlsplit
from fastapi import APIRouter, Request
from fastapi.responses import JSONResponse
from k1link.maps.routing import MapServiceRoutes
from k1link.maps.settings import MODES, MapServiceError, validate_egress, validate_token
def reply(value: dict[str, Any], status: int = 200) -> JSONResponse:
return JSONResponse(value, status_code=status, headers={"Cache-Control": "no-store"})
async def payload(request: Request) -> dict[str, Any]:
host = urlsplit(str(request.url)).hostname
origin = request.headers.get("origin")
if (
host not in {"127.0.0.1", "localhost", "::1"}
or request.headers.get("sec-fetch-site") == "cross-site"
or (origin is not None and origin != str(request.base_url).rstrip("/"))
):
raise MapServiceError("cesium_settings_local_only", 403)
if request.headers.get("content-type", "").split(";", 1)[0] != "application/json":
raise MapServiceError("cesium_settings_invalid_request", 415)
body = bytearray()
async for chunk in request.stream():
body.extend(chunk)
if len(body) > 16384:
raise MapServiceError("cesium_settings_invalid_request", 413)
try:
value = json.loads(body)
if not isinstance(value, dict):
raise ValueError
return value
except (ValueError, UnicodeError) as exc:
raise MapServiceError("cesium_settings_invalid_request", 422) from exc
def build_map_services_router(
service: MapServiceRoutes, require_local: Callable[[Request], None]
) -> APIRouter:
router = APIRouter(prefix="/services/cesium-ion")
@router.get("")
async def status(request: Request) -> JSONResponse:
require_local(request)
try:
return reply(service.status())
except MapServiceError as exc:
return reply({"code": exc.code}, exc.status)
@router.post("/verify")
async def verify(request: Request) -> JSONResponse:
require_local(request)
try:
value = await payload(request)
if set(value) - {"token", "egress_id"}:
raise MapServiceError("cesium_settings_invalid_request", 422)
token = validate_token(value["token"]) if "token" in value else None
return reply(
await service.verify(
token, validate_egress(value["egress_id"]) if "egress_id" in value else None
)
)
except MapServiceError as exc:
return reply({"code": exc.code}, exc.status)
@router.put("")
async def save(request: Request) -> JSONResponse:
require_local(request)
try:
value = await payload(request)
if (
set(value) - {"revision", "mode", "token", "remove_token", "egress_id"}
or type(value.get("revision")) is not int
or value["revision"] < 0
or not isinstance(value.get("mode"), str)
or value["mode"] not in MODES
or type(value.get("remove_token", False)) is not bool
or (value.get("remove_token") and "token" in value)
):
raise MapServiceError("cesium_settings_invalid_request", 422)
token = validate_token(value["token"]) if "token" in value else None
return reply(
await service.save(
value["revision"],
value["mode"],
token,
remove=value.get("remove_token", False),
egress_id=validate_egress(value["egress_id"]) if "egress_id" in value else None,
)
)
except MapServiceError as exc:
# Never reflect upstream bodies, validation input or secret values.
return reply({"code": exc.code}, exc.status)
return router
+26 -1
View File
@@ -11,6 +11,8 @@ from typing import Annotated, Literal
from fastapi import APIRouter, Depends, HTTPException, Request, Response
from pydantic import BaseModel, ConfigDict, Field
from k1link.fleet.egress import Egress
from k1link.fleet.egress import invitation as egress_invitation
from k1link.fleet.librespeed import LibreSpeed
from k1link.fleet.librespeed import invitation as speed_invitation
from k1link.fleet.network_profiles import parse_file
@@ -40,7 +42,7 @@ class Update(Details):
class ServiceImport(BaseModel):
model_config = ConfigDict(extra="forbid")
kind: Literal["arnavi", "wireguard", "librespeed"]
kind: Literal["arnavi", "wireguard", "librespeed", "egress"]
document: str = Field(min_length=1, max_length=16384)
network_interface: str | None = Field(default=None, max_length=20)
expected_revision: int = Field(ge=1, strict=True)
@@ -94,6 +96,23 @@ def services(fleet: FleetRegistry) -> list[Document]:
details={**item, "name": "LibreSpeed", "boards": 0, "last_verified": None},
)
)
for item in Egress(fleet.root).listing():
result.append(
dict(
kind="egress",
id=item["id"],
endpoint=item["endpoint"],
name="Маршрутизация трафика",
state=item["state"],
last_seen=None,
details={
**item,
"name": "Маршрутизация трафика",
"boards": 0,
"last_verified": None,
},
)
)
return result
@@ -133,6 +152,8 @@ async def health(key: str, request: Request, response: Response, fleet: Fleet) -
("librespeed", r) for r in LibreSpeed(fleet.root).rows() if ("librespeed", r["id"]) in known
]
rows += [("egress", r) for r in Egress(fleet.root).rows() if ("egress", r["id"]) in known]
async def inspect(kind: str, row: Document) -> Document:
observed = await observer.observe(kind, row, fleet.network_profiles.verify_status)
return {"kind": kind, "id": row.get("id", row.get("server_id")), **observed}
@@ -189,6 +210,8 @@ def connect_service(key: str, body: ServiceImport, fleet: Fleet) -> Document:
parsed = (
parse_file(body.document) # type: ignore[no-untyped-call] # existing invitation validator
if body.kind == "wireguard"
else egress_invitation(body.document)
if body.kind == "egress"
else speed_invitation(body.document)
if body.kind == "librespeed"
else invitation(body.document.strip())
@@ -199,6 +222,8 @@ def connect_service(key: str, body: ServiceImport, fleet: Fleet) -> Document:
fleet.network_profiles.import_file( # type: ignore[no-untyped-call] # existing admission authority
body.document, host["name"], body.network_interface
)
elif body.kind == "egress":
Egress(fleet.root).pair(body.document, body.network_interface)
elif body.kind == "librespeed":
LibreSpeed(fleet.root).pair(body.document, body.network_interface)
else:
+2 -2
View File
@@ -14,9 +14,9 @@ def probe(kind: str, row: Document, verify: Callable[[Document, Document], Docum
value = request(row, "GET", "/v1/status")
if kind == "wireguard":
verify(row, value)
elif kind == "librespeed":
elif kind in {"librespeed", "egress"}:
if (
value.get("schema") != "missioncore.librespeed/v1"
value.get("schema") != f"missioncore.{kind}/v1"
or value.get("server_id") != row["id"]
):
raise ValueError("Service identity mismatch")