Files
DecomEval/backend/tests/test_hosting.py
T

350 lines
16 KiB
Python

from __future__ import annotations
import os
import shutil
import time
from pathlib import Path
from urllib.parse import quote
import pytest
from fastapi.testclient import TestClient
TEST_DATA = Path(os.environ["DECOM_DATA_DIR"])
from app.auth.platform import base_href, platform_identity # noqa: E402
from app.db import reset_engine, session_scope # noqa: E402
from app.main import create_app # noqa: E402
TOKEN = "proxy-token-for-tests"
INDEX = '<!DOCTYPE html>\n<html>\n <head>\n <base href="/" />\n <title>DecomEval</title>\n </head>\n <body><script type="module" src="./assets/app.js"></script></body>\n</html>\n'
def identity(role: str, user_id: str = "u-1", username: str = "zhang", display: str = "张三", token: str = TOKEN) -> dict:
return {
"X-Metrix-Proxy-Token": token,
"X-Forwarded-Prefix": "/apps/decomeval",
"X-Metrix-User-Id": user_id,
"X-Metrix-Username": username,
"X-Metrix-Display-Name": quote(display, encoding="utf-8"),
"X-Metrix-App-Role": role,
}
def bearer(token: str, headers: dict | None = None) -> dict:
return {**(headers or {}), "Authorization": f"Bearer {token}"}
@pytest.fixture()
def web_dist() -> Path:
dist = TEST_DATA.parent / "web-dist"
if dist.exists():
shutil.rmtree(dist)
(dist / "assets").mkdir(parents=True)
(dist / "index.html").write_text(INDEX, encoding="utf-8")
(dist / "assets" / "app.js").write_text("console.log(1)", encoding="utf-8")
(dist / "favicon.svg").write_text("<svg/>", encoding="utf-8")
yield dist
shutil.rmtree(dist, ignore_errors=True)
@pytest.fixture()
def hosted(monkeypatch, web_dist: Path):
if TEST_DATA.exists():
shutil.rmtree(TEST_DATA)
monkeypatch.setenv("METRIX_APP_PROXY_TOKEN", TOKEN)
monkeypatch.setattr("app.install.hosted_database_url", lambda: f"sqlite+pysqlite:///{(TEST_DATA / 'decom.db').as_posix()}")
reset_engine()
with TestClient(create_app(web_dist=web_dist)) as test_client:
yield test_client
reset_engine()
if TEST_DATA.exists():
shutil.rmtree(TEST_DATA)
def admin_token(client: TestClient) -> str:
response = client.post("/api/auth/platform", headers=identity("admin", user_id="a-1", username="boss", display="管理员甲"))
assert response.status_code == 200
return response.json()["token"]
def test_config_falls_back_to_metrix_env(monkeypatch):
from app.config import data_dir, env_database, env_database_complete, hosted
monkeypatch.delenv("DECOM_DATA_DIR")
monkeypatch.setenv("METRIX_APP_DATA_DIR", "/data")
assert data_dir() == Path("/data")
monkeypatch.setenv("DECOM_DATA_DIR", "/var/lib/decom")
assert data_dir() == Path("/var/lib/decom")
assert env_database_complete() is False
monkeypatch.setenv("METRIX_PG_HOST", "postgres")
monkeypatch.setenv("METRIX_PG_PORT", "5432")
monkeypatch.setenv("METRIX_PG_DATABASE", "app_db")
monkeypatch.setenv("METRIX_PG_USER", "app_user")
monkeypatch.setenv("METRIX_PG_PASSWORD", "pg-pass")
assert env_database() == {"host": "postgres", "port": 5432, "database": "app_db", "username": "app_user", "password": "pg-pass"}
assert env_database_complete() is True
monkeypatch.setenv("DECOM_DB_HOST", "db.local")
monkeypatch.setenv("DECOM_DB_NAME", "decom")
assert env_database()["host"] == "db.local"
assert env_database()["database"] == "decom"
assert env_database()["username"] == "app_user"
for name in ("DECOM_DB_HOST", "DECOM_DB_NAME", "METRIX_PG_HOST", "METRIX_PG_PORT", "METRIX_PG_DATABASE", "METRIX_PG_USER", "METRIX_PG_PASSWORD"):
monkeypatch.delenv(name)
monkeypatch.setenv("METRIX_PG_URL", "postgresql://url_user:url%40pass@pg.example:6543/url_db")
assert env_database() == {"host": "pg.example", "port": 6543, "database": "url_db", "username": "url_user", "password": "url@pass"}
assert hosted() is False
monkeypatch.setenv("METRIX_APP_PROXY_TOKEN", " ")
assert hosted() is False
monkeypatch.setenv("METRIX_APP_PROXY_TOKEN", TOKEN)
assert hosted() is True
def test_identity_needs_matching_proxy_token(monkeypatch):
headers = {key.lower(): value for key, value in identity("admin").items()}
assert platform_identity(headers) is None
monkeypatch.setenv("METRIX_APP_PROXY_TOKEN", TOKEN)
found = platform_identity(headers)
assert found is not None
assert (found.user_id, found.username, found.display_name, found.role) == ("u-1", "zhang", "张三", "admin")
assert found.name == "张三"
assert platform_identity({**headers, "x-metrix-proxy-token": "wrong"}) is None
assert platform_identity({key: value for key, value in headers.items() if key != "x-metrix-proxy-token"}) is None
assert platform_identity({**headers, "x-metrix-app-role": "owner"}) is None
assert platform_identity({**headers, "x-metrix-user-id": ""}) is None
no_display = platform_identity({**headers, "x-metrix-display-name": ""})
assert no_display is not None and no_display.name == "zhang"
def test_base_href_only_accepts_app_prefix():
assert base_href({"x-forwarded-prefix": "/apps/decomeval"}) == "/apps/decomeval/"
assert base_href({"x-forwarded-prefix": "/apps/decom-eval-2"}) == "/apps/decom-eval-2/"
assert base_href({}) == "/"
for bad in ("/apps/DecomEval", "/apps/decomeval/", "/evil", "//evil.example", "/apps/a\"><script>", "/apps/"):
assert base_href({"x-forwarded-prefix": bad}) == "/"
def test_auto_install_on_start(hosted: TestClient):
from app.install import auto_install
from app.models import AppSetting, User
status = hosted.get("/api/install/status").json()
assert status["installed"] is True
assert status["hosted"] is True
assert hosted.get("/api/auth/mode").json() == {"mode": "local", "hosted": True}
with session_scope() as session:
setting = session.get(AppSetting, 1)
secret = setting.jwt_secret
assert len(secret) == 64
assert session.query(User).count() == 0
assert auto_install() is True
with session_scope() as session:
assert session.get(AppSetting, 1).jwt_secret == secret
assert session.query(AppSetting).count() == 1
def test_auto_install_skipped_without_database(monkeypatch):
from app.install import auto_install
monkeypatch.setenv("METRIX_APP_PROXY_TOKEN", TOKEN)
assert auto_install() is False
monkeypatch.delenv("METRIX_APP_PROXY_TOKEN")
monkeypatch.setattr("app.install.hosted_database_url", lambda: "sqlite+pysqlite:///never.db")
assert auto_install() is False
def test_platform_login_three_cases(hosted: TestClient):
admin = hosted.post("/api/auth/platform", headers=identity("admin", user_id="a-1", username="boss", display="管理员甲"))
assert admin.status_code == 200
assert admin.json()["user"] == {"kind": "platform", "id": "a-1", "role": "admin", "name": "管理员甲"}
user = hosted.post("/api/auth/platform", headers=identity("user"))
assert user.status_code == 200
assert user.json()["user"] == {"kind": "platform", "id": "u-1", "role": "user", "name": "张三"}
saved = hosted.put(
"/api/admin/settings",
json={"loginMode": "nqi", "credentialRefreshSeconds": 300, "workerConcurrency": 4},
headers=bearer(admin.json()["token"], identity("admin", user_id="a-1", username="boss", display="管理员甲")),
)
assert saved.status_code == 200
refused = hosted.post("/api/auth/platform", headers=identity("user"))
assert refused.status_code == 403
assert refused.json()["detail"] == "当前使用大数据平台账号登录"
still_admin = hosted.post("/api/auth/platform", headers=identity("admin", user_id="a-1"))
assert still_admin.status_code == 200
nobody = hosted.post("/api/auth/platform", headers={"X-Metrix-Proxy-Token": TOKEN})
assert nobody.status_code == 401
forged = hosted.post("/api/auth/platform", headers=identity("admin", token="forged"))
assert forged.status_code == 401
bare = hosted.post("/api/auth/platform")
assert bare.status_code == 401
def test_platform_login_refused_when_not_hosted(web_dist: Path):
if TEST_DATA.exists():
shutil.rmtree(TEST_DATA)
reset_engine()
with TestClient(create_app(web_dist=web_dist)) as client:
assert client.post("/api/install", json={"sqlite": True, "adminUsername": "admin", "adminPassword": "admin-pass"}).status_code == 200
assert client.get("/api/install/status").json()["hosted"] is False
refused = client.post("/api/auth/platform", headers=identity("admin"))
assert refused.status_code == 401
local = client.post("/api/auth/local", json={"username": "admin", "password": "admin-pass"})
assert local.status_code == 200
reset_engine()
shutil.rmtree(TEST_DATA, ignore_errors=True)
def test_local_password_login_closed_when_hosted(hosted: TestClient):
from app.models import User
from app.security import hash_password
with session_scope() as session:
session.add(User(username="admin", password_hash=hash_password("admin-pass"), role="admin"))
session.add(User(username="worker", password_hash=hash_password("worker-pass"), role="user"))
for username, password in (("admin", "admin-pass"), ("worker", "worker-pass")):
local = hosted.post("/api/auth/local", json={"username": username, "password": password})
assert local.status_code == 400
assert local.json()["detail"] == "请从平台登录"
combined = hosted.post("/api/auth/login", json={"username": username, "password": password})
assert combined.status_code == 400
assert combined.json()["detail"] == "请从平台登录"
admin_headers = identity("admin", user_id="a-1", username="boss", display="管理员甲")
headers = bearer(admin_token(hosted), admin_headers)
assert hosted.get("/api/admin/users", headers=headers).status_code == 404
assert hosted.post("/api/admin/users", json={"username": "x", "password": "y"}, headers=headers).status_code == 404
assert hosted.put("/api/admin/users/1/password", json={"password": "z"}, headers=headers).status_code == 404
assert hosted.delete("/api/admin/users/1", headers=headers).status_code == 404
def test_nqi_admin_name_goes_to_platform_when_hosted(hosted: TestClient, monkeypatch):
from app.models import User
from app.nqi.client import NqiError
from app.security import hash_password
with session_scope() as session:
session.add(User(username="admin", password_hash=hash_password("admin-pass"), role="admin"))
admin_headers = identity("admin", user_id="a-1", username="boss", display="管理员甲")
saved = hosted.put(
"/api/admin/settings",
json={"loginMode": "nqi"},
headers=bearer(admin_token(hosted), admin_headers),
)
assert saved.status_code == 200
calls: list[str] = []
async def fail_open(self):
calls.append("open")
raise NqiError("未连接平台")
monkeypatch.setattr("app.api.http.NqiClient.open_login", fail_open)
response = hosted.post("/api/auth/login", json={"username": "admin", "password": "admin-pass"})
assert response.status_code == 400
assert response.json()["detail"] == "未连接平台"
assert calls == ["open"]
def test_platform_token_follows_platform_login(hosted: TestClient):
admin_headers = identity("admin", user_id="a-1", username="boss", display="管理员甲")
token = admin_token(hosted)
me = hosted.get("/api/me", headers=bearer(token, admin_headers))
assert me.status_code == 200
assert me.json()["user"]["kind"] == "platform"
assert hosted.get("/api/me", headers=bearer(token)).status_code == 401
assert hosted.get("/api/me", headers=bearer(token, identity("admin", user_id="someone-else"))).status_code == 401
assert hosted.get("/api/me", headers=bearer(token, identity("user", user_id="a-1"))).status_code == 401
assert hosted.get("/api/me", headers=bearer(token, {**admin_headers, "X-Metrix-Proxy-Token": "forged"})).status_code == 401
def test_switch_to_local_needs_no_local_admin_when_hosted(hosted: TestClient):
admin_headers = identity("admin", user_id="a-1", username="boss", display="管理员甲")
headers = bearer(admin_token(hosted), admin_headers)
assert hosted.put("/api/admin/settings", json={"loginMode": "nqi"}, headers=headers).status_code == 200
back = hosted.put("/api/admin/settings", json={"loginMode": "local"}, headers=headers)
assert back.status_code == 200
assert back.json()["loginMode"] == "local"
def test_platform_user_runs_export(hosted: TestClient):
from app.models import ExportTask
user_headers = identity("user")
login = hosted.post("/api/auth/platform", headers=user_headers)
headers = bearer(login.json()["token"], user_headers)
created = hosted.post("/api/tasks", json={"format": "csv", "cellKey": ""}, headers=headers)
assert created.status_code == 200
task_id = created.json()["task"]["id"]
for _ in range(30):
listing = hosted.get("/api/tasks", headers=headers).json()["tasks"]
if listing[0]["status"] == "done":
break
time.sleep(0.1)
assert listing[0]["status"] == "done"
with session_scope() as session:
task = session.get(ExportTask, task_id)
assert (task.owner_kind, task.owner_id) == ("platform", "u-1")
downloaded = hosted.get(f"/api/tasks/{task_id}/file", headers=headers)
assert downloaded.status_code == 200
other = identity("user", user_id="u-2")
other_login = hosted.post("/api/auth/platform", headers=other)
assert hosted.get(f"/api/tasks/{task_id}/file", headers=bearer(other_login.json()["token"], other)).status_code == 404
admin_headers = identity("admin", user_id="a-1")
assert hosted.get("/api/tasks", headers=bearer(admin_token(hosted), admin_headers)).status_code == 403
def test_index_gets_base_for_prefix(hosted: TestClient):
proxied = hosted.get("/", headers={"X-Forwarded-Prefix": "/apps/decomeval"})
assert proxied.status_code == 200
assert '<base href="/apps/decomeval/" />' in proxied.text
assert proxied.text.count("<base") == 1
assert proxied.headers["cache-control"] == "no-store"
deep = hosted.get("/admin/users", headers={"X-Forwarded-Prefix": "/apps/decomeval"})
assert '<base href="/apps/decomeval/" />' in deep.text
direct = hosted.get("/tasks")
assert '<base href="/" />' in direct.text
evil = hosted.get("/", headers={"X-Forwarded-Prefix": "//evil.example"})
assert '<base href="/" />' in evil.text
named = hosted.get("/index.html", headers={"X-Forwarded-Prefix": "/apps/decomeval"})
assert '<base href="/apps/decomeval/" />' in named.text
asset = hosted.get("/assets/app.js")
assert asset.status_code == 200
assert asset.text == "console.log(1)"
assert hosted.get("/favicon.svg").text == "<svg/>"
assert hosted.get("/api/unknown").status_code == 404
def test_index_without_base_tag_gets_one():
from app.main import render_index
html = render_index("<html><head><title>x</title></head></html>", "/apps/decomeval/")
assert html.startswith('<html><head>\n <base href="/apps/decomeval/" />')
def test_queue_defer_uses_independent_sync_connection(monkeypatch):
import contextlib
from app.tasks import queue as task_queue
calls: list[tuple[str, object]] = []
class Deferrer:
def defer(self, **kwargs):
calls.append(("defer", kwargs))
monkeypatch.setattr(task_queue.defer_queue, "open", lambda: contextlib.nullcontext())
def configure(name: str, **kwargs):
calls.append(("configure", (name, kwargs)))
return Deferrer()
monkeypatch.setattr(task_queue.defer_queue, "configure_task", configure)
task_queue.defer("decom_export", task_id=7)
assert calls == [
("configure", ("decom_export", {"queue": "decom"})),
("defer", {"task_id": 7}),
]