313 lines
12 KiB
Python
313 lines
12 KiB
Python
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())
|