Files
planet/backend/tests/test_earth_api_access.py
T
linkong b3d2d9e9f1
ci / backend (push) Canceled after 0s
ci / frontend (push) Canceled after 0s
ci / delivery (push) Canceled after 0s
release: bump version to 0.81.0
2026-11-30 19:39:29 +08:00

619 lines
22 KiB
Python

"""Tests for zero-login Earth sessions, permanent/scoped API keys, anti-scraping gate, and controlled OpenAPI."""
from __future__ import annotations
from datetime import UTC, datetime, timedelta
import hashlib
import hmac
import importlib.util
import time
from typing import Any
from fastapi.testclient import TestClient
from httpx import ASGITransport, AsyncClient
import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import Session
from sqlalchemy.pool import StaticPool
from starlette.websockets import WebSocketDisconnect
from app import main as main_module
from app.core import access_gate
from app.core.access_gate import (
EARTH_SESSION_COOKIE,
EARTH_TOKEN_HEADER,
reset_access_gate_caches,
)
from app.core.config import settings
from app.core.security import create_access_token, get_password_hash
from app.db.session import Base, get_db
from app.main import app
from app.models.api_key import ApiKey
from app.models.collected_data import CollectedData
from app.models.system_setting import SystemSetting
from app.models.user import User
from app.services.api_keys import hash_api_key, reset_api_key_runtime_caches
class _AsyncSQLiteSession:
"""Minimal async wrapper around sync SQLAlchemy Session for fast isolated tests."""
def __init__(self, session: Session):
self._session = session
def add(self, instance: Any) -> None:
self._session.add(instance)
def add_all(self, instances: list[Any]) -> None:
self._session.add_all(instances)
async def delete(self, instance: Any) -> None:
self._session.delete(instance)
async def get(self, entity: Any, ident: Any) -> Any:
return self._session.get(entity, ident)
async def execute(self, statement: Any, params: dict[str, Any] | None = None):
if params is not None:
return self._session.execute(statement, params)
return self._session.execute(statement)
async def scalar(self, statement: Any):
return self._session.scalar(statement)
async def scalars(self, statement: Any):
return self._session.scalars(statement)
async def flush(self) -> None:
self._session.flush()
async def commit(self) -> None:
self._session.commit()
async def rollback(self) -> None:
self._session.rollback()
async def refresh(self, instance: Any) -> None:
self._session.refresh(instance)
class _NoRedisClient:
def sismember(self, *_args, **_kwargs):
return False
@staticmethod
def get_client():
raise RuntimeError("Redis disabled in unit test")
@pytest.fixture(autouse=True)
def _reset_gate_and_redis(monkeypatch):
reset_access_gate_caches()
reset_api_key_runtime_caches()
monkeypatch.setattr("app.core.security.redis_client", _NoRedisClient())
monkeypatch.setattr("app.core.security._AsyncRedisClient", _NoRedisClient)
monkeypatch.setattr("app.core.access_gate._AsyncRedisClient", _NoRedisClient)
monkeypatch.setattr("app.services.api_keys._AsyncRedisClient", _NoRedisClient)
yield
app.dependency_overrides.clear()
reset_access_gate_caches()
reset_api_key_runtime_caches()
@pytest.fixture
def access_db():
engine = create_engine(
"sqlite://",
connect_args={"check_same_thread": False},
poolclass=StaticPool,
)
Base.metadata.create_all(
engine,
tables=[
User.__table__,
ApiKey.__table__,
SystemSetting.__table__,
CollectedData.__table__,
],
)
with Session(engine) as session:
admin = User(
id=1,
username="admin-user",
email="admin@example.invalid",
password_hash=get_password_hash("AdminPass!123"),
role="admin",
is_active=True,
email_verified=True,
gatekeeper_groups=[],
)
viewer = User(
id=2,
username="plain-viewer",
email="viewer@example.invalid",
password_hash=get_password_hash("ViewerPass!123"),
role="viewer",
is_active=True,
email_verified=True,
gatekeeper_groups=[],
)
partner = User(
id=3,
username="partner-api",
email="partner@example.invalid",
password_hash=get_password_hash("PartnerPass!123"),
role="viewer",
is_active=True,
email_verified=True,
gatekeeper_groups=["api_access"],
)
docs_dev = User(
id=4,
username="docs-dev",
email="docsdev@example.invalid",
password_hash=get_password_hash("DocsDevPass!123"),
role="viewer",
is_active=True,
email_verified=True,
gatekeeper_groups=["docs_developer"],
)
session.add_all([admin, viewer, partner, docs_dev])
session.commit()
async_session = _AsyncSQLiteSession(session)
async def _override_get_db():
yield async_session
app.dependency_overrides[get_db] = _override_get_db
yield async_session
engine.dispose()
def _bearer_headers(user_id: int, username: str) -> dict[str, str]:
token = create_access_token({"sub": str(user_id), "username": username})
return {"Authorization": f"Bearer {token}"}
@pytest.mark.asyncio
async def test_enforce_mode_blocks_anonymous_endpoints_and_allows_public_exemptions(
monkeypatch, access_db
):
monkeypatch.setattr(settings, "EARTH_API_AUTH_MODE", "enforce")
class _ReadyDbContext:
async def __aenter__(self):
return self
async def __aexit__(self, *args):
return False
async def execute(self, *_args, **_kwargs):
return None
class _ReadyRedis:
class _Client:
async def ping(self):
return True
@staticmethod
def get_client():
return _ReadyRedis._Client()
monkeypatch.setattr(main_module, "async_session_factory", lambda: _ReadyDbContext())
monkeypatch.setattr(main_module, "_AsyncRedisClient", _ReadyRedis)
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as client:
for protected_path in [
"/api/v1/visualization/geo/summary",
"/api/v1/layers/cables?bbox=-10,-10,10,10&zoom=5",
"/api/v1/vessels/snapshot?bbox=-10,-10,10,10&zoom=5",
"/api/v1/news/earth-feed",
"/api/v1/data-products/compute/configuration",
"/api/v1/earth/brand",
"/api/v1/tv/streams",
]:
resp = await client.get(protected_path)
assert resp.status_code == 401, f"{protected_path} returned {resp.status_code}"
assert (await client.get("/health")).status_code == 200
assert (await client.get("/health/live")).status_code == 200
health_resp = await client.get("/health/ready")
assert health_resp.status_code == 200
manifest_resp = await client.get("/api/v1/client/update-manifest")
assert manifest_resp.status_code == 200
docs_resp = await client.get("/api/v1/docs/catalog")
assert docs_resp.status_code == 200
tc = TestClient(app)
with pytest.raises(WebSocketDisconnect) as exc_info:
with tc.websocket_connect("/ws"):
pass
assert exc_info.value.code == 4001
@pytest.mark.asyncio
async def test_web_earth_session_zero_login_origin_cookie_ws_and_turnstile(
monkeypatch, access_db
):
monkeypatch.setattr(settings, "EARTH_API_AUTH_MODE", "enforce")
monkeypatch.setattr(settings, "TURNSTILE_SECRET_KEY", "")
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as client:
no_origin = await client.post("/api/v1/auth/earth-session", json={"client_type": "web"})
assert no_origin.status_code == 403
cross_site = await client.post(
"/api/v1/auth/earth-session",
json={"client_type": "web"},
headers={"Origin": "https://evil.example", "Sec-Fetch-Site": "cross-site"},
)
assert cross_site.status_code == 403
ok = await client.post(
"/api/v1/auth/earth-session",
json={"client_type": "web"},
headers={"Origin": "http://test", "Sec-Fetch-Site": "same-origin"},
)
assert ok.status_code == 200
body = ok.json()
assert body["client_type"] == "web"
assert body["ws_token"]
assert body["turnstile_required"] is False
set_cookie = ok.headers.get("set-cookie", "")
assert EARTH_SESSION_COOKIE in set_cookie
assert "HttpOnly" in set_cookie
assert "samesite=strict" in set_cookie.lower()
authed_brand = await client.get("/api/v1/earth/brand")
assert authed_brand.status_code == 200
tc = TestClient(app)
with tc.websocket_connect(f"/ws?earth_token={body['ws_token']}") as ws:
hello = ws.receive_json()
assert hello["type"] == "connection_established"
monkeypatch.setattr(settings, "TURNSTILE_SECRET_KEY", "ts-secret")
class _MockTurnstileClient:
def __init__(self, success: bool):
self._success = success
async def __aenter__(self):
return self
async def __aexit__(self, *args):
return False
async def post(self, *_args, **_kwargs):
class _Resp:
def __init__(self, success_flag: bool):
self._success_flag = success_flag
def raise_for_status(self):
return None
def json(self):
return {"success": self._success_flag}
return _Resp(self._success)
async with AsyncClient(transport=transport, base_url="http://test") as client:
missing_ts = await client.post(
"/api/v1/auth/earth-session",
json={"client_type": "web"},
headers={"Origin": "http://test"},
)
assert missing_ts.status_code == 403
monkeypatch.setattr(
access_gate.httpx,
"AsyncClient",
lambda **_kw: _MockTurnstileClient(False),
)
failed_ts = await client.post(
"/api/v1/auth/earth-session",
json={"client_type": "web", "turnstile_token": "bad-token"},
headers={"Origin": "http://test"},
)
assert failed_ts.status_code == 403
monkeypatch.setattr(
access_gate.httpx,
"AsyncClient",
lambda **_kw: _MockTurnstileClient(True),
)
ok_ts = await client.post(
"/api/v1/auth/earth-session",
json={"client_type": "web", "turnstile_token": "good-token"},
headers={"Origin": "http://test"},
)
assert ok_ts.status_code == 200
assert ok_ts.json()["turnstile_required"] is True
@pytest.mark.asyncio
async def test_desktop_earth_handshake_hmac_replay_and_token_access(monkeypatch, access_db):
monkeypatch.setattr(settings, "EARTH_API_AUTH_MODE", "enforce")
secret = "desktop-shared-hmac-secret"
monkeypatch.setattr(settings, "EARTH_DESKTOP_HANDSHAKE_SECRET", secret)
client_header = "planet-earth-desktop/0.82.0"
ts = str(int(time.time()))
nonce = "nonce-unique-123"
sig = hmac.new(
secret.encode("utf-8"),
f"{ts}.{nonce}.{client_header}".encode("utf-8"),
hashlib.sha256,
).hexdigest()
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as client:
missing_hdr = await client.post("/api/v1/auth/earth-session", json={"client_type": "desktop"})
assert missing_hdr.status_code == 403
bad_sig = await client.post(
"/api/v1/auth/earth-session",
json={"client_type": "desktop"},
headers={
"X-Planet-Client": client_header,
"X-Planet-Client-Timestamp": ts,
"X-Planet-Client-Nonce": nonce,
"X-Planet-Client-Signature": "0" * 64,
},
)
assert bad_sig.status_code == 403
ok = await client.post(
"/api/v1/auth/earth-session",
json={"client_type": "desktop"},
headers={
"X-Planet-Client": client_header,
"X-Planet-Client-Timestamp": ts,
"X-Planet-Client-Nonce": nonce,
"X-Planet-Client-Signature": sig,
},
)
assert ok.status_code == 200
desktop_token = ok.json()["token"]
replay = await client.post(
"/api/v1/auth/earth-session",
json={"client_type": "desktop"},
headers={
"X-Planet-Client": client_header,
"X-Planet-Client-Timestamp": ts,
"X-Planet-Client-Nonce": nonce,
"X-Planet-Client-Signature": sig,
},
)
assert replay.status_code == 403
brand_resp = await client.get(
"/api/v1/earth/brand",
headers={EARTH_TOKEN_HEADER: desktop_token},
)
assert brand_resp.status_code == 200
tc = TestClient(app)
with tc.websocket_connect("/ws", headers={EARTH_TOKEN_HEADER: desktop_token}) as ws:
hello = ws.receive_json()
assert hello["type"] == "connection_established"
@pytest.mark.asyncio
async def test_api_key_lifecycle_permanent_scopes_rate_limit_revocation_and_ws(
monkeypatch, access_db
):
monkeypatch.setattr(settings, "EARTH_API_AUTH_MODE", "enforce")
admin_hdrs = _bearer_headers(1, "admin-user")
viewer_hdrs = _bearer_headers(2, "plain-viewer")
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as client:
denied_create = await client.post(
"/api/v1/system/api-keys",
json={"name": "unauthorized"},
headers=viewer_hdrs,
)
assert denied_create.status_code == 403
created = await client.post(
"/api/v1/system/api-keys",
json={
"name": "ue5-permanent",
"scopes": ["earth:all_read"],
"rate_limit_per_minute": None,
"expires_in_days": None,
},
headers=admin_hdrs,
)
assert created.status_code == 201
created_data = created.json()
raw_perm_key = created_data["api_key"]
perm_item = created_data["item"]
assert raw_perm_key.startswith("plt_live_")
assert perm_item["expires_at"] is None
assert perm_item["rate_limit_per_minute"] is None
listing = await client.get("/api/v1/system/api-keys", headers=admin_hdrs)
assert listing.status_code == 200
listed_item = listing.json()["items"][0]
assert listed_item["key_prefix"] == perm_item["key_prefix"]
assert raw_perm_key not in listing.text
ok_http = await client.get("/api/v1/earth/brand", headers={"X-API-Key": raw_perm_key})
assert ok_http.status_code == 200
ok_tv_query = await client.get(f"/api/v1/tv/streams?api_key={raw_perm_key}")
# /tv/streams intentionally requires header X-API-Key (not query), whereas /tv/proxy allows query
assert ok_tv_query.status_code == 401
ok_tv_header = await client.get("/api/v1/tv/streams", headers={"X-API-Key": raw_perm_key})
assert ok_tv_header.status_code == 200
tc = TestClient(app)
with tc.websocket_connect(f"/ws?api_key={raw_perm_key}") as ws:
hello = ws.receive_json()
assert hello["type"] == "connection_established"
async with AsyncClient(transport=transport, base_url="http://test") as client:
scoped_created = await client.post(
"/api/v1/system/api-keys",
json={
"name": "earth-only-limited",
"scopes": ["earth:read"],
"rate_limit_per_minute": 2,
"expires_in_days": 30,
},
headers=admin_hdrs,
)
assert scoped_created.status_code == 201
scoped_key = scoped_created.json()["api_key"]
assert (
await client.get("/api/v1/earth/brand", headers={"X-API-Key": scoped_key})
).status_code == 200
assert (
await client.get("/api/v1/earth/brand", headers={"X-API-Key": scoped_key})
).status_code == 200
assert (
await client.get("/api/v1/earth/brand", headers={"X-API-Key": scoped_key})
).status_code == 429
out_of_scope = await client.get(
"/api/v1/layers/cables?bbox=-10,-10,10,10&zoom=5",
headers={"X-API-Key": scoped_key},
)
assert out_of_scope.status_code == 403
revoked = await client.post(
f"/api/v1/system/api-keys/{perm_item['id']}/revoke",
headers=admin_hdrs,
)
assert revoked.status_code == 200
assert revoked.json()["item"]["status"] == "revoked"
assert (
await client.get("/api/v1/earth/brand", headers={"X-API-Key": raw_perm_key})
).status_code == 401
deleted = await client.delete(
f"/api/v1/system/api-keys/{scoped_created.json()['item']['id']}",
headers=admin_hdrs,
)
assert deleted.status_code == 200
expired_raw = "plt_live_expired_unit_test_key"
expired_row = ApiKey(
name="expired-key",
key_prefix="plt_live_exp...",
key_hash=hash_api_key(expired_raw),
scopes=["earth:all_read"],
is_active=True,
expires_at=datetime.now(UTC) - timedelta(days=1),
)
access_db.add(expired_row)
await access_db.commit()
async with AsyncClient(transport=transport, base_url="http://test") as client:
exp_resp = await client.get("/api/v1/earth/brand", headers={"X-API-Key": expired_raw})
assert exp_resp.status_code == 401
@pytest.mark.asyncio
async def test_jwt_api_access_group_enforcement(monkeypatch, access_db):
monkeypatch.setattr(settings, "EARTH_API_AUTH_MODE", "enforce")
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as client:
assert (
await client.get(
"/api/v1/earth/brand",
headers=_bearer_headers(1, "admin-user"),
)
).status_code == 200
assert (
await client.get(
"/api/v1/earth/brand",
headers=_bearer_headers(3, "partner-api"),
)
).status_code == 200
assert (
await client.get(
"/api/v1/earth/brand",
headers=_bearer_headers(2, "plain-viewer"),
)
).status_code == 403
@pytest.mark.asyncio
async def test_news_refresh_requires_auth_and_enforces_cooldown(monkeypatch, access_db):
monkeypatch.setattr(settings, "EARTH_API_AUTH_MODE", "enforce")
from app.services import scheduler as scheduler_service
monkeypatch.setattr(
scheduler_service,
"request_earth_news_region_refresh",
lambda region: {"refresh_id": "11111111111111111111111111111111", "region": region, "status": "queued"},
)
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as client:
anon = await client.post("/api/v1/news/refresh", json={"region": "global"})
assert anon.status_code == 401
hdrs = _bearer_headers(3, "partner-api")
for _ in range(3):
ok = await client.post("/api/v1/news/refresh", json={"region": "global"}, headers=hdrs)
assert ok.status_code == 202
limited = await client.post("/api/v1/news/refresh", json={"region": "global"}, headers=hdrs)
assert limited.status_code == 429
@pytest.mark.asyncio
async def test_controlled_openapi_and_production_mode_defaults(monkeypatch, access_db):
monkeypatch.setattr(settings, "APP_ENV", "production")
monkeypatch.setattr(settings, "EARTH_API_AUTH_MODE", "")
assert settings.effective_earth_api_auth_mode == "enforce"
spec = importlib.util.spec_from_file_location("app_main_prod_probe", main_module.__file__)
assert spec is not None and spec.loader is not None
prod_main = importlib.util.module_from_spec(spec)
spec.loader.exec_module(prod_main)
assert prod_main.app.docs_url is None
assert prod_main.app.redoc_url is None
assert prod_main.app.openapi_url is None
monkeypatch.setattr(settings, "APP_ENV", "development")
assert settings.effective_earth_api_auth_mode == "off"
monkeypatch.setattr(settings, "EARTH_API_AUTH_MODE", "enforce")
assert settings.effective_earth_api_auth_mode == "enforce"
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as client:
assert (await client.get("/api/v1/system/openapi.json")).status_code == 401
assert (
await client.get(
"/api/v1/system/openapi.json",
headers=_bearer_headers(2, "plain-viewer"),
)
).status_code == 403
full_resp = await client.get(
"/api/v1/system/openapi.json",
headers=_bearer_headers(4, "docs-dev"),
)
assert full_resp.status_code == 200
assert "/api/v1/users" in full_resp.json()["paths"]
ext_resp = await client.get(
"/api/v1/system/openapi-external.json",
headers=_bearer_headers(1, "admin-user"),
)
assert ext_resp.status_code == 200
ext = ext_resp.json()
assert "ApiKeyAuth" in ext["components"]["securitySchemes"]
assert "/api/v1/visualization/geo/summary" in ext["paths"]
assert "/api/v1/users" not in ext["paths"]
assert "/api/v1/settings/integrations" not in ext["paths"]