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
+211
View File
@@ -0,0 +1,211 @@
import asyncio
import base64
import hashlib
import hmac
import json
import httpx
import pytest
from k1link.fleet.egress import Egress
from k1link.fleet.egress_transport import RelayStream
from k1link.maps.direct import DirectCesium, json_response
from k1link.maps.egress import gateway_headers
from k1link.maps.routing import MapServiceRoutes
from k1link.maps.settings import CesiumSettings, CesiumSettingsStore, MapServiceError
IDENTIFIER = "eg_" + "a" * 32
BINDING = {
"id": IDENTIFIER,
"endpoint": "https://1.1.1.1:19446",
"fingerprint": "b" * 64,
"token": "c" * 43,
"state": "connected",
}
def test_signed_gateway_binding_is_method_and_path_scoped(tmp_path):
key = tmp_path / "key"
key.write_text("ab" * 32)
headers = gateway_headers(key, BINDING, "GET", "/api/map/cache")
payload = headers["x-nodedc-map-egress"]
raw = json.loads(base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4)))
assert raw["token"] == BINDING["token"]
expected = hmac.new(
bytes.fromhex("ab" * 32),
("nodedc.map-egress/v1\nGET\n/api/map/cache\n" + payload).encode(),
hashlib.sha256,
).hexdigest()
assert headers["x-nodedc-map-egress-signature"] == expected
with pytest.raises(MapServiceError, match="gateway_not_ready"):
gateway_headers(tmp_path / "absent", BINDING, "GET", "/healthz")
def test_legacy_settings_keep_route_and_new_id_is_durable(tmp_path):
store = CesiumSettingsStore(tmp_path / "settings.json")
store.save(CesiumSettings(token="private-token"), 0)
document = json.loads(store.path.read_text())
document.pop("egress_id")
store.path.write_text(json.dumps(document))
assert store.read().egress_id == ""
saved = store.save(CesiumSettings(token="private-token", egress_id=IDENTIFIER), 1)
assert store.read().egress_id == IDENTIFIER
assert "private-token" not in repr(saved)
assert "private-token" not in json.dumps(saved.public())
def test_region_refusal_is_not_invalid_token():
async def scenario():
async def relay(*args, **kwargs):
return httpx.Response(403, headers={"x-nodedc-egress-error": "upstream_region_denied"})
async with httpx.AsyncClient() as client:
result = await DirectCesium("private-token", client, relay).verify()
assert not result["ok"]
assert {x["code"] for x in result["assets"].values()} == {"cesium_egress_region_denied"}
asyncio.run(scenario())
def test_unreachable_provider_does_not_disable_warm_cache(tmp_path):
async def scenario():
requests = []
def gateway(request):
requests.append(request.url.path)
if request.url.path == "/healthz":
return json_response({"ok": True, "service": "nodedc-map-gateway"})
if request.url.params.get("url", "").endswith("cold"):
return json_response({"error": "map_egress_upstream_unavailable"}, 503)
return json_response({"warm": True})
async with httpx.AsyncClient(transport=httpx.MockTransport(gateway)) as client:
service = MapServiceRoutes(
CesiumSettingsStore(tmp_path / "settings.json"), "http://nas.test", client
)
with pytest.raises(MapServiceError, match="token_required"):
await service.send("GET", "/api/map/cache", {"url": "cold"}, {})
assert service.gateway_available is True
response = await service.send("GET", "/api/map/cache", {"url": "warm"}, {})
assert json.loads(await response.aread())["warm"]
assert requests.count("/healthz") == 1
asyncio.run(scenario())
def test_failed_route_admission_keeps_working_settings(tmp_path):
async def scenario():
fleet = tmp_path / "fleet"
Egress(fleet).save(BINDING)
store = CesiumSettingsStore(tmp_path / "services" / "cesium-ion" / "settings.json")
store.save(CesiumSettings(token="private-token"), 0)
async with httpx.AsyncClient() as client:
routes = MapServiceRoutes(store, None, client, fleet_root=fleet)
async def relay(*args, **kwargs):
return httpx.Response(
403, headers={"x-nodedc-egress-error": "upstream_region_denied"}
)
routes.egress_transport.request = relay
with pytest.raises(MapServiceError, match="cesium_egress_region_denied"):
await routes.save(1, "auto", None, egress_id=IDENTIFIER)
assert store.read().egress_id == ""
assert store.read().revision == 1
asyncio.run(scenario())
def test_nas_down_uses_selected_relay_without_direct_leak(tmp_path):
async def scenario():
fleet = tmp_path / "fleet"
Egress(fleet).save(BINDING)
store = CesiumSettingsStore(tmp_path / "settings.json")
store.save(CesiumSettings(token="private-token", egress_id=IDENTIFIER), 0)
def network(request):
assert request.url.host == "nas.test", "Provider request bypassed selected VPS"
raise httpx.ConnectError("offline")
async with httpx.AsyncClient(transport=httpx.MockTransport(network)) as client:
routes = MapServiceRoutes(store, "http://nas.test", client, fleet_root=fleet)
calls = []
async def relay(binding, method, target, headers):
calls.append(target)
assert binding["id"] == IDENTIFIER
return json_response(
{
"type": "TERRAIN",
"url": "https://assets.ion.cesium.com/1/",
"accessToken": "scoped-secret",
}
)
routes.egress_transport.request = relay
response = await routes.send("GET", "/api/map/ion/assets/1/endpoint", None, {})
body = await response.aread()
assert calls == ["https://api.cesium.com/v1/assets/1/endpoint"]
assert b"private-token" not in body and b"scoped-secret" not in body
assert not list(tmp_path.rglob("*.terrain"))
asyncio.run(scenario())
def test_offline_nas_cannot_bypass_gateway_setup_on_route_save(tmp_path):
async def scenario():
fleet = tmp_path / "fleet"
Egress(fleet).save(BINDING)
store = CesiumSettingsStore(tmp_path / "settings.json")
store.save(CesiumSettings(token="private-token"), 0)
def offline(request):
raise httpx.ConnectError("offline")
class VerifiedProvider:
async def verify(self):
return {"ok": True}
async with httpx.AsyncClient(transport=httpx.MockTransport(offline)) as client:
routes = MapServiceRoutes(store, "http://nas.test", client, fleet_root=fleet)
routes.provider = lambda *_: VerifiedProvider()
with pytest.raises(MapServiceError, match="gateway_not_ready"):
await routes.save(1, "auto", None, egress_id=IDENTIFIER)
assert store.read().egress_id == ""
assert store.read().revision == 1
asyncio.run(scenario())
def test_truncated_relay_stream_is_not_accepted_and_releases_slot():
class Connection:
sock = None
closed = False
def close(self):
self.closed = True
class Truncated:
length = 3
closed = False
def read(self, _):
return b""
def close(self):
self.closed = True
async def scenario():
connection, response = Connection(), Truncated()
slots = asyncio.Semaphore(1)
await slots.acquire()
stream = RelayStream(connection, response, slots)
with pytest.raises(httpx.ReadError):
async for _ in stream:
pass
assert connection.closed and response.closed
await asyncio.wait_for(slots.acquire(), 0.1)
await stream.aclose()
assert slots.locked(), "Repeated close must not release another caller's slot"
asyncio.run(scenario())
+312
View File
@@ -0,0 +1,312 @@
from __future__ import annotations
import asyncio
import json
import httpx
import pytest
from fastapi import FastAPI
from k1link.maps.direct import JsonStream, json_response
from k1link.maps.routing import MapServiceRoutes
from k1link.maps.settings import CesiumSettings, CesiumSettingsStore, MapServiceError
from k1link.web.map_api import MapGatewayConfiguration, MapGatewayProxy, build_map_router
MASTER = "test-master-secret"
ASSET = "test-scoped-secret"
BING = "test-bing-secret"
class Providers:
def __init__(self):
self.requests = []
self.nas = False
self.nas_status = 200
self.authorized = True
self.asset_status = 200
def __call__(self, request):
self.requests.append(request)
if request.url.host == "nas.test":
if not self.nas:
raise httpx.ConnectError("offline", request=request)
if request.url.path == "/healthz":
return json_response({"ok": True, "service": "nodedc-map-gateway"})
return json_response({"code": "offline_cache_miss", "nas": True}, self.nas_status)
if request.url.host == "api.cesium.com":
assert request.headers["authorization"] == f"Bearer {MASTER}"
if not self.authorized:
return json_response({"secret": MASTER}, 401)
asset = int(request.url.path.split("/")[-2])
if asset == 2:
return json_response(
{
"type": "IMAGERY",
"externalType": "BING",
"options": {
"url": "https://dev.virtualearth.net",
"key": BING,
"mapStyle": "Aerial",
},
}
)
return json_response(
{
"type": "TERRAIN" if asset == 1 else "3DTILES",
"url": f"https://assets.ion.cesium.com/{asset}/",
"accessToken": ASSET,
}
)
if request.url.host == "dev.virtualearth.net":
assert request.url.params["key"] == BING
return json_response(
{
"imageUrl": f"https://ecn.t0.tiles.virtualearth.net/tiles/a.jpg?key={BING}",
"accessToken": ASSET,
}
)
if request.url.host == "assets.ion.cesium.com":
assert request.headers["authorization"] == f"Bearer {ASSET}"
assert not any(key.startswith("nodedc_cache_") for key in request.url.params)
return httpx.Response(
self.asset_status,
stream=JsonStream(b"tile-data"),
headers={
"content-type": "application/octet-stream",
"content-range": "bytes 0-8/9",
},
)
raise AssertionError("Unexpected request")
def routes(tmp_path, providers, clock=lambda: 0):
store = CesiumSettingsStore(tmp_path / "services" / "cesium-ion" / "settings.json")
store.save(CesiumSettings(token=MASTER), 0)
return MapServiceRoutes(
store,
"http://nas.test",
httpx.AsyncClient(transport=httpx.MockTransport(providers)),
clock=clock,
)
def test_private_atomic_store_and_revision(tmp_path):
store = CesiumSettingsStore(tmp_path / "private" / "settings.json")
saved = store.save(CesiumSettings(token=MASTER), 0)
assert store.path.stat().st_mode & 0o777 == 0o600
assert store.path.parent.stat().st_mode & 0o777 == 0o700
assert MASTER not in repr(saved)
assert MASTER not in json.dumps(saved.public())
with pytest.raises(MapServiceError, match="conflict"):
store.save(CesiumSettings(token="other"), 0)
assert store.read().token == MASTER
assert len(list(store.path.parent.iterdir())) == 1
def test_nas_down_then_returns_without_new_cache_or_changed_query(tmp_path):
async def scenario():
upstream = Providers()
now = [0]
service = routes(tmp_path, upstream, lambda: now[0])
url = "https://assets.ion.cesium.com/1/tile.terrain?v=4&nodedc_cache_profile=live"
first = await service.send("GET", "/api/map/cache", {"url": url}, {})
assert await first.aread() == b"tile-data"
assert first.headers["x-nodedc-map-route"] == "direct"
await service.send("GET", "/api/map/cache", {"url": url}, {})
assert sum(r.url.host == "nas.test" for r in upstream.requests) == 1
upstream.nas = True
now[0] = 16
second = await service.send("GET", "/api/map/cache", {"url": url}, {})
assert second.headers["x-nodedc-map-route"] == "gateway"
assert upstream.requests[-1].url.params["url"] == url
assert list(tmp_path.rglob("*.*")) == [service.store.path]
await service.client.aclose()
asyncio.run(scenario())
def test_concurrent_tiles_share_probe_and_endpoint_resolution(tmp_path):
async def scenario():
upstream = Providers()
service = routes(tmp_path, upstream)
responses = await asyncio.gather(
*(
service.send(
"GET",
"/api/map/cache",
{"url": f"https://assets.ion.cesium.com/1/{index}.terrain"},
{},
)
for index in range(12)
)
)
for response in responses:
await response.aclose()
assert sum(r.url.host == "nas.test" for r in upstream.requests) == 1
assert sum(r.url.host == "api.cesium.com" for r in upstream.requests) == 1
await service.client.aclose()
asyncio.run(scenario())
def test_redirect_is_not_followed_and_missing_token_has_explicit_reason(tmp_path):
async def scenario():
upstream = Providers()
service = routes(tmp_path, upstream)
upstream.asset_status = 302
with pytest.raises(MapServiceError, match="unavailable"):
await service.direct().resource("GET", "https://assets.ion.cesium.com/1/a", {})
assert len(upstream.requests) == 2
await service.save(1, "auto", None, remove=True)
with pytest.raises(MapServiceError, match="token_required"):
await service.send("GET", "/healthz", None, {})
await service.client.aclose()
asyncio.run(scenario())
def test_bing_query_credential_not_written_to_http_log(tmp_path, caplog):
async def scenario():
upstream = Providers()
service = routes(tmp_path, upstream)
with caplog.at_level("INFO", logger="httpx"):
response = await service.direct().resource(
"GET", "https://dev.virtualearth.net/REST/v1/Imagery/Metadata/Aerial", {}
)
await response.aclose()
assert BING not in caplog.text and MASTER not in caplog.text
assert all(r.headers.get("referer") == "http://127.0.0.1:8000/" for r in upstream.requests)
await service.client.aclose()
asyncio.run(scenario())
@pytest.mark.parametrize("status", [401, 403, 404, 504])
def test_nas_cache_policy_is_never_bypassed(tmp_path, status):
async def scenario():
upstream = Providers()
upstream.nas, upstream.nas_status = True, status
service = routes(tmp_path, upstream)
response = await service.send(
"GET", "/api/map/cache", {"url": "https://assets.ion.cesium.com/1/x"}, {}
)
assert response.status_code == status
assert all(r.url.host == "nas.test" for r in upstream.requests)
await response.aclose()
await service.client.aclose()
asyncio.run(scenario())
def test_endpoint_and_bing_metadata_never_expose_credentials(tmp_path):
async def scenario():
upstream = Providers()
service = routes(tmp_path, upstream)
for asset in (1, 2, 96188):
response = await service.send("GET", f"/api/map/ion/assets/{asset}/endpoint", None, {})
payload = await response.aread()
assert all(secret.encode() not in payload for secret in (MASTER, ASSET, BING))
response = await service.send(
"GET",
"/api/map/cache",
{
"url": "https://dev.virtualearth.net/REST/v1/Imagery/Metadata/Aerial?key=nodedc-gateway"
},
{},
)
payload = await response.aread()
assert BING.encode() not in payload and ASSET.encode() not in payload
assert b"nodedc-gateway" in payload
await service.client.aclose()
asyncio.run(scenario())
@pytest.mark.parametrize(
"target",
[
"https://localhost/x",
"https://evil.test/x",
"https://assets.ion.cesium.com:123/1/x",
"https://assets.ion.cesium.com/1/../9/x",
"https://assets.ion.cesium.com/1/%2e%2e/9/x",
"https://assets.ion.cesium.com/1%2fx",
"https://assets.ion.cesium.com/999/x",
"https://user@assets.ion.cesium.com/1/x",
],
)
def test_no_arbitrary_proxy_or_credential_scope_escape(tmp_path, target):
async def scenario():
upstream = Providers()
service = routes(tmp_path, upstream)
with pytest.raises(MapServiceError):
await service.direct().resource("GET", target, {})
assert all(r.url.host == "api.cesium.com" for r in upstream.requests)
await service.client.aclose()
asyncio.run(scenario())
def test_invalid_candidate_does_not_replace_saved_token(tmp_path):
async def scenario():
upstream = Providers()
service = routes(tmp_path, upstream)
upstream.authorized = False
with pytest.raises(MapServiceError, match="unauthorized"):
await service.save(1, "direct", MASTER)
assert service.store.read() == CesiumSettings(1, "auto", MASTER)
await service.save(1, "gateway", None, remove=True)
assert service.store.read().token == ""
assert MASTER not in service.store.path.read_text()
await service.client.aclose()
asyncio.run(scenario())
def test_api_secret_redaction_csrf_ranges_and_recovery(tmp_path):
async def scenario():
upstream = Providers()
state = routes(tmp_path, upstream)
app = FastAPI()
proxy = MapGatewayProxy(
MapGatewayConfiguration("http://nas.test"),
client=state.client,
settings_path=state.store.path,
)
app.include_router(build_map_router(proxy))
async with httpx.AsyncClient(
transport=httpx.ASGITransport(app=app, client=("127.0.0.1", 9000)),
base_url="http://127.0.0.1:8000",
) as client:
base = "/api/v1/map/services/cesium-ion"
status = await client.get(base)
assert status.json()["token_configured"] is True
assert MASTER not in status.text
forbidden = await client.put(
base, json={"revision": 1, "mode": "auto"}, headers={"Origin": "https://evil.test"}
)
assert forbidden.status_code == 403
invalid = await client.put(base, json={"revision": 1, "mode": [], "token": MASTER})
assert invalid.status_code == 422 and MASTER not in invalid.text
health = await client.get("/api/v1/map/gateway/health")
assert health.json()["service"] == "missioncore-map-direct"
assert health.json()["cache"] is None
endpoint = await client.get("/api/v1/map/gateway/ion/assets/1/endpoint")
assert endpoint.status_code == 200 and ASSET not in endpoint.text
upstream.asset_status = 206
binary = await client.get(
"/api/v1/map/gateway/cache",
params={"url": "https://assets.ion.cesium.com/1/a.terrain"},
headers={"Range": "bytes=0-8"},
)
assert binary.status_code == 206 and binary.content == b"tile-data"
assert binary.headers["content-range"] == "bytes 0-8/9"
assert binary.headers["cache-control"] == "no-store"
assert upstream.requests[-1].headers["range"] == "bytes=0-8"
saved = await client.put(base, json={"revision": 1, "mode": "auto"})
assert saved.status_code == 200
conflict = await client.put(base, json={"revision": 1, "mode": "direct"})
assert conflict.status_code == 409
await state.client.aclose()
asyncio.run(scenario())
+31
View File
@@ -126,3 +126,34 @@ def test_api_cross_browser_read_and_stale_write(tmp_path):
== 403
)
assert a.get(url, headers={"Sec-Fetch-Site": "cross-site"}).status_code == 403
def test_observation_views_survive_new_clients_without_browser_storage(tmp_path):
camera = dict(longitude=37, latitude=55, height=600, heading=137, pitch=-28, roll=3)
document = {"schema": "missioncore.observation-map/v1", "camera": camera,
"layers": dict(imagery=True, terrain=True, buildings=False,
grid=False, targets=True)}
a = client(tmp_path)
url = "/api/v1/scene-profiles/observation-map?owner=rover-006"
assert a.put(url, json={"document": document, "expected_revision": 0}).status_code == 200
assert client(tmp_path).get(url).json()["document"] == document
assert client(tmp_path).get(url.replace("rover-006", "other")).json()["document"] is None
model = {"schema": "missioncore.rover-view/v1", "model": "dcd006-v022"}
url = "/api/v1/scene-profiles/rover-view?owner=rover-006"
assert a.put(url, json={"document": model, "expected_revision": 0}).status_code == 200
assert client(tmp_path).get(url).json()["document"] == model
model["armed"] = True
assert a.put(url, json={"document": model, "expected_revision": 1}).status_code == 422
@pytest.mark.parametrize("field,value", [("pitch", -100), ("height", True),
("longitude", 200), ("heading", "30")])
def test_observation_map_rejects_bad_pose(tmp_path, field, value):
camera = dict(longitude=37, latitude=55, height=600, heading=137, pitch=-28, roll=3)
camera[field] = value
document = {"schema": "missioncore.observation-map/v1", "camera": camera,
"layers": dict(imagery=True, terrain=True, buildings=False,
grid=False, targets=True)}
with pytest.raises(ValueError):
SceneProfileStore(tmp_path).save("observation-map", "rover", document, 0)
assert not SceneProfileStore(tmp_path).path("observation-map", "rover").exists()