fourcal-pms/backend/tests/test_hub_integration.py

1895 lines
82 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""统一身份(dsh-hub)对接的契约测试。
用例里的 JSON 一律照抄 unisoa《第三方系统对接指南》的原文示例,不按自己的想象造形状:
这层代码的唯一价值就是"对端返回什么我们就认什么",测试跟着实现走等于没测。
分两类:
* 不碰库的(信封解析、目录/增量解析、票据校验、游标推进判断)—— 常驻;
* 要连库的(增量落库、免登建号、口令回落是否被封死)—— 连不上测试库就整组 skip。
"""
from __future__ import annotations
import json
from datetime import datetime, timedelta, timezone
from types import SimpleNamespace
import pytest
from app.config import settings
from app.main import app as app_module
DB_READY = True
try:
from app.db import ensure_database, get_engine
ensure_database()
with get_engine().connect() as _probe:
_probe.exec_driver_sql("SELECT 1")
except Exception: # pragma: no cover
DB_READY = False
needs_db = pytest.mark.skipif(not DB_READY, reason="测试库连不上")
# ---------------------------------------------------------------------------
# 文档原文示例
# ---------------------------------------------------------------------------
DIRECTORY_PAYLOAD = {
"code": "200",
"data": {
"organizations": [
{"organization_id": 1, "code": "root", "name": "总公司", "path": "/1/",
"status": 1, "created_at": "2026-01-05T02:00:00Z",
"member_count": 120, "direct_member_count": 3, "members": [], "children": []},
{"organization_id": 12, "code": "wecom-12", "name": "研发部", "parent_id": 1,
"path": "/1/12/", "status": 1, "member_count": 8, "direct_member_count": 8,
"members": [], "children": []},
],
"users": [
{"user_id": 10086, "account": "zhangsan", "display_name": "张三",
"email": "zhangsan@example.com", "organization_id": 12, "status": 1},
],
"total_users": 500, "returned_users": 500, "member_limit": 2000,
"truncated": False, "permission_version": 17,
},
"message": "success",
}
CHANGES_PAYLOAD = {
"code": "200",
"data": {
"cursor": 1042, "oldest_seq": 1, "newest_seq": 1042, "has_more": False,
"changes": [{
"seq": 1042, "entity": "user", "entity_id": 10086, "op": "upsert", "source": "wecom",
"occurred_at": "2026-09-24T02:00:00Z",
"data": {"id": 10086, "account": "zhangsan", "display_name": "张三",
"organization_id": 12, "role": "user", "status": 1,
"created_at": "2026-01-05T02:00:00Z"},
}],
},
"message": "success",
}
TICKET_OK = {
"code": "200",
"data": {"active": True, "sub": "10086", "account": "zhangsan", "display_name": "张三",
"email": "zhangsan@example.com", "app_code": "pms",
"issued_at": "2026-09-24T10:00:00Z", "expires_at": "2026-09-24T10:00:30Z",
"state": "b7f1c2"},
"message": "success",
}
class FakeResponse:
def __init__(self, payload, status_code: int = 200) -> None:
self._payload = payload
self.status_code = status_code
self.text = json.dumps(payload, ensure_ascii=False)
def json(self):
return self._payload
def install_fake_httpx(monkeypatch, *, get_result=None, post_result=None,
get_status: int = 200, post_status: int = 200):
"""拦住 hub_api 里的 httpx,顺便把调用参数收下来供断言。"""
from app.service import hub_api
calls: list[dict] = []
def fake_get(url, headers=None, params=None, timeout=None):
calls.append({"method": "GET", "url": url, "headers": headers, "params": params})
return FakeResponse(get_result, get_status)
def fake_post(url, headers=None, json=None, timeout=None):
calls.append({"method": "POST", "url": url, "headers": headers, "json": json})
return FakeResponse(post_result, post_status)
monkeypatch.setattr(hub_api.httpx, "get", fake_get)
monkeypatch.setattr(hub_api.httpx, "post", fake_post)
return calls
@pytest.fixture()
def hub_on(monkeypatch):
"""把 Hub 配成"目录与免登两条通道都通"。"""
from app.service import hub_api
monkeypatch.setattr(hub_api.settings.hub, "enabled", True, raising=False)
monkeypatch.setattr(hub_api.settings.hub, "base_url", "https://hub.example.com", raising=False)
monkeypatch.setattr(hub_api.settings.hub, "directory_key", "dir-key", raising=False)
monkeypatch.setattr(hub_api.settings.hub, "app_code", "pms", raising=False)
monkeypatch.setattr(hub_api.settings.hub, "integration_key", "int-key", raising=False)
return hub_api.settings.hub
def future(seconds: int = 60) -> str:
moment = datetime.now(timezone.utc) + timedelta(seconds=seconds)
return moment.strftime("%Y-%m-%dT%H:%M:%SZ")
# ---------------------------------------------------------------------------
# 响应信封
# ---------------------------------------------------------------------------
class TestEnvelope:
def test_success_code_is_a_string(self, hub_on):
from app.service.hub_api import _unwrap
assert _unwrap({"code": "200", "data": {"a": 1}, "message": "success"},
what="x") == {"a": 1}
def test_numeric_200_also_passes(self, hub_on):
"""宽容收下 int 200,但判定口径仍然只认 code,不看 message。"""
from app.service.hub_api import _unwrap
assert _unwrap({"code": 200, "data": {"a": 1}}, what="x") == {"a": 1}
def test_non_success_code_raises(self, hub_on):
from app.service.hub_api import HubError, _unwrap
with pytest.raises(HubError, match="401001"):
_unwrap({"code": "401001", "data": None, "message": "集成密钥无效"}, what="票据校验")
def test_message_is_never_the_success_signal(self, hub_on):
from app.service.hub_api import HubError, _unwrap
# 中文文案改了不构成"成功",code 才算
with pytest.raises(HubError):
_unwrap({"code": "500", "data": {"x": 1}, "message": "success"}, what="x")
def test_bare_object_without_code_is_passed_through(self, hub_on):
from app.service.hub_api import _unwrap
assert _unwrap({"organizations": [], "users": []}, what="x") == {
"organizations": [], "users": []}
# ---------------------------------------------------------------------------
# 目录全量
# ---------------------------------------------------------------------------
class TestDirectory:
def test_parses_document_shape_and_requests_disabled(self, hub_on, monkeypatch):
from app.service import hub_api
calls = install_fake_httpx(monkeypatch, get_result=DIRECTORY_PAYLOAD)
result = hub_api.fetch_directory()
assert calls[0]["url"] == "https://hub.example.com/api/v1/auth/directory"
assert calls[0]["headers"]["X-Directory-Key"] == "dir-key"
# 不带这两个参数会整棵裁掉"父组织停用"下面的子树,静默少一批最难发现的人
assert calls[0]["params"]["include_disabled"] == "true"
assert calls[0]["params"]["include_disabled_users"] == "true"
assert len(result["organizations"]) == 2
assert result["users"][0]["account"] == "zhangsan"
assert result["total_users"] == 500
def test_truncated_refuses_instead_of_half_syncing(self, hub_on, monkeypatch):
"""truncated=true 时只同步一部分人,比同步失败更糟:会把没回来的人判成离职。"""
from app.service import hub_api
payload = json.loads(json.dumps(DIRECTORY_PAYLOAD))
payload["data"]["truncated"] = True
install_fake_httpx(monkeypatch, get_result=payload)
with pytest.raises(hub_api.HubError, match="截断"):
hub_api.fetch_directory()
def test_missing_lists_refuses_to_disable_everyone(self, hub_on, monkeypatch):
"""对端换了形状时宁可报错,也不能把"接口没返回人"当成"Hub 里没人了"。"""
from app.service import hub_api
install_fake_httpx(monkeypatch, get_result={"code": "200", "data": {}})
with pytest.raises(hub_api.HubError, match="拒绝据此改本地数据"):
hub_api.fetch_directory()
def test_unconfigured_raises_before_any_request(self, monkeypatch):
from app.service import hub_api
monkeypatch.setattr(hub_api.settings.hub, "enabled", False, raising=False)
with pytest.raises(hub_api.HubError, match="未启用"):
hub_api.fetch_directory()
def test_directory_key_rejection_never_blames_the_login_key(self, hub_on, monkeypatch):
"""Hub 在目录通道上复用了免登那句"集成密钥无效",原样抛出去会把人引去查免登密钥。
这条报错必须点名 X-Directory-Key 与 HUB_DIRECTORY_KEYS:免登可用而目录拉不动
是同一把密钥只登记在一条通道上的典型形状,两者的排查方向完全相反。
"""
from app.service import hub_api
install_fake_httpx(monkeypatch, get_status=401, get_result={
"code": "401001", "data": None, "message": "集成密钥无效"})
with pytest.raises(hub_api.HubError) as caught:
hub_api.fetch_directory()
text = str(caught.value)
assert "HUB_DIRECTORY_KEYS" in text
assert "免登" in text # 一句话说清"为什么免登能过而这里不过"
assert "401001" in text # Hub 原样的错误码不能被翻译吃掉
def test_changes_channel_uses_the_same_directory_hint(self, hub_on, monkeypatch):
"""增量流水与全量同一把密钥、同一套口径,别一处能查一处查不出来。"""
from app.service import hub_api
install_fake_httpx(monkeypatch, get_status=401, get_result={
"code": "401001", "data": None, "message": "集成密钥无效"})
with pytest.raises(hub_api.HubError, match="HUB_DIRECTORY_KEYS"):
hub_api.fetch_changes(0)
def test_member_limit_stays_inside_the_interface_range(self, hub_on, monkeypatch):
"""指南 §6.1:member_limit 越界直接 400 400001,这一接口又没有分页。"""
from app.service import hub_api
for configured, sent in ((9000, 5000), (0, 1), ("2500", 2500)):
monkeypatch.setattr(hub_api.settings.hub, "directory_member_limit",
configured, raising=False)
calls = install_fake_httpx(monkeypatch, get_result=DIRECTORY_PAYLOAD)
hub_api.fetch_directory()
assert calls[0]["params"]["member_limit"] == sent, configured
def test_truncated_at_the_ceiling_does_not_ask_for_the_impossible(
self, hub_on, monkeypatch):
"""已经按接口上限发出去还是被截断,再喊"调大配置"就是让人对着一个调不动的键空转。"""
from app.service import hub_api
monkeypatch.setattr(hub_api.settings.hub, "directory_member_limit",
hub_api.MEMBER_LIMIT_MAX, raising=False)
payload = json.loads(json.dumps(DIRECTORY_PAYLOAD))
payload["data"]["truncated"] = True
install_fake_httpx(monkeypatch, get_result=payload)
with pytest.raises(hub_api.HubError, match="拆分应用"):
hub_api.fetch_directory()
# ---------------------------------------------------------------------------
# 目录增量
# ---------------------------------------------------------------------------
class TestChanges:
def test_parses_cursor_and_changes(self, hub_on, monkeypatch):
from app.service import hub_api
calls = install_fake_httpx(monkeypatch, get_result=CHANGES_PAYLOAD)
result = hub_api.fetch_changes(1000)
assert calls[0]["params"] == {"since": 1000, "limit": hub_api.settings.hub.changes_limit}
assert result["cursor"] == 1042
assert result["has_more"] is False
assert result["behind"] is False
assert result["changes"][0]["entity"] == "user"
def test_behind_flag_when_cursor_fell_off_the_end(self, hub_on, monkeypatch):
"""since < oldest_seq 说明中间流水被裁剪,增量补不回来,只能回全量。"""
from app.service import hub_api
payload = json.loads(json.dumps(CHANGES_PAYLOAD))
payload["data"]["oldest_seq"] = 2000
install_fake_httpx(monkeypatch, get_result=payload)
assert hub_api.fetch_changes(1000)["behind"] is True
def test_has_more_is_carried_out(self, hub_on, monkeypatch):
from app.service import hub_api
payload = json.loads(json.dumps(CHANGES_PAYLOAD))
payload["data"]["has_more"] = True
install_fake_httpx(monkeypatch, get_result=payload)
assert hub_api.fetch_changes(1000)["has_more"] is True
# ---------------------------------------------------------------------------
# 免登票据
# ---------------------------------------------------------------------------
class TestTicket:
def test_success_uses_integration_key_not_directory_key(self, hub_on, monkeypatch):
from app.service import hub_api
payload = json.loads(json.dumps(TICKET_OK))
payload["data"]["expires_at"] = future()
calls = install_fake_httpx(monkeypatch, post_result=payload)
result = hub_api.verify_ticket("6a1f" * 16)
assert calls[0]["url"] == "https://hub.example.com/api/v1/auth/tickets/verify"
assert calls[0]["headers"]["X-Integration-Key"] == "int-key"
assert "X-Directory-Key" not in calls[0]["headers"] # 两条密钥通道互不通用
assert calls[0]["json"] == {"ticket": "6a1f" * 16} # 日常不传 app_code
assert result["sub"] == "10086"
def test_app_code_only_sent_when_asked(self, hub_on, monkeypatch):
from app.service import hub_api
payload = json.loads(json.dumps(TICKET_OK))
payload["data"]["expires_at"] = future()
calls = install_fake_httpx(monkeypatch, post_result=payload)
hub_api.verify_ticket("t", app_code="pms")
assert calls[0]["json"]["app_code"] == "pms"
@pytest.mark.parametrize("reason,status_hint", [
("ticket_invalid", "重新"),
("ticket_expired", "过期"),
("ticket_audience_mismatch", "不是发给本系统"),
("user_inactive", "停用"),
])
def test_inactive_reasons_map_to_readable_messages(self, hub_on, monkeypatch, reason,
status_hint):
"""票据失败也是 HTTP 200 + code 200,只能按 active / reason 分支。"""
from app.service import hub_api
install_fake_httpx(monkeypatch, post_result={
"code": "200",
"data": {"active": False, "reason": reason, "app_code": "pms"},
"message": "success",
})
with pytest.raises(hub_api.TicketRejected) as caught:
hub_api.verify_ticket("t")
assert caught.value.reason == reason
assert status_hint in caught.value.message
assert caught.value.retryable is False
def test_expired_ticket_rejected_locally_too(self, hub_on, monkeypatch):
"""文档要求下游对 expires_at 做二次校验:落地即失效的票不能放进人。"""
from app.service import hub_api
payload = json.loads(json.dumps(TICKET_OK))
payload["data"]["expires_at"] = "2020-01-01T00:00:00Z"
install_fake_httpx(monkeypatch, post_result=payload)
with pytest.raises(hub_api.TicketRejected) as caught:
hub_api.verify_ticket("t")
assert caught.value.reason == "ticket_expired"
def test_audience_mismatch_is_blocked(self, hub_on, monkeypatch):
from app.service import hub_api
payload = json.loads(json.dumps(TICKET_OK))
payload["data"]["expires_at"] = future()
payload["data"]["app_code"] = "oa" # 密钥配到别的应用上了
install_fake_httpx(monkeypatch, post_result=payload)
with pytest.raises(hub_api.TicketRejected) as caught:
hub_api.verify_ticket("t")
assert caught.value.reason == "ticket_audience_mismatch"
def test_missing_sub_is_rejected(self, hub_on, monkeypatch):
from app.service import hub_api
payload = json.loads(json.dumps(TICKET_OK))
payload["data"]["expires_at"] = future()
payload["data"]["sub"] = ""
install_fake_httpx(monkeypatch, post_result=payload)
with pytest.raises(hub_api.TicketRejected):
hub_api.verify_ticket("t")
def test_empty_ticket_never_reaches_the_network(self, hub_on, monkeypatch):
from app.service import hub_api
calls = install_fake_httpx(monkeypatch, post_result=TICKET_OK)
with pytest.raises(hub_api.TicketRejected):
hub_api.verify_ticket(" ")
assert calls == []
def test_key_level_http_error_is_not_blamed_on_the_user(self, hub_on, monkeypatch):
from app.service import hub_api
install_fake_httpx(monkeypatch, post_result={"code": "401001", "message": "集成密钥无效"},
post_status=401)
with pytest.raises(hub_api.TicketRejected) as caught:
hub_api.verify_ticket("t")
assert caught.value.reason == "hub_key_rejected"
# 提示要说人话:让人去查密钥,而不是去查那张票据
assert "密钥" in caught.value.message
assert caught.value.code == "401001"
assert "密钥" in caught.value.message
@pytest.mark.parametrize("status_code,code,reason", [
(401, "401001", "hub_key_rejected"),
(403, "403001", "hub_app_forbidden"),
(404, "404001", "hub_app_not_found"),
])
def test_three_hub_rejections_are_three_different_answers(self, hub_on, monkeypatch,
status_code, code, reason):
"""密钥不对、应用没启用、应用编码不存在:三句提示不能是同一句。"""
from app.service import hub_api
install_fake_httpx(monkeypatch, post_result={"code": code, "message": "x"},
post_status=status_code)
with pytest.raises(hub_api.TicketRejected) as caught:
hub_api.verify_ticket("t")
assert caught.value.reason == reason
def test_error_code_in_a_200_envelope_is_still_a_rejection(self, hub_on, monkeypatch):
"""有些部署把网关错误码塞进 200 的信封,口径得一样。"""
from app.service import hub_api
install_fake_httpx(monkeypatch, post_result={"code": "401001", "message": "集成密钥无效"})
with pytest.raises(hub_api.TicketRejected) as caught:
hub_api.verify_ticket("t")
assert caught.value.reason == "hub_key_rejected"
def test_network_timeout_does_not_retry_the_ticket(self, hub_on, monkeypatch):
"""超时后无法判断 Hub 是否已消费票据,唯一正确动作是丢掉它让用户重新发起。"""
import httpx
from app.service import hub_api
def always_fail(*args, **kwargs):
raise httpx.ConnectTimeout("boom")
monkeypatch.setattr(hub_api.httpx, "post", always_fail)
with pytest.raises(hub_api.TicketRejected) as caught:
hub_api.verify_ticket("t")
assert caught.value.reason == "hub_unavailable"
assert caught.value.retryable is False
def test_ticket_value_never_appears_in_the_error(self, hub_on, monkeypatch):
"""票据不入库、不写日志。错误文案里带原值就等于把它送到日志和前端去了。"""
from app.service import hub_api
secret = "deadbeef" * 8
install_fake_httpx(monkeypatch, post_result={"code": "401001", "message": "x"},
post_status=401)
with pytest.raises(hub_api.TicketRejected) as caught:
hub_api.verify_ticket(secret)
assert secret not in str(caught.value)
# ---------------------------------------------------------------------------
# 免登 state
# ---------------------------------------------------------------------------
def _fake_request(cookies: dict[str, str] | None = None, *, scheme: str = "http",
headers: dict[str, str] | None = None):
"""只喂 check_state 真正会读的那两样:cookies 与(is_https 用的)scheme/头。"""
from types import SimpleNamespace
return SimpleNamespace(cookies=cookies or {}, url=SimpleNamespace(scheme=scheme),
headers=headers or {})
def _set_cookie(response) -> str:
"""取响应里第一条 Set-Cookie(Starlette 的属性大小写不该被测试钉死)。"""
return next(v for k, v in response.raw_headers if k == b"set-cookie").decode()
def _issued(*, secure: bool = False) -> tuple[str, str]:
"""发一条 state,返回 ``(交给前端的明文, Cookie 里的值)``。"""
from fastapi.responses import Response
from app.service import sso_state
response = Response()
state = sso_state.issue_state(response, secure=secure)
cookie = _set_cookie(response).split(";")[0].split("=", 1)[1]
return state, cookie
class TestSsoState:
"""state 由服务端生成、存在 HttpOnly Cookie 里,前端脚本读不到才算"服务端保管"。"""
def test_cookie_is_httponly_samesite_lax(self):
from fastapi.responses import Response
from app.service import sso_state
response = Response()
sso_state.issue_state(response)
header = _set_cookie(response).lower()
assert "httponly" in header, "前端脚本能读到 state,就等于没有服务端保管"
assert "samesite=lax" in header, "跨站带不上才挡得住外站把票据塞进来"
assert sso_state.COOKIE_NAME.lower() in header
def test_secure_follows_the_request_scheme(self):
from fastapi.responses import Response
from app.service import sso_state
plain = Response()
sso_state.issue_state(plain, secure=sso_state.is_https(_fake_request()))
assert "secure" not in _set_cookie(plain).lower(), "HTTP 部署上加 Secure 等于没有 Cookie"
# 过了反代以后要看 X-Forwarded-Proto,否则会误把 Secure 位打开、Cookie 直接失效
assert sso_state.is_https(_fake_request(scheme="http",
headers={"x-forwarded-proto": "https"}))
def test_state_came_back_matched_and_cookie_consumed(self):
from fastapi.responses import Response
from app.service import sso_state
state, cookie = _issued()
response = Response()
check = sso_state.check_state(_fake_request({sso_state.COOKIE_NAME: cookie}),
response, state)
assert check.code == sso_state.MATCHED
assert check.verdict(required=True)[0] is True
# 一次性的:不管成不成,落地这趟都得把 Cookie 用掉
assert "max-age=0" in _set_cookie(response).lower()
def test_wrong_state_is_a_mismatch_at_every_setting(self):
from fastapi.responses import Response
from app.service import sso_state
_, cookie = _issued()
check = sso_state.check_state(_fake_request({sso_state.COOKIE_NAME: cookie}),
Response(), "someone-elses-state")
assert check.code == sso_state.MISMATCH
assert check.verdict(required=False)[0] is False
def test_portal_direct_click_passes_loosely_but_not_strictly(self):
"""本系统发过 state、门户直点卡片没带回:宽松档放行,严格档拒。"""
from fastapi.responses import Response
from app.service import sso_state
_, cookie = _issued()
check = sso_state.check_state(_fake_request({sso_state.COOKIE_NAME: cookie}),
Response(), "")
assert check.code == sso_state.NOT_RETURNED
assert check.verdict(required=False)[0] is True
assert check.verdict(required=True)[0] is False
def test_no_cookie_is_missing(self):
from fastapi.responses import Response
from app.service import sso_state
check = sso_state.check_state(_fake_request(), Response(), "")
assert check.code == sso_state.MISSING
assert check.verdict(required=False)[0] is True
assert check.verdict(required=True)[0] is False
def test_tampered_cookie_is_never_matched(self):
"""改一个字符就按被篡改处理——签名走常数时间比对,不靠"看起来一样"。"""
from fastapi.responses import Response
from app.service import sso_state
_, cookie = _issued()
forged = cookie[:-1] + ("a" if cookie[-1] != "a" else "b")
check = sso_state.check_state(_fake_request({sso_state.COOKIE_NAME: forged}),
Response(), "whatever")
assert check.code == sso_state.TAMPERED
assert check.verdict(required=False)[0] is False
def test_expired_cookie_says_expired(self):
"""签名对得上但超了窗口:说"过期",不要说"被篡改",否则排障方向就带偏了。"""
import time as _time
from fastapi.responses import Response
from app import security
from app.service import sso_state
raw = f"some-state.{int(_time.time()) - sso_state.STATE_TTL_SECONDS - 10}"
cookie = f"{raw}.{security.sign(raw)}"
check = sso_state.check_state(_fake_request({sso_state.COOKIE_NAME: cookie}),
Response(), "some-state")
assert check.code == sso_state.EXPIRED
def test_access_token_is_not_a_valid_state(self):
"""拿访问令牌冒充 state:Cookie 那层压根没有它,签不上名,按未发起处理。"""
from fastapi.responses import Response
from app.security import access_token_ttl, issue_tokens
from app.service import sso_state
tokens = issue_tokens(1, "admin")
assert access_token_ttl() > 0
check = sso_state.check_state(_fake_request(), Response(), tokens["accessToken"])
assert check.code == sso_state.MISSING
assert check.verdict(required=True)[0] is False
def test_forged_state_without_a_cookie_cannot_pass_the_strict_setting(self):
"""宽松档下"没有 Cookie"是门户直跳的合法形状,但严格档必须拦住。"""
from fastapi.responses import Response
from app.service import sso_state
check = sso_state.check_state(_fake_request(), Response(), "handwritten-state")
assert check.code == sso_state.MISSING
assert check.verdict(required=False)[0] is True
assert check.verdict(required=True)[0] is False
# ---------------------------------------------------------------------------
# 增量落库
# ---------------------------------------------------------------------------
@pytest.fixture()
def db_session():
if not DB_READY:
pytest.skip("测试库连不上")
from app.db import SessionFactory
session = SessionFactory()()
try:
yield session
finally:
session.rollback()
session.close()
class TestApplyChange:
def test_partial_org_event_escalates_instead_of_clobbering_the_name(self, db_session, hub_on):
"""事件只给 id+status 时不能套批量同步:payload 没有 name,会把部门名刷成"组织 N"。"""
from app.service import org_sync
stats = org_sync.SyncStats()
outcome = org_sync._apply_change(
db_session,
{"seq": 1, "entity": "organization", "entity_id": 12, "op": "upsert",
"source": "hub", "data": {"id": 12, "status": 0}},
stats=stats,
)
assert outcome == "escalate"
assert stats.escalate
# 内部信号不该带着实现细节漏到界面上
assert not any("ESCALATE" in str(item) for item in stats.errors)
def test_user_status_change_only_touches_given_fields(self, db_session, hub_on):
from app.models import Account, AccountSource, Status
from app.service import org_sync
from sqlalchemy import select
account = Account(account=f"hubuser_{datetime.now():%H%M%S%f}", password_hash="",
source=AccountSource.HUB, hub_user_id=999_981,
display_name="原名", status=Status.ACTIVE)
db_session.add(account)
db_session.flush()
stats = org_sync.SyncStats()
outcome = org_sync._apply_change(
db_session,
{"seq": 2, "entity": "user", "entity_id": 999_981, "op": "upsert",
"source": "hub", "data": {"id": 999_981, "status": 0}},
stats=stats,
)
db_session.flush()
reloaded = db_session.execute(
select(Account).where(Account.hub_user_id == 999_981)).scalars().first()
assert outcome == "ok"
assert reloaded.status == Status.DISABLED
assert reloaded.display_name == "原名" # payload 没给的一律不动
def test_user_delete_soft_deletes_and_keeps_the_row(self, db_session, hub_on):
"""审批记录、项目创建人要一直指得到人,所以是软删不是物理删。"""
from app.models import Account, AccountSource, Status
from app.service import org_sync
from sqlalchemy import select
account = Account(account=f"hubgone_{datetime.now():%H%M%S%f}", password_hash="",
source=AccountSource.HUB, hub_user_id=999_982,
display_name="要走的", status=Status.ACTIVE)
db_session.add(account)
db_session.flush()
account_id = account.id
org_sync._apply_change(
db_session,
{"seq": 3, "entity": "user", "entity_id": 999_982, "op": "delete", "source": "hub"},
stats=org_sync.SyncStats(),
)
db_session.flush()
reloaded = db_session.get(Account, account_id)
assert reloaded is not None
assert reloaded.is_deleted is True
assert reloaded.status == Status.DISABLED
def test_unknown_entity_is_recorded_not_raised(self, db_session, hub_on):
"""一条看不懂的事件不该把整批同步带崩。"""
from app.service import org_sync
stats = org_sync.SyncStats()
outcome = org_sync._apply_change(
db_session, {"seq": 9, "entity": "robot", "entity_id": 1, "op": "upsert", "data": {}},
stats=stats)
assert outcome == "ok"
assert stats.errors
class TestSyncChanges:
def test_without_cursor_it_rebuilds_with_full_sync(self, db_session, hub_on, monkeypatch):
"""本地从没成功全量过(游标 0)时,增量无从谈起,必须先补一次全量。"""
from app.service import org_sync, hub_api
monkeypatch.setattr(org_sync, "local_cursor", lambda db: 0)
calls = []
monkeypatch.setattr(org_sync, "sync_all",
lambda db, *, trigger="scheduled": calls.append(trigger) or _fake_run(0))
run = org_sync.sync_changes(db_session, trigger="manual")
assert calls == ["manual+full"]
assert run is not None
def test_behind_cursor_escalates_to_full(self, db_session, hub_on, monkeypatch):
from app.service import hub_api, org_sync
monkeypatch.setattr(org_sync, "local_cursor", lambda db: 1000)
payload = json.loads(json.dumps(CHANGES_PAYLOAD))
payload["data"]["oldest_seq"] = 5000
install_fake_httpx(monkeypatch, get_result=payload)
monkeypatch.setattr(org_sync, "sync_all", lambda db, *, trigger="": _fake_run(7777))
run = org_sync.sync_changes(db_session, trigger="manual")
assert run.cursor_after == 7777
def test_cursor_advances_only_after_the_whole_batch(self, db_session, hub_on, monkeypatch):
"""has_more=true 时要继续拉,直到 false 才提交游标;否则中间事件会永久漏掉。"""
from app.service import hub_api, org_sync
monkeypatch.setattr(org_sync, "local_cursor", lambda db: 100)
batches = [
{"code": "200", "data": {"cursor": 110, "oldest_seq": 1, "newest_seq": 120,
"has_more": True, "changes": []}, "message": "success"},
{"code": "200", "data": {"cursor": 120, "oldest_seq": 1, "newest_seq": 120,
"has_more": False, "changes": []}, "message": "success"},
]
seen: list[int] = []
def fake_get(url, headers=None, params=None, timeout=None):
seen.append(params["since"])
return FakeResponse(batches.pop(0))
monkeypatch.setattr(hub_api.httpx, "get", fake_get)
run = org_sync.sync_changes(db_session, trigger="manual")
assert seen == [100, 110] # 第二批用的是第一批返回的 cursor
assert run.cursor_after == 120
assert run.status == "success"
def test_failed_batch_does_not_advance_the_cursor(self, db_session, hub_on, monkeypatch):
"""拉失败可以,但不能把游标推过去——推过去就等于永久漏掉这批事件。"""
from app.service import hub_api, org_sync
monkeypatch.setattr(org_sync, "local_cursor", lambda db: 500)
install_fake_httpx(monkeypatch, get_result={"code": "500", "message": "boom"})
run = org_sync.sync_changes(db_session, trigger="manual")
assert run.cursor_after == 500 # 停在原地
assert run.status == "failed"
assert run.error
def _fake_run(cursor: int):
from app.models import HubSyncRun
return HubSyncRun(trigger="scheduled", status="success",
started_at=datetime.now(), cursor_after=cursor)
# ---------------------------------------------------------------------------
# 免登换会话 + 口令后门是否封死
# ---------------------------------------------------------------------------
@needs_db
class TestSsoLoginApi:
@pytest.fixture(autouse=True)
def _sweep_jit_accounts(self, request):
"""免登首次落地就地建号是被测行为,但那些号是测试造的,别留在开发库里。
与 ``TestSsoCallbackApi`` 里那条 ``pmscb%`` 的清扫同一个道理:账号列表按 id 排,
攒一堆 ``ssouserXXXX`` 既挤歪分页,又让人误以为是同步下来的真人。
"""
def _sweep() -> None:
from sqlalchemy import delete, select
from app.db import SessionFactory
from app.models import Account, AccountIdentity, PermAccountRole
session = SessionFactory()()
try:
ids = list(session.execute(
select(Account.id).where(Account.account.like("ssouser%"))
).scalars())
for model in (AccountIdentity, PermAccountRole):
session.execute(delete(model).where(model.account_id.in_(ids)))
session.execute(delete(Account).where(Account.id.in_(ids)))
session.commit()
finally:
session.close()
request.addfinalizer(_sweep)
def test_ticket_creates_account_keyed_on_sub(self, client, monkeypatch):
from app.api import auth as auth_api
from app.models import Account, AccountSource
from app.service import hub_api
from sqlalchemy import select
suffix = f"{datetime.now():%H%M%S%f}"
sub = 990_000 + int(suffix[-5:])
def fake_verify(ticket, app_code=None):
return {"active": True, "sub": str(sub), "account": f"ssouser{suffix}",
"display_name": "免登用户", "email": "", "app_code": "pms"}
monkeypatch.setattr(auth_api.settings.hub, "enabled", True, raising=False)
monkeypatch.setattr(auth_api.settings.hub, "app_code", "pms", raising=False)
monkeypatch.setattr(auth_api.settings.hub, "integration_key", "k", raising=False)
monkeypatch.setattr(hub_api, "verify_ticket", fake_verify)
response = client.post("/api/v1/auth/sso/ticket", json={"ticket": "t" * 64})
assert response.status_code == 200, response.text
data = response.json()["data"]
assert data["via"] == "hub"
assert data["user"]["account"] == f"ssouser{suffix}"
assert data["accessToken"]
account = client.post # noqa: B018 (只是占位,真正断言在下面)
session = None
from app.db import SessionFactory
session = SessionFactory()()
try:
row = session.execute(select(Account).where(Account.hub_user_id == sub)).scalars().first()
assert row is not None
assert row.source == AccountSource.HUB
assert row.password_hash == "" # 免登账号不留本地口令
finally:
# 回滚掉这次测试建出来的账号,别在测试库里堆垃圾
session.rollback()
assert account is not None
def test_rejected_ticket_returns_reason_as_error_code(self, client, monkeypatch):
from app.api import auth as auth_api
from app.service import hub_api
def reject(ticket, app_code=None):
raise hub_api.TicketRejected("user_inactive", "账号已停用")
monkeypatch.setattr(auth_api.settings.hub, "enabled", True, raising=False)
monkeypatch.setattr(auth_api.settings.hub, "app_code", "pms", raising=False)
monkeypatch.setattr(auth_api.settings.hub, "integration_key", "k", raising=False)
monkeypatch.setattr(hub_api, "verify_ticket", reject)
response = client.post("/api/v1/auth/sso/ticket", json={"ticket": "t" * 64})
assert response.status_code == 403
body = response.json()
assert body["ok"] is False
assert body["error"]["code"] == "user_inactive"
# 登录日志里绝不能出现票据原值
assert "t" * 64 not in json.dumps(body, ensure_ascii=False)
def test_disabled_hub_does_not_accept_tickets(self, client, monkeypatch):
from app.api import auth as auth_api
monkeypatch.setattr(auth_api.settings.hub, "enabled", False, raising=False)
response = client.post("/api/v1/auth/sso/ticket", json={"ticket": "t"})
assert response.status_code == 400
assert response.json()["error"]["code"] == "sso_disabled"
@needs_db
class TestPasswordFallbackIsClosed:
"""Hub 一开,就不能再有"Hub 连不上当本地账号放行"这种事。"""
def test_hub_account_password_never_verifies(self, monkeypatch):
from app.api import auth as auth_api
from app.db import SessionFactory
from app.models import Account, AccountSource, Status
from app.security import hash_password
monkeypatch.setattr(auth_api.settings.hub, "enabled", True, raising=False)
session = SessionFactory()()
try:
account = Account(account=f"hubfallback_{datetime.now():%H%M%S%f}",
password_hash=hash_password("Admin@12345"),
display_name="有口令的hub账号", source=AccountSource.HUB,
hub_user_id=999_979, status=Status.ACTIVE)
session.add(account)
session.flush()
# 就算库里存了可用口令,hub 来源也一律不放行
assert auth_api._verify(session, account, "Admin@12345") is False
finally:
session.rollback()
session.close()
def test_break_glass_only_covers_local_accounts(self, monkeypatch):
from app.api import auth as auth_api
from app.db import SessionFactory
from app.models import Account, AccountSource, Status
from app.security import hash_password
monkeypatch.setattr(auth_api.settings.hub, "enabled", True, raising=False)
monkeypatch.setattr(auth_api.settings.hub, "break_glass_login", False, raising=False)
session = SessionFactory()()
try:
local = Account(account=f"nobreakglass_{datetime.now():%H%M%S%f}",
password_hash=hash_password("Admin@12345"),
display_name="本地账号", source=AccountSource.LOCAL,
status=Status.ACTIVE)
session.add(local)
session.flush()
# 逃生门关掉之后,连本地账号也不给口令进来
assert auth_api._verify(session, local, "Admin@12345") is False
finally:
session.rollback()
session.close()
def test_local_login_still_works_when_hub_is_off(self, monkeypatch):
from app.api import auth as auth_api
from app.db import SessionFactory
from app.models import Account, AccountSource, Status
from app.security import hash_password
monkeypatch.setattr(auth_api.settings.hub, "enabled", False, raising=False)
session = SessionFactory()()
try:
local = Account(account=f"localonly_{datetime.now():%H%M%S%f}",
password_hash=hash_password("Admin@12345"),
display_name="本地账号", source=AccountSource.LOCAL,
status=Status.ACTIVE)
session.add(local)
session.flush()
assert auth_api._verify(session, local, "Admin@12345") is True
finally:
session.rollback()
session.close()
# ---------------------------------------------------------------------------
# 登录页直接输统一身份账号 + 口令
# ---------------------------------------------------------------------------
#: 真 Hub 的登录响应:令牌套了一层 tokens,人在 user 里(hubtest 就是这个形状)
LOGIN_OK = {
"code": "200",
"data": {
"tokens": {"access_token": "hub-access", "refresh_token": "hub-refresh", "expires_in": 3600},
"user": {"user_id": 10086, "account": "zhangsan", "display_name": "张三",
"email": "zhangsan@example.com", "status": 1},
},
"message": "success",
}
#: hubtest 对"验证码这一项不对"的真实回法:没有信封,只有 error 与中文 message
LOGIN_CAPTCHA_REQUIRED = {"error": "invalid_request", "message": "请输入有效的账号、密码和验证码"}
#: hubtest 对"账号或口令不对"的真实回法(HTTP 401)
LOGIN_BAD_CREDENTIALS = {"error": "invalid_credentials", "message": "账号或密码错误"}
LOCAL_PASSWORD = "Local@12345"
def hub_password_on(monkeypatch, hub_on):
"""把 Hub 配成"账号口令也归它验"。
用例里的账号名都不叫内置超管,天生不在 ``local_only_account_set`` 那批应急账号里,
一定会去问 Hub——不需要也不应该把它们塞进 ``local_only_accounts``,那是反的。
"""
monkeypatch.setattr(hub_on, "login_mode", "hub", raising=False)
monkeypatch.setattr(hub_on, "local_only_accounts", "", raising=False)
return hub_on
def hub_principal_payload(account: str, hub_user_id: int) -> dict:
"""照 hubtest 的形状造一份"Hub 认了这个账号"的响应。"""
payload = json.loads(json.dumps(LOGIN_OK))
payload["data"]["user"].update({"account": account, "user_id": hub_user_id})
return payload
def login_payload(account: str, password: str = "hub-pass", **extra) -> dict:
return {"account": account, "password": password, **extra}
def make_local_account(account: str, password: str = LOCAL_PASSWORD, *, hub_user_id: int | None = None,
source: str = "local") -> None:
"""建一条本系统自建的账号:验"Hub 挂了也不许拿本地口令兜底"这类用例的道具。"""
from app.db import SessionFactory
from app.models import Account, Status
from app.security import hash_password
session = SessionFactory()()
try:
session.add(Account(account=account, password_hash=hash_password(password),
display_name="路径道具账号", source=source, status=Status.ACTIVE,
hub_user_id=hub_user_id))
session.commit()
finally:
session.close()
@pytest.fixture()
def prop_accounts():
"""用例建的账号跑完删掉:它们只是登录路径的道具,不该留在开发库里。
``hub_user_id`` 上有唯一索引,所以随手写死的数字第二次跑就会撞车——统一给一个
9 亿起步的随机值,既不会跟 hubtest 真人(百万级)撞上,也不会跟历史用例撞上。
"""
from sqlalchemy import select
from app.db import SessionFactory
from app.models import Account
created: list[str] = []
yield created
session = SessionFactory()()
try:
for name in created:
for row in session.execute(
select(Account).where(Account.account.like(f"{name}%"))
).scalars().all():
session.delete(row)
session.commit()
finally:
session.close()
def new_hub_id() -> int:
import random
return random.randrange(900_000_000, 999_999_999)
class TestHubPasswordContract:
"""``GET /auth/captcha`` 与 ``POST /auth/login`` 的契约,照 hubtest 的真实回法写。"""
def test_captcha_maps_id_and_image(self, hub_on, monkeypatch):
from app.service import hub_api
calls = install_fake_httpx(monkeypatch, get_result={
"id": "cap-1", "image": "data:image/svg+xml;base64,AAA="})
view = hub_api.fetch_captcha()
assert view["captchaId"] == "cap-1"
assert view["image"].startswith("data:image/svg+xml")
assert calls[0]["url"] == "https://hub.example.com/auth/captcha"
def test_login_sends_the_documented_field_names(self, hub_on, monkeypatch):
from app.service import hub_api
calls = install_fake_httpx(monkeypatch, post_result=LOGIN_OK)
principal = hub_api.login_with_password("zhangsan", "pw", captcha_id="c1", captcha_answer="10")
assert calls[0]["url"] == "https://hub.example.com/auth/login"
assert calls[0]["json"] == {"account": "zhangsan", "password": "pw",
"captcha_id": "c1", "captcha_answer": "10"}
assert (principal["sub"], principal["account"], principal["display_name"]) == (
"10086", "zhangsan", "张三")
def test_empty_captcha_is_not_sent_at_all(self, hub_on, monkeypatch):
"""有些部署没开验证码,带一个空串过去会被当成"验证码错误"白拒一次。"""
from app.service import hub_api
calls = install_fake_httpx(monkeypatch, post_result=LOGIN_OK)
hub_api.login_with_password("zhangsan", "pw")
assert calls[0]["json"] == {"account": "zhangsan", "password": "pw"}
def test_wrong_password_is_a_rejection_not_an_outage(self, hub_on, monkeypatch):
from app.service import hub_api
install_fake_httpx(monkeypatch, post_result=LOGIN_BAD_CREDENTIALS, post_status=401)
with pytest.raises(hub_api.HubRejected) as caught:
hub_api.login_with_password("zhangsan", "错口令")
assert caught.value.needs_captcha is False
assert "账号或密码错误" in str(caught.value)
def test_captcha_rejection_asks_for_a_new_one(self, hub_on, monkeypatch):
from app.service import hub_api
install_fake_httpx(monkeypatch, post_result=LOGIN_CAPTCHA_REQUIRED, post_status=400)
with pytest.raises(hub_api.HubRejected) as caught:
hub_api.login_with_password("zhangsan", "pw", captcha_id="c1", captcha_answer="9")
assert caught.value.needs_captcha is True
def test_server_side_failure_is_an_outage(self, hub_on, monkeypatch):
"""5xx 与被拒必须分开:只有前者才谈得上 hybrid 回落本地口令。"""
from app.service import hub_api
install_fake_httpx(monkeypatch, post_result={"message": "boom"}, post_status=503)
with pytest.raises(hub_api.HubError):
hub_api.login_with_password("zhangsan", "pw")
def test_unreachable_hub_is_an_outage(self, hub_on, monkeypatch):
import httpx
from app.service import hub_api
def boom(*args, **kwargs):
raise httpx.ConnectError("connection refused")
monkeypatch.setattr(hub_api.httpx, "post", boom)
with pytest.raises(hub_api.HubError):
hub_api.login_with_password("zhangsan", "pw")
def test_unknown_login_path_is_an_outage_not_a_wrong_password(self, hub_on, monkeypatch):
"""404 说明接口路径配错了,跟用户填什么无关。"""
from app.service import hub_api
install_fake_httpx(monkeypatch, post_result={"detail": "Not Found"}, post_status=404)
with pytest.raises(hub_api.HubError):
hub_api.login_with_password("zhangsan", "pw")
def test_a_200_without_a_token_is_not_a_login(self, hub_on, monkeypatch):
from app.service import hub_api
install_fake_httpx(monkeypatch, post_result={"code": "200", "data": {}})
with pytest.raises(hub_api.HubError):
hub_api.login_with_password("zhangsan", "pw")
@pytest.mark.parametrize("payload", [
LOGIN_OK,
# 有的部署不套 tokens,令牌直接放在 data 上
{"code": "200", "data": {"access_token": "t", "user_id": 7, "account": "lisi"}},
])
def test_token_shapes_are_all_understood(self, hub_on, monkeypatch, payload):
from app.service import hub_api
install_fake_httpx(monkeypatch, post_result=payload)
assert hub_api.login_with_password("x", "pw")["access_token"]
@needs_db
class TestHubPasswordLogin:
"""登录页那个账号口令框:口令归 Hub 验,认下来才换本系统自己的会话。"""
def test_hub_accepted_account_gets_a_session(self, client, monkeypatch, hub_on, prop_accounts):
from app.db import SessionFactory
from app.models import Account
from app.service import hub_api
hub_password_on(monkeypatch, hub_on)
account = f"hublogin{datetime.now():%H%M%S%f}"
prop_accounts.append(account)
hub_id = new_hub_id()
install_fake_httpx(monkeypatch, post_result=hub_principal_payload(account, hub_id))
response = client.post("/api/v1/auth/login", json=login_payload(account))
assert response.status_code == 200, response.text
data = response.json()["data"]
assert data["via"] == "hub"
assert data["user"]["account"] == account
assert data["user"]["source"] == "hub"
session = SessionFactory()()
try:
row = session.query(Account).filter(Account.account == account).one()
assert row.hub_user_id == hub_id
finally:
session.close()
def test_hub_rejection_never_counts_toward_the_local_lock(self, client, monkeypatch, hub_on,
prop_accounts):
"""被 Hub 拒不能去累加本地锁定计数,否则等于送外面一条锁死管理员的免费通道。"""
from app.db import SessionFactory
from app.models import Account
from app.service import hub_api
hub_password_on(monkeypatch, hub_on)
account = f"hubreject{datetime.now():%H%M%S%f}"
prop_accounts.append(account)
make_local_account(account)
install_fake_httpx(monkeypatch, post_result=LOGIN_BAD_CREDENTIALS, post_status=401)
for _ in range(3):
response = client.post("/api/v1/auth/login", json=login_payload(account))
assert response.status_code == 401
assert response.json()["error"]["code"] == "bad_credentials"
session = SessionFactory()()
try:
row = session.query(Account).filter(Account.account == account).one()
assert (row.login_failed_count or 0) == 0
assert row.locked_until is None
finally:
session.close()
def test_captcha_problem_comes_back_as_a_stable_code(self, client, monkeypatch, hub_on):
from app.service import hub_api
hub_password_on(monkeypatch, hub_on)
install_fake_httpx(monkeypatch, post_result=LOGIN_CAPTCHA_REQUIRED, post_status=400)
response = client.post("/api/v1/auth/login",
json=login_payload("whoever", captchaId="c1", captchaAnswer="9"))
assert response.status_code == 401
assert response.json()["error"]["code"] == "captcha_required"
def test_mode_hub_refuses_to_guess_with_the_local_hash(self, client, monkeypatch, hub_on,
prop_accounts):
"""Hub 只是连不上时也不能拿本地口令兜——除非显式改成 hybrid。"""
from app.service import hub_api
hub_password_on(monkeypatch, hub_on)
account = f"hubdown{datetime.now():%H%M%S%f}"
prop_accounts.append(account)
make_local_account(account)
monkeypatch.setattr(hub_api, "login_with_password",
lambda *a, **k: (_ for _ in ()).throw(hub_api.HubError("连不上")))
# 库里明明躺着一行可用的本地口令,这一档也照样不放人
response = client.post("/api/v1/auth/login", json=login_payload(account))
assert response.status_code == 503
assert response.json()["error"]["code"] == "hub_unavailable"
def test_hybrid_falls_back_only_when_the_hub_is_unreachable(self, client, monkeypatch, hub_on,
prop_accounts):
import httpx
from app.service import hub_api
hub_password_on(monkeypatch, hub_on)
monkeypatch.setattr(hub_on, "login_mode", "hybrid", raising=False)
account = f"hybridfb{datetime.now():%H%M%S%f}"
prop_accounts.append(account)
make_local_account(account)
def refuse(*args, **kwargs):
raise httpx.ConnectError("hub down")
monkeypatch.setattr(hub_api.httpx, "post", refuse)
response = client.post("/api/v1/auth/login", json=login_payload(account, LOCAL_PASSWORD))
assert response.status_code == 200, response.text
assert response.json()["data"]["via"] == "local"
# 但 Hub 明说"口令不对"就不是"连不上",这时候本地口令再对也不放
install_fake_httpx(monkeypatch, post_result=LOGIN_BAD_CREDENTIALS, post_status=401)
response = client.post("/api/v1/auth/login", json=login_payload(account, LOCAL_PASSWORD))
assert response.status_code == 401
assert response.json()["error"]["code"] == "bad_credentials"
def test_emergency_accounts_never_reach_the_hub(self, client, monkeypatch, hub_on):
"""内置超管即使没写进 local_only_accounts 也永远走本地口令。"""
from app.config import settings
from app.service import hub_api
hub_password_on(monkeypatch, hub_on)
calls = install_fake_httpx(monkeypatch, post_result=LOGIN_BAD_CREDENTIALS, post_status=401)
response = client.post("/api/v1/auth/login", json={
"account": settings.seed.admin_account, "password": settings.seed.admin_password})
assert response.status_code == 200, response.text
assert response.json()["data"]["via"] == "local"
assert calls == []
def test_sso_mode_closes_the_password_door(self, client, monkeypatch, hub_on):
from app.config import settings
from app.service import hub_api
hub_password_on(monkeypatch, hub_on)
monkeypatch.setattr(hub_on, "login_mode", "sso", raising=False)
calls = install_fake_httpx(monkeypatch, post_result=LOGIN_OK)
assert client.get("/api/v1/auth/captcha").json()["data"]["required"] is False
# 连内置超管都不认口令了:这一档就是"只许从统一门户免登进入"
response = client.post("/api/v1/auth/login", json={
"account": settings.seed.admin_account, "password": settings.seed.admin_password})
assert response.status_code == 401
assert calls == []
def test_claim_by_account_binds_the_hub_key(self, client, monkeypatch, hub_on, prop_accounts):
"""本人亲自过了 Hub 的口令校验,把还没绑主键的同名本地账号认下来是安全的。"""
from app.db import SessionFactory
from app.models import Account, AccountSource
from app.service import hub_api
hub_password_on(monkeypatch, hub_on)
account = f"claimme{datetime.now():%H%M%S%f}"
prop_accounts.append(account)
hub_id = new_hub_id()
make_local_account(account)
install_fake_httpx(monkeypatch, post_result=hub_principal_payload(account, hub_id))
response = client.post("/api/v1/auth/login", json=login_payload(account))
assert response.status_code == 200, response.text
assert response.json()["data"]["user"]["account"] == account
session = SessionFactory()()
try:
row = session.query(Account).filter(Account.account == account).one()
assert row.hub_user_id == hub_id
assert row.source == AccountSource.HUB
finally:
session.close()
def test_an_account_already_bound_to_someone_else_is_not_merged(self, client, monkeypatch,
hub_on, prop_accounts):
"""两个 Hub 主键并成一条会把权限、待办、流程历史一起并掉,宁可拒。"""
from app.db import SessionFactory
from app.models import Account
from app.service import hub_api
hub_password_on(monkeypatch, hub_on)
account = f"boundguy{datetime.now():%H%M%S%f}"
prop_accounts.append(account)
mine = new_hub_id()
make_local_account(account, hub_user_id=mine, source="hub")
install_fake_httpx(monkeypatch, post_result=hub_principal_payload(account, new_hub_id()))
response = client.post("/api/v1/auth/login", json=login_payload(account))
assert response.status_code == 403
assert response.json()["error"]["code"] == "account_identity_conflict"
session = SessionFactory()()
try:
row = session.query(Account).filter(Account.account == account).one()
assert row.hub_user_id == mine
finally:
session.close()
def test_captcha_endpoint_proxies_the_hub_question(self, client, monkeypatch, hub_on):
from app.service import hub_api
hub_password_on(monkeypatch, hub_on)
install_fake_httpx(monkeypatch, get_result={"id": "cap-9",
"image": "data:image/svg+xml;base64,BBB="})
data = client.get("/api/v1/auth/captcha").json()["data"]
assert data["required"] is True
assert data["captchaId"] == "cap-9"
assert data["image"].startswith("data:image/svg+xml")
def test_captcha_endpoint_stays_quiet_when_nobody_is_asked(self, client, monkeypatch, hub_on):
from app.service import hub_api
monkeypatch.setattr(hub_on, "login_mode", "local", raising=False)
calls = install_fake_httpx(monkeypatch, get_result={"id": "should-not-be-read"})
data = client.get("/api/v1/auth/captcha").json()["data"]
assert data["required"] is False
assert calls == []
def test_a_broken_captcha_service_does_not_lock_the_form(self, client, monkeypatch, hub_on):
"""取不到验证码不该把登录页问死:真需要时 Hub 会当场拒,前端再亮出这个框。"""
import httpx
from app.service import hub_api
hub_password_on(monkeypatch, hub_on)
def boom(*args, **kwargs):
raise httpx.ConnectError("nope")
monkeypatch.setattr(hub_api.httpx, "get", boom)
data = client.get("/api/v1/auth/captcha").json()["data"]
assert data["required"] is False
assert data["warning"]
def test_the_password_never_ends_up_in_a_log_or_the_response(self, client, monkeypatch, hub_on):
from app.db import SessionFactory
from app.models import LoginLog
from app.service import hub_api
hub_password_on(monkeypatch, hub_on)
secret = f"S3cr3t-{datetime.now():%H%M%S%f}"
install_fake_httpx(monkeypatch, post_result=LOGIN_BAD_CREDENTIALS, post_status=401)
response = client.post("/api/v1/auth/login", json=login_payload("whoever", secret))
assert secret not in response.text
session = SessionFactory()()
try:
rows = session.query(LoginLog).order_by(LoginLog.id.desc()).limit(5).all()
assert all(secret not in f"{row.reason}{row.account}" for row in rows)
finally:
session.close()
@needs_db
class TestLoginLogAudit:
"""登录审计里 ``mode`` 得说清"这次是谁判的":password 本地口令 / hub 统一身份 / sso 免登。
这一列是排查"这个人到底怎么进来的"唯一的凭据,三条入口都从 ``_issue_session`` 过,
很容易全落成默认值,所以每条都钉一下。
"""
@staticmethod
def _since() -> int:
from sqlalchemy import func, select
from app.db import SessionFactory
from app.models import LoginLog
session = SessionFactory()()
try:
return int(session.execute(select(func.max(LoginLog.id))).scalar() or 0)
finally:
session.close()
@staticmethod
def _latest(account: str, since: int) -> dict:
from sqlalchemy import select
from app.db import SessionFactory
from app.models import LoginLog
session = SessionFactory()()
try:
row = session.execute(
select(LoginLog)
.where(LoginLog.account == account, LoginLog.id > since)
.order_by(LoginLog.id.desc())
).scalars().first()
assert row is not None, f"没给 {account} 记登录日志"
return {"success": bool(row.success), "reason": row.reason, "mode": row.mode}
finally:
session.close()
def test_hub_password_login_is_logged_as_hub(self, client, monkeypatch, hub_on, prop_accounts):
from app.service import hub_api
hub_password_on(monkeypatch, hub_on)
account = f"hubaudit{datetime.now():%H%M%S%f}"
prop_accounts.append(account)
hub_id = new_hub_id()
install_fake_httpx(monkeypatch, post_result=hub_principal_payload(account, hub_id))
since = self._since()
response = client.post("/api/v1/auth/login", json=login_payload(account))
assert response.status_code == 200, response.text
assert response.json()["data"]["via"] == "hub"
row = self._latest(account, since)
assert row["mode"] == "hub"
assert row["success"] is True
assert f"sub={hub_id}" in row["reason"]
def test_hub_rejection_is_logged_as_hub_too(self, client, monkeypatch, hub_on, prop_accounts):
"""被 Hub 拒也要记成 hub:排查时"Hub 判的"和"本地判的"必须分得开。"""
from app.service import hub_api
hub_password_on(monkeypatch, hub_on)
account = f"hubauditno{datetime.now():%H%M%S%f}"
prop_accounts.append(account)
install_fake_httpx(monkeypatch, post_result=LOGIN_BAD_CREDENTIALS, post_status=401)
since = self._since()
response = client.post("/api/v1/auth/login", json=login_payload(account))
assert response.status_code == 401
row = self._latest(account, since)
assert row["mode"] == "hub"
assert row["success"] is False
def test_local_password_login_is_logged_as_password(self, client, monkeypatch, hub_on,
prop_accounts):
account = f"localaudit{datetime.now():%H%M%S%f}"
prop_accounts.append(account)
make_local_account(account)
monkeypatch.setattr(hub_on, "login_mode", "local", raising=False)
since = self._since()
response = client.post("/api/v1/auth/login",
json=login_payload(account, LOCAL_PASSWORD))
assert response.status_code == 200, response.text
assert response.json()["data"]["via"] == "local"
row = self._latest(account, since)
assert row["mode"] == "password"
assert row["success"] is True
def test_ticket_login_is_logged_as_sso(self, client, monkeypatch, prop_accounts):
from app.api import auth as auth_api
from app.service import hub_api
suffix = f"{datetime.now():%H%M%S%f}"
account = f"ssoaudit{suffix}"
prop_accounts.append(account)
def fake_verify(ticket, app_code=None):
return {"active": True, "sub": str(new_hub_id()), "account": account,
"display_name": "免登审计", "email": "", "app_code": "pms"}
monkeypatch.setattr(auth_api.settings.hub, "enabled", True, raising=False)
monkeypatch.setattr(auth_api.settings.hub, "app_code", "pms", raising=False)
monkeypatch.setattr(auth_api.settings.hub, "integration_key", "k", raising=False)
monkeypatch.setattr(hub_api, "verify_ticket", fake_verify)
since = self._since()
response = client.post("/api/v1/auth/sso/ticket", json={"ticket": "t" * 64})
assert response.status_code == 200, response.text
row = self._latest(account, since)
assert row["mode"] == "sso"
assert row["success"] is True
def test_sso_status_shape_matches_the_frontend(client):
"""登录页要按这几个键决定留不留口令表单、"去门户"按钮跳哪、回调地址抄哪一条。"""
response = client.get("/api/v1/auth/sso/status")
assert response.status_code == 200
data = response.json()["data"]
assert set(data) == {
"enabled", "hubEnabled", "passwordLoginAllowed", "hubPasswordLogin",
"localPasswordAllowed", "loginMode", "hubBaseUrl", "portalUrl",
"appCode", "missing", "callbackUrl", "aliasUrl", "landingUrl",
"callbackPath", "aliasPath", "landingPath", "cookieName", "codeTtlSeconds",
}
# 逃生门(break_glass_login)默认开着,口令入口必须在,否则 Hub 一挂谁都进不来
assert data["localPasswordAllowed"] is True
# 登录页那个账号口令框永远跟着 passwordLoginAllowed 走:Hub 开着也要留,
# 因为那框收的是统一身份账号(hubPasswordLogin 为真时还要多摆一个验证码)。
assert data["passwordLoginAllowed"] is True
assert data["hubPasswordLogin"] is False # conftest 把 login_mode 压成了 local
assert data["loginMode"] == "local"
# 回调地址要能直接抄进 Hub 后台,且必须就是管理员登记的那一条路径
assert data["callbackPath"] == "/api/v1/auth/sso/callback"
assert data["callbackUrl"].endswith("/api/v1/auth/sso/callback")
assert "ticket" not in data["callbackUrl"]
def test_hub_status_advertises_the_callback_to_register(client, admin_headers):
"""对接时最费时间的是"到底该在 Hub 上填哪个地址",所以状态接口要自己说清楚。"""
response = client.get("/api/v1/auth/hub/status", headers=admin_headers)
assert response.status_code == 200
sso = response.json()["data"]["sso"]
assert sso["callbackPath"] == "/api/v1/auth/sso/callback"
assert sso["aliasPath"] == "/sso/hub"
assert sso["landingPath"] == "/sso"
assert isinstance(sso["missing"], list)
# 状态接口是只读的,任何情况下都不能把密钥本身带出去
assert "integration_key" not in json.dumps(sso)
# ---------------------------------------------------------------------------
# 后端免登回调 + 一次性短码
# ---------------------------------------------------------------------------
def _identity(sub: int, suffix: str, **extra) -> dict:
data = {"active": True, "sub": str(sub), "account": f"pmscb{suffix}",
"display_name": "回调免登用户", "email": "", "app_code": "pms"}
data.update(extra)
return data
@needs_db
class TestSsoCallbackApi:
"""Hub 302 到后端这一路:票据不进浏览器,换来的是一条只许用一次的短码。"""
@pytest.fixture()
def hub_sso(self, client, monkeypatch, request):
"""打开免登并把验票这一步换成可控的桩;``calls`` 记下打了几次。
每个用例都另起一个 TestClient:短码与 state 都靠 Cookie,用会话级的那个
client 会把上一个用例的 Cookie 带进来,测出来的"能兑"是假的。
"""
from fastapi.testclient import TestClient
from app.api import auth as auth_api
from app.service import hub_api
monkeypatch.setattr(auth_api.settings.hub, "enabled", True, raising=False)
monkeypatch.setattr(auth_api.settings.hub, "app_code", "pms", raising=False)
monkeypatch.setattr(auth_api.settings.hub, "integration_key", "k", raising=False)
calls: list[dict] = []
def make(payload=None, error=None):
def fake_verify(ticket, app_code=None):
calls.append({"ticket": ticket, "app_code": app_code})
if error is not None:
raise error
return payload
monkeypatch.setattr(hub_api, "verify_ticket", fake_verify)
return calls
# 免登首次落地会就地建号(这是被测行为之一),但那些号是测试造的,
# 留在开发库里会把"按 id 排序的账号列表"挤歪,连带别的用例找不到种子里的人。
def _sweep():
from app.db import SessionFactory
from app.models import Account, AccountIdentity, PermAccountRole, SsoHandoff
from sqlalchemy import delete, select
session = SessionFactory()()
try:
ids = list(session.execute(
select(Account.id).where(Account.account.like("pmscb%"))
).scalars())
for model in (AccountIdentity, PermAccountRole):
session.execute(delete(model).where(model.account_id.in_(ids)))
session.execute(delete(Account).where(Account.id.in_(ids)))
session.execute(delete(SsoHandoff))
session.commit()
finally:
session.close()
request.addfinalizer(_sweep)
return SimpleNamespace(make=make, calls=calls,
new_client=lambda: TestClient(app_module))
def test_callback_exchanges_a_one_time_code_for_a_session(self, hub_sso):
from datetime import datetime
from app.db import SessionFactory
from app.models import SsoHandoff
from sqlalchemy import select
suffix = f"{datetime.now():%H%M%S%f}"
sub = 960_000 + int(suffix[-6:])
hub_sso.make(_identity(sub, suffix))
http = hub_sso.new_client()
landing = http.get("/api/v1/auth/sso/callback",
params={"ticket": "t" * 64, "redirect": "/projects"},
follow_redirects=False)
assert landing.status_code == 302, landing.text
location = landing.headers["location"]
assert location.startswith("/sso#code="), location
assert "ticket" not in location
# 落地地址不许被缓存,缓存了就会拿同一条短码兑两次
assert landing.headers["cache-control"] == "no-store"
cookie_header = landing.headers["set-cookie"].lower()
assert "pms_sso_handoff=" in cookie_header and "httponly" in cookie_header
assert "t" * 64 not in str(landing.headers).lower()
# 库里只存哈希,拿到数据库也换不出一条可用的短码
row = None
session = SessionFactory()()
try:
row = session.execute(select(SsoHandoff).order_by(SsoHandoff.id.desc())
.limit(1)).scalars().first()
assert row is not None and row.redirect == "/projects"
assert "t" * 64 not in (row.code_hash + row.bind_hash + row.detail)
finally:
session.close()
code = location.split("code=", 1)[1]
exchanged = http.post("/api/v1/auth/sso/exchange", json={"code": code})
assert exchanged.status_code == 200, exchanged.text
data = exchanged.json()["data"]
assert data["via"] == "hub"
assert data["accessToken"]
assert data["user"]["account"] == f"pmscb{suffix}"
assert data["redirect"] == "/projects"
# 短码只能用一次:第二次来就是"回门户重新点一次"
again = http.post("/api/v1/auth/sso/exchange", json={"code": code})
assert again.status_code == 401
assert again.json()["error"]["code"] == "handoff_invalid"
def test_code_without_the_cookie_is_worthless(self, hub_sso):
"""把落地地址原样发给别人:别人没有那条 HttpOnly Cookie,兑不走会话。"""
from datetime import datetime
suffix = f"{datetime.now():%H%M%S%f}"
hub_sso.make(_identity(970_000 + int(suffix[-6:]), suffix))
landing = hub_sso.new_client().get("/api/v1/auth/sso/callback",
params={"ticket": "t" * 40},
follow_redirects=False)
code = landing.headers["location"].split("code=", 1)[1]
stranger = hub_sso.new_client()
assert stranger.post("/api/v1/auth/sso/exchange", json={"code": code}).status_code == 401
def test_wrong_cookie_is_the_same_answer_as_no_cookie(self, hub_sso):
"""存在性探针要挡掉:短码对不对、Cookie 对不对,对外只回同一句话。"""
from datetime import datetime
suffix = f"{datetime.now():%H%M%S%f}"
hub_sso.make(_identity(971_000 + int(suffix[-6:]), suffix))
http = hub_sso.new_client()
landing = http.get("/api/v1/auth/sso/callback", params={"ticket": "t" * 40},
follow_redirects=False)
code = landing.headers["location"].split("code=", 1)[1]
stranger = hub_sso.new_client()
stranger.cookies.set("pms_sso_handoff", "not-the-bind-this-callback-issued")
response = stranger.post("/api/v1/auth/sso/exchange", json={"code": code})
assert response.status_code == 401
assert response.json()["error"]["code"] == "handoff_invalid"
def test_expired_code_is_rejected(self, hub_sso):
from datetime import datetime, timedelta
from app.db import SessionFactory
from app.models import SsoHandoff
from sqlalchemy import update
suffix = f"{datetime.now():%H%M%S%f}"
hub_sso.make(_identity(972_000 + int(suffix[-6:]), suffix))
http = hub_sso.new_client()
landing = http.get("/api/v1/auth/sso/callback", params={"ticket": "t" * 40},
follow_redirects=False)
code = landing.headers["location"].split("code=", 1)[1]
session = SessionFactory()()
try:
from app.security import hash_token
session.execute(update(SsoHandoff)
.where(SsoHandoff.code_hash == hash_token(code))
.values(expires_at=datetime.now() - timedelta(seconds=1)))
session.commit()
finally:
session.close()
assert http.post("/api/v1/auth/sso/exchange", json={"code": code}).status_code == 401
@pytest.mark.parametrize("case", ["missing", "expired", "failed", "unknown"])
def test_failures_land_on_the_page_with_a_stable_reason(self, hub_sso, case):
"""回调是浏览器整页跳转过来的入口,失败只能 302 带原因码,不能回一屏 JSON。"""
from datetime import datetime
from app.service import hub_api
suffix = f"{datetime.now():%H%M%S%f}"
if case == "missing":
params, expect = {"ticket": ""}, "ticket_missing"
hub_sso.make(_identity(973_000, suffix))
elif case == "expired":
params, expect = {"ticket": "t" * 40}, "ticket_expired"
hub_sso.make(error=hub_api.TicketRejected("ticket_expired", "过期了"))
elif case == "failed":
params, expect = {"ticket": "t" * 40}, "user_inactive"
hub_sso.make(error=hub_api.TicketRejected("user_inactive", "账号已停用"))
else:
params, expect = {"ticket": "t" * 40}, "sso_failed"
hub_sso.make(error=hub_api.TicketRejected("brand_new_reason", "后端新增的原因码"))
response = hub_sso.new_client().get("/api/v1/auth/sso/callback", params=params,
follow_redirects=False)
assert response.status_code == 302
location = response.headers["location"]
assert location == f"/sso?error={expect}", location
assert "code=" not in location
def test_state_is_compared_against_the_cookie_on_the_callback(self, hub_sso):
"""先从本系统发起(写 Cookie),落地却带回另一个 state:拒。"""
from datetime import datetime
suffix = f"{datetime.now():%H%M%S%f}"
hub_sso.make(_identity(974_000 + int(suffix[-6:]), suffix))
http = hub_sso.new_client()
begun = http.post("/api/v1/auth/sso/state")
assert begun.status_code == 200
assert "httponly" in begun.headers["set-cookie"].lower()
assert begun.json()["data"]["portalUrl"]
response = http.get("/api/v1/auth/sso/callback",
params={"ticket": "t" * 40, "state": "not-the-issued-one"},
follow_redirects=False)
assert response.headers["location"] == "/sso?error=sso_state_rejected"
# 被 state 挡在门外时,连 Hub 都不该去打一次——票据是消耗品
assert hub_sso.calls == []
def test_state_echoed_by_the_ticket_must_match_too(self, hub_sso):
"""票据回传了 state 却与这一趟对不上:说明这张票不是开给这次跳转的。"""
from datetime import datetime
suffix = f"{datetime.now():%H%M%S%f}"
hub_sso.make(_identity(975_000 + int(suffix[-6:]), suffix, state="a-different-run"))
response = hub_sso.new_client().get("/api/v1/auth/sso/callback",
params={"ticket": "t" * 40},
follow_redirects=False)
assert response.headers["location"] == "/sso?error=sso_state_rejected"
def test_matching_state_from_our_own_launch_gets_in(self, hub_sso):
"""完整一条:发起拿 state -> 门户把同一个 state 带回来 -> 换到会话。"""
from datetime import datetime
suffix = f"{datetime.now():%H%M%S%f}"
sub = 976_000 + int(suffix[-6:])
http = hub_sso.new_client()
state = http.post("/api/v1/auth/sso/state").json()["data"]["state"]
hub_sso.make(_identity(sub, suffix, state=state))
landing = http.get("/api/v1/auth/sso/callback",
params={"ticket": "t" * 40, "state": state},
follow_redirects=False)
assert landing.headers["location"].startswith("/sso#code=")
code = landing.headers["location"].split("code=", 1)[1]
assert http.post("/api/v1/auth/sso/exchange", json={"code": code}).status_code == 200
def test_alias_path_is_the_same_entry(self, hub_sso):
"""Hub 上习惯填 /sso/hub,这条别名得和后端回调是同一个入口。"""
from datetime import datetime
suffix = f"{datetime.now():%H%M%S%f}"
hub_sso.make(_identity(977_000 + int(suffix[-6:]), suffix))
response = hub_sso.new_client().get("/sso/hub", params={"ticket": "t" * 40},
follow_redirects=False)
assert response.status_code == 302
assert response.headers["location"].startswith("/sso#code=")
def test_offsite_redirect_is_dropped(self, hub_sso):
"""``redirect`` 只认站内路径:``//host`` 会被浏览器当成另一台主机。"""
from datetime import datetime
suffix = f"{datetime.now():%H%M%S%f}"
hub_sso.make(_identity(978_000 + int(suffix[-6:]), suffix))
http = hub_sso.new_client()
landing = http.get("/api/v1/auth/sso/callback",
params={"ticket": "t" * 40, "redirect": "//evil.example.com"},
follow_redirects=False)
code = landing.headers["location"].split("code=", 1)[1]
data = http.post("/api/v1/auth/sso/exchange", json={"code": code}).json()["data"]
assert data["redirect"] == ""
def test_ticket_value_never_leaves_the_server(self, hub_sso):
"""票据原值不进 302 地址、不进响应头、不进兑换响应。"""
from datetime import datetime
suffix = f"{datetime.now():%H%M%S%f}"
hub_sso.make(_identity(979_000 + int(suffix[-6:]), suffix))
secret = "SECRETTICKET" + suffix
http = hub_sso.new_client()
landing = http.get("/api/v1/auth/sso/callback", params={"ticket": secret},
follow_redirects=False)
code = landing.headers["location"].split("code=", 1)[1]
exchanged = http.post("/api/v1/auth/sso/exchange", json={"code": code})
assert secret not in str(landing.headers)
assert secret not in exchanged.text
# ---------------------------------------------------------------------------
# 上线体检
# ---------------------------------------------------------------------------
def _prod_like(**hub_values):
"""造一份"除 hub 之外都合格"的生产档配置。"""
import copy
from app.config import load_settings, warnings as prod_warnings
probe = copy.deepcopy(load_settings())
probe.env = "prod"
probe.security.jwt_secret = "x" * 40
probe.database.password = "p"
probe.seed.demo_data = False
probe.database.auto_create_schema = False
probe.legacy.enabled = False
for key, value in hub_values.items():
setattr(probe.hub, key, value)
return [item for item in prod_warnings(probe) if "hub" in item]
class TestProdWarnings:
def test_hub_off_produces_no_hub_warnings(self):
assert _prod_like(enabled=False) == []
def test_http_base_url_is_called_out(self):
"""票据和密钥都会走明文。"""
notes = _prod_like(enabled=True, base_url="http://hub.internal",
directory_key="k" * 40, app_code="pms", integration_key="k" * 40)
assert any("HTTPS" in item for item in notes)
def test_missing_directory_key_is_called_out(self):
notes = _prod_like(enabled=True, base_url="https://hub.internal",
directory_key="", app_code="pms", integration_key="k" * 40)
assert any("directory_key" in item for item in notes)
def test_half_configured_sso_is_called_out(self):
"""只配 app_code 不配密钥,免登会在第一次跳转时才炸,上线时必须拦住。"""
notes = _prod_like(enabled=True, base_url="https://hub.internal",
directory_key="k" * 40, app_code="pms", integration_key="")
assert any("只配了一半" in item for item in notes)
def test_fully_configured_hub_is_silent(self):
notes = _prod_like(enabled=True, base_url="https://hub.internal",
directory_key="k" * 40, app_code="pms", integration_key="k" * 40)
assert notes == []