feat: 后端支持托管到 Metrix,启动自动安装并接入平台登录
This commit is contained in:
+22
-3
@@ -2,8 +2,9 @@ from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from fastapi import Header, HTTPException
|
||||
from fastapi import Header, HTTPException, Request
|
||||
|
||||
from app.auth.platform import platform_identity
|
||||
from app.security import read_token
|
||||
|
||||
|
||||
@@ -15,13 +16,31 @@ class Actor:
|
||||
name: str
|
||||
|
||||
|
||||
def current_actor(authorization: str | None = Header(default=None)) -> Actor:
|
||||
def current_actor(request: Request, authorization: str | None = Header(default=None)) -> Actor:
|
||||
if not authorization or not authorization.lower().startswith("bearer "):
|
||||
raise HTTPException(status_code=401, detail="请先登录")
|
||||
body = read_token(authorization.split(" ", 1)[1].strip())
|
||||
if body is None:
|
||||
raise HTTPException(status_code=401, detail="登录已失效")
|
||||
return Actor(str(body.get("kind") or ""), str(body.get("id") or ""), str(body.get("role") or "user"), str(body.get("name") or ""))
|
||||
actor = Actor(str(body.get("kind") or ""), str(body.get("id") or ""), str(body.get("role") or "user"), str(body.get("name") or ""))
|
||||
if actor.kind == "platform":
|
||||
_check_platform(request, actor)
|
||||
return actor
|
||||
|
||||
|
||||
def _check_platform(request: Request, actor: Actor) -> None:
|
||||
"""平台账号的令牌跟随平台登录:换人、退出或角色变化后即失效。"""
|
||||
identity = platform_identity(request.headers)
|
||||
if identity is None or identity.user_id != actor.id or identity.role != actor.role:
|
||||
raise HTTPException(status_code=401, detail="平台登录已变化,请重新进入")
|
||||
if actor.role == "user":
|
||||
from app.db import session_scope
|
||||
from app.models import AppSetting
|
||||
|
||||
with session_scope() as session:
|
||||
setting = session.get(AppSetting, 1)
|
||||
if setting is not None and setting.login_mode != "local":
|
||||
raise HTTPException(status_code=401, detail="当前使用大数据平台账号登录")
|
||||
|
||||
|
||||
def require_admin(actor: Actor) -> None:
|
||||
|
||||
+35
-10
@@ -1,16 +1,16 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import os
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from fastapi.responses import Response
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.api.deps import Actor, current_actor, require_admin
|
||||
from app.config import installed, result_dir
|
||||
from app.auth.platform import platform_identity
|
||||
from app.config import env_database, hosted, installed, result_dir
|
||||
from app.install import InstallError, perform_install
|
||||
from app.db import get_session, session_scope
|
||||
from app.models import AppSetting, CollectionSource, ExportTask, NqiAccount, User, utcnow
|
||||
@@ -24,13 +24,15 @@ router = APIRouter(prefix="/api")
|
||||
|
||||
@router.get("/install/status")
|
||||
def install_status() -> dict:
|
||||
db = env_database()
|
||||
return {
|
||||
"installed": installed(),
|
||||
"hosted": hosted(),
|
||||
"defaults": {
|
||||
"host": os.environ.get("DECOM_DB_HOST", "127.0.0.1"),
|
||||
"port": int(os.environ.get("DECOM_DB_PORT", "5432")),
|
||||
"database": os.environ.get("DECOM_DB_NAME", "decom"),
|
||||
"username": os.environ.get("DECOM_DB_USER", "postgres"),
|
||||
"host": db["host"] or "127.0.0.1",
|
||||
"port": db["port"] or 5432,
|
||||
"database": db["database"] or "decom",
|
||||
"username": db["username"] or "postgres",
|
||||
},
|
||||
}
|
||||
|
||||
@@ -91,10 +93,22 @@ def _public_source(source: CollectionSource) -> dict:
|
||||
|
||||
@router.get("/auth/mode")
|
||||
def auth_mode(session: Session = Depends(get_session)) -> dict:
|
||||
return {"mode": _setting(session).login_mode}
|
||||
return {"mode": _setting(session).login_mode, "hosted": hosted()}
|
||||
|
||||
|
||||
@router.post("/auth/platform")
|
||||
def platform_login(request: Request, session: Session = Depends(get_session)) -> dict:
|
||||
identity = platform_identity(request.headers)
|
||||
if identity is None:
|
||||
raise _bad("没有平台登录", 401)
|
||||
if identity.role == "user" and _setting(session).login_mode != "local":
|
||||
raise _bad("当前使用大数据平台账号登录", 403)
|
||||
return _token_for("platform", identity.user_id, identity.role, identity.name)
|
||||
|
||||
|
||||
def _matched_local_user(session: Session, username: str) -> User | None:
|
||||
if hosted():
|
||||
return None
|
||||
user = session.scalar(select(User).where(User.username == username))
|
||||
if user is None:
|
||||
return None
|
||||
@@ -117,7 +131,7 @@ async def login(body: dict) -> dict:
|
||||
return _token_for("local", str(user.id), user.role, user.username)
|
||||
mode = _setting(session).login_mode
|
||||
if mode != "nqi":
|
||||
raise _bad("账号或密码不正确")
|
||||
raise _bad("请从平台登录" if hosted() else "账号或密码不正确")
|
||||
if str(body.get("sessionId") or ""):
|
||||
return await nqi_finish(body)
|
||||
started = await nqi_start({"username": username, "purpose": "login"})
|
||||
@@ -128,6 +142,8 @@ async def login(body: dict) -> dict:
|
||||
|
||||
@router.post("/auth/local")
|
||||
def local_login(body: dict, session: Session = Depends(get_session)) -> dict:
|
||||
if hosted():
|
||||
raise _bad("请从平台登录")
|
||||
if _setting(session).login_mode != "local":
|
||||
raise _bad("当前使用大数据平台账号登录")
|
||||
username = str(body.get("username") or "").strip()
|
||||
@@ -335,7 +351,7 @@ def update_settings(body: dict, actor: Actor = Depends(current_actor), session:
|
||||
mode = str(body.get("loginMode") or setting.login_mode)
|
||||
if mode not in {"local", "nqi"}:
|
||||
raise _bad("登录方式不正确")
|
||||
if mode == "local" and session.scalar(select(User).where(User.role == "admin")) is None:
|
||||
if mode == "local" and not hosted() and session.scalar(select(User).where(User.role == "admin")) is None:
|
||||
raise _bad("还没有自有账号管理员,不能切换")
|
||||
if "credentialRefreshSeconds" in body:
|
||||
try:
|
||||
@@ -355,9 +371,15 @@ def update_settings(body: dict, actor: Actor = Depends(current_actor), session:
|
||||
}
|
||||
|
||||
|
||||
def _require_local_users() -> None:
|
||||
if hosted():
|
||||
raise _bad("自有账号由平台管理", 404)
|
||||
|
||||
|
||||
@router.get("/admin/users")
|
||||
def list_users(actor: Actor = Depends(current_actor), session: Session = Depends(get_session)) -> dict:
|
||||
require_admin(actor)
|
||||
_require_local_users()
|
||||
rows = session.scalars(select(User).order_by(User.id)).all()
|
||||
return {"users": [{"id": row.id, "username": row.username, "role": row.role} for row in rows]}
|
||||
|
||||
@@ -365,6 +387,7 @@ def list_users(actor: Actor = Depends(current_actor), session: Session = Depends
|
||||
@router.post("/admin/users")
|
||||
def create_user(body: dict, actor: Actor = Depends(current_actor), session: Session = Depends(get_session)) -> dict:
|
||||
require_admin(actor)
|
||||
_require_local_users()
|
||||
username = str(body.get("username") or "").strip()
|
||||
password = str(body.get("password") or "")
|
||||
role = "admin" if body.get("role") == "admin" else "user"
|
||||
@@ -379,6 +402,7 @@ def create_user(body: dict, actor: Actor = Depends(current_actor), session: Sess
|
||||
@router.delete("/admin/users/{user_id}")
|
||||
def delete_user(user_id: int, actor: Actor = Depends(current_actor), session: Session = Depends(get_session)) -> dict:
|
||||
require_admin(actor)
|
||||
_require_local_users()
|
||||
user = session.get(User, user_id)
|
||||
if user is None:
|
||||
raise _bad("账号不存在", 404)
|
||||
@@ -391,6 +415,7 @@ def delete_user(user_id: int, actor: Actor = Depends(current_actor), session: Se
|
||||
@router.put("/admin/users/{user_id}/password")
|
||||
def update_user_password(user_id: int, body: dict, actor: Actor = Depends(current_actor), session: Session = Depends(get_session)) -> dict:
|
||||
require_admin(actor)
|
||||
_require_local_users()
|
||||
user = session.get(User, user_id)
|
||||
if user is None:
|
||||
raise _bad("账号不存在", 404)
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
"""托管到 Metrix 时,由平台代理带来的登录身份。
|
||||
|
||||
只有请求带的代理令牌与 METRIX_APP_PROXY_TOKEN 一致时,才相信 X-Metrix-* 身份头。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hmac
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from collections.abc import Mapping
|
||||
from urllib.parse import unquote
|
||||
|
||||
from app.config import proxy_token
|
||||
|
||||
PREFIX_PATTERN = re.compile(r"^/apps/[a-z0-9-]+$")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PlatformIdentity:
|
||||
user_id: str
|
||||
username: str
|
||||
display_name: str
|
||||
role: str
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
return self.display_name or self.username or self.user_id
|
||||
|
||||
|
||||
def from_proxy(headers: Mapping[str, str]) -> bool:
|
||||
expected = proxy_token()
|
||||
if not expected:
|
||||
return False
|
||||
given = headers.get("x-metrix-proxy-token") or ""
|
||||
return hmac.compare_digest(given.encode("utf-8"), expected.encode("utf-8"))
|
||||
|
||||
|
||||
def platform_identity(headers: Mapping[str, str]) -> PlatformIdentity | None:
|
||||
if not from_proxy(headers):
|
||||
return None
|
||||
user_id = (headers.get("x-metrix-user-id") or "").strip()
|
||||
role = (headers.get("x-metrix-app-role") or "").strip().lower()
|
||||
if not user_id or role not in {"admin", "user"}:
|
||||
return None
|
||||
username = (headers.get("x-metrix-username") or "").strip()
|
||||
display_name = unquote(headers.get("x-metrix-display-name") or "", encoding="utf-8", errors="replace").strip()
|
||||
return PlatformIdentity(user_id=user_id, username=username, display_name=display_name, role=role)
|
||||
|
||||
|
||||
def base_href(headers: Mapping[str, str]) -> str:
|
||||
prefix = (headers.get("x-forwarded-prefix") or "").strip()
|
||||
if PREFIX_PATTERN.match(prefix):
|
||||
return prefix + "/"
|
||||
return "/"
|
||||
@@ -1,26 +1,76 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from collections.abc import Callable, Iterator
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
|
||||
from alembic import command
|
||||
from alembic.config import Config
|
||||
from sqlalchemy import create_engine, pool, text
|
||||
|
||||
from app.config import BACKEND_ROOT, data_dir, installed
|
||||
from app.config import BACKEND_ROOT, data_dir, database_url, installed
|
||||
|
||||
logger = logging.getLogger("decom")
|
||||
INSTALL_LOCK = 7_316_501_842
|
||||
|
||||
|
||||
def migrate() -> None:
|
||||
@contextmanager
|
||||
def _install_lock() -> Iterator[None]:
|
||||
"""接口和排队进程可能同时启动,建表和初始化依次进行。"""
|
||||
url = database_url()
|
||||
if not url.startswith("postgresql"):
|
||||
yield
|
||||
return
|
||||
engine = create_engine(url, poolclass=pool.NullPool, isolation_level="AUTOCOMMIT")
|
||||
try:
|
||||
with engine.connect() as connection:
|
||||
connection.execute(text("SELECT pg_advisory_lock(:key)"), {"key": INSTALL_LOCK})
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
connection.execute(text("SELECT pg_advisory_unlock(:key)"), {"key": INSTALL_LOCK})
|
||||
finally:
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def _ensure_queue_schema() -> None:
|
||||
from app.config import postgres_conninfo
|
||||
|
||||
conninfo = postgres_conninfo()
|
||||
if not conninfo:
|
||||
return
|
||||
import psycopg
|
||||
from procrastinate.schema import SchemaManager
|
||||
|
||||
with psycopg.connect(conninfo) as connection:
|
||||
exists = connection.execute("SELECT to_regclass('procrastinate_jobs')").fetchone()
|
||||
if exists and exists[0]:
|
||||
return
|
||||
connection.execute(SchemaManager.get_schema())
|
||||
logger.info("已建立排队表")
|
||||
|
||||
|
||||
def migrate(then: Callable[[], None] | None = None) -> None:
|
||||
data_dir().mkdir(parents=True, exist_ok=True)
|
||||
config = Config(str(Path(BACKEND_ROOT) / "alembic.ini"))
|
||||
config.set_main_option("script_location", str(Path(BACKEND_ROOT) / "alembic"))
|
||||
config.attributes["configure_logger"] = False
|
||||
command.upgrade(config, "head")
|
||||
with _install_lock():
|
||||
command.upgrade(config, "head")
|
||||
_ensure_queue_schema()
|
||||
if then is not None:
|
||||
then()
|
||||
|
||||
|
||||
def init_db() -> None:
|
||||
def init_db() -> bool:
|
||||
"""准备数据库。返回数据库是否已可用。"""
|
||||
from app.install import auto_install
|
||||
|
||||
if auto_install():
|
||||
return True
|
||||
if not installed():
|
||||
logger.info("尚未安装,等待安装页")
|
||||
return
|
||||
return False
|
||||
migrate()
|
||||
return True
|
||||
|
||||
+67
-2
@@ -1,4 +1,7 @@
|
||||
"""运行配置。连接信息在安装后写入 data/install.json,其余配置保存在数据库。"""
|
||||
"""运行配置。连接信息在安装后写入 data/install.json,其余配置保存在数据库。
|
||||
|
||||
托管到 Metrix 时,平台注入的 METRIX_* 变量作为 DECOM_* 缺省时的回退。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -9,8 +12,24 @@ from pathlib import Path
|
||||
BACKEND_ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def _env(*names: str) -> str:
|
||||
for name in names:
|
||||
value = os.environ.get(name, "").strip()
|
||||
if value:
|
||||
return value
|
||||
return ""
|
||||
|
||||
|
||||
def hosted() -> bool:
|
||||
return bool(proxy_token())
|
||||
|
||||
|
||||
def proxy_token() -> str:
|
||||
return os.environ.get("METRIX_APP_PROXY_TOKEN", "").strip()
|
||||
|
||||
|
||||
def data_dir() -> Path:
|
||||
override = os.environ.get("DECOM_DATA_DIR", "").strip()
|
||||
override = _env("DECOM_DATA_DIR", "METRIX_APP_DATA_DIR")
|
||||
if override:
|
||||
return Path(override)
|
||||
return BACKEND_ROOT / "data"
|
||||
@@ -44,3 +63,49 @@ def postgres_conninfo() -> str | None:
|
||||
return None
|
||||
|
||||
|
||||
def env_database() -> dict:
|
||||
"""环境变量里的数据库连接。缺的项为空,端口缺省 5432。"""
|
||||
url_parts: dict = {}
|
||||
raw_url = _env("METRIX_PG_URL")
|
||||
if raw_url:
|
||||
try:
|
||||
from sqlalchemy.engine import make_url
|
||||
|
||||
parsed = make_url(raw_url)
|
||||
url_parts = {
|
||||
"host": parsed.host or "",
|
||||
"port": parsed.port or 0,
|
||||
"database": parsed.database or "",
|
||||
"username": parsed.username or "",
|
||||
"password": parsed.password or "",
|
||||
}
|
||||
except Exception:
|
||||
url_parts = {}
|
||||
port_text = _env("DECOM_DB_PORT", "METRIX_PG_PORT")
|
||||
try:
|
||||
port = int(port_text) if port_text else int(url_parts.get("port") or 5432)
|
||||
except ValueError:
|
||||
port = 5432
|
||||
return {
|
||||
"host": _env("DECOM_DB_HOST", "METRIX_PG_HOST") or url_parts.get("host", ""),
|
||||
"port": port,
|
||||
"database": _env("DECOM_DB_NAME", "METRIX_PG_DATABASE") or url_parts.get("database", ""),
|
||||
"username": _env("DECOM_DB_USER", "METRIX_PG_USER") or url_parts.get("username", ""),
|
||||
"password": _env("DECOM_DB_PASSWORD", "METRIX_PG_PASSWORD") or url_parts.get("password", ""),
|
||||
}
|
||||
|
||||
|
||||
def env_database_complete() -> bool:
|
||||
db = env_database()
|
||||
return all(db[key] for key in ("host", "database", "username", "password"))
|
||||
|
||||
|
||||
def database_wait_seconds() -> int:
|
||||
try:
|
||||
return max(1, int(_env("DECOM_DB_WAIT_SECONDS") or "120"))
|
||||
except ValueError:
|
||||
return 120
|
||||
|
||||
|
||||
def inline_worker_allowed() -> bool:
|
||||
return _env("DECOM_INLINE_WORKER") != "0"
|
||||
|
||||
+107
-6
@@ -1,21 +1,27 @@
|
||||
"""首次安装:连接数据库、建表、创建管理员,并把配置写入数据库。"""
|
||||
"""首次安装:连接数据库、建表、创建管理员,并把配置写入数据库。
|
||||
|
||||
托管到 Metrix 且平台提供了数据库时,启动即自动安装,不经过安装页。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import time
|
||||
|
||||
from sqlalchemy import create_engine, select, text
|
||||
from sqlalchemy.engine import URL
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app.config import data_dir, install_file, installed
|
||||
from app.config import data_dir, database_wait_seconds, env_database, env_database_complete, hosted, install_file, installed
|
||||
from app.db import reset_engine, session_scope
|
||||
from app.models import AppSetting, User
|
||||
from app.security import hash_password
|
||||
|
||||
logger = logging.getLogger("decom")
|
||||
_IDENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,62}$")
|
||||
|
||||
|
||||
@@ -40,10 +46,24 @@ def build_postgres_url(host: str, port: int, database: str, username: str, passw
|
||||
).render_as_string(hide_password=False)
|
||||
|
||||
|
||||
def _can_connect(url: str) -> bool:
|
||||
engine = create_engine(url, connect_args={"connect_timeout": 5})
|
||||
try:
|
||||
with engine.connect() as connection:
|
||||
connection.execute(text("SELECT 1"))
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
finally:
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def ensure_database(host: str, port: int, database: str, username: str, password: str) -> None:
|
||||
if _can_connect(build_postgres_url(host, port, database, username, password)):
|
||||
return
|
||||
maintenance = build_postgres_url(host, port, "postgres", username, password)
|
||||
try:
|
||||
checker = create_engine(maintenance, isolation_level="AUTOCOMMIT")
|
||||
checker = create_engine(maintenance, isolation_level="AUTOCOMMIT", connect_args={"connect_timeout": 5})
|
||||
with checker.connect() as connection:
|
||||
exists = connection.execute(
|
||||
text("SELECT 1 FROM pg_database WHERE datname = :name"),
|
||||
@@ -56,12 +76,93 @@ def ensure_database(host: str, port: int, database: str, username: str, password
|
||||
raise InstallError("无法连接数据库,请检查主机、端口、账号和密码") from exc
|
||||
|
||||
|
||||
def wait_for_database(host: str, port: int, database: str, username: str, password: str, timeout: int) -> None:
|
||||
deadline = time.monotonic() + timeout
|
||||
attempt = 0
|
||||
while True:
|
||||
attempt += 1
|
||||
try:
|
||||
ensure_database(host, port, database, username, password)
|
||||
if attempt > 1:
|
||||
logger.info("数据库已就绪")
|
||||
return
|
||||
except InstallError as exc:
|
||||
if time.monotonic() >= deadline:
|
||||
raise InstallError(f"等待数据库 {host}:{port}/{database} 超过 {timeout} 秒") from exc
|
||||
if attempt == 1 or attempt % 10 == 0:
|
||||
logger.info("等待数据库 %s:%s/%s 就绪", host, port, database)
|
||||
time.sleep(2)
|
||||
|
||||
|
||||
def _write_install(url: str) -> None:
|
||||
content = json.dumps({"databaseUrl": url}, ensure_ascii=False)
|
||||
target = install_file()
|
||||
if target.is_file() and target.read_text(encoding="utf-8") == content:
|
||||
return
|
||||
staging = target.with_name(f"{target.name}.{os.getpid()}.tmp")
|
||||
staging.write_text(content, encoding="utf-8")
|
||||
os.replace(staging, target)
|
||||
|
||||
|
||||
def hosted_database_url() -> str | None:
|
||||
if not env_database_complete():
|
||||
return None
|
||||
db = env_database()
|
||||
return build_postgres_url(db["host"], db["port"], db["database"], db["username"], db["password"])
|
||||
|
||||
|
||||
def _ensure_setting(host: str, port: int, database: str, username: str, password: str) -> bool:
|
||||
with session_scope() as session:
|
||||
setting = session.get(AppSetting, 1)
|
||||
if setting is not None:
|
||||
if not setting.jwt_secret:
|
||||
setting.jwt_secret = secrets.token_hex(32)
|
||||
return True
|
||||
session.add(
|
||||
AppSetting(
|
||||
id=1,
|
||||
login_mode="local",
|
||||
credential_refresh_seconds=300,
|
||||
worker_concurrency=4,
|
||||
db_host=host,
|
||||
db_port=port,
|
||||
db_name=database,
|
||||
db_user=username,
|
||||
db_password=password,
|
||||
jwt_secret=secrets.token_hex(32),
|
||||
)
|
||||
)
|
||||
return False
|
||||
|
||||
|
||||
def auto_install() -> bool:
|
||||
"""托管模式下按平台提供的数据库完成安装。API 和排队进程同时启动也只会装一次。"""
|
||||
if not hosted():
|
||||
return False
|
||||
url = hosted_database_url()
|
||||
if url is None:
|
||||
return False
|
||||
db = env_database()
|
||||
if url.startswith("postgresql"):
|
||||
wait_for_database(db["host"], db["port"], db["database"], db["username"], db["password"], database_wait_seconds())
|
||||
data_dir().mkdir(parents=True, exist_ok=True)
|
||||
_write_install(url)
|
||||
reset_engine()
|
||||
from app.bootstrap import migrate
|
||||
|
||||
already: list[bool] = []
|
||||
migrate(then=lambda: already.append(_ensure_setting(db["host"], db["port"], db["database"], db["username"], db["password"])))
|
||||
logger.info("托管安装已就绪" if already and already[0] else "托管安装已完成")
|
||||
return True
|
||||
|
||||
|
||||
def perform_install(body: dict) -> bool:
|
||||
if installed():
|
||||
raise InstallError("已经安装")
|
||||
admin_username = str(body.get("adminUsername") or "").strip()
|
||||
admin_password = str(body.get("adminPassword") or "")
|
||||
if not admin_username or not admin_password:
|
||||
with_admin = not hosted()
|
||||
if with_admin and (not admin_username or not admin_password):
|
||||
raise InstallError("请填写管理员账号和密码")
|
||||
use_sqlite = bool(body.get("sqlite"))
|
||||
data_dir().mkdir(parents=True, exist_ok=True)
|
||||
@@ -83,7 +184,7 @@ def perform_install(body: dict) -> bool:
|
||||
raise InstallError("请填写完整的数据库连接")
|
||||
ensure_database(host, port, database, username, password)
|
||||
url = build_postgres_url(host, port, database, username, password)
|
||||
install_file().write_text(json.dumps({"databaseUrl": url}, ensure_ascii=False), encoding="utf-8")
|
||||
_write_install(url)
|
||||
reset_engine()
|
||||
try:
|
||||
from app.bootstrap import migrate
|
||||
@@ -106,7 +207,7 @@ def perform_install(body: dict) -> bool:
|
||||
jwt_secret=secrets.token_hex(32),
|
||||
)
|
||||
)
|
||||
if session.scalar(select(User).where(User.username == admin_username)) is None:
|
||||
if with_admin and session.scalar(select(User).where(User.username == admin_username)) is None:
|
||||
session.add(User(username=admin_username, password_hash=hash_password(admin_password), role="admin"))
|
||||
return already
|
||||
except IntegrityError as exc:
|
||||
|
||||
+31
-11
@@ -1,15 +1,17 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI, HTTPException
|
||||
from fastapi.responses import FileResponse, JSONResponse
|
||||
from fastapi import FastAPI, HTTPException, Request
|
||||
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
from app.api.http import router
|
||||
from app.auth.platform import base_href
|
||||
from app.bootstrap import init_db
|
||||
from app.config import installed
|
||||
|
||||
@@ -25,6 +27,7 @@ WEB_DIST = next(
|
||||
),
|
||||
Path(__file__).resolve().parents[2] / "web" / "dist",
|
||||
)
|
||||
BASE_TAG = re.compile(r"<base\b[^>]*>", re.IGNORECASE)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
@@ -33,10 +36,18 @@ async def lifespan(_application: FastAPI):
|
||||
yield
|
||||
|
||||
|
||||
def create_app() -> FastAPI:
|
||||
def render_index(html: str, href: str) -> str:
|
||||
tag = f'<base href="{href}" />'
|
||||
if BASE_TAG.search(html):
|
||||
return BASE_TAG.sub(tag, html, count=1)
|
||||
return html.replace("<head>", f"<head>\n {tag}", 1)
|
||||
|
||||
|
||||
def create_app(web_dist: Path | None = None) -> FastAPI:
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
application = FastAPI(title="DecomEval", lifespan=lifespan)
|
||||
application.include_router(router)
|
||||
dist = (web_dist or WEB_DIST).resolve()
|
||||
|
||||
@application.middleware("http")
|
||||
async def require_install(request, call_next):
|
||||
@@ -45,17 +56,26 @@ def create_app() -> FastAPI:
|
||||
return JSONResponse({"detail": "尚未安装"}, status_code=503)
|
||||
return await call_next(request)
|
||||
|
||||
if (WEB_DIST / "index.html").is_file():
|
||||
application.mount("/assets", StaticFiles(directory=WEB_DIST / "assets"), name="assets")
|
||||
if (dist / "index.html").is_file():
|
||||
if (dist / "assets").is_dir():
|
||||
application.mount("/assets", StaticFiles(directory=dist / "assets"), name="assets")
|
||||
|
||||
@application.get("/{path:path}")
|
||||
def pages(path: str) -> FileResponse:
|
||||
def index(request: Request) -> HTMLResponse:
|
||||
html = (dist / "index.html").read_text(encoding="utf-8")
|
||||
return HTMLResponse(
|
||||
render_index(html, base_href(request.headers)),
|
||||
headers={"Cache-Control": "no-store", "Vary": "X-Forwarded-Prefix"},
|
||||
)
|
||||
|
||||
@application.get("/{path:path}", response_model=None)
|
||||
def pages(path: str, request: Request) -> FileResponse | HTMLResponse:
|
||||
if path == "api" or path.startswith("api/"):
|
||||
raise HTTPException(status_code=404, detail="接口不存在")
|
||||
target = WEB_DIST / path
|
||||
if path and target.is_file():
|
||||
return FileResponse(target)
|
||||
return FileResponse(WEB_DIST / "index.html")
|
||||
if path and path != "index.html":
|
||||
target = (dist / path).resolve()
|
||||
if target.is_file() and target.is_relative_to(dist):
|
||||
return FileResponse(target)
|
||||
return index(request)
|
||||
|
||||
return application
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ from sqlalchemy import select
|
||||
|
||||
from app.collect.io import parse_upload, write_table
|
||||
from app.collect.remote import fetch_ftp, fetch_nqi
|
||||
from app.config import postgres_conninfo, result_dir
|
||||
from app.config import inline_worker_allowed, postgres_conninfo, result_dir
|
||||
from app.db import session_scope
|
||||
from app.models import CellData, CollectionSource, ExportTask, NqiAccount, utcnow
|
||||
from app.nqi.client import NqiAuthError, NqiClient, NqiError
|
||||
@@ -204,13 +204,20 @@ def _fetch_nqi_sync(cookies: list, config: dict) -> tuple[str, bytes]:
|
||||
def enqueue_export(task_id: int) -> None:
|
||||
if _defer("decom_export", task_id=task_id):
|
||||
return
|
||||
threading.Thread(target=execute_export, args=(task_id,), daemon=True).start()
|
||||
_run_inline(execute_export, task_id)
|
||||
|
||||
|
||||
def enqueue_collection(source_id: int) -> None:
|
||||
if _defer("decom_collect", source_id=source_id):
|
||||
return
|
||||
threading.Thread(target=execute_collection, args=(source_id,), daemon=True).start()
|
||||
_run_inline(execute_collection, source_id)
|
||||
|
||||
|
||||
def _run_inline(target, item_id: int) -> None:
|
||||
if not inline_worker_allowed():
|
||||
logger.info("没有排队数据库,任务 %s 留在排队中", item_id)
|
||||
return
|
||||
threading.Thread(target=target, args=(item_id,), daemon=True).start()
|
||||
|
||||
|
||||
def _defer(name: str, **kwargs) -> bool:
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
for _name in list(os.environ):
|
||||
if _name.startswith("METRIX_") or _name.startswith("DECOM_DB_") or _name == "DECOM_INLINE_WORKER":
|
||||
os.environ.pop(_name)
|
||||
|
||||
TEST_ROOT = Path(os.environ.get("DECOM_TEST_DATA_DIR") or Path(tempfile.gettempdir()) / "decomeval-pytest")
|
||||
os.environ["DECOM_DATA_DIR"] = str(TEST_ROOT / "data")
|
||||
os.environ["DECOM_ALLOW_SQLITE"] = "1"
|
||||
@@ -9,9 +9,7 @@ from pathlib import Path
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
TEST_DATA = Path(__file__).resolve().parents[1] / "data" / "pytest"
|
||||
os.environ["DECOM_DATA_DIR"] = str(TEST_DATA)
|
||||
os.environ["DECOM_ALLOW_SQLITE"] = "1"
|
||||
TEST_DATA = Path(os.environ["DECOM_DATA_DIR"])
|
||||
|
||||
from app.collect.io import parse_csv, write_csv # noqa: E402
|
||||
from app.db import reset_engine # noqa: E402
|
||||
|
||||
@@ -0,0 +1,325 @@
|
||||
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/" />')
|
||||
@@ -15,13 +15,14 @@ def main() -> None:
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
if sys.platform == "win32":
|
||||
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
|
||||
init_db()
|
||||
ready = init_db()
|
||||
start_background()
|
||||
import time
|
||||
|
||||
while not postgres_conninfo():
|
||||
time.sleep(2)
|
||||
init_db()
|
||||
if not ready:
|
||||
init_db()
|
||||
from app.tasks.queue import serve
|
||||
|
||||
serve()
|
||||
|
||||
Reference in New Issue
Block a user