Files
NODEDC_MISSION_CORE/tests/test_cesium_egress.py
T

212 lines
7.9 KiB
Python

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())