Files
planet/backend/tests/test_client_updates.py
T
linkong e53c3af355
ci / backend (push) Waiting to run
ci / frontend (push) Waiting to run
release / images (push) Waiting to run
release / client_release (push) Waiting to run
release: bump version to 0.79.0
2026-11-24 15:40:10 +08:00

175 lines
6.6 KiB
Python

"""Tests for client L1 hot-update manifest and bundle hosting APIs."""
import hashlib
import io
import tarfile
import pytest
from httpx import ASGITransport, AsyncClient
from app.core.config import settings
from app.core.security import create_access_token
from app.db.session import get_db
from app.main import app
from app.models.user import User
class _DummyDbSession:
pass
class _ScalarResult:
def __init__(self, user: User):
self._user = user
def scalar_one_or_none(self):
return self._user
class _UserLookupSession:
def __init__(self, user: User):
self._user = user
async def execute(self, _stmt):
return _ScalarResult(self._user)
def _make_tar_gz(entries: dict[str, bytes], *, prefix: str = "") -> bytes:
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w:gz") as tar:
for name, data in entries.items():
info = tarfile.TarInfo(name=f"{prefix}{name}")
info.size = len(data)
tar.addfile(info, io.BytesIO(data))
return buf.getvalue()
@pytest.fixture(autouse=True)
def _isolate_client_updates_dir(tmp_path, monkeypatch):
monkeypatch.setattr(settings, "CLIENT_UPDATES_DIR", str(tmp_path))
monkeypatch.setattr(settings, "CLIENT_UPDATE_PUBLISH_TOKEN", "ci-publish-secret-token")
monkeypatch.setattr("app.core.security.redis_client", type("NoRedis", (), {"sismember": staticmethod(lambda *_a, **_k: False)})())
yield
app.dependency_overrides.clear()
@pytest.mark.asyncio
async def test_default_manifest_before_any_hotfix_published():
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as client:
res = await client.get("/api/v1/client/update-manifest?shell=0.78.0&bundle=0.78.0")
assert res.status_code == 200
assert res.headers["cache-control"] == "no-store"
data = res.json()
assert data["shell"]["version"] == settings.VERSION
assert data["bundle"] is None
@pytest.mark.asyncio
async def test_publish_bundle_auth_validation_and_download():
valid_tar = _make_tar_gz(
{
"index.html": b"<!doctype html><html><body>updated</body></html>",
"js/main.js": b"console.log('hotfix');",
}
)
expected_sha = hashlib.sha256(valid_tar).hexdigest()
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as client:
# Unauthenticated rejected
unauth = await client.post(
"/api/v1/client/updates/bundle",
data={"version": "0.78.1"},
files={"file": ("bundle.tar.gz", valid_tar, "application/gzip")},
)
assert unauth.status_code == 401
# Wrong CI publish token rejected
bad_token = await client.post(
"/api/v1/client/updates/bundle",
headers={"X-Client-Update-Token": "wrong-token"},
data={"version": "0.78.1"},
files={"file": ("bundle.tar.gz", valid_tar, "application/gzip")},
)
assert bad_token.status_code == 401
# Non-admin JWT rejected
async def _non_admin_db():
yield _UserLookupSession(User(id=2, username="viewer", email="v@example.com", role="viewer", is_active=True))
app.dependency_overrides[get_db] = _non_admin_db
viewer_jwt = create_access_token({"sub": "2", "username": "viewer"})
forbidden = await client.post(
"/api/v1/client/updates/bundle",
headers={"Authorization": f"Bearer {viewer_jwt}"},
data={"version": "0.78.1"},
files={"file": ("bundle.tar.gz", valid_tar, "application/gzip")},
)
assert forbidden.status_code == 403
app.dependency_overrides.clear()
# Malicious path traversal archive rejected
evil_tar = _make_tar_gz({"../evil.js": b"alert(1)", "index.html": b"ok"})
evil_res = await client.post(
"/api/v1/client/updates/bundle",
headers={"X-Client-Update-Token": "ci-publish-secret-token"},
data={"version": "0.78.1"},
files={"file": ("evil.tar.gz", evil_tar, "application/gzip")},
)
assert evil_res.status_code == 400
# Valid publish via CI token succeeds and updates manifest
pub = await client.post(
"/api/v1/client/updates/bundle",
headers={"X-Client-Update-Token": "ci-publish-secret-token"},
data={
"version": "0.78.1",
"min_shell_version": "0.78.0",
"release_notes": "Fix WebGL recovery",
"shell_version": "0.78.1",
"shell_min_required": "0.78.0",
"shell_download_url": "https://gitea.rclaw.top/linkong/planet/releases/tag/v0.78.1",
},
files={"file": ("planet-earth-bundle-0.78.1.tar.gz", valid_tar, "application/gzip")},
)
assert pub.status_code == 200
pub_data = pub.json()
assert pub_data["status"] == "published"
assert pub_data["manifest"]["bundle"]["version"] == "0.78.1"
assert pub_data["manifest"]["bundle"]["sha256"] == expected_sha
assert pub_data["manifest"]["bundle"]["size"] == len(valid_tar)
assert pub_data["manifest"]["bundle"]["filesCount"] == 2
# Manifest reflects published bundle
manifest_res = await client.get("/api/v1/client/update-manifest")
assert manifest_res.status_code == 200
bundle = manifest_res.json()["bundle"]
assert bundle["version"] == "0.78.1"
assert bundle["url"] == "/api/v1/client/updates/files/planet-earth-bundle-0.78.1.tar.gz"
# Download serves exact archive bytes
dl = await client.get(bundle["url"])
assert dl.status_code == 200
assert dl.content == valid_tar
# Admin JWT publish also works cleanly
missing_index_tar = _make_tar_gz({"js/main.js": b"console.log(1)"})
async def _admin_db():
yield _UserLookupSession(User(id=1, username="admin", email="a@example.com", role="admin", is_active=True))
app.dependency_overrides[get_db] = _admin_db
admin_jwt = create_access_token({"sub": "1", "username": "admin"})
no_idx = await client.post(
"/api/v1/client/updates/bundle",
headers={"Authorization": f"Bearer {admin_jwt}"},
data={"version": "0.78.2"},
files={"file": ("no-index.tar.gz", missing_index_tar, "application/gzip")},
)
assert no_idx.status_code == 400
# Invalid download filename rejected
bad_dl = await client.get("/api/v1/client/updates/files/not-allowed.txt")
assert bad_dl.status_code == 400