自动登录接口 + 有状态端容器化部署 + 三服务合并 openapi 导出

自动登录(此前只能人工跑 scripts/login.py 再 /api/auth/reload):
- 新增 POST /api/auth/login:动作顺序与下单前的 require_logged_in 一致(探测 →
  未登录则按 account.yaml 登一次 → 再探测),已登录直接跳过不白起浏览器。
  刻意**不抛 5001**:失败以 logged_in=false + 各站 detail 正常返回,调用方自己
  决定是人工接管还是换账号。
- 新增 RAKUTEN_AUTO_LOGIN_ON_START(默认 false):启动即准备登录态,为容器部署
  而存在(镜像里没有落盘的 storage_state)。做成后台任务而非启动阻塞——登录最长
  等 relogin_timeout_seconds(默认 300s,撞验证码时在等人工),阻塞会让 /health
  在这段时间里连端口都不通;关服务时 cancel 掉在途的那次。
- 自动登录不绕过站点校验:凭据是用户自己配在 account.yaml 里的,代填进站点自己的
  登录表单,撞 reCAPTCHA / 设备验证会停在有头浏览器等人工,等不到就超时失败。

容器化部署(新增 Dockerfile.trading + docker-compose.yml):
- 有状态端单独出镜像不是为了整洁:下单/结算必须用**有头** Chromium(headless 会让
  结算 SPA 失灵),镜像要带 Xvfb + 日文字体 + 给人工接管用的可选 x11vnc,抓取镜像
  没有这些。网关复用同一镜像只换 command。
- Jenkinsfile 一条流水线产出两个镜像,BUILD_SCRAPING / BUILD_TRADING 两个开关控制。
- .dockerignore 补上 account.yaml / .auth/ / .browser-data/ / data/:明文密码+卡号、
  可直接冒充账号的 cookie、带登录态的浏览器 profile、含真实 PII 的证据快照,都不该
  进镜像也不该进 build context,运行时一律走挂载。
- .env.example 里 RAKUTEN_AUTO_LOGIN_ON_START 刻意留成注释:compose 的变量插值与
  env_file 读的是同一个 ./.env,这里写成显式值会让 compose 的 `${...:-true}` 失效,
  按 compose 文件头「cp .env.example .env」走反而不会自动登录。

openapi 导出(scripts/export_openapi.py):三服务合并成一份可直接导入 Apifox /
Postman 的文档,每条接口带 operation 级 servers(不必手动切端口)。鉴权标注是遍历
FastAPI 依赖树认出真的挂了 require_bearer_token 的接口,不按路径猜。

openapi.json 本身仍是 gitignore 的本地生成物,因此 tests/test_openapi_export.py
只在内存里校验合并逻辑(三服务覆盖、operation 级 servers、除 /health 外全部标鉴权、
operationId 唯一、$ref 可解析),不断言「文件内容 == 当前导出结果」——CI 的全新
clone 里没有这个文件,那种断言必然失败。代价是「改了接口忘了重新导出」没有自动
兜底,得手动跑 --check,已在 README 里点明。

398 测试全绿;另单独验证过缺 openapi.json 时该文件 5 个用例仍通过(CI 场景)。
compose 的变量插值行为只按文档核对,本机没有 docker 未能实测。

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-08-14 14:27:38 +08:00
co-authored by Claude Opus 5
parent e2875f0c00
commit 63c41b61e7
13 changed files with 1092 additions and 19 deletions
+105
View File
@@ -0,0 +1,105 @@
"""openapi.json 导出测试:守住「一份文档覆盖三个服务」的合并结果
这份文档是外部(Apifox / Postman / 上游联调)唯一的接口来源,合并逻辑错了就会
把人引到不存在的接口、或漏标鉴权。下面的用例全部在内存里 build_spec() 检查合并
结果,不读仓库里的 openapi.json——那个文件是 gitignore 的生成物,CI 的全新 clone
里根本不存在,断言「文件内容 == 当前导出结果」在 CI 上必然失败。
因此「改了接口忘了重新导出」没有自动兜底,得手动跑:
.venv/Scripts/python.exe scripts/export_openapi.py --check
"""
from __future__ import annotations
import importlib.util
import json
import re
import sys
from pathlib import Path
import pytest
ROOT = Path(__file__).resolve().parent.parent
SCRIPT = ROOT / "scripts" / "export_openapi.py"
_METHODS = ("get", "put", "post", "delete", "options", "head", "patch", "trace")
def _load_exporter():
"""按路径加载 scripts/export_openapi.py(scripts 不是包)
必须先塞进 sys.modules 再 exec:dataclass 解析类型注解时会去
sys.modules[cls.__module__] 找命名空间,没登记就直接 AttributeError。
"""
spec = importlib.util.spec_from_file_location("export_openapi", SCRIPT)
assert spec is not None and spec.loader is not None
module = importlib.util.module_from_spec(spec)
sys.modules[spec.name] = module
spec.loader.exec_module(module)
return module
@pytest.fixture(scope="module")
def exporter():
return _load_exporter()
@pytest.fixture(scope="module")
def spec(exporter):
return exporter.build_spec()
def _operations(document: dict) -> list[tuple[str, str, dict]]:
return [
(path, method, operation)
for path, item in document["paths"].items()
for method, operation in item.items()
if method in _METHODS
]
def test_covers_all_three_services(spec):
paths = spec["paths"]
# 抓取
assert "/api/search" in paths
assert "/api/rakuma/search" in paths
# 交易(有状态端)
assert "/api/auth/login" in paths
assert "/api/cart/add" in paths
# 网关
assert "/api/orders" in paths
assert "/api/orders/lease" in paths
def test_each_operation_points_at_its_own_service(spec):
"""operation 级 servers:导入后不必手动切 base URL"""
by_path = {path: operation["servers"][0]["url"] for path, _, operation in _operations(spec)}
assert by_path["/api/search"].endswith(":31107")
assert by_path["/api/cart/add"].endswith(":31108")
assert by_path["/api/orders/lease"].endswith(":31109")
# /health 三个服务都有,合成一条并列出三个 server
health_servers = {s["url"] for s in spec["paths"]["/health"]["get"]["servers"]}
assert len(health_servers) == 3
def test_only_health_is_public(spec):
"""除 /health 外都必须标 Bearer 鉴权——漏标会让调用方以为能匿名调"""
unprotected = [
f"{method.upper()} {path}"
for path, method, operation in _operations(spec)
if "security" not in operation
]
assert unprotected == ["GET /health"]
assert "BearerAuth" in spec["components"]["securitySchemes"]
def test_operation_ids_are_unique(spec):
"""三个服务的 /health 原本都叫 health_health_get,撞了会让导入工具丢接口"""
ids = [operation["operationId"] for _, _, operation in _operations(spec)]
assert len(ids) == len(set(ids))
def test_all_refs_resolve(spec):
"""合并 schema 时如果重名处理错了,$ref 会指向不存在的定义"""
names = set(spec["components"]["schemas"])
refs = set(re.findall(r"#/components/schemas/([^\"]+)", json.dumps(spec)))
assert not refs - names
+100 -1
View File
@@ -24,7 +24,10 @@ class StubAuthSession:
def __init__(self) -> None:
self.checked: list[str] = []
self.reloaded: list[str] = []
self.relogin_calls: list[str] = []
self.logged_in = True
# try_relogin 的结果;None 表示「登录成功并转为登录态」
self.relogin_result: bool | None = None
@property
def sites(self) -> tuple[str, ...]:
@@ -53,6 +56,14 @@ class StubAuthSession:
self.reloaded.append(site)
return 3
async def try_relogin(self, site: str) -> bool:
"""默认「登录成功」:翻成登录态并返回 True;relogin_result 可注入失败"""
self.relogin_calls.append(site)
if self.relogin_result is None:
self.logged_in = True
return True
return self.relogin_result
async def require_logged_in(self, site: str) -> None:
if not self.logged_in:
raise NotLoggedInError(site=site, detail="stub")
@@ -168,7 +179,9 @@ def test_health_does_not_probe_the_site(client, stub):
# ---- 鉴权 ----
@pytest.mark.parametrize("path", ["/api/auth/status", "/api/auth/reload"])
@pytest.mark.parametrize(
"path", ["/api/auth/status", "/api/auth/login", "/api/auth/reload"]
)
def test_auth_endpoints_reject_missing_token(client, path):
response = client.post(path, json={})
assert response.status_code == 401
@@ -213,6 +226,92 @@ def test_status_rejects_unknown_site(client):
assert response.json()["code"] == 1002
# ---- 自动登录 ----
def test_login_skips_when_already_logged_in(client, stub):
"""已登录时不该白起一次登录流程(起浏览器 + 打站点,代价不小)"""
response = client.post("/api/auth/login", json={}, headers=AUTH)
assert response.status_code == 200
body = response.json()
assert body["data"]["logged_in"] is True
assert body["data"]["relogin_attempted"] == {"rakuten": False}
assert stub.relogin_calls == []
# 结论必须来自真实探测,不能只看缓存
assert stub.checked == ["rakuten"]
def test_login_triggers_relogin_when_logged_out(client, stub):
stub.logged_in = False
response = client.post("/api/auth/login", json={"site": "rakuten"}, headers=AUTH)
assert response.status_code == 200
body = response.json()
assert body["data"]["logged_in"] is True
assert body["data"]["relogin_attempted"] == {"rakuten": True}
assert stub.relogin_calls == ["rakuten"]
# 登录后必须再探测一次确认,不能拿登录流程的自述当结论
assert stub.checked == ["rakuten", "rakuten"]
def test_login_reports_failure_without_raising(client, stub):
"""登录失败按 logged_in=false 正常返回,不是 5001
调用方要据此决定人工接管还是换账号;抛错会把「为什么失败」压成一个错误码。
"""
stub.logged_in = False
stub.relogin_result = False
response = client.post("/api/auth/login", json={}, headers=AUTH)
assert response.status_code == 200
body = response.json()
assert body["success"] is True
assert body["data"]["logged_in"] is False
assert body["data"]["relogin_attempted"] == {"rakuten": True}
def test_login_rejects_unknown_site(client):
response = client.post("/api/auth/login", json={"site": "mercari"}, headers=AUTH)
assert response.status_code == 422
assert response.json()["code"] == 1002
# ---- 启动时自动登录(RAKUTEN_AUTO_LOGIN_ON_START)----
class _FakeContainer:
def __init__(self, auth_session) -> None:
self.auth_session = auth_session
async def test_auto_login_on_start_skips_when_logged_in():
from app.trading.main import auto_login_on_start
stub = StubAuthSession()
await auto_login_on_start(_FakeContainer(stub))
assert stub.relogin_calls == []
async def test_auto_login_on_start_logs_in_when_logged_out():
from app.trading.main import auto_login_on_start
stub = StubAuthSession()
stub.logged_in = False
await auto_login_on_start(_FakeContainer(stub))
assert stub.relogin_calls == ["rakuten"]
async def test_auto_login_on_start_swallows_errors():
"""探测抛错也不能把启动流程带崩——服务要能起来报「未登录」"""
from app.trading.main import auto_login_on_start
class Boom(StubAuthSession):
async def check(self, site: str):
raise RuntimeError("站点不可达")
stub = Boom()
await auto_login_on_start(_FakeContainer(stub))
assert stub.relogin_calls == []
# ---- 登录态重载 ----